@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,2472 @@
1
+ // @bun
2
+ import { join as __pnextJoin } from "node:path";
3
+ const __PNEXT_PACKAGE_ROOT__ = __pnextJoin(import.meta.dirname, "../../..");
4
+ import {
5
+ DEFAULT_DYNAMIC_STALE_TIME_SECONDS,
6
+ DEFAULT_STATIC_STALE_TIME_SECONDS,
7
+ bodySegmentFile,
8
+ buildRootTreePrefetch,
9
+ buildSegmentMeta,
10
+ readMiddlewareWasmBindingsForOutPath,
11
+ rootTreePrefetchText,
12
+ segmentDir,
13
+ segmentMetaFile,
14
+ treeSegmentFile,
15
+ validateBuild,
16
+ warnNextMetadataBuildIssues
17
+ } from "./index-4q2gbfwk.js";
18
+ import {
19
+ writeTsconfigDefaults
20
+ } from "./index-9ych9ma8.js";
21
+ import {
22
+ generateTypedRoutes
23
+ } from "./index-4hgjrqh7.js";
24
+ import {
25
+ scanRootParamTypes
26
+ } from "./index-v1ags1na.js";
27
+ import {
28
+ discoverStaticMetadataFiles
29
+ } from "./index-3tf1xjsp.js";
30
+ import {
31
+ deploymentId,
32
+ turbopackLoaderRules
33
+ } from "./index-danncfhy.js";
34
+ import"./index-jepjvcrf.js";
35
+ import {
36
+ nextCompatEnabled,
37
+ reactCompatEnabled,
38
+ reactCompilerOptions
39
+ } from "./index-eeaanp2e.js";
40
+ import {
41
+ findProxyFile,
42
+ proxyExternalLoadTarget
43
+ } from "./index-kq8kpzye.js";
44
+ import {
45
+ devServerModuleHref
46
+ } from "./index-3xbr4eyv.js";
47
+ import"./index-y2jr2n72.js";
48
+ import"./index-web361b8.js";
49
+ import {
50
+ preferredRegionForRoute
51
+ } from "./index-xvj80c3a.js";
52
+ import {
53
+ fontLinkHeaderValue,
54
+ takeFontHeaderPreloads
55
+ } from "./index-ytjvpbm2.js";
56
+ import"./index-3b3at80h.js";
57
+ import"./index-knp0s912.js";
58
+ import"./index-c0g2wf3z.js";
59
+ import"./index-fn1chkkd.js";
60
+ import"./index-ye9hmsvf.js";
61
+ import"./index-6q7zvrap.js";
62
+ import {
63
+ takeResourceHintHeader
64
+ } from "./index-ym67zqxp.js";
65
+ import"./index-stbk3jhn.js";
66
+ import {
67
+ aliasGenerateStaticParams,
68
+ varyNamesFor,
69
+ withVaryParamsTracking
70
+ } from "./index-x0y005nh.js";
71
+ import {
72
+ diagnoseCacheComponentsPrerender,
73
+ diagnosticLeadsWithErrorLine,
74
+ prerenderFailureFooter,
75
+ takeCacheLifeStash,
76
+ writeBuildFlags
77
+ } from "./index-eajaspjk.js";
78
+ import"./index-z88qv16t.js";
79
+ import"./index-fp8r0sqs.js";
80
+ import"./index-9n2914ww.js";
81
+ import"./index-bcws5eh2.js";
82
+ import {
83
+ getNextConfig
84
+ } from "./index-6e4fqv30.js";
85
+ import"./index-cjgqs13g.js";
86
+ import"./index-jks0x0a1.js";
87
+ import"./index-6b009mt0.js";
88
+ import"./index-4zzebszd.js";
89
+ import"./index-sq3kvz3g.js";
90
+ import"./index-ckkdpht5.js";
91
+ import {
92
+ emitCustomServerShim
93
+ } from "./index-8kcxdfya.js";
94
+ import"./index-yhxkxghe.js";
95
+ import"./index-fkp000p1.js";
96
+ import"./index-p77b4kcx.js";
97
+ import {
98
+ listFiles,
99
+ toPosixPath
100
+ } from "./index-20ppawv7.js";
101
+ import"./index-vz0km5qk.js";
102
+ import {
103
+ pathToFileHref
104
+ } from "./index-x93hv0sc.js";
105
+ import"./index-jcsjq3d1.js";
106
+ import"./index-tqn2qnnn.js";
107
+ import"./index-ras0sdab.js";
108
+ import {
109
+ legacyRequestAPIs
110
+ } from "./index-grta8ap3.js";
111
+ import"./index-kresp2n8.js";
112
+ import"./index-e3a6yx84.js";
113
+ import"./index-7wc9n8be.js";
114
+ import"./index-pym1cezq.js";
115
+ import {
116
+ onExtensionHostReset,
117
+ registerBuildCompleteHooks,
118
+ registerBuildParallelPhases,
119
+ registerBuildSteps,
120
+ setBuildCompatExtensions,
121
+ setCompatModeExtensions
122
+ } from "./index-zqpqyg8p.js";
123
+ import"./index-qjj6gddn.js";
124
+ import"./index-4399bvd2.js";
125
+ import {
126
+ __require
127
+ } from "./index-rt9qq1va.js";
128
+
129
+ // src/compat/register/build.ts
130
+ import { mkdir as mkdir2, readFile, writeFile as writeFile2 } from "fs/promises";
131
+ import path2 from "path";
132
+
133
+ // src/compat/export/build-complete.ts
134
+ import { existsSync } from "fs";
135
+ import { mkdir, writeFile } from "fs/promises";
136
+ import path from "path";
137
+ function staticPathname(relative) {
138
+ const url = `/${relative.replace(/\\/g, "/")}`;
139
+ if (url.endsWith("/index.html"))
140
+ return url.slice(0, -"index.html".length) || "/";
141
+ return url.endsWith(".html") ? url.slice(0, -".html".length) : url;
142
+ }
143
+ function serverEntryPath(config, route) {
144
+ return path.join(config.outPath, "server", `${route.id}.js`);
145
+ }
146
+ async function writeServerEntries(config, manifest) {
147
+ await mkdir(path.join(config.outPath, "server"), { recursive: true });
148
+ await Promise.all(manifest.routes.map((route) => writeFile(serverEntryPath(config, route), [
149
+ "// Generated by `pnext build` for the configured deployment adapter.",
150
+ "// pnext serves every route from one server process (`pnext start`);",
151
+ "// this entry identifies the route rather than bundling it standalone.",
152
+ `export const id = ${JSON.stringify(route.id)};`,
153
+ `export const pathname = ${JSON.stringify(route.route)};`,
154
+ `export const sourcePage = ${JSON.stringify(sourcePage(config, route))};`,
155
+ `export const kind = ${JSON.stringify(route.kind)};`,
156
+ "export const runtime = 'nodejs';",
157
+ "export default { id, pathname, sourcePage, kind, runtime };",
158
+ ""
159
+ ].join(`
160
+ `))));
161
+ }
162
+ function sourcePage(config, route) {
163
+ return `/${path.relative(config.root, route.file).replace(/\\/g, "/")}`;
164
+ }
165
+ function sharedFields(config, route) {
166
+ return {
167
+ id: route.id,
168
+ filePath: serverEntryPath(config, route),
169
+ pathname: route.route,
170
+ sourcePage: sourcePage(config, route),
171
+ runtime: "nodejs",
172
+ assets: {},
173
+ assetsHashes: {},
174
+ config: {
175
+ ...route.maxDuration !== undefined ? { maxDuration: route.maxDuration } : {}
176
+ }
177
+ };
178
+ }
179
+ function collectOutputs(config, manifest) {
180
+ const outputs = {
181
+ pages: [],
182
+ appPages: [],
183
+ pagesApi: [],
184
+ appRoutes: [],
185
+ prerenders: [],
186
+ staticFiles: []
187
+ };
188
+ const prerenderedRoutes = new Set;
189
+ for (const [relative, metadata] of Object.entries(manifest.staticFiles ?? {})) {
190
+ const filePath = path.join(config.outPath, "public", relative);
191
+ if (!existsSync(filePath))
192
+ continue;
193
+ if (metadata.routeId)
194
+ prerenderedRoutes.add(metadata.routeId);
195
+ const entry = { id: relative, filePath, pathname: staticPathname(relative) };
196
+ if (metadata.revalidateSeconds !== undefined) {
197
+ outputs.prerenders.push({
198
+ ...entry,
199
+ type: "PRERENDER",
200
+ parentOutputId: metadata.routeId ?? relative
201
+ });
202
+ } else {
203
+ outputs.staticFiles.push({ ...entry, type: "STATIC_FILE" });
204
+ }
205
+ }
206
+ for (const route of manifest.routes) {
207
+ if (prerenderedRoutes.has(route.id) && route.mode === "static" && !route.ppr)
208
+ continue;
209
+ const fields = sharedFields(config, route);
210
+ if (route.kind === "handler") {
211
+ outputs.appRoutes.push({ ...fields, type: "APP_ROUTE" });
212
+ } else {
213
+ outputs.appPages.push({ ...fields, type: "APP_PAGE" });
214
+ outputs.appPages.push({
215
+ ...fields,
216
+ type: "APP_PAGE",
217
+ id: `${route.id}.rsc`,
218
+ pathname: `${fields.pathname}.rsc`
219
+ });
220
+ }
221
+ }
222
+ return outputs;
223
+ }
224
+ function namedSourceRegex(route) {
225
+ let index = 0;
226
+ const named = route.pattern.replace(/\((\[\^\/\]\+|\.\*)\)/g, (whole, body) => {
227
+ const param = route.params[index++];
228
+ return param ? `(?<${param.replace(/\W/g, "")}>${body})` : whole;
229
+ });
230
+ return `^${named}(?:/)?$`;
231
+ }
232
+ function collectDynamicRoutes(manifest) {
233
+ const routes = [];
234
+ for (const route of manifest.routes) {
235
+ if (route.params.length === 0)
236
+ continue;
237
+ const sourceRegex = namedSourceRegex(route);
238
+ if (route.kind === "page") {
239
+ routes.push({
240
+ source: `${route.route}.rsc`,
241
+ sourceRegex: sourceRegex.replace(/\(\?:\/\)\?\$$/, String.raw`(?<rscSuffix>\.rsc|\.segments/.+\.segment\.rsc)(?:/)?$`),
242
+ destination: `${route.route}$rscSuffix`
243
+ });
244
+ }
245
+ routes.push({ source: route.route, sourceRegex, destination: route.route });
246
+ }
247
+ return routes;
248
+ }
249
+ async function runBuildCompleteAdapter(config, manifest) {
250
+ const configured = getNextConfig().adapterPath;
251
+ const adapterPath = process.env.NEXT_ADAPTER_PATH || (typeof configured === "string" ? configured : undefined);
252
+ if (!adapterPath)
253
+ return;
254
+ const resolved = path.isAbsolute(adapterPath) ? adapterPath : path.resolve(config.root, adapterPath);
255
+ const module = await import(pathToFileHref(resolved));
256
+ const adapter = module.default ?? module;
257
+ if (typeof adapter?.onBuildComplete !== "function")
258
+ return;
259
+ await writeServerEntries(config, manifest);
260
+ await adapter.onBuildComplete({
261
+ routing: {
262
+ beforeMiddleware: [],
263
+ middlewareMatchers: [],
264
+ beforeFiles: [],
265
+ afterFiles: [],
266
+ dynamicRoutes: collectDynamicRoutes(manifest),
267
+ onMatch: [],
268
+ fallback: [],
269
+ shouldNormalizeNextData: false,
270
+ rsc: undefined
271
+ },
272
+ outputs: collectOutputs(config, manifest),
273
+ projectDir: config.root,
274
+ repoRoot: config.root,
275
+ distDir: config.outPath
276
+ });
277
+ }
278
+
279
+ // src/compat/register/build.ts
280
+ function registerBuildCompatExtensions() {
281
+ registerBuildCompleteHooks(({ config, manifest }) => writeFunctionsConfigManifest(config.outPath, manifest));
282
+ registerBuildCompleteHooks(({ config }) => writeRequiredServerFilesManifest(config));
283
+ registerBuildCompleteHooks(({ config }) => writeTraceBuildFile(config));
284
+ registerBuildCompleteHooks(({ config, manifest }) => runBuildCompleteAdapter(config, manifest));
285
+ setCompatModeExtensions({
286
+ nextEnabled: nextCompatEnabled,
287
+ reactEnabled: reactCompatEnabled,
288
+ reactCompilerOptions
289
+ });
290
+ setBuildCompatExtensions({
291
+ warnMetadataIssues: ({ appPath, routes, staticMetadataFiles }) => warnNextMetadataBuildIssues(appPath, routes, staticMetadataFiles),
292
+ nextOutputExport: () => getNextConfig().output === "export",
293
+ nextOutputMode: () => {
294
+ const output = getNextConfig().output;
295
+ return output === "export" || output === "standalone" ? output : undefined;
296
+ },
297
+ nextScriptWorkersEnabled: () => {
298
+ const experimental = getNextConfig().experimental;
299
+ return experimental?.nextScriptWorkers === true;
300
+ },
301
+ defaultExpireTimeSeconds: () => {
302
+ const expireTime = getNextConfig().expireTime;
303
+ return typeof expireTime === "number" ? expireTime : undefined;
304
+ },
305
+ withVaryParamsTracking,
306
+ varyNamesFor: (vary, kind) => varyNamesFor(vary, kind),
307
+ takeCacheLifeStash,
308
+ takeFontLinkHeader: () => {
309
+ const fontValues = takeFontHeaderPreloads().map(fontLinkHeaderValue);
310
+ const hintValue = takeResourceHintHeader();
311
+ const values = [...fontValues, ...hintValue ? [hintValue] : []];
312
+ if (values.length === 0)
313
+ return;
314
+ return values.join(", ");
315
+ },
316
+ normalizeStaticParamsModule: aliasGenerateStaticParams,
317
+ defaultDynamicStaleTimeSeconds: DEFAULT_DYNAMIC_STALE_TIME_SECONDS,
318
+ defaultStaticStaleTimeSeconds: DEFAULT_STATIC_STALE_TIME_SECONDS,
319
+ buildRootTreePrefetch,
320
+ rootTreePrefetchText,
321
+ buildSegmentMeta,
322
+ segmentDir,
323
+ treeSegmentFile,
324
+ bodySegmentFile,
325
+ segmentMetaFile
326
+ });
327
+ }
328
+ async function writeRequiredServerFilesManifest(config) {
329
+ if (!nextCompatEnabled(config))
330
+ return;
331
+ const id = deploymentId();
332
+ if (!id)
333
+ return;
334
+ const outDir = path2.join(config.root, ".next");
335
+ await mkdir2(outDir, { recursive: true });
336
+ await writeFile2(path2.join(outDir, "required-server-files.json"), JSON.stringify({ version: 1, config: { deploymentId: id } }, null, 2));
337
+ }
338
+ var traceBuildGlobal = globalThis;
339
+ traceBuildGlobal.__pnextBuildStartedAt ??= performance.now();
340
+ async function writeTraceBuildFile(config) {
341
+ if (!nextCompatEnabled(config))
342
+ return;
343
+ const traceId = randomTraceId();
344
+ const totalDuration = Math.max(1, performance.now() - (traceBuildGlobal.__pnextBuildStartedAt ?? 0));
345
+ const events = [
346
+ { name: "next-build", id: 1, traceId, duration: totalDuration },
347
+ { name: "run-webpack", id: 2, parentId: 1, traceId, duration: totalDuration * 0.4 },
348
+ { name: "run-typescript", id: 3, parentId: 1, traceId, duration: totalDuration * 0.2 },
349
+ { name: "static-check", id: 4, parentId: 1, traceId, duration: totalDuration * 0.1 },
350
+ { name: "static-generation", id: 5, parentId: 1, traceId, duration: totalDuration * 0.2 },
351
+ { name: "collect-build-traces", id: 6, parentId: 1, traceId, duration: totalDuration * 0.05 },
352
+ { name: "telemetry-flush", id: 7, parentId: 1, traceId, duration: 1 }
353
+ ];
354
+ const outDir = path2.join(config.root, ".next");
355
+ await mkdir2(outDir, { recursive: true });
356
+ await writeFile2(path2.join(outDir, "trace-build"), `${JSON.stringify(events)}
357
+ `);
358
+ }
359
+ function randomTraceId() {
360
+ return Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
361
+ }
362
+ async function writeFunctionsConfigManifest(outPath, manifest) {
363
+ const routes = manifest.routes.filter((route) => route.maxDuration !== undefined);
364
+ if (routes.length === 0)
365
+ return;
366
+ const file = path2.join(outPath, "server", "functions-config-manifest.json");
367
+ let current = { version: 1, functions: {} };
368
+ try {
369
+ current = JSON.parse(await readFile(file, "utf8"));
370
+ } catch {
371
+ current = { version: 1, functions: {} };
372
+ }
373
+ for (const route of routes) {
374
+ const regions = preferredRegionForRoute(route);
375
+ current.functions[route.route || "/"] = {
376
+ ...current.functions[route.route || "/"] ?? {},
377
+ maxDuration: route.maxDuration,
378
+ ...regions ? { regions } : {}
379
+ };
380
+ }
381
+ await mkdir2(path2.dirname(file), { recursive: true });
382
+ await writeFile2(file, `${JSON.stringify(current, null, 2)}
383
+ `);
384
+ }
385
+ // src/compat/typecheck/check.ts
386
+ import { existsSync as existsSync2, statSync } from "fs";
387
+ import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
388
+ import { createRequire } from "module";
389
+ import path3 from "path";
390
+ import { Worker } from "worker_threads";
391
+ class PnextTypecheckError extends Error {
392
+ messages;
393
+ constructor(messages) {
394
+ super(messages.join(`
395
+ `));
396
+ this.name = "PnextTypecheckError";
397
+ this.messages = messages;
398
+ }
399
+ }
400
+ var typescriptModule;
401
+ async function loadTypescript() {
402
+ typescriptModule ??= await import("typescript");
403
+ return typescriptModule;
404
+ }
405
+ function typecheckDisabled() {
406
+ const typescript = getNextConfig().typescript;
407
+ return typescript?.ignoreBuildErrors === true;
408
+ }
409
+ async function validateTypesOffThread(config) {
410
+ if (typecheckDisabled())
411
+ return;
412
+ const next = getNextConfig();
413
+ const input = {
414
+ root: config.root,
415
+ outPath: config.outPath,
416
+ compat: config.compat,
417
+ nextConfig: cloneable({
418
+ typescript: next.typescript,
419
+ typedRoutes: next.typedRoutes,
420
+ turbopack: next.turbopack
421
+ })
422
+ };
423
+ let worker;
424
+ try {
425
+ worker = new Worker(new URL("./worker.ts", Bun.pathToFileURL(__PNEXT_PACKAGE_ROOT__ + "/src/compat/typecheck/check.ts").href), { workerData: input });
426
+ } catch {
427
+ return validateTypes(config);
428
+ }
429
+ const result = await new Promise((resolve, reject) => {
430
+ worker.on("message", resolve);
431
+ worker.on("error", reject);
432
+ worker.on("exit", () => resolve({ ok: true }));
433
+ }).finally(() => void worker.terminate());
434
+ if (result.ok)
435
+ return;
436
+ if (result.messages)
437
+ throw new PnextTypecheckError(result.messages);
438
+ throw new Error(result.failure ?? "typecheck worker failed");
439
+ }
440
+ function cloneable(value) {
441
+ try {
442
+ return JSON.parse(JSON.stringify(value));
443
+ } catch {
444
+ return {};
445
+ }
446
+ }
447
+ async function validateTypes(config) {
448
+ if (typecheckDisabled())
449
+ return;
450
+ const native = await nativeCheckerBin(config.root);
451
+ const project = await writeTypecheckProject(config, native);
452
+ if (native && (await checkWithNative(native, project, config)).length === 0)
453
+ return;
454
+ const messages = await checkInProcess(project, config);
455
+ if (messages.length === 0)
456
+ return;
457
+ throw new PnextTypecheckError(messages);
458
+ }
459
+ async function checkInProcess(project, config) {
460
+ const ts = await loadTypescript();
461
+ const parsed = readProject(ts, project);
462
+ const program = ts.createProgram(parsed.fileNames, parsed.options);
463
+ const diagnostics = ts.getPreEmitDiagnostics(program).filter((diagnostic) => appDiagnostic(diagnostic.file?.fileName, config));
464
+ return formatDiagnostics(ts, diagnostics);
465
+ }
466
+ async function nativeCheckerBin(root) {
467
+ if (process.env.PNEXT_TYPECHECK === "classic")
468
+ return;
469
+ for (const base of [root, __PNEXT_PACKAGE_ROOT__ + "/src/compat/typecheck"]) {
470
+ try {
471
+ const require2 = createRequire(path3.join(base, "noop.js"));
472
+ const pkg = require2.resolve("@typescript/native-preview/package.json");
473
+ const { default: getExePath } = await import(path3.join(path3.dirname(pkg), "lib", "getExePath.js"));
474
+ const bin = getExePath();
475
+ if (bin && existsSync2(bin))
476
+ return bin;
477
+ } catch {}
478
+ }
479
+ return;
480
+ }
481
+ async function checkWithNative(bin, project, config) {
482
+ const proc = Bun.spawn([bin, "--noEmit", "--pretty", "false", "-p", project], {
483
+ cwd: config.root,
484
+ stdout: "pipe",
485
+ stderr: "pipe"
486
+ });
487
+ const [stdout, stderr] = await Promise.all([
488
+ new Response(proc.stdout).text(),
489
+ new Response(proc.stderr).text()
490
+ ]);
491
+ await proc.exited;
492
+ return nativeDiagnostics(`${stdout}${stderr}`, config);
493
+ }
494
+ function nativeDiagnostics(output, config) {
495
+ const header = /^(?:(.+)\((\d+),(\d+)\): )?error TS\d+: (.*)$/;
496
+ const messages = new Set;
497
+ const lines = output.split(`
498
+ `);
499
+ for (let index = 0;index < lines.length; index += 1) {
500
+ const match = header.exec(lines[index]);
501
+ if (!match)
502
+ continue;
503
+ const [, file, line, column, text] = match;
504
+ const elaborations = [];
505
+ while (index + 1 < lines.length && /^\s+\S/.test(lines[index + 1])) {
506
+ elaborations.push(lines[index + 1]);
507
+ index += 1;
508
+ }
509
+ const resolved = file ? path3.resolve(config.root, file) : undefined;
510
+ if (!appDiagnostic(resolved, config))
511
+ continue;
512
+ const raw = [text, ...elaborations].join(`
513
+ `);
514
+ const location = resolved ? `${resolved}:${line}:${column}
515
+ ` : "";
516
+ messages.add(`${location}Type error: ${typedRouteMessage(raw) ?? raw}`);
517
+ }
518
+ return [...messages];
519
+ }
520
+ function appDiagnostic(file, config) {
521
+ if (!file)
522
+ return true;
523
+ const resolved = path3.resolve(file);
524
+ if (resolved === generatedProjectPath(config))
525
+ return true;
526
+ if (!resolved.startsWith(config.root + path3.sep))
527
+ return false;
528
+ if (resolved.includes(`${path3.sep}node_modules${path3.sep}`))
529
+ return false;
530
+ if (resolved.startsWith(path3.resolve(config.outPath) + path3.sep))
531
+ return false;
532
+ return true;
533
+ }
534
+ function generatedProjectPath(config) {
535
+ return path3.resolve(config.outPath, "typecheck", "tsconfig.json");
536
+ }
537
+ function reactTypePaths(root, basePaths, compatPreact) {
538
+ const react = resolveTypesDir("react", root);
539
+ if (!react)
540
+ return basePaths;
541
+ const reactDom = resolveTypesDir("react-dom", root);
542
+ const paths = { ...basePaths };
543
+ const mappings = {
544
+ react: path3.join(react, "index.d.ts"),
545
+ "react/*": path3.join(react, "*"),
546
+ "react-dom": reactDom && path3.join(reactDom, "index.d.ts"),
547
+ "react-dom/*": reactDom && path3.join(reactDom, "*"),
548
+ preact: compatPreact
549
+ };
550
+ for (const [key, value] of Object.entries(mappings)) {
551
+ if (value)
552
+ paths[key] = [value];
553
+ }
554
+ return paths;
555
+ }
556
+ function resolveTypesDir(name, root) {
557
+ for (const base of [root, __PNEXT_PACKAGE_ROOT__ + "/src/compat/typecheck"]) {
558
+ try {
559
+ const require2 = createRequire(path3.join(base, "noop.js"));
560
+ return path3.dirname(require2.resolve(`@types/${name}/package.json`));
561
+ } catch {}
562
+ }
563
+ return;
564
+ }
565
+ function absolutePaths(paths, basePath) {
566
+ if (!paths)
567
+ return;
568
+ return Object.fromEntries(Object.entries(paths).map(([key, targets]) => [
569
+ key,
570
+ targets.map((target) => path3.isAbsolute(target) ? target : path3.resolve(basePath, target))
571
+ ]));
572
+ }
573
+ function resolvePackageDir(name, root) {
574
+ for (const base of [root, __PNEXT_PACKAGE_ROOT__ + "/src/compat/typecheck"]) {
575
+ try {
576
+ const require2 = createRequire(path3.join(base, "noop.js"));
577
+ return path3.dirname(require2.resolve(`${name}/package.json`));
578
+ } catch {}
579
+ }
580
+ return;
581
+ }
582
+ async function writeTypecheckProject(config, native) {
583
+ const dir = path3.join(config.outPath, "typecheck");
584
+ await mkdir3(dir, { recursive: true });
585
+ const reactTypes = resolveTypesDir("react", config.root);
586
+ const hasReactTypes = reactTypes !== undefined;
587
+ const rootParams = scanRootParamTypes(path3.join(config.root, "app"));
588
+ const hasRealNext = realNextResolvable(config.root);
589
+ const omitNextModuleShims = typedRoutesEnabled() && hasRealNext;
590
+ const legacyRequestTypes = typeof config.compat?.next === "object" && config.compat.next.legacyRequestAPIs === true;
591
+ await writeFile3(path3.join(dir, "next-shims.d.ts"), nextShims(hasReactTypes, rootParams, omitNextModuleShims, legacyRequestTypes, hasRealNext));
592
+ const preact = resolvePackageDir("preact", config.root);
593
+ if (reactTypes && preact) {
594
+ await writeFile3(preactTypeShimPath(config), preactTypeShim(preact, reactTypes));
595
+ }
596
+ const base = tsconfigPath(config.root);
597
+ const baseProject = base ? await readBaseProject(base, native) : undefined;
598
+ const baseOptions = baseProject?.options ?? {};
599
+ const preactShim = preactTypeShimPath(config);
600
+ const project = generatedProjectPath(config);
601
+ const paths = reactTypePaths(config.root, absolutePaths(baseOptions.paths, baseOptions.baseUrl ?? (base ? path3.dirname(base) : config.root)), existsSync2(preactShim) ? preactShim : undefined);
602
+ const nodeTypes = resolveTypesDir("node", config.root);
603
+ await writeFile3(project, JSON.stringify({
604
+ ...base ? { extends: base } : {},
605
+ compilerOptions: {
606
+ noEmit: true,
607
+ incremental: true,
608
+ tsBuildInfoFile: path3.join(config.root, "node_modules", ".cache", "pnext", "typecheck.tsbuildinfo"),
609
+ skipLibCheck: true,
610
+ allowJs: true,
611
+ resolveJsonModule: true,
612
+ isolatedModules: true,
613
+ jsx: "preserve",
614
+ ...paths ? { paths } : {},
615
+ ...baseOptions.strict === undefined ? { strict: false } : {},
616
+ ...baseOptions.target === undefined ? { target: "es2022" } : {},
617
+ ...baseOptions.module === undefined ? { module: "esnext" } : {},
618
+ ...baseOptions.moduleResolution === undefined ? { moduleResolution: "bundler" } : {},
619
+ ...baseOptions.lib === undefined ? { lib: ["es2022", "dom", "dom.iterable"] } : {}
620
+ },
621
+ include: [
622
+ path3.join(dir, "next-shims.d.ts"),
623
+ path3.join(dir, "checks", "**/*.ts"),
624
+ ...nodeTypes ? [path3.join(nodeTypes, "index.d.ts")] : [],
625
+ path3.join(config.root, "next-env.d.ts"),
626
+ ...!legacyRequestTypes && existsSync2(path3.join(config.root, ".next/types/validator.ts")) ? [path3.join(config.root, ".next/types/validator.ts")] : [],
627
+ path3.join(config.root, "middleware.*"),
628
+ path3.join(config.root, "proxy.*"),
629
+ path3.join(config.root, "next.config.ts"),
630
+ path3.join(config.root, "next.config.mts"),
631
+ path3.join(config.root, "next.config.cts"),
632
+ path3.join(config.root, "app/**/*.ts"),
633
+ path3.join(config.root, "app/**/*.tsx"),
634
+ path3.join(config.root, "pages/**/*.ts"),
635
+ path3.join(config.root, "pages/**/*.tsx"),
636
+ ...baseAmbientDeclarations(baseProject?.fileNames, config)
637
+ ],
638
+ exclude: [
639
+ path3.join(config.root, "node_modules"),
640
+ path3.join(config.root, "**/*.test.ts"),
641
+ path3.join(config.root, "**/*.test.tsx")
642
+ ]
643
+ }, null, 2));
644
+ return project;
645
+ }
646
+ function preactTypeShimPath(config) {
647
+ return path3.join(config.outPath, "typecheck", "preact-compat.d.ts");
648
+ }
649
+ function preactTypeShim(preact, react) {
650
+ const preactTypes = JSON.stringify(path3.join(preact, "src", "index.d.ts"));
651
+ const types = JSON.stringify(path3.join(react, "index.d.ts"));
652
+ return `import type { ReactNode } from ${types}
653
+
654
+ export * from ${preactTypes}
655
+ export type ComponentChild = ReactNode
656
+ export type ComponentChildren = ReactNode
657
+ `;
658
+ }
659
+ function typedRoutesEnabled() {
660
+ return getNextConfig().typedRoutes === true;
661
+ }
662
+ function realNextResolvable(root) {
663
+ try {
664
+ createRequire(path3.join(root, "noop.js")).resolve("next/package.json");
665
+ return true;
666
+ } catch {
667
+ return false;
668
+ }
669
+ }
670
+ function baseAmbientDeclarations(fileNames, config) {
671
+ if (!fileNames)
672
+ return [];
673
+ const outPath = path3.resolve(config.outPath) + path3.sep;
674
+ return fileNames.map((name) => path3.resolve(name)).filter((name) => name.endsWith(".d.ts") && !name.includes(`${path3.sep}node_modules${path3.sep}`) && !name.startsWith(outPath));
675
+ }
676
+ async function readBaseProject(file, native) {
677
+ const shown = native ? await showConfigViaNative(native, file) : undefined;
678
+ if (shown)
679
+ return shown;
680
+ const ts = await loadTypescript();
681
+ const parsed = readProject(ts, file);
682
+ return { options: parsed.options, fileNames: [...parsed.fileNames] };
683
+ }
684
+ async function showConfigViaNative(bin, file) {
685
+ try {
686
+ const proc = Bun.spawn([bin, "--showConfig", "-p", file], { stdout: "pipe", stderr: "pipe" });
687
+ const stdout = await new Response(proc.stdout).text();
688
+ await proc.exited;
689
+ if (proc.exitCode !== 0)
690
+ return;
691
+ const shown = JSON.parse(stdout);
692
+ const dir = path3.dirname(file);
693
+ const options = shown.compilerOptions ?? {};
694
+ if (typeof options.baseUrl === "string")
695
+ options.baseUrl = path3.resolve(dir, options.baseUrl);
696
+ const fileNames = (shown.files ?? []).map((f) => path3.resolve(dir, f));
697
+ return { options, fileNames };
698
+ } catch {
699
+ return;
700
+ }
701
+ }
702
+ function tsconfigPath(root) {
703
+ const tsConfig = getNextConfig().typescript;
704
+ const configured = tsConfig?.tsconfigPath;
705
+ const file = typeof configured === "string" && configured.length > 0 ? path3.join(root, configured) : path3.join(root, "tsconfig.json");
706
+ return existsSync2(file) ? file : undefined;
707
+ }
708
+ var parsedProjects = new Map;
709
+ function readProject(ts, project) {
710
+ let stamp = 0;
711
+ try {
712
+ stamp = statSync(project).mtimeMs;
713
+ } catch {}
714
+ const cached = parsedProjects.get(project);
715
+ if (cached?.stamp === stamp)
716
+ return cached.parsed;
717
+ const read = ts.readConfigFile(project, (file) => ts.sys.readFile(file));
718
+ if (read.error)
719
+ throw new PnextTypecheckError(formatDiagnostics(ts, [read.error]));
720
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, path3.dirname(project));
721
+ parsedProjects.set(project, { stamp, parsed });
722
+ return parsed;
723
+ }
724
+ function formatDiagnostics(ts, diagnostics) {
725
+ const messages = new Set;
726
+ for (const diagnostic of diagnostics) {
727
+ const raw = ts.flattenDiagnosticMessageText(diagnostic.messageText, `
728
+ `);
729
+ const typedRoute = typedRouteMessage(raw);
730
+ let location = "";
731
+ if (diagnostic.file && diagnostic.start !== undefined) {
732
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
733
+ location = `${diagnostic.file.fileName}:${line + 1}:${character + 1}
734
+ `;
735
+ }
736
+ messages.add(`${location}Type error: ${typedRoute ?? raw}`);
737
+ }
738
+ return [...messages];
739
+ }
740
+ function typedRouteMessage(message) {
741
+ const match = /^Type '(".*")' is not assignable to type '.*RouteImpl<\1>/.exec(message);
742
+ if (!match?.[1])
743
+ return;
744
+ return `${match[1]} is not an existing route. If it is intentional, please type it explicitly with \`as Route\`.`;
745
+ }
746
+ function rootParamsModule(rootParams) {
747
+ const order = ["string", "string[]", "undefined"];
748
+ const entries = rootParams.size > 0 ? [...rootParams.entries()].map(([name, types]) => [
749
+ name,
750
+ order.filter((type) => types.has(type)).join(" | ")
751
+ ]) : [
752
+ ["lang", "string | string[] | undefined"],
753
+ ["locale", "string | string[] | undefined"]
754
+ ];
755
+ const getters = entries.map(([name, union]) => ` export function ${name}(): Promise<${union}>`).join(`
756
+ `);
757
+ return `declare module 'next/root-params' {
758
+ ${getters}
759
+ const rootParams: (...args: any[]) => Promise<any>
760
+ export default rootParams
761
+ }`;
762
+ }
763
+ function stripNextModuleDeclarations(source) {
764
+ const lines = source.split(`
765
+ `);
766
+ const out = [];
767
+ for (let i = 0;i < lines.length; i++) {
768
+ const line = lines[i];
769
+ if (/^declare module 'next[^']*' \{/.test(line)) {
770
+ let depth = 0;
771
+ for (;i < lines.length; i++) {
772
+ const current = lines[i];
773
+ depth += (current.match(/\{/g)?.length ?? 0) - (current.match(/\}/g)?.length ?? 0);
774
+ if (depth === 0)
775
+ break;
776
+ }
777
+ continue;
778
+ }
779
+ out.push(line);
780
+ }
781
+ return out.join(`
782
+ `);
783
+ }
784
+ function nextShims(hasReactTypes, rootParams, omitNextModuleShims = false, legacyRequestTypes = false, hasRealNext = false) {
785
+ const reactShims = hasReactTypes ? "" : `
786
+ declare namespace JSX {
787
+ interface Element {}
788
+ interface IntrinsicElements {
789
+ [name: string]: any
790
+ }
791
+ }
792
+
793
+ declare namespace React {
794
+ type ReactNode = any
795
+ type ComponentType<P = any> = (props: P) => ReactNode
796
+ }
797
+
798
+ declare module 'react' {
799
+ export type ReactNode = any
800
+ export type ComponentType<P = any> = (props: P) => ReactNode
801
+ export type AnchorHTMLAttributes<T> = any
802
+ export type DetailedHTMLProps<E, T> = any
803
+ export const Suspense: ComponentType<any>
804
+ export const ViewTransition: ComponentType<any>
805
+ export function addTransitionType(type: string): void
806
+ }
807
+
808
+ declare module 'react/jsx-runtime' {
809
+ export const jsx: any
810
+ export const jsxs: any
811
+ export const Fragment: any
812
+ }
813
+ `;
814
+ const requestType = (type) => legacyRequestTypes ? `Promise<${type}> & ${type}` : `Promise<${type}>`;
815
+ const requestShims = `declare module 'next/headers'{interface CookieSetOptions{name?:string;value?:string;path?:string;maxAge?:number;expires?:Date|number;httpOnly?:boolean;secure?:boolean;sameSite?:'strict'|'lax'|'none'|boolean;domain?:string}interface CookieStore{get(name:string):{name:string;value:string}|undefined;get(options:{name:string;value?:string}):{name:string;value:string}|undefined;getAll(name?:string):{name:string;value:string}[];getAll(options:{name:string;value?:string}):{name:string;value:string}[];has(name:string):boolean;readonly size:number;set(options:CookieSetOptions):CookieStore;set(name:string,value:string,options?:CookieSetOptions):CookieStore;delete(name:string):boolean;clear():CookieStore;[Symbol.iterator]():IterableIterator<readonly[string,{name?:string;value:string}]>}export function cookies():${requestType("CookieStore")};export function headers():${requestType("Headers")};export function draftMode():${requestType(`{isEnabled:boolean;enable():void;disable():void}`)}}
816
+ `;
817
+ const fontShims = hasRealNext ? "" : `declare module 'next/font'{export interface FontModule{className:string;style:{fontFamily:string;fontWeight?:number;fontStyle?:string};variable:string}}
818
+ declare module 'next/font/local'{import type{FontModule}from'next/font';export default function localFont(options:any):FontModule}
819
+ declare module 'next/font/google'{import type{FontModule}from'next/font';type FontLoader=(options?:any)=>FontModule;const font:FontLoader;export default font;export const Inter:FontLoader,Geist:FontLoader,Geist_Mono:FontLoader,Roboto:FontLoader,Roboto_Mono:FontLoader,Open_Sans:FontLoader,Lato:FontLoader,Montserrat:FontLoader,Poppins:FontLoader,Noto_Sans:FontLoader}
820
+ `;
821
+ const source = `${reactShims}
822
+ declare const process: {
823
+ env: Record<string, string | undefined>
824
+ emit?: (...args: any[]) => boolean
825
+ cwd(): string
826
+ platform: string
827
+ arch: string
828
+ version: string
829
+ versions: Record<string, string>
830
+ nextTick(callback: (...args: any[]) => void, ...args: any[]): void
831
+ argv: string[]
832
+ pid: number
833
+ exit(code?: number): never
834
+ [key: string]: any
835
+ }
836
+
837
+ declare const EdgeRuntime: string
838
+
839
+ declare const require: (id: string) => any
840
+
841
+ declare class Buffer extends Uint8Array {}
842
+
843
+ declare module 'async_hooks' {
844
+ export class AsyncLocalStorage<T> {
845
+ run<R>(store: T, callback: () => R): R
846
+ getStore(): T | undefined
847
+ }
848
+ }
849
+
850
+ declare module 'timers/promises' {
851
+ export function setTimeout<T = void>(delay?: number, value?: T, options?: any): Promise<T>
852
+ export function setImmediate<T = void>(value?: T, options?: any): Promise<T>
853
+ export function setInterval<T = void>(delay?: number, value?: T, options?: any): AsyncIterable<T>
854
+ }
855
+
856
+ declare module 'node:timers/promises' {
857
+ export * from 'timers/promises'
858
+ }
859
+
860
+ declare module 'node:crypto' {
861
+ interface KeyObject {
862
+ export(...args: any[]): any
863
+ toString(...args: any[]): string
864
+ }
865
+ export function randomInt(...args: any[]): number
866
+ export function randomBytes(...args: any[]): Buffer
867
+ export function randomFillSync<T extends Uint8Array>(buffer: T, ...args: any[]): T
868
+ export function randomUUID(...args: any[]): string
869
+ export function getRandomValues<T extends Uint8Array>(array: T): T
870
+ export function generateKeyPairSync(...args: any[]): { publicKey: any; privateKey: any }
871
+ export function generateKeySync(...args: any[]): KeyObject
872
+ export function generatePrimeSync(...args: any[]): ArrayBuffer | Uint8Array
873
+ const crypto: {
874
+ randomInt: typeof randomInt
875
+ randomBytes: typeof randomBytes
876
+ randomFillSync: typeof randomFillSync
877
+ randomUUID: typeof randomUUID
878
+ getRandomValues: typeof getRandomValues
879
+ generateKeyPairSync: typeof generateKeyPairSync
880
+ generateKeySync: typeof generateKeySync
881
+ generatePrimeSync: typeof generatePrimeSync
882
+ }
883
+ export default crypto
884
+ }
885
+
886
+ declare module 'crypto' {
887
+ export * from 'node:crypto'
888
+ export { default } from 'node:crypto'
889
+ }
890
+
891
+ // Next.js augments the fetch RequestInit with a "next" field for its extended
892
+ // fetch semantics (revalidate/tags); mirror that here so app code using
893
+ // fetch(url, next revalidate) typechecks.
894
+ interface RequestInit {
895
+ next?: {
896
+ revalidate?: number | false
897
+ tags?: string[]
898
+ }
899
+ }
900
+
901
+ interface ResponseInit {
902
+ request?: {
903
+ headers?: HeadersInit
904
+ }
905
+ }
906
+
907
+ declare module 'node:buffer' {
908
+ export const Buffer: any
909
+ export const constants: any
910
+ export const kMaxLength: number
911
+ export const kStringMaxLength: number
912
+ export const SlowBuffer: any
913
+ }
914
+
915
+ declare module 'url' {
916
+ export interface UrlObject {
917
+ pathname?: string
918
+ query?: Record<string, string | string[]>
919
+ hash?: string
920
+ }
921
+ }
922
+
923
+ declare module 'next/types.js' {
924
+ export interface NextConfig {
925
+ env?: Record<string, string | number | boolean | undefined>
926
+ typedRoutes?: boolean
927
+ typescript?: { tsconfigPath?: string; ignoreBuildErrors?: boolean }
928
+ eslint?: { ignoreDuringBuilds?: boolean; dirs?: string[] }
929
+ [key: string]: any
930
+ }
931
+ export type Metadata = any
932
+ export type Viewport = any
933
+ export type ResolvingMetadata = Promise<Metadata>
934
+ export type ResolvingViewport = Promise<Viewport>
935
+ export type NextApiHandler<T = any> = (...args: any[]) => any
936
+ export type NextApiRequest = any
937
+ export type NextApiResponse<T = any> = any
938
+ export namespace MetadataRoute {
939
+ type Robots = any
940
+ type Sitemap = any[]
941
+ type Manifest = any
942
+ }
943
+ export type Route<T = string> = string
944
+ export type NextPage<P = {}, IP = P> = ((props: P) => any) & { [key: string]: any }
945
+ export type NextComponentType<C = any, IP = any, P = any> = any
946
+ export type PageProps<P = any> = any
947
+ export type LayoutProps<P = any> = any
948
+ }
949
+
950
+ declare module 'next/types' {
951
+ export * from 'next/types.js'
952
+ export { MetadataRoute } from 'next/types.js'
953
+ }
954
+
955
+ declare module 'next' {
956
+ export type {
957
+ NextConfig,
958
+ Metadata,
959
+ Viewport,
960
+ ResolvingMetadata,
961
+ ResolvingViewport,
962
+ NextApiRequest,
963
+ NextApiResponse,
964
+ NextApiHandler,
965
+ Route,
966
+ NextPage,
967
+ NextComponentType,
968
+ PageProps,
969
+ LayoutProps,
970
+ } from 'next/types.js'
971
+ export { MetadataRoute } from 'next/types.js'
972
+ export type GetServerSideProps<P = any, Q = any> = any
973
+ export type GetStaticProps<P = any, Q = any> = any
974
+ export type GetStaticPaths<Q = any> = any
975
+ export type InferGetServerSidePropsType<T = any> = any
976
+ export type InferGetStaticPropsType<T = any> = any
977
+ }
978
+
979
+ declare module 'next/cache' {
980
+ export function revalidatePath(path: string, type?: 'page' | 'layout'): void
981
+ export function revalidateTag(tag: string, profile: string | { expire?: number }): void
982
+ export function updateTag(tag: string): void
983
+ export function unstable_cache(...args: any[]): any
984
+ export function unstable_noStore(): void
985
+ export function unstable_expirePath(path: string, type?: 'page' | 'layout'): void
986
+ export function unstable_expireTag(...tags: string[]): void
987
+ export function expirePath(path: string, type?: 'page' | 'layout'): void
988
+ export function expireTag(...tags: string[]): void
989
+ export function refresh(): void
990
+ export function unstable_refresh(): void
991
+ export const io: any
992
+ export const cacheTag: (...tags: string[]) => void
993
+ export const cacheLife: (...args: any[]) => void
994
+ export const unstable_cacheTag: (...tags: string[]) => void
995
+ export const unstable_cacheLife: (...args: any[]) => void
996
+ }
997
+
998
+ ${requestShims}
999
+
1000
+ declare module 'next/server' {
1001
+ interface NextURL extends URL {
1002
+ clone(): NextURL
1003
+ basePath: string
1004
+ buildId?: string
1005
+ locale: string
1006
+ defaultLocale?: string
1007
+ }
1008
+ interface RequestCookie {
1009
+ name: string
1010
+ value: string
1011
+ }
1012
+ interface RequestCookies {
1013
+ get(name: string): RequestCookie | undefined
1014
+ getAll(name?: string): RequestCookie[]
1015
+ has(name: string): boolean
1016
+ set(name: string, value: string): RequestCookies
1017
+ set(cookie: RequestCookie): RequestCookies
1018
+ delete(name: string | string[]): boolean | boolean[]
1019
+ clear(): RequestCookies
1020
+ readonly size: number
1021
+ [Symbol.iterator](): IterableIterator<[string, RequestCookie]>
1022
+ }
1023
+ interface ResponseCookies {
1024
+ get(name: string): (RequestCookie & Record<string, any>) | undefined
1025
+ getAll(name?: string): (RequestCookie & Record<string, any>)[]
1026
+ has(name: string): boolean
1027
+ set(name: string, value: string, options?: any): ResponseCookies
1028
+ set(options: { name: string; value: string; [key: string]: any }): ResponseCookies
1029
+ delete(name: string, options?: any): ResponseCookies
1030
+ [Symbol.iterator](): IterableIterator<[string, RequestCookie & Record<string, any>]>
1031
+ }
1032
+ export class NextRequest extends Request {
1033
+ nextUrl: NextURL
1034
+ cookies: RequestCookies
1035
+ geo?: any
1036
+ ip?: string
1037
+ }
1038
+ export class NextResponse extends Response {
1039
+ cookies: ResponseCookies
1040
+ static json(body: any, init?: ResponseInit): NextResponse
1041
+ static next(init?: ResponseInit): NextResponse
1042
+ static redirect(url: string | URL, init?: number | ResponseInit): NextResponse
1043
+ static rewrite(url: string | URL, init?: ResponseInit): NextResponse
1044
+ }
1045
+ export type NextFetchEvent = any
1046
+ export type NextMiddleware = (...args: any[]) => any
1047
+ export type NextMiddlewareResult = any
1048
+ export interface ProxyConfig {
1049
+ matcher?: string | { source: string } | Array<string | { source: string }>
1050
+ }
1051
+ export class ImageResponse extends Response {
1052
+ constructor(element: any, options?: any)
1053
+ }
1054
+ export const URLPattern: any
1055
+ export function userAgent(request: { headers: Headers }): any
1056
+ export function userAgentFromString(ua: string | undefined): any
1057
+ export function after(task: any): void
1058
+ export function connection(): Promise<void>
1059
+ export const io: any
1060
+ }
1061
+
1062
+ declare module 'next/server.js' {
1063
+ export * from 'next/server'
1064
+ }
1065
+
1066
+ declare module 'next/navigation.js' {
1067
+ export * from 'next/navigation'
1068
+ }
1069
+
1070
+ declare module 'next/headers.js' {
1071
+ export * from 'next/headers'
1072
+ }
1073
+
1074
+ declare module 'next/cache.js' {
1075
+ export * from 'next/cache'
1076
+ }
1077
+
1078
+ declare module 'next/link.js' {
1079
+ export * from 'next/link'
1080
+ export { default } from 'next/link'
1081
+ }
1082
+
1083
+ declare module 'next/image.js' {
1084
+ export * from 'next/image'
1085
+ export { default } from 'next/image'
1086
+ }
1087
+
1088
+ declare module 'next/script.js' {
1089
+ export * from 'next/script'
1090
+ export { default } from 'next/script'
1091
+ }
1092
+
1093
+ declare module 'next/dist/client/link.js' {
1094
+ export interface LinkProps {
1095
+ href: any
1096
+ }
1097
+ export function useLinkStatus(): any
1098
+ }
1099
+
1100
+ declare module 'next/link' {
1101
+ import type { AnchorHTMLAttributes, ComponentType } from 'react'
1102
+ // Mirror Next's public LinkProps: standard anchor attributes plus Link's own
1103
+ // props, but NO catch-all index signature. A wildcard string index signature
1104
+ // would silently accept non-public props (e.g. unstable_dynamicOnHover),
1105
+ // making a fixture's ts-expect-error on such a prop report as unused.
1106
+ export interface LinkProps
1107
+ extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
1108
+ href: any
1109
+ // Next 16's public prefetch type. The unstable_forceStale value is
1110
+ // runtime-only and Next deliberately keeps it OUT of the public union, so an
1111
+ // exhaustive switch over prefetch ending in "prefetch satisfies never"
1112
+ // stays valid. Including it here would leave that value in the default
1113
+ // branch and break such fixtures under our shim.
1114
+ prefetch?: boolean | 'auto' | null
1115
+ scroll?: boolean
1116
+ replace?: boolean
1117
+ as?: any
1118
+ shallow?: boolean
1119
+ passHref?: boolean
1120
+ locale?: string | false
1121
+ legacyBehavior?: boolean
1122
+ onNavigate?: (event: { preventDefault(): void }) => void
1123
+ transitionTypes?: string[]
1124
+ children?: any
1125
+ }
1126
+ const Link: ComponentType<LinkProps>
1127
+ export default Link
1128
+ export function useLinkStatus(): { pending: boolean }
1129
+ }
1130
+
1131
+ declare module 'next/image' {
1132
+ import type { ComponentType } from 'react'
1133
+ export interface ImageProps {
1134
+ src: any
1135
+ alt: string
1136
+ width?: number | string
1137
+ height?: number | string
1138
+ fill?: boolean
1139
+ priority?: boolean
1140
+ loading?: 'lazy' | 'eager'
1141
+ placeholder?: string
1142
+ blurDataURL?: string
1143
+ unoptimized?: boolean
1144
+ sizes?: string
1145
+ quality?: number | string
1146
+ className?: string
1147
+ [key: string]: any
1148
+ }
1149
+ export interface StaticImageData {
1150
+ src: string
1151
+ height: number
1152
+ width: number
1153
+ blurDataURL?: string
1154
+ blurWidth?: number
1155
+ blurHeight?: number
1156
+ }
1157
+ const Image: ComponentType<ImageProps>
1158
+ export default Image
1159
+ export function getImageProps(props: ImageProps): { props: any }
1160
+ export function unstable_getImgProps(props: ImageProps): { props: any }
1161
+ }
1162
+
1163
+ declare module '@vercel/og' {
1164
+ export class ImageResponse extends Response {
1165
+ constructor(element: any, options?: any)
1166
+ }
1167
+ export type ImageResponseOptions = any
1168
+ }
1169
+
1170
+ declare module 'next/og' {
1171
+ export class ImageResponse extends Response {
1172
+ constructor(element: any, options?: any)
1173
+ static json(...args: any[]): ImageResponse
1174
+ }
1175
+ export interface ImageResponseOptions {
1176
+ width?: number
1177
+ height?: number
1178
+ fonts?: any[]
1179
+ debug?: boolean
1180
+ status?: number
1181
+ statusText?: string
1182
+ headers?: HeadersInit
1183
+ emoji?: string
1184
+ [key: string]: any
1185
+ }
1186
+ }
1187
+
1188
+ declare module 'next/dynamic' {
1189
+ import type { ComponentType } from 'react'
1190
+ export interface DynamicOptions {
1191
+ loading?: ComponentType<any>
1192
+ ssr?: boolean
1193
+ loadableGenerated?: any
1194
+ suspense?: boolean
1195
+ [key: string]: any
1196
+ }
1197
+ // Infer P from the loader like real next/dynamic's Loader<P>; a bare
1198
+ // Promise<any> loader would collapse P to any and strip prop types.
1199
+ type LoaderComponent<P> = ComponentType<P> | { default: ComponentType<P> }
1200
+ export default function dynamic<P = {}>(
1201
+ loader: (() => Promise<LoaderComponent<P>>) | Promise<LoaderComponent<P>>,
1202
+ options?: DynamicOptions,
1203
+ ): ComponentType<P>
1204
+ }
1205
+
1206
+ declare module 'next/error' {
1207
+ import type { ComponentType, ReactNode } from 'react'
1208
+ export interface ErrorInfo {
1209
+ error: Error
1210
+ reset: () => void
1211
+ unstable_retry: () => void
1212
+ [key: string]: any
1213
+ }
1214
+ export interface ErrorProps {
1215
+ statusCode: number
1216
+ title?: string
1217
+ withDarkMode?: boolean
1218
+ [key: string]: any
1219
+ }
1220
+ const ErrorComponent: ComponentType<ErrorProps>
1221
+ export default ErrorComponent
1222
+ // Wraps a fallback renderer (props, info) => JSX in an error boundary. The
1223
+ // returned component takes the fallback's own props plus children (the
1224
+ // guarded subtree) and an optional clearError reset callback. Mirrors the
1225
+ // runtime in src/compat/next/error.tsx.
1226
+ export function unstable_catchError<P extends Record<string, any> = any>(
1227
+ fallback: (props: P, info: ErrorInfo) => ReactNode,
1228
+ ): ComponentType<P & { children?: ReactNode; clearError?: () => void }>
1229
+ }
1230
+
1231
+ ${fontShims}
1232
+
1233
+ declare module 'next/script' {
1234
+ import type { ComponentType } from 'react'
1235
+ export interface ScriptProps {
1236
+ src?: string
1237
+ strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive' | 'worker'
1238
+ onLoad?: (...args: any[]) => void
1239
+ onReady?: (...args: any[]) => void
1240
+ onError?: (...args: any[]) => void
1241
+ id?: string
1242
+ children?: any
1243
+ [key: string]: any
1244
+ }
1245
+ const Script: ComponentType<ScriptProps>
1246
+ export default Script
1247
+ }
1248
+
1249
+ declare module 'next/legacy/image' {
1250
+ import type { ComponentType } from 'react'
1251
+ export interface ImageProps {
1252
+ src: any
1253
+ alt?: string
1254
+ width?: number | string
1255
+ height?: number | string
1256
+ layout?: 'fixed' | 'intrinsic' | 'responsive' | 'fill'
1257
+ objectFit?: string
1258
+ objectPosition?: string
1259
+ priority?: boolean
1260
+ loading?: 'lazy' | 'eager'
1261
+ placeholder?: string
1262
+ blurDataURL?: string
1263
+ unoptimized?: boolean
1264
+ sizes?: string
1265
+ quality?: number | string
1266
+ [key: string]: any
1267
+ }
1268
+ const Image: ComponentType<ImageProps>
1269
+ export default Image
1270
+ }
1271
+
1272
+ ${rootParamsModule(rootParams)}
1273
+
1274
+ declare module 'next/web-vitals' {
1275
+ export interface NextWebVitalsMetric {
1276
+ id: string
1277
+ name: string
1278
+ startTime: number
1279
+ value: number
1280
+ label: 'web-vital' | 'custom'
1281
+ [key: string]: any
1282
+ }
1283
+ export function useReportWebVitals(reportFn: (metric: NextWebVitalsMetric) => void): void
1284
+ }
1285
+
1286
+ declare module 'next/dist/client/components/app-router-headers' {
1287
+ export const NEXT_RSC_UNION_QUERY: string
1288
+ export const RSC_HEADER: string
1289
+ export const NEXT_ROUTER_STATE_TREE_HEADER: string
1290
+ export const NEXT_ROUTER_PREFETCH_HEADER: string
1291
+ export const NEXT_URL: string
1292
+ const headers: Record<string, string>
1293
+ export default headers
1294
+ }
1295
+
1296
+ declare module 'next/dist/server/app-render/work-unit-async-storage.external' {
1297
+ export const workUnitAsyncStorage: {
1298
+ getStore(): any
1299
+ run<R>(store: any, callback: () => R): R
1300
+ }
1301
+ }
1302
+
1303
+ declare module 'next/dist/server/web/spec-extension/adapters/headers' {
1304
+ export class ReadonlyHeaders extends Headers {}
1305
+ }
1306
+
1307
+ declare module 'next/dist/server/web/spec-extension/adapters/request-cookies' {
1308
+ export interface ReadonlyRequestCookies {
1309
+ get(name: string): { name: string; value: string } | undefined
1310
+ getAll(name?: string): { name: string; value: string }[]
1311
+ has(name: string): boolean
1312
+ readonly size: number
1313
+ [Symbol.iterator](): IterableIterator<[string, { name: string; value: string }]>
1314
+ }
1315
+ }
1316
+
1317
+ declare module 'node-fetch' {
1318
+ export class Headers {
1319
+ get(name: string): string | null
1320
+ has(name: string): boolean
1321
+ set(name: string, value: string): void
1322
+ append(name: string, value: string): void
1323
+ delete(name: string): void
1324
+ forEach(callback: (value: string, name: string) => void): void
1325
+ [Symbol.iterator](): IterableIterator<[string, string]>
1326
+ }
1327
+ const fetch: (...args: any[]) => Promise<any>
1328
+ export default fetch
1329
+ }
1330
+
1331
+ declare module 'next/router' {
1332
+ export interface NextRouter {
1333
+ route: string
1334
+ pathname: string
1335
+ asPath: string
1336
+ query: Record<string, string | string[] | undefined>
1337
+ push(url: any, as?: any, options?: any): Promise<boolean>
1338
+ replace(url: any, as?: any, options?: any): Promise<boolean>
1339
+ prefetch(url: string): Promise<void>
1340
+ back(): void
1341
+ reload(): void
1342
+ beforePopState(callback: (...args: any[]) => boolean): void
1343
+ events: {
1344
+ on(type: string, handler: (...args: any[]) => void): void
1345
+ off(type: string, handler: (...args: any[]) => void): void
1346
+ emit(type: string, ...args: any[]): void
1347
+ }
1348
+ }
1349
+ export function useRouter(): NextRouter
1350
+ const router: NextRouter
1351
+ export default router
1352
+ }
1353
+
1354
+ declare module 'next/app' {
1355
+ // Pages-router shim: pnext builds the app directory only, but fixtures and
1356
+ // hybrid apps may carry a pages/ tree whose _app imports next/app. The type
1357
+ // program includes pages/**, so this keeps the typecheck from failing a
1358
+ // build over files pnext never bundles.
1359
+ export interface AppProps<P = any> {
1360
+ Component: (props: P) => any
1361
+ pageProps: P
1362
+ router?: any
1363
+ [key: string]: any
1364
+ }
1365
+ export type AppType = (props: AppProps) => any
1366
+ const App: AppType
1367
+ export default App
1368
+ }
1369
+
1370
+ declare module 'next/dist/client/components/navigation.js' {
1371
+ export interface NavigateOptions {
1372
+ scroll?: boolean
1373
+ }
1374
+ export interface PrefetchOptions {
1375
+ kind?: 'auto' | 'full'
1376
+ onInvalidate?: () => void
1377
+ }
1378
+ export interface AppRouterInstance {
1379
+ push(href: string, options?: NavigateOptions): void
1380
+ replace(href: string, options?: NavigateOptions): void
1381
+ prefetch(href: string, options?: PrefetchOptions): void
1382
+ refresh(): void
1383
+ back(): void
1384
+ forward(): void
1385
+ bfcacheId: string
1386
+ }
1387
+ export function useRouter(): AppRouterInstance
1388
+ export function notFound(): never
1389
+ }
1390
+
1391
+ declare module 'next/navigation' {
1392
+ export interface NavigateOptions {
1393
+ scroll?: boolean
1394
+ }
1395
+ export interface PrefetchOptions {
1396
+ kind?: 'auto' | 'full'
1397
+ onInvalidate?: () => void
1398
+ }
1399
+ export interface AppRouterInstance {
1400
+ push(href: string, options?: NavigateOptions): void
1401
+ replace(href: string, options?: NavigateOptions): void
1402
+ prefetch(href: string, options?: PrefetchOptions): void
1403
+ refresh(): void
1404
+ back(): void
1405
+ forward(): void
1406
+ bfcacheId: string
1407
+ }
1408
+ export function useRouter(): AppRouterInstance
1409
+ export function usePathname(): string
1410
+ export class ReadonlyURLSearchParams extends URLSearchParams {
1411
+ append(): never
1412
+ delete(): never
1413
+ set(): never
1414
+ sort(): never
1415
+ }
1416
+ export function useSearchParams(): ReadonlyURLSearchParams
1417
+ export function useParams<T = Record<string, string | string[]>>(): T
1418
+ export function useSelectedLayoutSegment(parallelRoutesKey?: string): string | null
1419
+ export function useSelectedLayoutSegments(parallelRoutesKey?: string): string[]
1420
+ export function useLayoutSegments(parallelRoutesKey?: string): string[]
1421
+ export function useLinkStatus(): { pending: boolean }
1422
+ export function unstable_isUnrecognizedActionError(error: unknown): boolean
1423
+ export const RedirectType: { push: 'push'; replace: 'replace' }
1424
+ export type RedirectType = 'push' | 'replace'
1425
+ export function notFound(): never
1426
+ export function forbidden(): never
1427
+ export function unauthorized(): never
1428
+ export function redirect(url: string, type?: RedirectType): never
1429
+ export function permanentRedirect(url: string, type?: RedirectType): never
1430
+ export function unstable_rethrow(error: unknown): void
1431
+ export function useServerInsertedHTML(callback: () => any): void
1432
+ }
1433
+
1434
+ declare module 'next/dist/shared/lib/app-router-context.shared-runtime.js' {
1435
+ export interface NavigateOptions {
1436
+ scroll?: boolean
1437
+ }
1438
+ export interface PrefetchOptions {
1439
+ kind?: 'auto' | 'full'
1440
+ onInvalidate?: () => void
1441
+ }
1442
+ export interface AppRouterInstance {
1443
+ push(href: string, options?: NavigateOptions): void
1444
+ replace(href: string, options?: NavigateOptions): void
1445
+ prefetch(href: string, options?: PrefetchOptions): void
1446
+ refresh(): void
1447
+ back(): void
1448
+ forward(): void
1449
+ bfcacheId: string
1450
+ }
1451
+ }
1452
+
1453
+ declare module 'next/dist/client/components/redirect-error.js' {
1454
+ export type RedirectType = 'replace' | 'push'
1455
+ }
1456
+
1457
+ declare module 'next/dist/client/form.js' {
1458
+ export interface FormProps {
1459
+ action: any
1460
+ }
1461
+ }
1462
+
1463
+ declare module 'next/form' {
1464
+ export interface FormProps {
1465
+ action: string | ((formData: FormData) => void | Promise<void>)
1466
+ replace?: boolean
1467
+ scroll?: boolean
1468
+ prefetch?: boolean
1469
+ [key: string]: any
1470
+ }
1471
+ export default function Form(props: FormProps): any
1472
+ }
1473
+
1474
+ declare module '*.module.css' {
1475
+ const classes: Record<string, string>
1476
+ export default classes
1477
+ }
1478
+
1479
+ declare module '*.module.scss' {
1480
+ const classes: Record<string, string>
1481
+ export default classes
1482
+ }
1483
+
1484
+ declare module '*.module.sass' {
1485
+ const classes: Record<string, string>
1486
+ export default classes
1487
+ }
1488
+
1489
+ declare module '*.css' {
1490
+ const href: string | undefined
1491
+ export default href
1492
+ }
1493
+
1494
+ declare module '*.scss' {
1495
+ const href: string | undefined
1496
+ export default href
1497
+ }
1498
+
1499
+ declare module '*.sass' {
1500
+ const href: string | undefined
1501
+ export default href
1502
+ }
1503
+
1504
+ declare module '*.png' {
1505
+ const content: { src: string; height: number; width: number; blurDataURL?: string }
1506
+ export default content
1507
+ }
1508
+
1509
+ declare module '*.jpg' {
1510
+ const content: { src: string; height: number; width: number; blurDataURL?: string }
1511
+ export default content
1512
+ }
1513
+
1514
+ declare module '*.jpeg' {
1515
+ const content: { src: string; height: number; width: number; blurDataURL?: string }
1516
+ export default content
1517
+ }
1518
+
1519
+ declare module '*.gif' {
1520
+ const content: { src: string; height: number; width: number; blurDataURL?: string }
1521
+ export default content
1522
+ }
1523
+
1524
+ declare module '*.svg' {
1525
+ // \`any\` (not the static-image descriptor shape used above) to avoid
1526
+ // conflicts with \`@svgr/webpack\`-style loader rules that import an SVG as
1527
+ // a component, matching Next's own image-types/global.d.ts.
1528
+ const content: any
1529
+ export default content
1530
+ }
1531
+
1532
+ declare module '*.webp' {
1533
+ const content: { src: string; height: number; width: number; blurDataURL?: string }
1534
+ export default content
1535
+ }
1536
+
1537
+ declare module '*.wasm' {
1538
+ const content: any
1539
+ export default content
1540
+ }
1541
+
1542
+ declare module '*.mdx' {
1543
+ const MDXComponent: (props: any) => any
1544
+ export default MDXComponent
1545
+ }
1546
+
1547
+ declare module '*.md' {
1548
+ const MDXComponent: (props: any) => any
1549
+ export default MDXComponent
1550
+ }
1551
+ ${loaderRuleAssetDeclarations()}`;
1552
+ return omitNextModuleShims ? stripNextModuleDeclarations(source) : source;
1553
+ }
1554
+ var STANDARD_ASSET_DECLARATIONS = new Set([
1555
+ ".css",
1556
+ ".scss",
1557
+ ".sass",
1558
+ ".png",
1559
+ ".jpg",
1560
+ ".jpeg",
1561
+ ".gif",
1562
+ ".svg",
1563
+ ".webp",
1564
+ ".wasm",
1565
+ ".mdx",
1566
+ ".md"
1567
+ ]);
1568
+ var TS_RESOLVED_EXTENSIONS = new Set([
1569
+ ".ts",
1570
+ ".tsx",
1571
+ ".mts",
1572
+ ".cts",
1573
+ ".d.ts",
1574
+ ".js",
1575
+ ".jsx",
1576
+ ".mjs",
1577
+ ".cjs",
1578
+ ".json"
1579
+ ]);
1580
+ function loaderRuleAssetDeclarations() {
1581
+ const specs = new Set;
1582
+ for (const rule of turbopackLoaderRules()) {
1583
+ if (!rule.glob.startsWith("*"))
1584
+ continue;
1585
+ const ext = rule.glob.slice(1).toLowerCase();
1586
+ if (STANDARD_ASSET_DECLARATIONS.has(ext) || TS_RESOLVED_EXTENSIONS.has(ext))
1587
+ continue;
1588
+ specs.add(rule.glob);
1589
+ }
1590
+ if (specs.size === 0)
1591
+ return "";
1592
+ return `${[...specs].map((spec) => `
1593
+ declare module '${spec}' {
1594
+ const content: any
1595
+ export default content
1596
+ }`).join("")}
1597
+ `;
1598
+ }
1599
+
1600
+ // src/compat/register/typed-routes.ts
1601
+ function registerTypedRoutesExtensions(_config) {
1602
+ registerBuildSteps(runTypedRoutesBuildStep);
1603
+ }
1604
+ async function runTypedRoutesBuildStep(ctx) {
1605
+ if (!nextCompatEnabled(ctx.config))
1606
+ return;
1607
+ if (!legacyRequestAPIs())
1608
+ await writeTsconfigDefaults(ctx.config);
1609
+ await generateTypedRoutes(ctx.config, ctx.routes);
1610
+ if (typecheckDisabled())
1611
+ return;
1612
+ const startedAt = performance.now();
1613
+ registerBuildParallelPhases({
1614
+ name: "Typecheck",
1615
+ run: validateTypesOffThread(ctx.config).then(() => performance.now() - startedAt)
1616
+ });
1617
+ }
1618
+ // src/compat/register/validation.ts
1619
+ var registered = false;
1620
+ onExtensionHostReset(() => registered = false);
1621
+ function registerValidationExtensions(config) {
1622
+ if (registered)
1623
+ return;
1624
+ if (!nextCompatEnabled(config))
1625
+ return;
1626
+ registered = true;
1627
+ const step = async (ctx) => {
1628
+ if (!nextCompatEnabled(ctx.config))
1629
+ return;
1630
+ await ctx.log.step("validate build", () => Promise.resolve(validateBuild(ctx.config, ctx.routes)));
1631
+ };
1632
+ step.gate = true;
1633
+ registerBuildSteps(step);
1634
+ setBuildCompatExtensions({
1635
+ diagnoseCacheComponentsPrerender,
1636
+ diagnosticLeadsWithErrorLine,
1637
+ prerenderFailureFooter,
1638
+ recordBuildFlags: writeBuildFlags
1639
+ });
1640
+ }
1641
+ // src/compat/register/middleware.ts
1642
+ import path4 from "path";
1643
+ import { mkdir as mkdir4, writeFile as writeFile4 } from "fs/promises";
1644
+ import { fileURLToPath } from "url";
1645
+ function registerMiddlewareExtensions() {
1646
+ registerBuildSteps(async ({ config, routes }) => {
1647
+ if (!nextCompatEnabled(config))
1648
+ return;
1649
+ const file = findProxyFile(config);
1650
+ let relative;
1651
+ if (file) {
1652
+ const href = await devServerModuleHref(config, file, "prod", {
1653
+ conditionTarget: "edge",
1654
+ externalLoadTarget: proxyExternalLoadTarget(file),
1655
+ reactServerLayer: true
1656
+ });
1657
+ relative = toPosixPath(path4.relative(config.outPath, fileURLToPath(href)));
1658
+ }
1659
+ await writeMiddlewareManifests(config, relative, routes);
1660
+ });
1661
+ }
1662
+ async function writeMiddlewareManifests(config, entryFile, routes = []) {
1663
+ const source = findProxyFile(config);
1664
+ const functions = edgeFunctionEntries(config, routes);
1665
+ if (!source || !entryFile) {
1666
+ if (Object.keys(functions).length === 0)
1667
+ return;
1668
+ const serverDir2 = path4.join(config.outPath, "server");
1669
+ await mkdir4(serverDir2, { recursive: true });
1670
+ await writeFile4(path4.join(serverDir2, "middleware-manifest.json"), `${JSON.stringify({ ...emptyMiddlewareManifest(), functions }, null, 2)}
1671
+ `);
1672
+ return;
1673
+ }
1674
+ const moduleFile = path4.resolve(config.outPath, entryFile);
1675
+ const module = await import(pathToFileHref(moduleFile));
1676
+ const matchers = manifestMatchers(module.config);
1677
+ const runtime = proxyRuntime(module.config);
1678
+ const entrypoint = toServerEntrypoint(entryFile);
1679
+ const serverDir = path4.join(config.outPath, "server");
1680
+ await mkdir4(serverDir, { recursive: true });
1681
+ if (runtime === "nodejs") {
1682
+ const functionsConfig = {
1683
+ version: 1,
1684
+ functions: { "/_middleware": { runtime: "nodejs", matchers } }
1685
+ };
1686
+ await writeFile4(path4.join(serverDir, "functions-config-manifest.json"), `${JSON.stringify(functionsConfig, null, 2)}
1687
+ `);
1688
+ await writeFile4(path4.join(serverDir, "middleware-manifest.json"), `${JSON.stringify({ ...emptyMiddlewareManifest(), functions }, null, 2)}
1689
+ `);
1690
+ return;
1691
+ }
1692
+ const entry = {
1693
+ name: "middleware",
1694
+ page: "/",
1695
+ matchers,
1696
+ wasm: readMiddlewareWasmBindingsForOutPath(config.outPath),
1697
+ assets: [],
1698
+ files: [entrypoint],
1699
+ entrypoint,
1700
+ env: {}
1701
+ };
1702
+ const manifest = {
1703
+ version: 3,
1704
+ sortedMiddleware: ["/"],
1705
+ middleware: { "/": entry },
1706
+ functions
1707
+ };
1708
+ await writeFile4(path4.join(serverDir, "middleware-manifest.json"), `${JSON.stringify(manifest, null, 2)}
1709
+ `);
1710
+ }
1711
+ function emptyMiddlewareManifest() {
1712
+ return { version: 3, sortedMiddleware: [], middleware: {}, functions: {} };
1713
+ }
1714
+ function edgeFunctionEntries(config, routes) {
1715
+ const entries = {};
1716
+ if (!config.appPath)
1717
+ return entries;
1718
+ for (const route of routes) {
1719
+ const runtime = route.segmentConfig?.runtime;
1720
+ if (runtime !== "edge" && runtime !== "experimental-edge")
1721
+ continue;
1722
+ const page = appManifestKey(config.appPath, route.file);
1723
+ if (!page)
1724
+ continue;
1725
+ const regions = preferredRegionForRoute(route);
1726
+ entries[page] = {
1727
+ files: [],
1728
+ name: `app${page}`,
1729
+ page,
1730
+ matchers: [{ regexp: `^${routeMatcherRegexp(route.route)}$`, originalSource: route.route }],
1731
+ wasm: [],
1732
+ assets: [],
1733
+ env: {},
1734
+ ...regions ? { regions } : {}
1735
+ };
1736
+ }
1737
+ return entries;
1738
+ }
1739
+ function appManifestKey(appPath, file) {
1740
+ const relative = toPosixPath(path4.relative(appPath, file));
1741
+ if (!relative || relative.startsWith(".."))
1742
+ return;
1743
+ return `/${relative.replace(/\.[^./]+$/, "")}`;
1744
+ }
1745
+ function routeMatcherRegexp(route) {
1746
+ return route.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/:([^/\\]+)/g, "[^/]+");
1747
+ }
1748
+ function manifestMatchers(config) {
1749
+ const matcher = config?.matcher;
1750
+ if (!matcher)
1751
+ return [{ regexp: "^/.*$", originalSource: "/:path*" }];
1752
+ const list = Array.isArray(matcher) ? matcher : [matcher];
1753
+ return list.map((item) => {
1754
+ const originalSource = typeof item === "string" ? item : item.source;
1755
+ return { regexp: `^${matcherRegexp(originalSource)}$`, originalSource };
1756
+ });
1757
+ }
1758
+ function matcherRegexp(matcher) {
1759
+ if (matcher.includes("("))
1760
+ return matcher;
1761
+ if (matcher === "/")
1762
+ return "/";
1763
+ let source = "";
1764
+ for (const segment of matcher.split("/").filter(Boolean)) {
1765
+ if (/^:[^/]+\*$/.test(segment))
1766
+ source += "(?:/.*)?";
1767
+ else if (/^:[^/]+$/.test(segment))
1768
+ source += "/[^/]+";
1769
+ else
1770
+ source += `/${segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`;
1771
+ }
1772
+ return source || "/";
1773
+ }
1774
+ function proxyRuntime(config) {
1775
+ const runtime = config?.runtime;
1776
+ return runtime === "nodejs" ? "nodejs" : "edge";
1777
+ }
1778
+ function toServerEntrypoint(entryFile) {
1779
+ const posix = toPosixPath(entryFile).replace(/^\.?\//, "");
1780
+ const withinServer = posix.startsWith("server/") ? posix : `server/${path4.posix.basename(posix)}`;
1781
+ return withinServer.replace(/\.[^./]+$/, ".js");
1782
+ }
1783
+ // src/compat/metadata-artifacts.ts
1784
+ import { createRequire as createRequire2 } from "module";
1785
+ import { access, mkdir as mkdir5, readdir, readFile as readFile2, writeFile as writeFile5 } from "fs/promises";
1786
+ import path5 from "path";
1787
+ var foundGeistFontPath;
1788
+ async function emitMetadataRouteArtifacts(ctx) {
1789
+ if (!nextCompatEnabled(ctx.config))
1790
+ return;
1791
+ const routes = ctx.manifest.routes.filter((route) => route.kind === "handler" && route.metadataRoute !== undefined);
1792
+ if (routes.length === 0)
1793
+ return;
1794
+ const outPath = ctx.config.outPath;
1795
+ const outputRoots = Array.from(new Set([
1796
+ outPath,
1797
+ path5.join(ctx.config.root, ".next"),
1798
+ path5.join(path5.dirname(outPath), ".next"),
1799
+ path5.resolve(process.cwd(), ".next")
1800
+ ]));
1801
+ const staticFiles = ctx.manifest.staticFiles ?? {};
1802
+ const routeFilesById = staticFilesByRouteId(staticFiles);
1803
+ const appDir = path5.join(ctx.config.root, ctx.config.appDir);
1804
+ const emittedRouteDirs = new Set;
1805
+ for (const route of routes) {
1806
+ const nextPath = toAppPath(route, appDir);
1807
+ const routeDir = removeLeadingSlash(nextPath);
1808
+ emittedRouteDirs.add(routeDir);
1809
+ const fontPaths = route.metadataRoute?.kind === "opengraph-image" ? await resolveGeistFontFiles() : [];
1810
+ for (const root of outputRoots) {
1811
+ const routeModuleDir = path5.join(root, "server", "app", routeDir);
1812
+ await mkdir5(routeModuleDir, { recursive: true });
1813
+ await writeFile5(path5.join(routeModuleDir, "route.js"), routeJsModule(route), "utf8");
1814
+ await writeFile5(path5.join(routeModuleDir, "route_client-reference-manifest.js"), `self.__RSC_MANIFEST={}
1815
+ `, "utf8");
1816
+ await writeFile5(path5.join(routeModuleDir, "route.js.nft.json"), `${JSON.stringify({ version: 1, files: ["route_client-reference-manifest.js", ...fontPaths] }, null, 2)}
1817
+ `, "utf8");
1818
+ if (isForceDynamicRoute(route))
1819
+ continue;
1820
+ const outputs = routeFilesById.get(route.id) ?? [];
1821
+ for (const relative of outputs) {
1822
+ await writeStaticMetadataArtifacts(outPath, root, relative, staticFiles[relative]);
1823
+ }
1824
+ }
1825
+ }
1826
+ await emitStaticMetadataRouteTraces(outputRoots, appDir, emittedRouteDirs);
1827
+ await writeAppPathsManifest(outputRoots, routes, appDir);
1828
+ await mergeMiddlewareFunctionsManifest(outputRoots, routes, appDir, ctx.manifest.routes);
1829
+ await writePrerenderManifests(outputRoots, ctx.manifest);
1830
+ }
1831
+ var prerenderAllowHeader = [
1832
+ "host",
1833
+ "x-matched-path",
1834
+ "x-prerender-revalidate",
1835
+ "x-prerender-revalidate-if-generated",
1836
+ "x-next-revalidated-tags",
1837
+ "x-next-revalidate-tag-token"
1838
+ ];
1839
+ var prerenderBypass = [
1840
+ { key: "next-action", type: "header" },
1841
+ { key: "content-type", type: "header", value: "multipart/form-data;.*" }
1842
+ ];
1843
+ async function writePrerenderManifests(outputRoots, manifest) {
1844
+ const byId = new Map(manifest.routes.map((route) => [route.id, route]));
1845
+ const entries = {};
1846
+ for (const [relative, metadata] of Object.entries(manifest.staticFiles ?? {})) {
1847
+ const route = metadata.routeId ? byId.get(metadata.routeId) : undefined;
1848
+ if (route && isEdgeRoute(route))
1849
+ continue;
1850
+ const pathname = staticFilePathname(relative);
1851
+ entries[pathname] = prerenderEntry(pathname, metadata, route);
1852
+ }
1853
+ for (const route of manifest.routes) {
1854
+ for (const generated of route.metadataRoute?.generatedRoutes ?? []) {
1855
+ if (entries[generated] || isEdgeRoute(route) || route.usesRequest)
1856
+ continue;
1857
+ entries[generated] = prerenderEntry(generated, undefined, route);
1858
+ }
1859
+ if (entries[route.route] || !isStaticPrerenderRoute(route))
1860
+ continue;
1861
+ entries[route.route] = prerenderEntry(route.route, undefined, route);
1862
+ }
1863
+ for (const root of outputRoots) {
1864
+ const file = path5.join(root, "prerender-manifest.json");
1865
+ const existing = await readJsonManifest(file);
1866
+ await mkdir5(path5.dirname(file), { recursive: true });
1867
+ await writeFile5(file, `${JSON.stringify({
1868
+ version: 4,
1869
+ routes: { ...existing?.routes ?? {}, ...entries },
1870
+ dynamicRoutes: existing?.dynamicRoutes ?? {},
1871
+ notFoundRoutes: existing?.notFoundRoutes ?? [],
1872
+ preview: existing?.preview ?? {
1873
+ previewModeId: "pnext-preview-id",
1874
+ previewModeSigningKey: "pnext-preview-signing-key",
1875
+ previewModeEncryptionKey: "pnext-preview-encryption-key"
1876
+ }
1877
+ }, null, 2)}
1878
+ `);
1879
+ }
1880
+ }
1881
+ function staticFilePathname(relative) {
1882
+ if (relative === "index.html")
1883
+ return "/";
1884
+ if (relative.endsWith("/index.html"))
1885
+ return `/${relative.slice(0, -"/index.html".length)}`;
1886
+ if (relative.endsWith(".html"))
1887
+ return `/${relative.slice(0, -".html".length)}`;
1888
+ return `/${relative}`;
1889
+ }
1890
+ function isStaticPrerenderRoute(route) {
1891
+ if (route.mode !== "static" || route.usesRequest || isEdgeRoute(route))
1892
+ return false;
1893
+ if (route.kind === "page")
1894
+ return route.params.length === 0 && !route.catchAll;
1895
+ return route.kind === "handler" && route.metadataRoute !== undefined && route.params.length === 0;
1896
+ }
1897
+ function isEdgeRoute(route) {
1898
+ return route.segmentConfig?.runtime === "edge" || route.segmentConfig?.runtime === "experimental-edge";
1899
+ }
1900
+ function prerenderEntry(pathname, metadata, route) {
1901
+ return {
1902
+ initialRevalidateSeconds: metadata?.revalidateSeconds ?? false,
1903
+ srcRoute: route?.route ?? pathname,
1904
+ dataRoute: pathname === "/" ? "/index.rsc" : `${pathname}.rsc`,
1905
+ allowHeader: prerenderAllowHeader,
1906
+ experimentalBypassFor: prerenderBypass
1907
+ };
1908
+ }
1909
+ function staticFilesByRouteId(staticFiles) {
1910
+ const routeFilesById = new Map;
1911
+ for (const [relative, metadata] of Object.entries(staticFiles)) {
1912
+ if (!metadata.routeId)
1913
+ continue;
1914
+ const existing = routeFilesById.get(metadata.routeId) ?? [];
1915
+ existing.push(relative);
1916
+ routeFilesById.set(metadata.routeId, existing);
1917
+ }
1918
+ return routeFilesById;
1919
+ }
1920
+ async function emitStaticMetadataRouteTraces(outputRoots, appDir, emittedRouteDirs) {
1921
+ for (const file of discoverStaticMetadataFiles(appDir)) {
1922
+ const routeDir = file.outputPath;
1923
+ if (emittedRouteDirs.has(routeDir))
1924
+ continue;
1925
+ for (const root of outputRoots) {
1926
+ const dir = path5.join(root, "server", "app", routeDir);
1927
+ await mkdir5(dir, { recursive: true });
1928
+ await writeFile5(path5.join(dir, "route.js"), `export default {}
1929
+ `, "utf8");
1930
+ await writeFile5(path5.join(dir, "route.js.nft.json"), `${JSON.stringify({ version: 1, files: [] }, null, 2)}
1931
+ `, "utf8");
1932
+ }
1933
+ }
1934
+ }
1935
+ async function writeAppPathsManifest(outputRoots, routes, appDir) {
1936
+ const nextEntries = {};
1937
+ for (const route of routes) {
1938
+ const appPath = toAppPath(route, appDir);
1939
+ const key = `${appPath}/route`;
1940
+ nextEntries[key] = `app${appPath}/route.js`;
1941
+ }
1942
+ for (const root of outputRoots) {
1943
+ const manifestPath = path5.join(root, "server", "app-paths-manifest.json");
1944
+ const existing = await readJsonManifest(manifestPath) ?? {};
1945
+ await mkdir5(path5.dirname(manifestPath), { recursive: true });
1946
+ await writeFile5(manifestPath, `${JSON.stringify({ ...existing, ...nextEntries }, null, 2)}
1947
+ `);
1948
+ }
1949
+ }
1950
+ async function mergeMiddlewareFunctionsManifest(outputRoots, routes, appDir, allRoutes) {
1951
+ const edgeRoutes = routes.filter((route) => route.segmentConfig?.runtime === "edge" || route.segmentConfig?.runtime === "experimental-edge");
1952
+ const edgePages = allRoutes.filter((route) => route.kind === "page" && isEdgeRoute(route));
1953
+ if (edgeRoutes.length === 0 && edgePages.length === 0)
1954
+ return;
1955
+ const routeEntries = edgeRoutes.map((route) => ({
1956
+ route: `${toAppPath(route, appDir)}/route`,
1957
+ value: {}
1958
+ }));
1959
+ const sharedImageChunk = "server/edge-chunks/image-response.js";
1960
+ const hasImageResponseRoute = routes.some((route) => ["opengraph-image", "twitter-image", "apple-icon", "icon"].includes(route.metadataRoute?.kind ?? ""));
1961
+ for (const root of outputRoots) {
1962
+ const manifestPath = path5.join(root, "server", "middleware-manifest.json");
1963
+ const manifest = await readJsonManifest(manifestPath);
1964
+ const target = {
1965
+ version: 3,
1966
+ sortedMiddleware: [],
1967
+ middleware: {},
1968
+ functions: {},
1969
+ ...manifest ?? {}
1970
+ };
1971
+ target.functions = target.functions ?? {};
1972
+ for (const { route, value } of routeEntries) {
1973
+ target.functions[route] = target.functions[route] ?? value;
1974
+ }
1975
+ if (hasImageResponseRoute && edgePages.length > 0) {
1976
+ const chunkPath = path5.join(root, sharedImageChunk);
1977
+ await mkdir5(path5.dirname(chunkPath), { recursive: true });
1978
+ await writeFile5(chunkPath, `export const loadAdditionalAsset = true
1979
+ `);
1980
+ for (const page of edgePages) {
1981
+ const key = page.route === "/" ? "/page" : `${page.route}/page`;
1982
+ target.functions[key] = { files: [sharedImageChunk] };
1983
+ }
1984
+ }
1985
+ await mkdir5(path5.dirname(manifestPath), { recursive: true });
1986
+ await writeFile5(manifestPath, `${JSON.stringify(target, null, 2)}
1987
+ `);
1988
+ }
1989
+ }
1990
+ function isForceDynamicRoute(route) {
1991
+ return route.segmentConfig?.dynamic === "force-dynamic";
1992
+ }
1993
+ function toRouteMeta(metadata) {
1994
+ const headers = {};
1995
+ for (const [name, value] of metadata.headers ?? []) {
1996
+ headers[name.toLowerCase()] = value;
1997
+ }
1998
+ return {
1999
+ status: metadata.status,
2000
+ headers
2001
+ };
2002
+ }
2003
+ async function writeStaticMetadataArtifacts(outPath, root, relative, metadata) {
2004
+ if (!metadata)
2005
+ return;
2006
+ const source = path5.join(outPath, "public", relative);
2007
+ const outputBase = path5.join(root, "server", "app", toPosixPath(relative));
2008
+ await mkdir5(path5.dirname(outputBase), { recursive: true });
2009
+ const routeMeta = JSON.stringify(toRouteMeta(metadata));
2010
+ await writeFile5(`${outputBase}.meta`, routeMeta, "utf8");
2011
+ try {
2012
+ await access(source);
2013
+ } catch {
2014
+ return;
2015
+ }
2016
+ await writeFile5(`${outputBase}.body`, await readFile2(source));
2017
+ }
2018
+ function routeJsModule(route) {
2019
+ const runtime = route.segmentConfig?.runtime ?? "nodejs";
2020
+ const data = JSON.stringify({
2021
+ segmentConfig: route.segmentConfig ?? null,
2022
+ runtime,
2023
+ metadataRoute: route.metadataRoute?.kind,
2024
+ route: route.route
2025
+ });
2026
+ return `export default ${data}
2027
+ `;
2028
+ }
2029
+ function toAppPath(route, appDir) {
2030
+ const generated = route.metadataRoute?.generatedParam;
2031
+ const normalized = route.route.replace(/^\/+|\/+$/g, "");
2032
+ const fileSegments = routeFileGroups(route.file, appDir);
2033
+ const routeSegments = normalized.length > 0 ? normalized.split("/") : [];
2034
+ const converted = routeSegments.map((segment) => routeSegmentToNextPath(segment, generated));
2035
+ const nextPathSegments = [...fileSegments, ...converted];
2036
+ return `/${nextPathSegments.join("/")}`;
2037
+ }
2038
+ function routeSegmentToNextPath(segment, generatedParam) {
2039
+ const match = /^:([^*.]+)(\*)?(\..*)?$/.exec(segment);
2040
+ if (!match)
2041
+ return segment;
2042
+ const name = match[1] ?? "";
2043
+ const star = match[2] ? "..." : "";
2044
+ const suffix = match[3] ?? "";
2045
+ const key = generatedParam && name === "id" ? generatedParam : name;
2046
+ return `[${star}${key}]${generatedParam && name === "id" ? "" : suffix}`;
2047
+ }
2048
+ function routeFileGroups(file, appDir) {
2049
+ const relative = toPosixPath(path5.relative(appDir, file));
2050
+ const parts = relative.split("/").filter(Boolean);
2051
+ const withoutLeaf = parts.slice(0, -1);
2052
+ const groups = [];
2053
+ for (const segment of withoutLeaf) {
2054
+ if (!segment.startsWith("(") || !segment.endsWith(")"))
2055
+ break;
2056
+ groups.push(segment);
2057
+ }
2058
+ return groups;
2059
+ }
2060
+ function removeLeadingSlash(pathValue) {
2061
+ return pathValue.replace(/^\//, "");
2062
+ }
2063
+ async function readJsonManifest(filePath) {
2064
+ try {
2065
+ const raw = await readFile2(filePath, "utf8");
2066
+ return JSON.parse(raw);
2067
+ } catch {
2068
+ return;
2069
+ }
2070
+ }
2071
+ async function resolveGeistFontFiles() {
2072
+ if (foundGeistFontPath)
2073
+ return [foundGeistFontPath];
2074
+ const req = createRequire2(process.cwd() + "/");
2075
+ const candidateRoots = resolveVercelOgRoots(req);
2076
+ for (const root of candidateRoots) {
2077
+ const files = await findFiles(root, "Geist-Regular.ttf");
2078
+ if (files.length === 0)
2079
+ continue;
2080
+ foundGeistFontPath = files[0];
2081
+ return files.slice(0, 1);
2082
+ }
2083
+ return [];
2084
+ }
2085
+ function resolveVercelOgRoots(req) {
2086
+ const roots = [];
2087
+ for (const spec of ["@vercel/og/package.json", "next/package.json"]) {
2088
+ try {
2089
+ roots.push(path5.dirname(req.resolve(spec)));
2090
+ } catch {}
2091
+ }
2092
+ return roots;
2093
+ }
2094
+ async function findFiles(root, targetName) {
2095
+ const found = [];
2096
+ const stack = [root];
2097
+ const maxDepth = 6;
2098
+ while (stack.length > 0) {
2099
+ const current = stack.pop();
2100
+ if (!current)
2101
+ continue;
2102
+ const normalizedRoot = root.replace(/\\/g, "/");
2103
+ const normalizedCurrent = current.replace(/\\/g, "/");
2104
+ if (normalizedCurrent.includes(`${path5.sep}.next${path5.sep}`) || normalizedCurrent.includes(`${path5.sep}.git${path5.sep}`) || normalizedCurrent.includes(`${path5.sep}node_modules${path5.sep}.cache${path5.sep}`)) {
2105
+ continue;
2106
+ }
2107
+ const depth = normalizedCurrent.split("/").length;
2108
+ if (depth > normalizedRoot.split("/").length + maxDepth)
2109
+ continue;
2110
+ let entries;
2111
+ try {
2112
+ entries = await readdir(current, { withFileTypes: true });
2113
+ } catch {
2114
+ continue;
2115
+ }
2116
+ for (const entry of entries) {
2117
+ const child = path5.join(current, entry.name);
2118
+ if (entry.isDirectory()) {
2119
+ stack.push(child);
2120
+ continue;
2121
+ }
2122
+ if (entry.isFile() && entry.name === targetName) {
2123
+ found.push(child);
2124
+ }
2125
+ }
2126
+ }
2127
+ return found;
2128
+ }
2129
+
2130
+ // src/compat/export/emit.ts
2131
+ import { copyFile, mkdir as mkdir7, readFile as readFile3, rm as rm2, writeFile as writeFile7 } from "fs/promises";
2132
+ import path7 from "path";
2133
+
2134
+ // src/compat/export/standalone.ts
2135
+ import { existsSync as existsSync3, readFileSync } from "fs";
2136
+ import { mkdir as mkdir6, rm, writeFile as writeFile6 } from "fs/promises";
2137
+ import path6 from "path";
2138
+ var ENTRY_FILE = /(?:^|[\\/])(page|route)\.(?:js|jsx|ts|tsx|mjs|cjs)$/;
2139
+ async function emitStandalone({
2140
+ config,
2141
+ manifest,
2142
+ log
2143
+ }) {
2144
+ await log.step("standalone output", () => writeStandalone(config, manifest));
2145
+ }
2146
+ async function writeStandalone(config, manifest) {
2147
+ const standaloneDir = path6.join(config.root, ".next", "standalone");
2148
+ await rm(standaloneDir, { recursive: true, force: true });
2149
+ await mkdir6(standaloneDir, { recursive: true });
2150
+ await writeServerEntry(config, standaloneDir);
2151
+ await writeTraceFiles(config, standaloneDir);
2152
+ await writeMiddlewareManifest(manifest, standaloneDir);
2153
+ }
2154
+ async function writeServerEntry(config, standaloneDir) {
2155
+ await writeFile6(path6.join(standaloneDir, "package.json"), `${JSON.stringify({ name: "pnext-standalone", version: "0.0.0", type: "commonjs", private: true }, null, 2)}
2156
+ `);
2157
+ await writeFile6(path6.join(standaloneDir, "server.js"), standaloneServerSource(config));
2158
+ }
2159
+ function standaloneServerSource(config) {
2160
+ const cliPath = path6.resolve(__PNEXT_PACKAGE_ROOT__ + "/src/compat/export", "..", "..", "cli", "index.ts");
2161
+ return `'use strict';
2162
+ // pnext standalone launcher. Generated by pnext build; see
2163
+ // src/compat/export/standalone.ts. Spawned as \`node server.js\` from the moved
2164
+ // standalone directory; re-execs the real pnext server under Bun.
2165
+ const { spawn } = require('node:child_process');
2166
+
2167
+ const PNEXT_CLI = ${JSON.stringify(cliPath)};
2168
+ const PNEXT_ROOT = ${JSON.stringify(config.root)};
2169
+ const port = String(process.env.PORT || '3000');
2170
+ const hostname = process.env.HOSTNAME || '0.0.0.0';
2171
+
2172
+ const child = spawn(
2173
+ 'bun',
2174
+ ['--conditions=react-server', PNEXT_CLI, 'start', '--port', port, '--hostname', hostname],
2175
+ {
2176
+ cwd: PNEXT_ROOT,
2177
+ env: {
2178
+ ...process.env,
2179
+ // Suppresses \`pnext start\`'s "output: standalone" warning (Next gates the
2180
+ // same warning on this private env being set by its standalone server).
2181
+ __NEXT_PRIVATE_STANDALONE_CONFIG: '1',
2182
+ PNEXT_COMPAT: 'next',
2183
+ BROWSER: 'none',
2184
+ NODE_ENV: 'production',
2185
+ PORT: port,
2186
+ HOSTNAME: hostname,
2187
+ },
2188
+ stdio: ['ignore', 'inherit', 'inherit'],
2189
+ }
2190
+ );
2191
+
2192
+ child.on('error', (error) => {
2193
+ console.error('pnext standalone: failed to start the pnext server:', error);
2194
+ process.exit(1);
2195
+ });
2196
+ child.on('exit', (code, signal) => {
2197
+ process.exit(code == null ? (signal ? 1 : 0) : code);
2198
+ });
2199
+
2200
+ for (const signal of ['SIGINT', 'SIGTERM']) {
2201
+ process.on(signal, () => {
2202
+ if (child.exitCode === null) child.kill(signal);
2203
+ });
2204
+ }
2205
+ `;
2206
+ }
2207
+ async function writeTraceFiles(config, standaloneDir) {
2208
+ const serverDir = path6.join(standaloneDir, ".next", "server");
2209
+ await emitTracesFor(path6.join(config.root, "app"), path6.join(serverDir, "app"));
2210
+ await emitTracesFor(path6.join(config.root, "src", "app"), path6.join(serverDir, "app"));
2211
+ await emitTracesFor(path6.join(config.root, "pages"), path6.join(serverDir, "pages"));
2212
+ await emitTracesFor(path6.join(config.root, "src", "pages"), path6.join(serverDir, "pages"));
2213
+ }
2214
+ async function writeMiddlewareManifest(manifest, standaloneDir) {
2215
+ const functions = {};
2216
+ for (const route of manifest.routes) {
2217
+ if (!isEdgeRoute2(route))
2218
+ continue;
2219
+ const page = route.route || "/";
2220
+ functions[page] = {
2221
+ files: [],
2222
+ name: `edge${page === "/" ? "/index" : page}`,
2223
+ page,
2224
+ matchers: [{ regexp: `^${escapeRouteRegexp(page)}$`, originalSource: page }],
2225
+ wasm: [],
2226
+ assets: [],
2227
+ env: {}
2228
+ };
2229
+ }
2230
+ if (Object.keys(functions).length === 0)
2231
+ return;
2232
+ const serverDir = path6.join(standaloneDir, ".next", "server");
2233
+ await mkdir6(serverDir, { recursive: true });
2234
+ await writeFile6(path6.join(serverDir, "middleware-manifest.json"), `${JSON.stringify({ version: 3, sortedMiddleware: [], middleware: {}, functions }, null, 2)}
2235
+ `);
2236
+ }
2237
+ function isEdgeRoute2(route) {
2238
+ const runtime = route.segmentConfig?.runtime;
2239
+ if (runtime === "edge" || runtime === "experimental-edge")
2240
+ return true;
2241
+ for (const file of [route.file, ...route.sourceFiles ?? []]) {
2242
+ if (!file || !existsSync3(file))
2243
+ continue;
2244
+ let source;
2245
+ try {
2246
+ source = readFileSync(file, "utf8");
2247
+ } catch {
2248
+ continue;
2249
+ }
2250
+ if (/\bruntime\s*:\s*['"](?:edge|experimental-edge)['"]/.test(source))
2251
+ return true;
2252
+ if (/export\s+const\s+runtime\s*=\s*['"](?:edge|experimental-edge)['"]/.test(source))
2253
+ return true;
2254
+ }
2255
+ return false;
2256
+ }
2257
+ function escapeRouteRegexp(route) {
2258
+ return route.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/:([^/\\]+)/g, "[^/]+");
2259
+ }
2260
+ async function emitTracesFor(sourceDir, targetDir) {
2261
+ if (!existsSync3(sourceDir))
2262
+ return;
2263
+ for (const file of await listFiles(sourceDir)) {
2264
+ const match = ENTRY_FILE.exec(file);
2265
+ if (!match)
2266
+ continue;
2267
+ const relative = toPosixPath(path6.relative(sourceDir, file));
2268
+ const relativeDir = path6.posix.dirname(relative);
2269
+ const dir = path6.join(targetDir, ...relativeDir === "." ? [] : relativeDir.split("/"));
2270
+ await mkdir6(dir, { recursive: true });
2271
+ await writeFile6(path6.join(dir, `${match[1]}.js.nft.json`), `${JSON.stringify({ version: 1, files: [] })}
2272
+ `);
2273
+ }
2274
+ }
2275
+
2276
+ // src/compat/export/emit.ts
2277
+ var BUILD_ID = "pnext";
2278
+ var COMMON_SEGMENTS = ["_full", "_head", "_index", "_tree"];
2279
+ var RUNTIME_ASSET_DIR = "_next/static/chunks";
2280
+ var EXPORT_MODE_SCRIPT = "<script>window.__PNEXT_OUTPUT_EXPORT__=true;</script>";
2281
+ async function emitStaticExport({ config, manifest, log }) {
2282
+ await log.step("build manifest", () => writeBuildManifests(path7.join(config.outPath, "public")));
2283
+ const output = getNextConfig().output;
2284
+ if (output === "standalone") {
2285
+ await emitStandalone({ config, manifest, log });
2286
+ return;
2287
+ }
2288
+ if (output !== "export")
2289
+ return;
2290
+ await log.step("static export", () => writeExportTree(config, manifest));
2291
+ }
2292
+ async function writeExportTree(config, manifest) {
2293
+ const outDir = exportOutDir(config);
2294
+ await rm2(outDir, { recursive: true, force: true });
2295
+ await mkdir7(outDir, { recursive: true });
2296
+ const assets = await copyRuntimeAssets(config, outDir);
2297
+ await copyPublicTree(config, outDir, assets);
2298
+ await writeBuildManifests(outDir);
2299
+ const pages = exportPages(config, manifest);
2300
+ for (const page of pages)
2301
+ await writePageArtifacts(page, assets);
2302
+ await writeNotFoundArtifacts(config, outDir);
2303
+ }
2304
+ async function copyRuntimeAssets(config, outDir) {
2305
+ const assetsDir = path7.join(config.outPath, "public", "assets");
2306
+ const assets = new Set;
2307
+ for (const file of await listFiles(assetsDir)) {
2308
+ const relative = toPosixPath(path7.relative(assetsDir, file));
2309
+ assets.add(relative);
2310
+ const target = path7.join(outDir, ...RUNTIME_ASSET_DIR.split("/"), ...relative.split("/"));
2311
+ await mkdir7(path7.dirname(target), { recursive: true });
2312
+ await copyFile(file, target);
2313
+ }
2314
+ return assets;
2315
+ }
2316
+ async function copyPublicTree(config, outDir, assets) {
2317
+ const publicDir = path7.join(config.outPath, "public");
2318
+ for (const file of await listFiles(publicDir)) {
2319
+ const relative = toPosixPath(path7.relative(publicDir, file));
2320
+ if (relative.startsWith("assets/"))
2321
+ continue;
2322
+ const target = path7.join(outDir, ...relative.split("/"));
2323
+ await mkdir7(path7.dirname(target), { recursive: true });
2324
+ if (relative.endsWith(".html")) {
2325
+ await writeFile7(target, exportDocument(await readFile3(file, "utf8"), assets));
2326
+ } else {
2327
+ await copyFile(file, target);
2328
+ }
2329
+ }
2330
+ }
2331
+ function exportDocument(html, assets) {
2332
+ const repointed = html.replace(/\/_next\/static\/([^"'`\s<>)?#]+)([?#][^"'`\s<>]*)?/g, (match, rest, suffix) => assets.has(rest) ? `/${RUNTIME_ASSET_DIR}/${rest}${suffix ?? ""}` : match);
2333
+ const anchor = /<head[^>]*>|<body[^>]*>/.exec(repointed);
2334
+ if (!anchor)
2335
+ return EXPORT_MODE_SCRIPT + repointed;
2336
+ const at = anchor.index + anchor[0].length;
2337
+ return `${repointed.slice(0, at)}${EXPORT_MODE_SCRIPT}${repointed.slice(at)}`;
2338
+ }
2339
+ async function writeBuildManifests(outDir) {
2340
+ const dir = path7.join(outDir, "_next", "static", BUILD_ID);
2341
+ await mkdir7(dir, { recursive: true });
2342
+ await writeFile7(path7.join(dir, "_buildManifest.js"), `self.__BUILD_MANIFEST={};self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB();
2343
+ `);
2344
+ await writeFile7(path7.join(dir, "_ssgManifest.js"), `self.__SSG_MANIFEST=new Set();
2345
+ `);
2346
+ }
2347
+ function exportOutDir(config) {
2348
+ const distDir = getNextConfig().distDir;
2349
+ const dir = typeof distDir === "string" && distDir.length > 0 && distDir !== ".next" ? distDir : "out";
2350
+ return path7.resolve(config.root, dir);
2351
+ }
2352
+ function exportPages(config, manifest) {
2353
+ const staticFiles = manifest.staticFiles ?? {};
2354
+ const routeById = new Map(manifest.routes.map((route) => [route.id, route]));
2355
+ const pages = [];
2356
+ for (const [relative, metadata] of Object.entries(staticFiles)) {
2357
+ if (metadata.kind !== "page" || !relative.endsWith(".html"))
2358
+ continue;
2359
+ const route = metadata.routeId ? routeById.get(metadata.routeId) : undefined;
2360
+ if (route?.kind !== "page")
2361
+ continue;
2362
+ const htmlFile = path7.join(config.outPath, "public", ...relative.split("/"));
2363
+ pages.push({
2364
+ route,
2365
+ htmlFile,
2366
+ ...exportPathsForHtml(config, relative)
2367
+ });
2368
+ }
2369
+ return pages.sort((a, b) => a.outHtml.localeCompare(b.outHtml));
2370
+ }
2371
+ function exportPathsForHtml(config, relative) {
2372
+ const outDir = exportOutDir(config);
2373
+ const normalized = toPosixPath(relative);
2374
+ if (normalized === "index.html") {
2375
+ return {
2376
+ outHtml: path7.join(outDir, "index.html"),
2377
+ outPageTxt: path7.join(outDir, "index.txt"),
2378
+ segmentDir: outDir
2379
+ };
2380
+ }
2381
+ if (normalized.endsWith("/index.html")) {
2382
+ const routePath2 = normalized.slice(0, -"/index.html".length);
2383
+ return {
2384
+ outHtml: path7.join(outDir, ...normalized.split("/")),
2385
+ outPageTxt: path7.join(outDir, ...routePath2.split("/"), "index.txt"),
2386
+ segmentDir: path7.join(outDir, ...routePath2.split("/"))
2387
+ };
2388
+ }
2389
+ const routePath = normalized.slice(0, -".html".length);
2390
+ return {
2391
+ outHtml: path7.join(outDir, ...normalized.split("/")),
2392
+ outPageTxt: path7.join(outDir, `${routePath}.txt`),
2393
+ segmentDir: path7.join(outDir, ...routePath.split("/"))
2394
+ };
2395
+ }
2396
+ async function writePageArtifacts(page, assets) {
2397
+ const html = exportDocument(await readFile3(page.htmlFile, "utf8"), assets);
2398
+ await mkdir7(path7.dirname(page.outPageTxt), { recursive: true });
2399
+ await writeFile7(page.outPageTxt, html);
2400
+ await writeSegmentFiles(page.segmentDir, page.route, html);
2401
+ }
2402
+ async function writeSegmentFiles(segmentDir2, route, body) {
2403
+ await mkdir7(segmentDir2, { recursive: true });
2404
+ for (const segment of COMMON_SEGMENTS) {
2405
+ await writeFile7(path7.join(segmentDir2, `__next.${segment}.txt`), body);
2406
+ }
2407
+ const keys = segmentKeys(route);
2408
+ const leaf = keys.at(-1) ?? "";
2409
+ await writeFile7(path7.join(segmentDir2, leaf ? `__next.${leaf}.__PAGE__.txt` : "__next.__PAGE__.txt"), body);
2410
+ if (leaf)
2411
+ await writeFile7(path7.join(segmentDir2, `__next.${leaf}.txt`), body);
2412
+ for (const key of keys.slice(0, -1)) {
2413
+ if (key)
2414
+ await writeFile7(path7.join(segmentDir2, `__next.${key}.txt`), body);
2415
+ }
2416
+ }
2417
+ function segmentKeys(route) {
2418
+ const params = new Set(route.params);
2419
+ const parts = route.route.replace(/^\/|\/$/g, "").split("/").filter(Boolean).map((part) => part.startsWith(":") ? `$d$${part.replace(/^:|[*?]$/g, "")}` : part);
2420
+ if (parts.length === 0)
2421
+ return [""];
2422
+ const keys = [];
2423
+ for (const [index, part] of parts.entries()) {
2424
+ const key = part.startsWith("$d$") && !params.has(part.slice(3)) ? part.slice(3) : part;
2425
+ keys.push([...parts.slice(0, index), key].join("."));
2426
+ }
2427
+ return keys;
2428
+ }
2429
+ async function writeNotFoundArtifacts(config, outDir) {
2430
+ const htmlFile = path7.join(outDir, "404.html");
2431
+ const html = await readFile3(htmlFile, "utf8").catch(() => {
2432
+ return;
2433
+ });
2434
+ if (html === undefined)
2435
+ return;
2436
+ if (config.trailingSlash === true) {
2437
+ const nested = path7.join(outDir, "404", "index.html");
2438
+ await mkdir7(path7.dirname(nested), { recursive: true });
2439
+ await writeFile7(nested, html);
2440
+ }
2441
+ const outHtml = config.trailingSlash === true ? path7.join(outDir, "_not-found", "index.html") : path7.join(outDir, "_not-found.html");
2442
+ const outTxt = config.trailingSlash === true ? path7.join(outDir, "_not-found", "index.txt") : path7.join(outDir, "_not-found.txt");
2443
+ await mkdir7(path7.dirname(outHtml), { recursive: true });
2444
+ await writeFile7(outHtml, html);
2445
+ await writeFile7(outTxt, html);
2446
+ await writeSegmentFiles(path7.join(outDir, "_not-found"), { route: "/_not-found", params: [] }, html);
2447
+ }
2448
+
2449
+ // src/compat/register/export.ts
2450
+ var registered2 = false;
2451
+ onExtensionHostReset(() => registered2 = false);
2452
+ function registerExportExtensions(config) {
2453
+ if (registered2)
2454
+ return;
2455
+ if (!nextCompatEnabled(config))
2456
+ return;
2457
+ registered2 = true;
2458
+ registerBuildCompleteHooks(async (ctx) => {
2459
+ if (!nextCompatEnabled(ctx.config))
2460
+ return;
2461
+ await emitStaticExport(ctx);
2462
+ await emitMetadataRouteArtifacts(ctx);
2463
+ await emitCustomServerShim(ctx.config);
2464
+ });
2465
+ }
2466
+ export {
2467
+ registerBuildCompatExtensions,
2468
+ registerExportExtensions,
2469
+ registerMiddlewareExtensions,
2470
+ registerTypedRoutesExtensions,
2471
+ registerValidationExtensions
2472
+ };