nitro-nightly 3.0.0-beta-28969273.f7aa9de6 → 4.0.0-20251010-091516-7cafddba

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 (417) hide show
  1. package/README.md +8 -39
  2. package/dist/_chunks/app.mjs +19797 -0
  3. package/dist/_chunks/build.mjs +84 -0
  4. package/dist/_chunks/build2.mjs +318 -0
  5. package/dist/_chunks/build3.mjs +6452 -0
  6. package/dist/_chunks/detect-acorn.mjs +503 -0
  7. package/dist/_chunks/index.mjs +22242 -0
  8. package/dist/_chunks/index2.mjs +297 -0
  9. package/dist/_chunks/index3.mjs +1058 -0
  10. package/dist/_chunks/index4.mjs +1206 -0
  11. package/dist/_chunks/info.mjs +11157 -0
  12. package/dist/_chunks/json5.mjs +68 -0
  13. package/dist/_chunks/jsonc.mjs +51 -0
  14. package/dist/_chunks/pathe.M-eThtNZ.mjs +204 -0
  15. package/dist/_chunks/plugin.mjs +960 -0
  16. package/dist/_chunks/server.mjs +254 -0
  17. package/dist/_chunks/snapshot.mjs +284 -0
  18. package/dist/_chunks/toml.mjs +259 -0
  19. package/dist/_chunks/yaml.mjs +86 -0
  20. package/dist/cli/build.mjs +10 -3
  21. package/dist/cli/dev.mjs +41 -9
  22. package/dist/cli/index.mjs +460 -1
  23. package/dist/cli/index2.mjs +4 -1
  24. package/dist/cli/list.mjs +10 -4
  25. package/dist/cli/prepare.mjs +6 -3
  26. package/dist/cli/run.mjs +7 -4
  27. package/dist/index.d.mts +52 -0
  28. package/dist/index.mjs +55 -0
  29. package/dist/node_modules/@poppinss/colors/build/index.js +169 -0
  30. package/dist/node_modules/@poppinss/colors/package.json +116 -0
  31. package/dist/node_modules/@poppinss/dumper/build/chunk-26HALFTP.js +602 -0
  32. package/dist/node_modules/@poppinss/dumper/build/formatters/console/main.js +441 -0
  33. package/dist/node_modules/@poppinss/dumper/build/formatters/html/main.js +717 -0
  34. package/dist/node_modules/@poppinss/dumper/package.json +122 -0
  35. package/dist/node_modules/@poppinss/exception/build/index.js +63 -0
  36. package/dist/node_modules/@poppinss/exception/package.json +106 -0
  37. package/dist/node_modules/@sindresorhus/is/distribution/index.js +1313 -0
  38. package/dist/node_modules/@sindresorhus/is/distribution/utilities.js +3 -0
  39. package/dist/node_modules/@sindresorhus/is/package.json +81 -0
  40. package/dist/node_modules/@speed-highlight/core/dist/index.js +4 -0
  41. package/dist/node_modules/@speed-highlight/core/dist/terminal.js +2 -0
  42. package/dist/node_modules/@speed-highlight/core/package.json +90 -0
  43. package/dist/node_modules/cookie/dist/index.js +239 -0
  44. package/dist/node_modules/cookie/package.json +42 -0
  45. package/dist/node_modules/croner/dist/croner.js +1 -0
  46. package/dist/node_modules/croner/package.json +63 -0
  47. package/dist/node_modules/defu/dist/defu.mjs +69 -0
  48. package/dist/node_modules/defu/package.json +43 -0
  49. package/dist/node_modules/destr/dist/index.mjs +72 -0
  50. package/dist/node_modules/destr/package.json +47 -0
  51. package/dist/node_modules/error-stack-parser-es/dist/index.mjs +38 -0
  52. package/dist/node_modules/error-stack-parser-es/dist/lite.mjs +167 -0
  53. package/dist/node_modules/error-stack-parser-es/package.json +83 -0
  54. package/dist/node_modules/get-port-please/dist/index.mjs +430 -0
  55. package/dist/node_modules/get-port-please/package.json +39 -0
  56. package/dist/node_modules/hookable/dist/index.mjs +290 -0
  57. package/dist/node_modules/hookable/package.json +49 -0
  58. package/dist/node_modules/kleur/index.js +110 -0
  59. package/dist/node_modules/kleur/index.mjs +110 -0
  60. package/dist/node_modules/kleur/package.json +51 -0
  61. package/dist/node_modules/klona/dist/index.mjs +81 -0
  62. package/dist/node_modules/klona/full/index.mjs +53 -0
  63. package/dist/node_modules/klona/package.json +74 -0
  64. package/dist/node_modules/scule/dist/index.mjs +80 -0
  65. package/dist/node_modules/scule/package.json +43 -0
  66. package/dist/node_modules/source-map/lib/array-set.js +100 -0
  67. package/dist/node_modules/source-map/lib/base64-vlq.js +94 -0
  68. package/dist/node_modules/source-map/lib/base64.js +19 -0
  69. package/dist/node_modules/source-map/lib/binary-search.js +113 -0
  70. package/dist/node_modules/source-map/lib/mapping-list.js +83 -0
  71. package/dist/node_modules/source-map/lib/mappings.wasm +0 -0
  72. package/dist/node_modules/source-map/lib/read-wasm.js +27 -0
  73. package/dist/node_modules/source-map/lib/source-map-consumer.js +1081 -0
  74. package/dist/node_modules/source-map/lib/source-map-generator.js +439 -0
  75. package/dist/node_modules/source-map/lib/source-node.js +430 -0
  76. package/dist/node_modules/source-map/lib/url.js +13 -0
  77. package/dist/node_modules/source-map/lib/util.js +444 -0
  78. package/dist/node_modules/source-map/lib/wasm.js +138 -0
  79. package/dist/node_modules/source-map/package.json +79 -0
  80. package/dist/node_modules/source-map/source-map.js +10 -0
  81. package/dist/node_modules/std-env/dist/index.mjs +1 -0
  82. package/dist/node_modules/std-env/package.json +46 -0
  83. package/dist/node_modules/supports-color/index.js +202 -0
  84. package/dist/node_modules/supports-color/package.json +64 -0
  85. package/dist/node_modules/ufo/dist/index.mjs +638 -0
  86. package/dist/node_modules/ufo/package.json +47 -0
  87. package/dist/node_modules/unctx/dist/index.mjs +131 -0
  88. package/dist/node_modules/unctx/package.json +67 -0
  89. package/dist/node_modules/youch/build/chunk-4L7RY2JA.js +42 -0
  90. package/dist/node_modules/youch/build/chunk-4XB2BYKC.js +85 -0
  91. package/dist/node_modules/youch/build/chunk-4YEN7HVQ.js +61 -0
  92. package/dist/node_modules/youch/build/chunk-EUJBVOYB.js +83 -0
  93. package/dist/node_modules/youch/build/chunk-HFSXRSKS.js +85 -0
  94. package/dist/node_modules/youch/build/chunk-JAN2TFI2.js +222 -0
  95. package/dist/node_modules/youch/build/chunk-OSUFJZHZ.js +6 -0
  96. package/dist/node_modules/youch/build/chunk-PINJDICN.js +72 -0
  97. package/dist/node_modules/youch/build/chunk-PUHGL6HA.js +41 -0
  98. package/dist/node_modules/youch/build/chunk-VE4LENUR.js +45 -0
  99. package/dist/node_modules/youch/build/index.js +352 -0
  100. package/dist/node_modules/youch/build/public/error_cause/style.css +5 -0
  101. package/dist/node_modules/youch/build/public/error_info/script.js +13 -0
  102. package/dist/node_modules/youch/build/public/error_info/style.css +144 -0
  103. package/dist/node_modules/youch/build/public/error_stack/script.js +74 -0
  104. package/dist/node_modules/youch/build/public/error_stack/style.css +220 -0
  105. package/dist/node_modules/youch/build/public/error_stack_source/style.css +123 -0
  106. package/dist/node_modules/youch/build/public/header/script.js +16 -0
  107. package/dist/node_modules/youch/build/public/header/style.css +56 -0
  108. package/dist/node_modules/youch/build/public/layout/script.js +20 -0
  109. package/dist/node_modules/youch/build/public/layout/style.css +431 -0
  110. package/dist/node_modules/youch/package.json +133 -0
  111. package/dist/node_modules/youch-core/build/index.js +316 -0
  112. package/dist/node_modules/youch-core/package.json +124 -0
  113. package/dist/presets/_nitro/runtime/nitro-dev.mjs +48 -73
  114. package/dist/presets/_nitro/runtime/{nitro-prerenderer.d.ts → nitro-prerenderer.d.mts} +1 -1
  115. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +12 -1
  116. package/dist/presets/_nitro/runtime/service-worker.mjs +5 -15
  117. package/dist/presets/aws-amplify/runtime/aws-amplify.mjs +2 -2
  118. package/dist/presets/aws-lambda/runtime/_utils.d.mts +18 -0
  119. package/dist/presets/aws-lambda/runtime/_utils.mjs +102 -0
  120. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.mts +3 -0
  121. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +12 -32
  122. package/dist/presets/aws-lambda/runtime/aws-lambda.d.mts +3 -0
  123. package/dist/presets/aws-lambda/runtime/aws-lambda.mjs +6 -38
  124. package/dist/{runtime/internal/utils.azure.d.ts → presets/azure/runtime/_utils.d.mts} +1 -1
  125. package/dist/{runtime/internal/utils.azure.mjs → presets/azure/runtime/_utils.mjs} +3 -4
  126. package/dist/presets/azure/runtime/azure-swa.mjs +11 -13
  127. package/dist/presets/bun/runtime/bun.mjs +13 -18
  128. package/dist/presets/cloudflare/runtime/_module-handler.d.mts +13 -0
  129. package/dist/presets/cloudflare/runtime/_module-handler.mjs +93 -0
  130. package/dist/presets/cloudflare/runtime/cloudflare-durable.d.mts +19 -0
  131. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +74 -0
  132. package/dist/presets/cloudflare/runtime/cloudflare-module.d.mts +9 -0
  133. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +13 -97
  134. package/dist/presets/cloudflare/runtime/{cloudflare-pages.d.ts → cloudflare-pages.d.mts} +1 -1
  135. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +19 -27
  136. package/dist/{runtime/internal/timing.d.ts → presets/cloudflare/runtime/plugin.dev.d.mts} +1 -0
  137. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +89 -0
  138. package/dist/presets/deno/runtime/deno-deploy.mjs +11 -25
  139. package/dist/presets/deno/runtime/deno-server.d.mts +6 -0
  140. package/dist/presets/deno/runtime/deno-server.mjs +15 -21
  141. package/dist/presets/netlify/runtime/netlify-edge.d.mts +3 -0
  142. package/dist/presets/netlify/runtime/netlify-edge.mjs +8 -16
  143. package/dist/presets/netlify/runtime/netlify.mjs +16 -45
  144. package/dist/presets/node/runtime/{cluster.mjs → node-cluster.mjs} +1 -3
  145. package/dist/presets/node/runtime/node-middleware.d.mts +4 -0
  146. package/dist/presets/node/runtime/{node-listener.mjs → node-middleware.mjs} +3 -4
  147. package/dist/presets/node/runtime/node-server.mjs +3 -4
  148. package/dist/presets/standard/runtime/server.d.mts +5 -0
  149. package/dist/presets/standard/runtime/server.mjs +6 -0
  150. package/dist/presets/stormkit/runtime/stormkit.mjs +8 -12
  151. package/dist/presets/vercel/runtime/vercel.d.mts +8 -0
  152. package/dist/presets/vercel/runtime/vercel.mjs +11 -11
  153. package/dist/presets/winterjs/runtime/winterjs.mjs +22 -4
  154. package/dist/presets/{node/runtime/node-server.d.ts → zeabur/runtime/zeabur.d.mts} +1 -1
  155. package/dist/presets/zeabur/runtime/zeabur.mjs +2 -6
  156. package/dist/presets.mjs +2460 -0
  157. package/dist/runtime/index.d.mts +11 -0
  158. package/dist/runtime/index.mjs +8 -8
  159. package/dist/runtime/internal/app.d.mts +2 -0
  160. package/dist/runtime/internal/app.mjs +129 -128
  161. package/dist/runtime/internal/cache.d.mts +7 -0
  162. package/dist/runtime/internal/cache.mjs +82 -175
  163. package/dist/runtime/internal/{context.d.ts → context.d.mts} +3 -3
  164. package/dist/runtime/internal/context.mjs +6 -6
  165. package/dist/runtime/internal/error/dev.d.mts +9 -0
  166. package/dist/runtime/internal/error/dev.mjs +122 -0
  167. package/dist/runtime/internal/error/prod.d.mts +8 -0
  168. package/dist/runtime/internal/error/prod.mjs +62 -0
  169. package/dist/runtime/internal/error/utils.d.mts +8 -0
  170. package/dist/runtime/internal/error/utils.mjs +3 -0
  171. package/dist/runtime/internal/index.d.mts +3 -0
  172. package/dist/runtime/internal/index.mjs +1 -14
  173. package/dist/runtime/internal/renderer.d.mts +3 -0
  174. package/dist/runtime/internal/renderer.mjs +29 -33
  175. package/dist/runtime/internal/route-rules.d.mts +8 -0
  176. package/dist/runtime/internal/route-rules.mjs +58 -63
  177. package/dist/runtime/internal/routes/dev-tasks.d.mts +3 -0
  178. package/dist/runtime/internal/routes/dev-tasks.mjs +23 -0
  179. package/dist/runtime/internal/routes/openapi.d.mts +3 -0
  180. package/dist/runtime/internal/routes/openapi.mjs +24 -9
  181. package/dist/runtime/internal/routes/renderer-template.d.mts +2 -0
  182. package/dist/runtime/internal/routes/renderer-template.dev.d.mts +3 -0
  183. package/dist/runtime/internal/routes/renderer-template.dev.mjs +21 -0
  184. package/dist/runtime/internal/routes/renderer-template.mjs +4 -0
  185. package/dist/runtime/internal/routes/scalar.d.mts +3 -0
  186. package/dist/runtime/internal/routes/scalar.mjs +7 -4
  187. package/dist/runtime/internal/routes/swagger.d.mts +3 -0
  188. package/dist/runtime/internal/routes/swagger.mjs +5 -4
  189. package/dist/runtime/internal/{utils.env.d.ts → runtime-config.d.mts} +4 -2
  190. package/dist/runtime/internal/{utils.env.mjs → runtime-config.mjs} +16 -6
  191. package/dist/runtime/internal/static.d.mts +3 -0
  192. package/dist/runtime/internal/static.mjs +24 -36
  193. package/dist/runtime/internal/storage.mjs +2 -1
  194. package/dist/runtime/internal/task.mjs +6 -6
  195. package/dist/runtime/internal/utils.d.mts +1 -0
  196. package/dist/runtime/internal/utils.mjs +1 -116
  197. package/dist/runtime/internal/vite/dev-entry.d.mts +1 -0
  198. package/dist/runtime/internal/vite/dev-entry.mjs +6 -0
  199. package/dist/runtime/internal/vite/dev-worker.mjs +362 -0
  200. package/dist/runtime/internal/vite/prod-setup.d.mts +4 -0
  201. package/dist/runtime/internal/vite/prod-setup.mjs +55 -0
  202. package/dist/runtime/internal/vite/ssr-renderer.d.mts +4 -0
  203. package/dist/runtime/internal/vite/ssr-renderer.mjs +4 -0
  204. package/dist/types/index.d.mts +2688 -138
  205. package/dist/vite.d.mts +59 -0
  206. package/dist/vite.mjs +68 -0
  207. package/lib/config.d.mts +9 -0
  208. package/lib/deps/h3.d.mts +1 -0
  209. package/lib/deps/h3.mjs +1 -0
  210. package/lib/deps/ofetch.mjs +1 -0
  211. package/lib/deps/ofetch.mts +1 -0
  212. package/lib/meta.d.mts +5 -0
  213. package/lib/meta.mjs +21 -0
  214. package/{runtime-meta.d.ts → lib/runtime-meta.d.mts} +1 -0
  215. package/{runtime-meta.mjs → lib/runtime-meta.mjs} +12 -4
  216. package/package.json +142 -160
  217. package/cli.d.ts +0 -1
  218. package/config.d.ts +0 -1
  219. package/core.d.ts +0 -1
  220. package/dist/cli/index.d.ts +0 -1
  221. package/dist/config/index.d.mts +0 -6
  222. package/dist/config/index.d.ts +0 -6
  223. package/dist/core/index.d.mts +0 -30
  224. package/dist/core/index.d.ts +0 -30
  225. package/dist/core/index.mjs +0 -2456
  226. package/dist/kit/index.d.mts +0 -44
  227. package/dist/kit/index.d.ts +0 -44
  228. package/dist/kit/index.mjs +0 -71
  229. package/dist/meta/index.d.mts +0 -3
  230. package/dist/meta/index.d.ts +0 -3
  231. package/dist/meta/index.mjs +0 -3
  232. package/dist/presets/_all.gen.d.ts +0 -2
  233. package/dist/presets/_all.gen.mjs +0 -52
  234. package/dist/presets/_nitro/base-worker.d.ts +0 -2
  235. package/dist/presets/_nitro/base-worker.mjs +0 -25
  236. package/dist/presets/_nitro/nitro-dev.d.ts +0 -2
  237. package/dist/presets/_nitro/nitro-dev.mjs +0 -19
  238. package/dist/presets/_nitro/nitro-prerender.d.ts +0 -2
  239. package/dist/presets/_nitro/nitro-prerender.mjs +0 -17
  240. package/dist/presets/_nitro/preset.d.ts +0 -2
  241. package/dist/presets/_nitro/preset.mjs +0 -5
  242. package/dist/presets/_nitro/service-worker.d.ts +0 -2
  243. package/dist/presets/_nitro/service-worker.mjs +0 -110
  244. package/dist/presets/_resolve.d.ts +0 -8
  245. package/dist/presets/_resolve.mjs +0 -44
  246. package/dist/presets/_static/preset.d.ts +0 -2
  247. package/dist/presets/_static/preset.mjs +0 -69
  248. package/dist/presets/_types.gen.d.ts +0 -16
  249. package/dist/presets/alwaysdata/preset.d.ts +0 -2
  250. package/dist/presets/alwaysdata/preset.mjs +0 -14
  251. package/dist/presets/aws-amplify/preset.d.ts +0 -3
  252. package/dist/presets/aws-amplify/preset.mjs +0 -27
  253. package/dist/presets/aws-amplify/types.d.ts +0 -141
  254. package/dist/presets/aws-amplify/utils.d.ts +0 -2
  255. package/dist/presets/aws-amplify/utils.mjs +0 -82
  256. package/dist/presets/aws-lambda/preset.d.ts +0 -2
  257. package/dist/presets/aws-lambda/preset.mjs +0 -21
  258. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.ts +0 -14
  259. package/dist/presets/aws-lambda/runtime/aws-lambda.d.ts +0 -4
  260. package/dist/presets/azure/preset.d.ts +0 -3
  261. package/dist/presets/azure/preset.mjs +0 -44
  262. package/dist/presets/azure/runtime/azure-functions.mjs +0 -24
  263. package/dist/presets/azure/runtime/azure-swa.d.ts +0 -5
  264. package/dist/presets/azure/types.d.ts +0 -13
  265. package/dist/presets/azure/types.mjs +0 -0
  266. package/dist/presets/azure/utils.d.ts +0 -3
  267. package/dist/presets/azure/utils.mjs +0 -183
  268. package/dist/presets/bun/preset.d.ts +0 -2
  269. package/dist/presets/bun/preset.mjs +0 -17
  270. package/dist/presets/cleavr/preset.d.ts +0 -2
  271. package/dist/presets/cleavr/preset.mjs +0 -12
  272. package/dist/presets/cloudflare/preset.d.ts +0 -3
  273. package/dist/presets/cloudflare/preset.mjs +0 -145
  274. package/dist/presets/cloudflare/runtime/cloudflare-module.d.ts +0 -13
  275. package/dist/presets/cloudflare/runtime/cloudflare-worker.mjs +0 -64
  276. package/dist/presets/cloudflare/types.d.ts +0 -89
  277. package/dist/presets/cloudflare/types.mjs +0 -0
  278. package/dist/presets/cloudflare/types.wrangler.d.ts +0 -974
  279. package/dist/presets/cloudflare/types.wrangler.mjs +0 -0
  280. package/dist/presets/cloudflare/utils.d.ts +0 -3
  281. package/dist/presets/cloudflare/utils.mjs +0 -163
  282. package/dist/presets/deno/preset.d.ts +0 -2
  283. package/dist/presets/deno/preset.mjs +0 -148
  284. package/dist/presets/deno/runtime/_deno-env-polyfill.d.ts +0 -0
  285. package/dist/presets/deno/runtime/_deno-env-polyfill.mjs +0 -1
  286. package/dist/presets/digitalocean/preset.d.ts +0 -2
  287. package/dist/presets/digitalocean/preset.mjs +0 -11
  288. package/dist/presets/edgio/preset.d.ts +0 -2
  289. package/dist/presets/edgio/preset.mjs +0 -95
  290. package/dist/presets/firebase/preset.d.ts +0 -3
  291. package/dist/presets/firebase/preset.mjs +0 -50
  292. package/dist/presets/firebase/runtime/firebase-gen-1.d.ts +0 -2
  293. package/dist/presets/firebase/runtime/firebase-gen-1.mjs +0 -7
  294. package/dist/presets/firebase/runtime/firebase-gen-2.d.ts +0 -2
  295. package/dist/presets/firebase/runtime/firebase-gen-2.mjs +0 -14
  296. package/dist/presets/firebase/runtime/firebase-gen-default.d.ts +0 -1
  297. package/dist/presets/firebase/runtime/firebase-gen-default.mjs +0 -1
  298. package/dist/presets/firebase/types.d.ts +0 -38
  299. package/dist/presets/firebase/types.mjs +0 -0
  300. package/dist/presets/firebase/utils.d.ts +0 -3
  301. package/dist/presets/firebase/utils.mjs +0 -50
  302. package/dist/presets/flightcontrol/preset.d.ts +0 -2
  303. package/dist/presets/flightcontrol/preset.mjs +0 -11
  304. package/dist/presets/heroku/preset.d.ts +0 -2
  305. package/dist/presets/heroku/preset.mjs +0 -11
  306. package/dist/presets/iis/preset.d.ts +0 -2
  307. package/dist/presets/iis/preset.mjs +0 -32
  308. package/dist/presets/iis/utils.d.ts +0 -3
  309. package/dist/presets/iis/utils.mjs +0 -161
  310. package/dist/presets/index.d.mts +0 -1
  311. package/dist/presets/index.d.ts +0 -2
  312. package/dist/presets/index.mjs +0 -1
  313. package/dist/presets/koyeb/preset.d.ts +0 -2
  314. package/dist/presets/koyeb/preset.mjs +0 -11
  315. package/dist/presets/netlify/legacy/preset.d.ts +0 -2
  316. package/dist/presets/netlify/legacy/preset.mjs +0 -143
  317. package/dist/presets/netlify/legacy/runtime/_deno-env-polyfill.d.ts +0 -0
  318. package/dist/presets/netlify/legacy/runtime/_deno-env-polyfill.mjs +0 -1
  319. package/dist/presets/netlify/legacy/runtime/netlify-builder.d.ts +0 -3
  320. package/dist/presets/netlify/legacy/runtime/netlify-builder.mjs +0 -5
  321. package/dist/presets/netlify/legacy/runtime/netlify-edge.d.ts +0 -2
  322. package/dist/presets/netlify/legacy/runtime/netlify-edge.mjs +0 -25
  323. package/dist/presets/netlify/legacy/runtime/netlify-lambda.d.ts +0 -3
  324. package/dist/presets/netlify/legacy/runtime/netlify-lambda.mjs +0 -38
  325. package/dist/presets/netlify/legacy/runtime/netlify.d.ts +0 -4
  326. package/dist/presets/netlify/legacy/runtime/netlify.mjs +0 -22
  327. package/dist/presets/netlify/legacy/utils.d.ts +0 -4
  328. package/dist/presets/netlify/legacy/utils.mjs +0 -113
  329. package/dist/presets/netlify/preset.d.ts +0 -3
  330. package/dist/presets/netlify/preset.mjs +0 -128
  331. package/dist/presets/netlify/runtime/_deno-env-polyfill.d.ts +0 -0
  332. package/dist/presets/netlify/runtime/_deno-env-polyfill.mjs +0 -1
  333. package/dist/presets/netlify/runtime/netlify-edge.d.ts +0 -2
  334. package/dist/presets/netlify/types.d.ts +0 -12
  335. package/dist/presets/netlify/types.mjs +0 -0
  336. package/dist/presets/netlify/utils.d.ts +0 -5
  337. package/dist/presets/netlify/utils.mjs +0 -94
  338. package/dist/presets/node/preset.d.ts +0 -2
  339. package/dist/presets/node/preset.mjs +0 -49
  340. package/dist/presets/node/runtime/cli.d.ts +0 -1
  341. package/dist/presets/node/runtime/cli.mjs +0 -22
  342. package/dist/presets/node/runtime/node-listener.d.ts +0 -6
  343. package/dist/presets/platform.sh/preset.d.ts +0 -2
  344. package/dist/presets/platform.sh/preset.mjs +0 -11
  345. package/dist/presets/render.com/preset.d.ts +0 -2
  346. package/dist/presets/render.com/preset.mjs +0 -11
  347. package/dist/presets/stormkit/preset.d.ts +0 -2
  348. package/dist/presets/stormkit/preset.mjs +0 -15
  349. package/dist/presets/vercel/preset.d.ts +0 -3
  350. package/dist/presets/vercel/preset.mjs +0 -104
  351. package/dist/presets/vercel/runtime/vercel-edge.d.ts +0 -2
  352. package/dist/presets/vercel/runtime/vercel-edge.mjs +0 -22
  353. package/dist/presets/vercel/runtime/vercel.d.ts +0 -4
  354. package/dist/presets/vercel/types.d.ts +0 -78
  355. package/dist/presets/vercel/types.mjs +0 -0
  356. package/dist/presets/vercel/utils.d.ts +0 -5
  357. package/dist/presets/vercel/utils.mjs +0 -186
  358. package/dist/presets/winterjs/preset.d.ts +0 -2
  359. package/dist/presets/winterjs/preset.mjs +0 -20
  360. package/dist/presets/winterjs/runtime/winterjs.d.ts +0 -1
  361. package/dist/presets/zeabur/preset.d.ts +0 -2
  362. package/dist/presets/zeabur/preset.mjs +0 -70
  363. package/dist/presets/zeabur/runtime/zeabur.d.ts +0 -4
  364. package/dist/rollup/index.d.mts +0 -5
  365. package/dist/rollup/index.d.ts +0 -5
  366. package/dist/rollup/index.mjs +0 -1673
  367. package/dist/runtime/index.d.ts +0 -12
  368. package/dist/runtime/internal/app.d.ts +0 -3
  369. package/dist/runtime/internal/cache.d.ts +0 -8
  370. package/dist/runtime/internal/client.mjs +0 -4
  371. package/dist/runtime/internal/config.d.ts +0 -5
  372. package/dist/runtime/internal/config.mjs +0 -45
  373. package/dist/runtime/internal/error.d.ts +0 -4
  374. package/dist/runtime/internal/error.mjs +0 -73
  375. package/dist/runtime/internal/index.d.ts +0 -6
  376. package/dist/runtime/internal/renderer.d.ts +0 -2
  377. package/dist/runtime/internal/route-rules.d.ts +0 -14
  378. package/dist/runtime/internal/routes/openapi.d.ts +0 -3
  379. package/dist/runtime/internal/routes/scalar.d.ts +0 -2
  380. package/dist/runtime/internal/routes/swagger.d.ts +0 -2
  381. package/dist/runtime/internal/static.d.ts +0 -2
  382. package/dist/runtime/internal/timing.mjs +0 -29
  383. package/dist/runtime/internal/utils.d.ts +0 -21
  384. package/dist/runtime/internal/utils.lambda.d.ts +0 -10
  385. package/dist/runtime/internal/utils.lambda.mjs +0 -30
  386. package/dist/shared/nitro.bra5i6ER.d.mts +0 -620
  387. package/dist/shared/nitro.bra5i6ER.d.ts +0 -620
  388. package/dist/types/index.d.ts +0 -260
  389. package/kit.d.ts +0 -1
  390. package/meta.d.ts +0 -1
  391. package/presets.d.ts +0 -1
  392. package/rollup.d.ts +0 -1
  393. package/runtime.d.ts +0 -1
  394. package/types.d.ts +0 -1
  395. /package/dist/presets/_nitro/runtime/{nitro-dev.d.ts → nitro-dev.d.mts} +0 -0
  396. /package/dist/presets/_nitro/runtime/{service-worker.d.ts → service-worker.d.mts} +0 -0
  397. /package/dist/presets/aws-amplify/runtime/{aws-amplify.d.ts → aws-amplify.d.mts} +0 -0
  398. /package/dist/presets/azure/runtime/{azure-functions.d.ts → azure-swa.d.mts} +0 -0
  399. /package/dist/presets/bun/runtime/{bun.d.ts → bun.d.mts} +0 -0
  400. /package/dist/presets/{cloudflare/runtime/cloudflare-worker.d.ts → deno/runtime/deno-deploy.d.mts} +0 -0
  401. /package/dist/presets/netlify/runtime/{netlify.d.ts → netlify.d.mts} +0 -0
  402. /package/dist/presets/node/runtime/{cluster.d.ts → node-cluster.d.mts} +0 -0
  403. /package/dist/presets/{deno/runtime/deno-server.d.ts → node/runtime/node-server.d.mts} +0 -0
  404. /package/dist/presets/stormkit/runtime/{stormkit.d.ts → stormkit.d.mts} +0 -0
  405. /package/dist/presets/{deno/runtime/deno-deploy.d.ts → winterjs/runtime/winterjs.d.mts} +0 -0
  406. /package/dist/runtime/internal/{database.d.ts → database.d.mts} +0 -0
  407. /package/dist/runtime/internal/{debug.d.ts → debug.d.mts} +0 -0
  408. /package/dist/{presets/_types.gen.mjs → runtime/internal/empty.d.mts} +0 -0
  409. /package/dist/{presets/aws-amplify/types.mjs → runtime/internal/empty.mjs} +0 -0
  410. /package/dist/runtime/internal/lib/{http-graceful-shutdown.d.ts → http-graceful-shutdown.d.mts} +0 -0
  411. /package/dist/runtime/internal/{meta.d.ts → meta.d.mts} +0 -0
  412. /package/dist/runtime/internal/{plugin.d.ts → plugin.d.mts} +0 -0
  413. /package/dist/runtime/internal/{shutdown.d.ts → shutdown.d.mts} +0 -0
  414. /package/dist/runtime/internal/{storage.d.ts → storage.d.mts} +0 -0
  415. /package/dist/runtime/internal/{task.d.ts → task.d.mts} +0 -0
  416. /package/dist/runtime/internal/{client.d.ts → vite/dev-worker.d.mts} +0 -0
  417. /package/{dist/config/index.mjs → lib/config.mjs} +0 -0
@@ -1,2456 +0,0 @@
1
- import consola, { consola as consola$1 } from 'consola';
2
- import { createHooks, createDebugger } from 'hookable';
3
- import { runtimeDir, pkgDir } from 'nitro/runtime/meta';
4
- import { join, resolve, relative, normalize, isAbsolute, dirname } from 'pathe';
5
- import { createUnimport } from 'unimport';
6
- import { watchConfig, loadConfig } from 'c12';
7
- import { resolveCompatibilityDatesFromEnv, formatDate, resolveCompatibilityDates, formatCompatibilityDate } from 'compatx';
8
- import { klona } from 'klona/full';
9
- import { isDebug, isTest } from 'std-env';
10
- import { existsSync, promises, accessSync } from 'node:fs';
11
- import defu$1, { defu } from 'defu';
12
- import { withLeadingSlash, withoutTrailingSlash, withTrailingSlash, withBase, parseURL, joinURL, withoutBase } from 'ufo';
13
- import { colors } from 'consola/utils';
14
- import escapeRE from 'escape-string-regexp';
15
- import { resolveModuleExportNames, resolvePath, parseNodeModulePath, lookupNodeModuleSubpath } from 'mlly';
16
- import { resolveNitroPath, isDirectory, writeFile, prettyPath } from 'nitro/kit';
17
- import { findWorkspaceDir } from 'pkg-types';
18
- import { createJiti } from 'jiti';
19
- import { globby } from 'globby';
20
- import fsp, { readFile, writeFile as writeFile$1 } from 'node:fs/promises';
21
- import { ofetch } from 'ofetch';
22
- import { createStorage as createStorage$1, builtinDrivers } from 'unstorage';
23
- import { pathToFileURL } from 'node:url';
24
- import mime from 'mime';
25
- import { toRouteMatcher, createRouter } from 'radix3';
26
- import { getRollupConfig } from 'nitro/rollup';
27
- import { watch } from 'chokidar';
28
- import { debounce } from 'perfect-debounce';
29
- import * as rollup from 'rollup';
30
- import { upperFirst } from 'scule';
31
- import { resolveAlias } from 'pathe/utils';
32
- import { generateTypes, resolveSchema } from 'untyped';
33
- import { version } from 'nitro/meta';
34
- import { gzipSize } from 'gzip-size';
35
- import prettyBytes from 'pretty-bytes';
36
- import zlib from 'node:zlib';
37
- import { Worker } from 'node:worker_threads';
38
- import { setResponseHeader, setResponseStatus, getResponseStatus, getResponseStatusText, send, eventHandler, getRequestHeader, createError, createApp, fromNodeMiddleware, toNodeListener } from 'h3';
39
- import { createProxyServer } from 'httpxy';
40
- import { listen } from 'listhen';
41
- import { servePlaceholder } from 'serve-placeholder';
42
- import serveStatic from 'serve-static';
43
- import fse from 'fs-extra';
44
-
45
- const NitroDefaults = {
46
- // General
47
- debug: isDebug,
48
- timing: isDebug,
49
- logLevel: isTest ? 1 : 3,
50
- runtimeConfig: { app: {}, nitro: {} },
51
- // Dirs
52
- scanDirs: [],
53
- buildDir: ".nitro",
54
- output: {
55
- dir: "{{ rootDir }}/.output",
56
- serverDir: "{{ output.dir }}/server",
57
- publicDir: "{{ output.dir }}/public"
58
- },
59
- // Features
60
- experimental: {
61
- asyncContext: true
62
- },
63
- future: {},
64
- storage: {},
65
- devStorage: {},
66
- bundledStorage: [],
67
- publicAssets: [],
68
- serverAssets: [],
69
- plugins: [],
70
- tasks: {},
71
- scheduledTasks: {},
72
- imports: {
73
- exclude: [],
74
- dirs: [],
75
- presets: [],
76
- virtualImports: ["#imports"]
77
- },
78
- virtual: {},
79
- compressPublicAssets: false,
80
- ignore: [],
81
- // Dev
82
- dev: false,
83
- devServer: { watch: [] },
84
- watchOptions: { ignoreInitial: true },
85
- devProxy: {},
86
- // Logging
87
- logging: {
88
- compressedSizes: true,
89
- buildSuccess: true
90
- },
91
- // Routing
92
- baseURL: process.env.NITRO_APP_BASE_URL || "/",
93
- handlers: [],
94
- devHandlers: [],
95
- errorHandler: join(runtimeDir, "internal/error"),
96
- routeRules: {},
97
- prerender: {
98
- autoSubfolderIndex: true,
99
- concurrency: 1,
100
- interval: 0,
101
- retry: 3,
102
- retryDelay: 500,
103
- failOnError: false,
104
- crawlLinks: false,
105
- ignore: [],
106
- routes: []
107
- },
108
- // Rollup
109
- unenv: {},
110
- analyze: false,
111
- moduleSideEffects: [
112
- "unenv/runtime/polyfill/",
113
- "node-fetch-native/polyfill",
114
- "node-fetch-native/dist/polyfill",
115
- resolve(runtimeDir, "polyfill/")
116
- ],
117
- replace: {},
118
- node: true,
119
- sourceMap: true,
120
- esbuild: {
121
- options: {
122
- jsxFactory: "h",
123
- jsxFragment: "Fragment"
124
- }
125
- },
126
- // Advanced
127
- typescript: {
128
- strict: true,
129
- generateTsConfig: true,
130
- generateRuntimeConfigTypes: true,
131
- tsconfigPath: "types/tsconfig.json",
132
- internalPaths: false,
133
- tsConfig: {}
134
- },
135
- nodeModulesDirs: [],
136
- hooks: {},
137
- commands: {},
138
- // Framework
139
- framework: {
140
- name: "nitro",
141
- version: ""
142
- }
143
- };
144
-
145
- async function resolveAssetsOptions(options) {
146
- for (const publicAsset of options.publicAssets) {
147
- publicAsset.dir = resolve(options.srcDir, publicAsset.dir);
148
- publicAsset.baseURL = withLeadingSlash(
149
- withoutTrailingSlash(publicAsset.baseURL || "/")
150
- );
151
- }
152
- for (const dir of options.scanDirs) {
153
- const publicDir = resolve(dir, "public");
154
- if (!existsSync(publicDir)) {
155
- continue;
156
- }
157
- if (options.publicAssets.some((asset) => asset.dir === publicDir)) {
158
- continue;
159
- }
160
- options.publicAssets.push({ dir: publicDir });
161
- }
162
- for (const serverAsset of options.serverAssets) {
163
- serverAsset.dir = resolve(options.srcDir, serverAsset.dir);
164
- }
165
- options.serverAssets.push({
166
- baseName: "server",
167
- dir: resolve(options.srcDir, "assets")
168
- });
169
- for (const asset of options.publicAssets) {
170
- asset.baseURL = asset.baseURL || "/";
171
- const isTopLevel = asset.baseURL === "/";
172
- asset.fallthrough = asset.fallthrough ?? isTopLevel;
173
- const routeRule = options.routeRules[asset.baseURL + "/**"];
174
- asset.maxAge = routeRule?.cache?.maxAge ?? asset.maxAge ?? 0;
175
- if (asset.maxAge && !asset.fallthrough) {
176
- options.routeRules[asset.baseURL + "/**"] = defu(routeRule, {
177
- headers: {
178
- "cache-control": `public, max-age=${asset.maxAge}, immutable`
179
- }
180
- });
181
- }
182
- }
183
- }
184
-
185
- const fallbackCompatibilityDate = "2024-04-03";
186
- async function resolveCompatibilityOptions(options) {
187
- options.compatibilityDate = resolveCompatibilityDatesFromEnv(
188
- options.compatibilityDate
189
- );
190
- if (!options.compatibilityDate.default && options.preset !== "nitro-prerender") {
191
- options.compatibilityDate.default = await _resolveDefault(options);
192
- }
193
- }
194
- let _fallbackInfoShown = false;
195
- let _promptedUserToUpdate = false;
196
- async function _resolveDefault(options) {
197
- const _todayDate = formatDate(/* @__PURE__ */ new Date());
198
- const consola$1 = consola.withTag("nitro");
199
- consola$1.warn(`No valid compatibility date is specified.`);
200
- const onFallback = () => {
201
- if (!_fallbackInfoShown) {
202
- consola$1.info(
203
- [
204
- `Using \`${fallbackCompatibilityDate}\` as fallback.`,
205
- ` Please specify compatibility date to avoid unwanted behavior changes:`,
206
- ` - Add \`compatibilityDate: '${_todayDate}'\` to the config file.`,
207
- ` - Or set \`COMPATIBILITY_DATE=${_todayDate}\` environment variable.`,
208
- ``
209
- ].join("\n")
210
- );
211
- _fallbackInfoShown = true;
212
- }
213
- return fallbackCompatibilityDate;
214
- };
215
- const shallUpdate = options._cli?.command === "dev" && !_promptedUserToUpdate && await consola$1.prompt(
216
- `Do you want to auto update config file to set ${colors.cyan(`compatibilityDate: '${_todayDate}'`)}?`,
217
- {
218
- type: "confirm",
219
- default: true
220
- }
221
- );
222
- _promptedUserToUpdate = true;
223
- if (!shallUpdate) {
224
- return onFallback();
225
- }
226
- const { updateConfig } = await import('c12/update');
227
- const updateResult = await updateConfig({
228
- configFile: "nitro.config",
229
- cwd: options.rootDir,
230
- async onCreate({ configFile }) {
231
- const shallCreate = await consola$1.prompt(
232
- `Do you want to initialize a new config in ${colors.cyan(relative(".", configFile))}?`,
233
- {
234
- type: "confirm",
235
- default: true
236
- }
237
- );
238
- if (shallCreate !== true) {
239
- return false;
240
- }
241
- return _getDefaultNitroConfig();
242
- },
243
- async onUpdate(config) {
244
- config.compatibilityDate = _todayDate;
245
- }
246
- }).catch((error) => {
247
- consola$1.error(`Failed to update config: ${error.message}`);
248
- return null;
249
- });
250
- if (updateResult?.configFile) {
251
- consola$1.success(
252
- `Compatibility date set to \`${_todayDate}\` in \`${relative(".", updateResult.configFile)}\``
253
- );
254
- return _todayDate;
255
- }
256
- return onFallback();
257
- }
258
- function _getDefaultNitroConfig() {
259
- return (
260
- /* js */
261
- `
262
- import { defineNitroConfig } from 'nitro/config'
263
-
264
- export default defineNitroConfig({})
265
- `
266
- );
267
- }
268
-
269
- async function resolveDatabaseOptions(options) {
270
- if (options.experimental.database && options.imports) {
271
- options.imports.presets.push({
272
- from: "nitro/runtime",
273
- imports: ["useDatabase"]
274
- });
275
- if (options.dev && !options.database && !options.devDatabase) {
276
- options.devDatabase = {
277
- default: {
278
- connector: "sqlite",
279
- options: {
280
- cwd: options.rootDir
281
- }
282
- }
283
- };
284
- } else if (options.node && !options.database) {
285
- options.database = {
286
- default: {
287
- connector: "sqlite",
288
- options: {}
289
- }
290
- };
291
- }
292
- }
293
- }
294
-
295
- async function resolveExportConditionsOptions(options) {
296
- options.exportConditions = _resolveExportConditions(
297
- options.exportConditions || [],
298
- { dev: options.dev, node: options.node, wasm: options.experimental.wasm }
299
- );
300
- }
301
- function _resolveExportConditions(conditions, opts) {
302
- const resolvedConditions = [];
303
- resolvedConditions.push(opts.dev ? "development" : "production");
304
- resolvedConditions.push(...conditions);
305
- if (opts.node) {
306
- resolvedConditions.push("node");
307
- } else {
308
- resolvedConditions.push(
309
- "wintercg",
310
- "worker",
311
- "web",
312
- "browser",
313
- "workerd",
314
- "edge-light",
315
- "netlify",
316
- "edge-routine",
317
- "deno"
318
- );
319
- }
320
- if (opts.wasm) {
321
- resolvedConditions.push("wasm", "unwasm");
322
- }
323
- resolvedConditions.push("import", "default");
324
- return resolvedConditions.filter(
325
- (c, i) => resolvedConditions.indexOf(c) === i
326
- );
327
- }
328
-
329
- async function resolveFetchOptions(options) {
330
- options.alias = {
331
- "node-fetch-native/polyfill": "unenv/runtime/mock/empty",
332
- "node-fetch-native": "node-fetch-native/native",
333
- ...options.alias
334
- };
335
- }
336
-
337
- async function resolveImportsOptions(options) {
338
- if (options.imports === false) {
339
- return;
340
- }
341
- options.imports.presets ??= [];
342
- options.imports.presets.push(...getNitroImportsPreset());
343
- const h3Exports = await resolveModuleExportNames("h3", {
344
- url: import.meta.url
345
- });
346
- options.imports.presets ??= [];
347
- options.imports.presets.push({
348
- from: "h3",
349
- imports: h3Exports.filter((n) => !/^[A-Z]/.test(n) && n !== "use")
350
- });
351
- options.imports.dirs ??= [];
352
- options.imports.dirs.push(
353
- ...options.scanDirs.map((dir) => join(dir, "utils/*"))
354
- );
355
- if (Array.isArray(options.imports.exclude) && options.imports.exclude.length === 0) {
356
- options.imports.exclude.push(/[/\\]\.git[/\\]/);
357
- options.imports.exclude.push(options.buildDir);
358
- const scanDirsInNodeModules = options.scanDirs.map((dir) => dir.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean);
359
- options.imports.exclude.push(
360
- scanDirsInNodeModules.length > 0 ? new RegExp(
361
- `node_modules\\/(?!${scanDirsInNodeModules.map((dir) => escapeRE(dir)).join("|")})`
362
- ) : /[/\\]node_modules[/\\]/
363
- );
364
- }
365
- }
366
- function getNitroImportsPreset() {
367
- return [
368
- {
369
- from: "nitro/runtime",
370
- imports: [
371
- "defineCachedFunction",
372
- "defineCachedEventHandler",
373
- "cachedFunction",
374
- "cachedEventHandler",
375
- "useRuntimeConfig",
376
- "useStorage",
377
- "useNitroApp",
378
- "defineNitroPlugin",
379
- "nitroPlugin",
380
- "defineRenderHandler",
381
- "defineRouteMeta",
382
- "getRouteRules",
383
- "useEvent",
384
- "defineTask",
385
- "runTask",
386
- "defineNitroErrorHandler"
387
- ]
388
- }
389
- ];
390
- }
391
-
392
- async function resolveOpenAPIOptions(options) {
393
- if (!options.experimental.openAPI) {
394
- return;
395
- }
396
- if (!options.dev && !options.openAPI?.production) {
397
- return;
398
- }
399
- const shouldPrerender = !options.dev && options.openAPI?.production === "prerender";
400
- const handlersEnv = shouldPrerender ? "prerender" : "";
401
- const prerenderRoutes = [];
402
- const jsonRoute = options.openAPI?.route || "/_openapi.json";
403
- prerenderRoutes.push(jsonRoute);
404
- options.handlers.push({
405
- route: jsonRoute,
406
- env: handlersEnv,
407
- handler: join(runtimeDir, "internal/routes/openapi")
408
- });
409
- if (options.openAPI?.ui?.scalar !== false) {
410
- const scalarRoute = options.openAPI?.ui?.scalar?.route || "/_scalar";
411
- prerenderRoutes.push(scalarRoute);
412
- options.handlers.push({
413
- route: options.openAPI?.ui?.scalar?.route || "/_scalar",
414
- env: handlersEnv,
415
- handler: join(runtimeDir, "internal/routes/scalar")
416
- });
417
- }
418
- if (options.openAPI?.ui?.swagger !== false) {
419
- const swaggerRoute = options.openAPI?.ui?.swagger?.route || "/_swagger";
420
- prerenderRoutes.push(swaggerRoute);
421
- options.handlers.push({
422
- route: swaggerRoute,
423
- env: handlersEnv,
424
- handler: join(runtimeDir, "internal/routes/swagger")
425
- });
426
- }
427
- if (shouldPrerender) {
428
- options.prerender ??= {};
429
- options.prerender.routes ??= [];
430
- options.prerender.routes.push(...prerenderRoutes);
431
- }
432
- }
433
-
434
- async function resolvePathOptions(options) {
435
- options.rootDir = resolve(options.rootDir || ".");
436
- options.workspaceDir = await findWorkspaceDir(options.rootDir).catch(
437
- () => options.rootDir
438
- );
439
- options.srcDir = resolve(options.srcDir || options.rootDir);
440
- for (const key of ["srcDir", "buildDir"]) {
441
- options[key] = resolve(options.rootDir, options[key]);
442
- }
443
- options.alias = {
444
- ...options.alias,
445
- "~/": join(options.srcDir, "/"),
446
- "@/": join(options.srcDir, "/"),
447
- "~~/": join(options.rootDir, "/"),
448
- "@@/": join(options.rootDir, "/")
449
- };
450
- if (!options.static && !options.entry) {
451
- throw new Error(
452
- `Nitro entry is missing! Is "${options.preset}" preset correct?`
453
- );
454
- }
455
- if (options.entry) {
456
- options.entry = resolveNitroPath(options.entry, options);
457
- }
458
- options.output.dir = resolveNitroPath(
459
- options.output.dir || NitroDefaults.output.dir,
460
- options,
461
- options.rootDir
462
- );
463
- options.output.publicDir = resolveNitroPath(
464
- options.output.publicDir || NitroDefaults.output.publicDir,
465
- options,
466
- options.rootDir
467
- );
468
- options.output.serverDir = resolveNitroPath(
469
- options.output.serverDir || NitroDefaults.output.serverDir,
470
- options,
471
- options.rootDir
472
- );
473
- options.nodeModulesDirs.push(resolve(options.workspaceDir, "node_modules"));
474
- options.nodeModulesDirs.push(resolve(options.rootDir, "node_modules"));
475
- options.nodeModulesDirs.push(resolve(pkgDir, "node_modules"));
476
- options.nodeModulesDirs.push(resolve(pkgDir, ".."));
477
- options.nodeModulesDirs = [
478
- ...new Set(
479
- options.nodeModulesDirs.map((dir) => resolve(options.rootDir, dir))
480
- )
481
- ];
482
- options.plugins = options.plugins.map((p) => resolveNitroPath(p, options));
483
- options.scanDirs.unshift(options.srcDir);
484
- options.scanDirs = options.scanDirs.map(
485
- (dir) => resolve(options.srcDir, dir)
486
- );
487
- options.scanDirs = [...new Set(options.scanDirs)];
488
- }
489
-
490
- async function resolveRouteRulesOptions(options) {
491
- options.routeRules = defu(options.routeRules, options.routes || {});
492
- options.routeRules = normalizeRouteRules(options);
493
- }
494
- function normalizeRouteRules(config) {
495
- const normalizedRules = {};
496
- for (const path in config.routeRules) {
497
- const routeConfig = config.routeRules[path];
498
- const routeRules = {
499
- ...routeConfig,
500
- redirect: void 0,
501
- proxy: void 0
502
- };
503
- if (routeConfig.redirect) {
504
- routeRules.redirect = {
505
- // @ts-ignore
506
- to: "/",
507
- statusCode: 307,
508
- ...typeof routeConfig.redirect === "string" ? { to: routeConfig.redirect } : routeConfig.redirect
509
- };
510
- if (path.endsWith("/**")) {
511
- routeRules.redirect._redirectStripBase = path.slice(0, -3);
512
- }
513
- }
514
- if (routeConfig.proxy) {
515
- routeRules.proxy = typeof routeConfig.proxy === "string" ? { to: routeConfig.proxy } : routeConfig.proxy;
516
- if (path.endsWith("/**")) {
517
- routeRules.proxy._proxyStripBase = path.slice(0, -3);
518
- }
519
- }
520
- if (routeConfig.cors) {
521
- routeRules.headers = {
522
- "access-control-allow-origin": "*",
523
- "access-control-allow-methods": "*",
524
- "access-control-allow-headers": "*",
525
- "access-control-max-age": "0",
526
- ...routeRules.headers
527
- };
528
- }
529
- if (routeConfig.swr) {
530
- routeRules.cache = routeRules.cache || {};
531
- routeRules.cache.swr = true;
532
- if (typeof routeConfig.swr === "number") {
533
- routeRules.cache.maxAge = routeConfig.swr;
534
- }
535
- }
536
- if (routeConfig.cache === false) {
537
- routeRules.cache = false;
538
- }
539
- normalizedRules[path] = routeRules;
540
- }
541
- return normalizedRules;
542
- }
543
-
544
- async function resolveRuntimeConfigOptions(options) {
545
- options.runtimeConfig = normalizeRuntimeConfig(options);
546
- }
547
- function normalizeRuntimeConfig(config) {
548
- provideFallbackValues(config.runtimeConfig || {});
549
- const runtimeConfig = defu$1(
550
- config.runtimeConfig,
551
- {
552
- app: {
553
- baseURL: config.baseURL
554
- },
555
- nitro: {
556
- envExpansion: config.experimental?.envExpansion,
557
- openAPI: config.openAPI
558
- }
559
- }
560
- );
561
- runtimeConfig.nitro.routeRules = config.routeRules;
562
- checkSerializableRuntimeConfig(runtimeConfig);
563
- return runtimeConfig;
564
- }
565
- function provideFallbackValues(obj) {
566
- for (const key in obj) {
567
- if (obj[key] === void 0 || obj[key] === null) {
568
- obj[key] = "";
569
- } else if (typeof obj[key] === "object") {
570
- provideFallbackValues(obj[key]);
571
- }
572
- }
573
- }
574
- function checkSerializableRuntimeConfig(obj, path = []) {
575
- for (const key in obj) {
576
- const value = obj[key];
577
- if (value === null || typeof value === "string" || value === void 0 || typeof value === "number" || typeof value === "boolean") {
578
- continue;
579
- }
580
- if (Array.isArray(value)) {
581
- for (const [index, item] of value.entries())
582
- checkSerializableRuntimeConfig(item, [...path, `${key}[${index}]`]);
583
- } else if (typeof value === "object" && value.constructor === Object && (!value.constructor?.name || value.constructor.name === "Object")) {
584
- checkSerializableRuntimeConfig(value, [...path, key]);
585
- } else {
586
- console.warn(
587
- `Runtime config option \`${[...path, key].join(".")}\` may not be able to be serialized.`
588
- );
589
- }
590
- }
591
- }
592
-
593
- async function resolveURLOptions(options) {
594
- options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL));
595
- }
596
-
597
- const configResolvers = [
598
- resolveCompatibilityOptions,
599
- resolvePathOptions,
600
- resolveImportsOptions,
601
- resolveRouteRulesOptions,
602
- resolveDatabaseOptions,
603
- resolveFetchOptions,
604
- resolveExportConditionsOptions,
605
- resolveRuntimeConfigOptions,
606
- resolveOpenAPIOptions,
607
- resolveURLOptions,
608
- resolveAssetsOptions
609
- ];
610
- async function loadOptions(configOverrides = {}, opts = {}) {
611
- const options = await _loadUserConfig(configOverrides, opts);
612
- for (const resolver of configResolvers) {
613
- await resolver(options);
614
- }
615
- return options;
616
- }
617
- async function _loadUserConfig(configOverrides = {}, opts = {}) {
618
- let presetOverride = configOverrides.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET;
619
- if (configOverrides.dev) {
620
- presetOverride = "nitro-dev";
621
- }
622
- configOverrides = klona(configOverrides);
623
- globalThis.defineNitroConfig = globalThis.defineNitroConfig || ((c) => c);
624
- let compatibilityDate = configOverrides.compatibilityDate || opts.compatibilityDate || (process.env.NITRO_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE);
625
- const { resolvePreset } = await import('nitro/presets');
626
- const loadedConfig = await (opts.watch ? watchConfig : loadConfig)({
627
- name: "nitro",
628
- cwd: configOverrides.rootDir,
629
- dotenv: configOverrides.dev,
630
- extend: { extendKey: ["extends", "preset"] },
631
- overrides: {
632
- ...configOverrides,
633
- preset: presetOverride
634
- },
635
- async defaultConfig({ configs }) {
636
- if (!compatibilityDate) {
637
- compatibilityDate = configs.main?.compatibilityDate || configs.rc?.compatibilityDate || configs.packageJson?.compatibilityDate;
638
- }
639
- return {
640
- preset: (await resolvePreset("", {
641
- static: configOverrides.static,
642
- compatibilityDate: compatibilityDate || fallbackCompatibilityDate
643
- }))?._meta?.name
644
- };
645
- },
646
- defaults: NitroDefaults,
647
- jitiOptions: {
648
- alias: {
649
- nitropack: "nitro/config",
650
- "nitro/config": "nitro/config"
651
- }
652
- },
653
- async resolve(id) {
654
- const preset = await resolvePreset(id, {
655
- static: configOverrides.static,
656
- compatibilityDate: compatibilityDate || fallbackCompatibilityDate
657
- });
658
- if (preset) {
659
- return {
660
- config: preset
661
- };
662
- }
663
- },
664
- ...opts.c12
665
- });
666
- const options = klona(loadedConfig.config);
667
- options._config = configOverrides;
668
- options._c12 = loadedConfig;
669
- const _presetName = (loadedConfig.layers || []).find((l) => l.config?._meta?.name)?.config?._meta?.name || presetOverride;
670
- options.preset = _presetName;
671
- options.compatibilityDate = resolveCompatibilityDates(
672
- compatibilityDate,
673
- options.compatibilityDate
674
- );
675
- return options;
676
- }
677
-
678
- async function updateNitroConfig(nitro, config) {
679
- nitro.options.routeRules = normalizeRouteRules(
680
- config.routeRules ? config : nitro.options
681
- );
682
- nitro.options.runtimeConfig = normalizeRuntimeConfig(
683
- config.runtimeConfig ? config : nitro.options
684
- );
685
- await nitro.hooks.callHook("rollup:reload");
686
- consola.success("Nitro config hot reloaded!");
687
- }
688
-
689
- async function installModules(nitro) {
690
- const _modules = [...nitro.options.modules || []];
691
- const modules = await Promise.all(
692
- _modules.map((mod) => _resolveNitroModule(mod, nitro.options))
693
- );
694
- const _installedURLs = /* @__PURE__ */ new Set();
695
- for (const mod of modules) {
696
- if (mod._url) {
697
- if (_installedURLs.has(mod._url)) {
698
- continue;
699
- }
700
- _installedURLs.add(mod._url);
701
- }
702
- await mod.setup(nitro);
703
- }
704
- }
705
- async function _resolveNitroModule(mod, nitroOptions) {
706
- let _url;
707
- if (typeof mod === "string") {
708
- globalThis.defineNitroModule = // @ts-ignore
709
- globalThis.defineNitroModule || ((mod2) => mod2);
710
- const jiti = createJiti(nitroOptions.rootDir, {
711
- interopDefault: true,
712
- alias: nitroOptions.alias
713
- });
714
- const _modPath = jiti.esmResolve(mod);
715
- _url = _modPath;
716
- mod = await jiti.import(_modPath);
717
- }
718
- if (typeof mod === "function") {
719
- mod = { setup: mod };
720
- }
721
- if (!mod.setup) {
722
- mod.setup = () => {
723
- };
724
- }
725
- return {
726
- _url,
727
- ...mod
728
- };
729
- }
730
-
731
- const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
732
- const suffixRegex = /\.(connect|delete|get|head|options|patch|post|put|trace)(\.(dev|prod|prerender))?$/;
733
- async function scanAndSyncOptions(nitro) {
734
- const scannedPlugins = await scanPlugins(nitro);
735
- for (const plugin of scannedPlugins) {
736
- if (!nitro.options.plugins.includes(plugin)) {
737
- nitro.options.plugins.push(plugin);
738
- }
739
- }
740
- if (nitro.options.experimental.tasks) {
741
- const scannedTasks = await scanTasks(nitro);
742
- for (const scannedTask of scannedTasks) {
743
- if (scannedTask.name in nitro.options.tasks) {
744
- if (!nitro.options.tasks[scannedTask.name].handler) {
745
- nitro.options.tasks[scannedTask.name].handler = scannedTask.handler;
746
- }
747
- } else {
748
- nitro.options.tasks[scannedTask.name] = {
749
- handler: scannedTask.handler,
750
- description: ""
751
- };
752
- }
753
- }
754
- }
755
- const scannedModules = await scanModules(nitro);
756
- nitro.options.modules = nitro.options.modules || [];
757
- for (const modPath of scannedModules) {
758
- if (!nitro.options.modules.includes(modPath)) {
759
- nitro.options.modules.push(modPath);
760
- }
761
- }
762
- }
763
- async function scanHandlers(nitro) {
764
- const middleware = await scanMiddleware(nitro);
765
- const handlers = await Promise.all([
766
- scanServerRoutes(
767
- nitro,
768
- nitro.options.apiDir || "api",
769
- nitro.options.apiBaseURL || "/api"
770
- ),
771
- scanServerRoutes(nitro, nitro.options.routesDir || "routes")
772
- ]).then((r) => r.flat());
773
- nitro.scannedHandlers = [
774
- ...middleware,
775
- ...handlers.filter((h, index, array) => {
776
- return array.findIndex(
777
- (h2) => h.route === h2.route && h.method === h2.method && h.env === h2.env
778
- ) === index;
779
- })
780
- ];
781
- return handlers;
782
- }
783
- async function scanMiddleware(nitro) {
784
- const files = await scanFiles(nitro, "middleware");
785
- return files.map((file) => {
786
- return {
787
- middleware: true,
788
- handler: file.fullPath
789
- };
790
- });
791
- }
792
- async function scanServerRoutes(nitro, dir, prefix = "/") {
793
- const files = await scanFiles(nitro, dir);
794
- return files.map((file) => {
795
- let route = file.path.replace(/\.[A-Za-z]+$/, "").replace(/\[\.{3}]/g, "**").replace(/\[\.{3}(\w+)]/g, "**:$1").replace(/\[(\w+)]/g, ":$1");
796
- route = withLeadingSlash(withoutTrailingSlash(withBase(route, prefix)));
797
- const suffixMatch = route.match(suffixRegex);
798
- let method;
799
- let env;
800
- if (suffixMatch?.index) {
801
- route = route.slice(0, Math.max(0, suffixMatch.index));
802
- method = suffixMatch[1];
803
- env = suffixMatch[3];
804
- }
805
- route = route.replace(/\/index$/, "") || "/";
806
- return {
807
- handler: file.fullPath,
808
- lazy: true,
809
- middleware: false,
810
- route,
811
- method,
812
- env
813
- };
814
- });
815
- }
816
- async function scanPlugins(nitro) {
817
- const files = await scanFiles(nitro, "plugins");
818
- return files.map((f) => f.fullPath);
819
- }
820
- async function scanTasks(nitro) {
821
- const files = await scanFiles(nitro, "tasks");
822
- return files.map((f) => {
823
- const name = f.path.replace(/\/index$/, "").replace(/\.[A-Za-z]+$/, "").replace(/\//g, ":");
824
- return { name, handler: f.fullPath };
825
- });
826
- }
827
- async function scanModules(nitro) {
828
- const files = await scanFiles(nitro, "modules", [
829
- "*/index.{js,mjs,cjs,ts,mts,cts}",
830
- "*.{js,mjs,cjs,ts,mts,cts}"
831
- ]);
832
- return files.map((f) => f.fullPath);
833
- }
834
- async function scanFiles(nitro, name, patterns = [GLOB_SCAN_PATTERN]) {
835
- const files = await Promise.all(
836
- nitro.options.scanDirs.map((dir) => scanDir(nitro, dir, name, patterns))
837
- ).then((r) => r.flat());
838
- return files;
839
- }
840
- async function scanDir(nitro, dir, name, patterns) {
841
- const globbyPattern = [];
842
- for (const pattern of Array.isArray(patterns) ? patterns : [patterns]) {
843
- globbyPattern.push(join(name, pattern));
844
- }
845
- const fileNames = await globby(globbyPattern, {
846
- cwd: dir,
847
- dot: true,
848
- ignore: nitro.options.ignore,
849
- absolute: true
850
- });
851
- return fileNames.map((fullPath) => {
852
- return {
853
- fullPath,
854
- path: relative(join(dir, name), fullPath)
855
- };
856
- }).sort((a, b) => a.path.localeCompare(b.path));
857
- }
858
-
859
- async function runTask(taskEvent, opts) {
860
- const ctx = await _getTasksContext(opts);
861
- const result = await ctx.devFetch(`/_nitro/tasks/${taskEvent.name}`, {
862
- method: "POST",
863
- body: taskEvent
864
- });
865
- return result;
866
- }
867
- async function listTasks(opts) {
868
- const ctx = await _getTasksContext(opts);
869
- const res = await ctx.devFetch("/_nitro/tasks");
870
- return res.tasks;
871
- }
872
- function addNitroTasksVirtualFile(nitro) {
873
- nitro.options.virtual["#nitro-internal-virtual/tasks"] = () => {
874
- const _scheduledTasks = Object.entries(nitro.options.scheduledTasks || {}).map(([cron, _tasks]) => {
875
- const tasks = (Array.isArray(_tasks) ? _tasks : [_tasks]).filter(
876
- (name) => {
877
- if (!nitro.options.tasks[name]) {
878
- nitro.logger.warn(`Scheduled task \`${name}\` is not defined!`);
879
- return false;
880
- }
881
- return true;
882
- }
883
- );
884
- return { cron, tasks };
885
- }).filter((e) => e.tasks.length > 0);
886
- const scheduledTasks = _scheduledTasks.length > 0 ? _scheduledTasks : false;
887
- return (
888
- /* js */
889
- `
890
- export const scheduledTasks = ${JSON.stringify(scheduledTasks)};
891
-
892
- export const tasks = {
893
- ${Object.entries(nitro.options.tasks).map(
894
- ([name, task]) => `"${name}": {
895
- meta: {
896
- description: ${JSON.stringify(task.description)},
897
- },
898
- resolve: ${task.handler ? `() => import("${normalize(
899
- task.handler
900
- )}").then(r => r.default || r)` : "undefined"},
901
- }`
902
- ).join(",\n")}
903
- };`
904
- );
905
- };
906
- }
907
- const _devHint = `(is dev server running?)`;
908
- async function _getTasksContext(opts) {
909
- const cwd = resolve(process.cwd(), opts?.cwd || ".");
910
- const outDir = resolve(cwd, opts?.buildDir || ".nitro");
911
- const buildInfoPath = resolve(outDir, "nitro.json");
912
- if (!existsSync(buildInfoPath)) {
913
- throw new Error(`Missing info file: \`${buildInfoPath}\` ${_devHint}`);
914
- }
915
- const buildInfo = JSON.parse(
916
- await readFile(buildInfoPath, "utf8")
917
- );
918
- if (!buildInfo.dev?.pid || !buildInfo.dev?.workerAddress) {
919
- throw new Error(
920
- `Missing dev server info in: \`${buildInfoPath}\` ${_devHint}`
921
- );
922
- }
923
- if (!_pidIsRunning(buildInfo.dev.pid)) {
924
- throw new Error(`Dev server is not running (pid: ${buildInfo.dev.pid})`);
925
- }
926
- const devFetch = ofetch.create({
927
- baseURL: `http://${buildInfo.dev.workerAddress.host || "localhost"}:${buildInfo.dev.workerAddress.port || "3000"}`,
928
- // @ts-expect-error
929
- socketPath: buildInfo.dev.workerAddress.socketPath
930
- });
931
- return {
932
- buildInfo,
933
- devFetch
934
- };
935
- }
936
- function _pidIsRunning(pid) {
937
- try {
938
- process.kill(pid, 0);
939
- return true;
940
- } catch {
941
- return false;
942
- }
943
- }
944
-
945
- async function createStorage(nitro) {
946
- const storage = createStorage$1();
947
- const mounts = {
948
- ...nitro.options.storage,
949
- ...nitro.options.devStorage
950
- };
951
- for (const [path, opts] of Object.entries(mounts)) {
952
- if (opts.driver) {
953
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
954
- storage.mount(path, driver(opts));
955
- } else {
956
- nitro.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
957
- }
958
- }
959
- return storage;
960
- }
961
- async function snapshotStorage(nitro) {
962
- const data = {};
963
- const allKeys = [
964
- ...new Set(
965
- await Promise.all(
966
- nitro.options.bundledStorage.map((base) => nitro.storage.getKeys(base))
967
- ).then((r) => r.flat())
968
- )
969
- ];
970
- await Promise.all(
971
- allKeys.map(async (key) => {
972
- data[key] = await nitro.storage.getItem(key);
973
- })
974
- );
975
- return data;
976
- }
977
-
978
- async function createNitro(config = {}, opts = {}) {
979
- const options = await loadOptions(config, opts);
980
- const nitro = {
981
- options,
982
- hooks: createHooks(),
983
- vfs: {},
984
- logger: consola$1.withTag("nitro"),
985
- scannedHandlers: [],
986
- close: () => nitro.hooks.callHook("close"),
987
- storage: void 0,
988
- async updateConfig(config2) {
989
- updateNitroConfig(nitro, config2);
990
- }
991
- };
992
- await scanAndSyncOptions(nitro);
993
- nitro.storage = await createStorage(nitro);
994
- nitro.hooks.hook("close", async () => {
995
- await nitro.storage.dispose();
996
- });
997
- if (nitro.options.debug) {
998
- createDebugger(nitro.hooks, { tag: "nitro" });
999
- nitro.options.plugins.push(join(runtimeDir, "internal/debug"));
1000
- }
1001
- if (nitro.options.timing) {
1002
- nitro.options.plugins.push(join(runtimeDir, "internal/timing"));
1003
- }
1004
- if (nitro.options.logLevel !== void 0) {
1005
- nitro.logger.level = nitro.options.logLevel;
1006
- }
1007
- nitro.hooks.addHooks(nitro.options.hooks);
1008
- addNitroTasksVirtualFile(nitro);
1009
- if (nitro.options.imports) {
1010
- nitro.unimport = createUnimport(nitro.options.imports);
1011
- await nitro.unimport.init();
1012
- nitro.options.virtual["#imports"] = () => nitro.unimport?.toExports() || "";
1013
- nitro.options.virtual["#nitro"] = 'export * from "#imports"';
1014
- }
1015
- await installModules(nitro);
1016
- await scanHandlers(nitro);
1017
- return nitro;
1018
- }
1019
-
1020
- function nitroServerName(nitro) {
1021
- return nitro.options.framework.name === "nitro" ? "Nitro Server" : `${upperFirst(nitro.options.framework.name)} Nitro server`;
1022
- }
1023
-
1024
- function formatRollupError(_error) {
1025
- try {
1026
- const logs = [_error.toString()];
1027
- const errors = _error?.errors || [_error];
1028
- for (const error of errors) {
1029
- const id = error.path || error.id || _error.id;
1030
- let path = isAbsolute(id) ? relative(process.cwd(), id) : id;
1031
- const location = error.loc || error.location;
1032
- if (location) {
1033
- path += `:${location.line}:${location.column}`;
1034
- }
1035
- const text = error.text || error.frame;
1036
- logs.push(
1037
- `Rollup error while processing \`${path}\`` + text ? "\n\n" + text : ""
1038
- );
1039
- }
1040
- return logs.join("\n");
1041
- } catch {
1042
- return _error?.toString();
1043
- }
1044
- }
1045
-
1046
- async function writeTypes(nitro) {
1047
- const types = {
1048
- routes: {}
1049
- };
1050
- const typesDir = resolve(nitro.options.buildDir, "types");
1051
- const middleware = [...nitro.scannedHandlers, ...nitro.options.handlers];
1052
- for (const mw of middleware) {
1053
- if (typeof mw.handler !== "string" || !mw.route) {
1054
- continue;
1055
- }
1056
- const relativePath = relative(
1057
- typesDir,
1058
- resolveNitroPath(mw.handler, nitro.options)
1059
- ).replace(/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/, "");
1060
- const method = mw.method || "default";
1061
- types.routes[mw.route] ??= {};
1062
- types.routes[mw.route][method] ??= [];
1063
- types.routes[mw.route][method].push(
1064
- `Simplify<Serialize<Awaited<ReturnType<typeof import('${relativePath}').default>>>>`
1065
- );
1066
- }
1067
- let autoImportedTypes = [];
1068
- let autoImportExports = "";
1069
- if (nitro.unimport) {
1070
- await nitro.unimport.init();
1071
- autoImportExports = await nitro.unimport.toExports(typesDir).then(
1072
- (r) => r.replace(/#internal\/nitro/g, relative(typesDir, runtimeDir))
1073
- );
1074
- const resolvedImportPathMap = /* @__PURE__ */ new Map();
1075
- const imports = await nitro.unimport.getImports().then((r) => r.filter((i) => !i.type));
1076
- for (const i of imports) {
1077
- if (resolvedImportPathMap.has(i.from)) {
1078
- continue;
1079
- }
1080
- let path = resolveAlias(i.from, nitro.options.alias);
1081
- if (!isAbsolute(path)) {
1082
- const resolvedPath = await resolvePath(i.from, {
1083
- url: nitro.options.nodeModulesDirs
1084
- }).catch(() => null);
1085
- if (resolvedPath) {
1086
- const { dir, name } = parseNodeModulePath(resolvedPath);
1087
- if (!dir || !name) {
1088
- path = resolvedPath;
1089
- } else {
1090
- const subpath = await lookupNodeModuleSubpath(resolvedPath);
1091
- path = join(dir, name, subpath || "");
1092
- }
1093
- }
1094
- }
1095
- if (existsSync(path) && !await isDirectory(path)) {
1096
- path = path.replace(/\.[a-z]+$/, "");
1097
- }
1098
- if (isAbsolute(path)) {
1099
- path = relative(typesDir, path);
1100
- }
1101
- resolvedImportPathMap.set(i.from, path);
1102
- }
1103
- autoImportedTypes = [
1104
- nitro.options.imports && nitro.options.imports.autoImport !== false ? (await nitro.unimport.generateTypeDeclarations({
1105
- exportHelper: false,
1106
- resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
1107
- })).trim() : ""
1108
- ];
1109
- }
1110
- await nitro.hooks.callHook("types:extend", types);
1111
- const routes = [
1112
- "// Generated by nitro",
1113
- 'import type { Serialize, Simplify } from "nitro/types";',
1114
- 'declare module "nitro/types" {',
1115
- " type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T",
1116
- " interface InternalApi {",
1117
- ...Object.entries(types.routes).map(
1118
- ([path, methods]) => [
1119
- ` '${path}': {`,
1120
- ...Object.entries(methods).map(
1121
- ([method, types2]) => ` '${method}': ${types2.join(" | ")}`
1122
- ),
1123
- " }"
1124
- ].join("\n")
1125
- ),
1126
- " }",
1127
- "}",
1128
- // Makes this a module for augmentation purposes
1129
- "export {}"
1130
- ];
1131
- const config = [
1132
- "// Generated by nitro",
1133
- `
1134
- declare module "nitro/types" {
1135
- `,
1136
- nitro.options.typescript.generateRuntimeConfigTypes ? generateTypes(
1137
- await resolveSchema(
1138
- Object.fromEntries(
1139
- Object.entries(nitro.options.runtimeConfig).filter(
1140
- ([key]) => !["app", "nitro"].includes(key)
1141
- )
1142
- )
1143
- ),
1144
- {
1145
- interfaceName: "NitroRuntimeConfig",
1146
- addExport: false,
1147
- addDefaults: false,
1148
- allowExtraKeys: false,
1149
- indentation: 2
1150
- }
1151
- ) : "",
1152
- `}`,
1153
- // Makes this a module for augmentation purposes
1154
- "export {}"
1155
- ];
1156
- const declarations = [
1157
- // local nitro augmentations
1158
- '/// <reference path="./nitro-routes.d.ts" />',
1159
- '/// <reference path="./nitro-config.d.ts" />',
1160
- // global server auto-imports
1161
- '/// <reference path="./nitro-imports.d.ts" />'
1162
- ];
1163
- const buildFiles = [];
1164
- buildFiles.push({
1165
- path: join(typesDir, "nitro-routes.d.ts"),
1166
- contents: routes.join("\n")
1167
- });
1168
- buildFiles.push({
1169
- path: join(typesDir, "nitro-config.d.ts"),
1170
- contents: config.join("\n")
1171
- });
1172
- buildFiles.push({
1173
- path: join(typesDir, "nitro-imports.d.ts"),
1174
- contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
1175
- "\n"
1176
- )
1177
- });
1178
- buildFiles.push({
1179
- path: join(typesDir, "nitro.d.ts"),
1180
- contents: declarations.join("\n")
1181
- });
1182
- if (nitro.options.typescript.generateTsConfig) {
1183
- const tsConfigPath = resolve(
1184
- nitro.options.buildDir,
1185
- nitro.options.typescript.tsconfigPath
1186
- );
1187
- const tsconfigDir = dirname(tsConfigPath);
1188
- const tsConfig = defu(nitro.options.typescript.tsConfig, {
1189
- compilerOptions: {
1190
- /* Base options: */
1191
- esModuleInterop: true,
1192
- allowSyntheticDefaultImports: true,
1193
- skipLibCheck: true,
1194
- target: "ESNext",
1195
- allowJs: true,
1196
- resolveJsonModule: true,
1197
- moduleDetection: "force",
1198
- isolatedModules: true,
1199
- verbatimModuleSyntax: true,
1200
- /* Strictness */
1201
- strict: nitro.options.typescript.strict,
1202
- noUncheckedIndexedAccess: true,
1203
- noImplicitOverride: true,
1204
- forceConsistentCasingInFileNames: true,
1205
- /* If NOT transpiling with TypeScript: */
1206
- // TODO: consider using 'module: preserve' (requires TS 5.4+)
1207
- module: "ESNext",
1208
- noEmit: true,
1209
- moduleResolution: nitro.options.experimental.typescriptBundlerResolution === false ? "Node" : "Bundler",
1210
- /* JSX support */
1211
- jsx: "preserve",
1212
- jsxFactory: "h",
1213
- jsxFragmentFactory: "Fragment",
1214
- allowImportingTsExtensions: true,
1215
- paths: {
1216
- "#imports": [
1217
- relativeWithDot(tsconfigDir, join(typesDir, "nitro-imports"))
1218
- ],
1219
- "~/*": [
1220
- relativeWithDot(
1221
- tsconfigDir,
1222
- join(nitro.options.alias["~"] || nitro.options.srcDir, "*")
1223
- )
1224
- ],
1225
- "@/*": [
1226
- relativeWithDot(
1227
- tsconfigDir,
1228
- join(nitro.options.alias["@"] || nitro.options.srcDir, "*")
1229
- )
1230
- ],
1231
- "~~/*": [
1232
- relativeWithDot(
1233
- tsconfigDir,
1234
- join(nitro.options.alias["~~"] || nitro.options.rootDir, "*")
1235
- )
1236
- ],
1237
- "@@/*": [
1238
- relativeWithDot(
1239
- tsconfigDir,
1240
- join(nitro.options.alias["@@"] || nitro.options.rootDir, "*")
1241
- )
1242
- ],
1243
- ...nitro.options.typescript.internalPaths ? {
1244
- "nitro/runtime": [
1245
- relativeWithDot(tsconfigDir, join(runtimeDir, "index"))
1246
- ],
1247
- "#internal/nitro": [
1248
- relativeWithDot(tsconfigDir, join(runtimeDir, "index"))
1249
- ]
1250
- } : {}
1251
- }
1252
- },
1253
- include: [
1254
- relativeWithDot(tsconfigDir, join(typesDir, "nitro.d.ts")).replace(
1255
- /^(?=[^.])/,
1256
- "./"
1257
- ),
1258
- join(relativeWithDot(tsconfigDir, nitro.options.rootDir), "**/*"),
1259
- ...nitro.options.srcDir === nitro.options.rootDir ? [] : [join(relativeWithDot(tsconfigDir, nitro.options.srcDir), "**/*")]
1260
- ]
1261
- });
1262
- for (const alias in tsConfig.compilerOptions.paths) {
1263
- const paths = tsConfig.compilerOptions.paths[alias];
1264
- tsConfig.compilerOptions.paths[alias] = await Promise.all(
1265
- paths.map(async (path) => {
1266
- if (!isAbsolute(path)) {
1267
- return path;
1268
- }
1269
- const stats = await promises.stat(path).catch(
1270
- () => null
1271
- /* file does not exist */
1272
- );
1273
- return relativeWithDot(
1274
- tsconfigDir,
1275
- stats?.isFile() ? path.replace(/(?<=\w)\.\w+$/g, "") : path
1276
- );
1277
- })
1278
- );
1279
- }
1280
- tsConfig.include = [
1281
- ...new Set(
1282
- tsConfig.include.map(
1283
- (p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p
1284
- )
1285
- )
1286
- ];
1287
- if (tsConfig.exclude) {
1288
- tsConfig.exclude = [
1289
- ...new Set(
1290
- tsConfig.exclude.map(
1291
- (p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p
1292
- )
1293
- )
1294
- ];
1295
- }
1296
- buildFiles.push({
1297
- path: tsConfigPath,
1298
- contents: JSON.stringify(tsConfig, null, 2)
1299
- });
1300
- }
1301
- await Promise.all(
1302
- buildFiles.map(async (file) => {
1303
- await writeFile(
1304
- resolve(nitro.options.buildDir, file.path),
1305
- file.contents
1306
- );
1307
- })
1308
- );
1309
- }
1310
- const RELATIVE_RE = /^\.{1,2}\//;
1311
- function relativeWithDot(from, to) {
1312
- const rel = relative(from, to);
1313
- return RELATIVE_RE.test(rel) ? rel : "./" + rel;
1314
- }
1315
-
1316
- async function watchDev(nitro, rollupConfig) {
1317
- let rollupWatcher;
1318
- async function load() {
1319
- if (rollupWatcher) {
1320
- await rollupWatcher.close();
1321
- }
1322
- await scanHandlers(nitro);
1323
- rollupWatcher = startRollupWatcher(nitro, rollupConfig);
1324
- await writeTypes(nitro);
1325
- }
1326
- const reload = debounce(load);
1327
- const watchPatterns = nitro.options.scanDirs.flatMap((dir) => [
1328
- join(dir, nitro.options.apiDir || "api"),
1329
- join(dir, nitro.options.routesDir || "routes"),
1330
- join(dir, "middleware", GLOB_SCAN_PATTERN),
1331
- join(dir, "plugins"),
1332
- join(dir, "modules")
1333
- ]);
1334
- const watchReloadEvents = /* @__PURE__ */ new Set(["add", "addDir", "unlink", "unlinkDir"]);
1335
- const reloadWatcher = watch(watchPatterns, { ignoreInitial: true }).on(
1336
- "all",
1337
- (event) => {
1338
- if (watchReloadEvents.has(event)) {
1339
- reload();
1340
- }
1341
- }
1342
- );
1343
- nitro.hooks.hook("close", () => {
1344
- rollupWatcher.close();
1345
- reloadWatcher.close();
1346
- });
1347
- nitro.hooks.hook("rollup:reload", () => reload());
1348
- await load();
1349
- }
1350
- function startRollupWatcher(nitro, rollupConfig) {
1351
- const watcher = rollup.watch(
1352
- defu$1(rollupConfig, {
1353
- watch: {
1354
- chokidar: nitro.options.watchOptions
1355
- }
1356
- })
1357
- );
1358
- let start;
1359
- watcher.on("event", (event) => {
1360
- switch (event.code) {
1361
- // The watcher is (re)starting
1362
- case "START": {
1363
- return;
1364
- }
1365
- // Building an individual bundle
1366
- case "BUNDLE_START": {
1367
- start = Date.now();
1368
- return;
1369
- }
1370
- // Finished building all bundles
1371
- case "END": {
1372
- nitro.hooks.callHook("compiled", nitro);
1373
- if (nitro.options.logging.buildSuccess) {
1374
- nitro.logger.success(
1375
- `${nitroServerName(nitro)} built`,
1376
- start ? `in ${Date.now() - start} ms` : ""
1377
- );
1378
- }
1379
- nitro.hooks.callHook("dev:reload");
1380
- return;
1381
- }
1382
- // Encountered an error while bundling
1383
- case "ERROR": {
1384
- nitro.logger.error(formatRollupError(event.error));
1385
- }
1386
- }
1387
- });
1388
- return watcher;
1389
- }
1390
-
1391
- async function runParallel(inputs, cb, opts) {
1392
- const tasks = /* @__PURE__ */ new Set();
1393
- function queueNext() {
1394
- const route = inputs.values().next().value;
1395
- if (!route) {
1396
- return;
1397
- }
1398
- inputs.delete(route);
1399
- const task = (opts.interval ? new Promise((resolve) => setTimeout(resolve, opts.interval)) : Promise.resolve()).then(() => cb(route)).catch((error) => {
1400
- console.error(error);
1401
- });
1402
- tasks.add(task);
1403
- return task.then(() => {
1404
- tasks.delete(task);
1405
- if (inputs.size > 0) {
1406
- return refillQueue();
1407
- }
1408
- });
1409
- }
1410
- function refillQueue() {
1411
- const workers = Math.min(opts.concurrency - tasks.size, inputs.size);
1412
- return Promise.all(Array.from({ length: workers }, () => queueNext()));
1413
- }
1414
- await refillQueue();
1415
- }
1416
-
1417
- async function generateFSTree(dir, options = {}) {
1418
- if (isTest) {
1419
- return;
1420
- }
1421
- const files = await globby("**/*.*", { cwd: dir, ignore: ["*.map"] });
1422
- const items = [];
1423
- await runParallel(
1424
- new Set(files),
1425
- async (file) => {
1426
- const path = resolve(dir, file);
1427
- const src = await promises.readFile(path);
1428
- const size = src.byteLength;
1429
- const gzip = options.compressedSizes ? await gzipSize(src) : 0;
1430
- items.push({ file, path, size, gzip });
1431
- },
1432
- { concurrency: 10 }
1433
- );
1434
- items.sort((a, b) => a.path.localeCompare(b.path));
1435
- let totalSize = 0;
1436
- let totalGzip = 0;
1437
- let totalNodeModulesSize = 0;
1438
- let totalNodeModulesGzip = 0;
1439
- let treeText = "";
1440
- for (const [index, item] of items.entries()) {
1441
- dirname(item.file);
1442
- const rpath = relative(process.cwd(), item.path);
1443
- const treeChar = index === items.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
1444
- const isNodeModules = item.file.includes("node_modules");
1445
- if (isNodeModules) {
1446
- totalNodeModulesSize += item.size;
1447
- totalNodeModulesGzip += item.gzip;
1448
- continue;
1449
- }
1450
- treeText += colors.gray(
1451
- ` ${treeChar} ${rpath} (${prettyBytes(item.size)})`
1452
- );
1453
- if (options.compressedSizes) {
1454
- treeText += colors.gray(` (${prettyBytes(item.gzip)} gzip)`);
1455
- }
1456
- treeText += "\n";
1457
- totalSize += item.size;
1458
- totalGzip += item.gzip;
1459
- }
1460
- treeText += `${colors.cyan("\u03A3 Total size:")} ${prettyBytes(
1461
- totalSize + totalNodeModulesSize
1462
- )}`;
1463
- if (options.compressedSizes) {
1464
- treeText += ` (${prettyBytes(totalGzip + totalNodeModulesGzip)} gzip)`;
1465
- }
1466
- treeText += "\n";
1467
- return treeText;
1468
- }
1469
-
1470
- async function buildProduction(nitro, rollupConfig) {
1471
- await scanHandlers(nitro);
1472
- await writeTypes(nitro);
1473
- await _snapshot(nitro);
1474
- if (!nitro.options.static) {
1475
- nitro.logger.info(
1476
- `Building ${nitroServerName(nitro)} (preset: \`${nitro.options.preset}\`, compatibility date: \`${formatCompatibilityDate(nitro.options.compatibilityDate)}\`)`
1477
- );
1478
- const build = await rollup.rollup(rollupConfig).catch((error) => {
1479
- nitro.logger.error(formatRollupError(error));
1480
- throw error;
1481
- });
1482
- await build.write(rollupConfig.output);
1483
- }
1484
- const buildInfoPath = resolve(nitro.options.output.dir, "nitro.json");
1485
- const buildInfo = {
1486
- date: (/* @__PURE__ */ new Date()).toJSON(),
1487
- preset: nitro.options.preset,
1488
- framework: nitro.options.framework,
1489
- versions: {
1490
- nitro: version
1491
- },
1492
- commands: {
1493
- preview: nitro.options.commands.preview,
1494
- deploy: nitro.options.commands.deploy
1495
- }
1496
- };
1497
- await writeFile(buildInfoPath, JSON.stringify(buildInfo, null, 2));
1498
- if (!nitro.options.static) {
1499
- if (nitro.options.logging.buildSuccess) {
1500
- nitro.logger.success(`${nitroServerName(nitro)} built`);
1501
- }
1502
- if (nitro.options.logLevel > 1) {
1503
- process.stdout.write(
1504
- await generateFSTree(nitro.options.output.serverDir, {
1505
- compressedSizes: nitro.options.logging.compressedSizes
1506
- }) || ""
1507
- );
1508
- }
1509
- }
1510
- await nitro.hooks.callHook("compiled", nitro);
1511
- const rOutput = relative(process.cwd(), nitro.options.output.dir);
1512
- const rewriteRelativePaths = (input) => {
1513
- return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
1514
- };
1515
- if (buildInfo.commands.preview) {
1516
- nitro.logger.success(
1517
- `You can preview this build using \`${rewriteRelativePaths(
1518
- buildInfo.commands.preview
1519
- )}\``
1520
- );
1521
- }
1522
- if (buildInfo.commands.deploy) {
1523
- nitro.logger.success(
1524
- `You can deploy this build using \`${rewriteRelativePaths(
1525
- buildInfo.commands.deploy
1526
- )}\``
1527
- );
1528
- }
1529
- }
1530
- async function _snapshot(nitro) {
1531
- if (nitro.options.bundledStorage.length === 0 || nitro.options.preset === "nitro-prerender") {
1532
- return;
1533
- }
1534
- const storageDir = resolve(nitro.options.buildDir, "snapshot");
1535
- nitro.options.serverAssets.push({
1536
- baseName: "nitro:bundled",
1537
- dir: storageDir
1538
- });
1539
- const data = await snapshotStorage(nitro);
1540
- await Promise.all(
1541
- Object.entries(data).map(async ([path, contents]) => {
1542
- if (typeof contents !== "string") {
1543
- contents = JSON.stringify(contents);
1544
- }
1545
- const fsPath = join(storageDir, path.replace(/:/g, "/"));
1546
- await promises.mkdir(dirname(fsPath), { recursive: true });
1547
- await promises.writeFile(fsPath, contents, "utf8");
1548
- })
1549
- );
1550
- }
1551
-
1552
- async function build(nitro) {
1553
- const rollupConfig = getRollupConfig(nitro);
1554
- await nitro.hooks.callHook("rollup:before", nitro, rollupConfig);
1555
- return nitro.options.dev ? watchDev(nitro, rollupConfig) : buildProduction(nitro, rollupConfig);
1556
- }
1557
-
1558
- async function compressPublicAssets(nitro) {
1559
- const publicFiles = await globby("**", {
1560
- cwd: nitro.options.output.publicDir,
1561
- absolute: false,
1562
- dot: true,
1563
- ignore: ["**/*.gz", "**/*.br"]
1564
- });
1565
- await Promise.all(
1566
- publicFiles.map(async (fileName) => {
1567
- const filePath = resolve(nitro.options.output.publicDir, fileName);
1568
- if (existsSync(filePath + ".gz") || existsSync(filePath + ".br")) {
1569
- return;
1570
- }
1571
- const mimeType = mime.getType(fileName) || "text/plain";
1572
- const fileContents = await fsp.readFile(filePath);
1573
- if (fileContents.length < 1024 || fileName.endsWith(".map") || !isCompressibleMime(mimeType)) {
1574
- return;
1575
- }
1576
- const { gzip, brotli } = nitro.options.compressPublicAssets || {};
1577
- const encodings = [
1578
- gzip !== false && "gzip",
1579
- brotli !== false && "br"
1580
- ].filter(Boolean);
1581
- await Promise.all(
1582
- encodings.map(async (encoding) => {
1583
- const suffix = "." + (encoding === "gzip" ? "gz" : "br");
1584
- const compressedPath = filePath + suffix;
1585
- if (existsSync(compressedPath)) {
1586
- return;
1587
- }
1588
- const gzipOptions = { level: zlib.constants.Z_BEST_COMPRESSION };
1589
- const brotliOptions = {
1590
- [zlib.constants.BROTLI_PARAM_MODE]: isTextMime(mimeType) ? zlib.constants.BROTLI_MODE_TEXT : zlib.constants.BROTLI_MODE_GENERIC,
1591
- [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
1592
- [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fileContents.length
1593
- };
1594
- const compressedBuff = await new Promise(
1595
- (resolve2, reject) => {
1596
- const cb = (error, result) => error ? reject(error) : resolve2(result);
1597
- if (encoding === "gzip") {
1598
- zlib.gzip(fileContents, gzipOptions, cb);
1599
- } else {
1600
- zlib.brotliCompress(fileContents, brotliOptions, cb);
1601
- }
1602
- }
1603
- );
1604
- await fsp.writeFile(compressedPath, compressedBuff);
1605
- })
1606
- );
1607
- })
1608
- );
1609
- }
1610
- function isTextMime(mimeType) {
1611
- return /text|javascript|json|xml/.test(mimeType);
1612
- }
1613
- const COMPRESSIBLE_MIMES_RE = /* @__PURE__ */ new Set([
1614
- "application/dash+xml",
1615
- "application/eot",
1616
- "application/font",
1617
- "application/font-sfnt",
1618
- "application/javascript",
1619
- "application/json",
1620
- "application/opentype",
1621
- "application/otf",
1622
- "application/pdf",
1623
- "application/pkcs7-mime",
1624
- "application/protobuf",
1625
- "application/rss+xml",
1626
- "application/truetype",
1627
- "application/ttf",
1628
- "application/vnd.apple.mpegurl",
1629
- "application/vnd.mapbox-vector-tile",
1630
- "application/vnd.ms-fontobject",
1631
- "application/wasm",
1632
- "application/xhtml+xml",
1633
- "application/xml",
1634
- "application/x-font-opentype",
1635
- "application/x-font-truetype",
1636
- "application/x-font-ttf",
1637
- "application/x-httpd-cgi",
1638
- "application/x-javascript",
1639
- "application/x-mpegurl",
1640
- "application/x-opentype",
1641
- "application/x-otf",
1642
- "application/x-perl",
1643
- "application/x-ttf",
1644
- "font/eot",
1645
- "font/opentype",
1646
- "font/otf",
1647
- "font/ttf",
1648
- "image/svg+xml",
1649
- "text/css",
1650
- "text/csv",
1651
- "text/html",
1652
- "text/javascript",
1653
- "text/js",
1654
- "text/plain",
1655
- "text/richtext",
1656
- "text/tab-separated-values",
1657
- "text/xml",
1658
- "text/x-component",
1659
- "text/x-java-source",
1660
- "text/x-script",
1661
- "vnd.apple.mpegurl"
1662
- ]);
1663
- function isCompressibleMime(mimeType) {
1664
- return COMPRESSIBLE_MIMES_RE.has(mimeType);
1665
- }
1666
-
1667
- const allowedExtensions = /* @__PURE__ */ new Set(["", ".json"]);
1668
- const linkParents$1 = /* @__PURE__ */ new Map();
1669
- const LINK_REGEX = /(?<=\s)href=(?!&quot;)["']?([^"'>]+)/g;
1670
- const HTML_ENTITIES = {
1671
- "&lt;": "<",
1672
- "&gt;": ">",
1673
- "&amp;": "&",
1674
- "&apos;": "'",
1675
- "&quot;": '"'
1676
- };
1677
- function escapeHtml(text) {
1678
- return text.replace(
1679
- /&(lt|gt|amp|apos|quot);/g,
1680
- (ch) => HTML_ENTITIES[ch] || ch
1681
- );
1682
- }
1683
- function extractLinks(html, from, res, crawlLinks) {
1684
- const links = [];
1685
- const _links = [];
1686
- if (crawlLinks) {
1687
- _links.push(
1688
- ...[...html.matchAll(LINK_REGEX)].map((m) => escapeHtml(m[1])).filter((m) => !decodeURIComponent(m).startsWith("#")).filter((link) => allowedExtensions.has(getExtension(link)))
1689
- );
1690
- }
1691
- const header = res.headers.get("x-nitro-prerender") || "";
1692
- _links.push(...header.split(",").map((i) => decodeURIComponent(i.trim())));
1693
- for (const link of _links.filter(Boolean)) {
1694
- const _link = parseURL(link);
1695
- if (_link.protocol || _link.host) {
1696
- continue;
1697
- }
1698
- if (!_link.pathname.startsWith("/")) {
1699
- const fromURL = new URL(from, "http://localhost");
1700
- _link.pathname = new URL(_link.pathname, fromURL).pathname;
1701
- }
1702
- links.push(_link.pathname + _link.search);
1703
- }
1704
- for (const link of links) {
1705
- const _parents = linkParents$1.get(link);
1706
- if (_parents) {
1707
- _parents.add(from);
1708
- } else {
1709
- linkParents$1.set(link, /* @__PURE__ */ new Set([from]));
1710
- }
1711
- }
1712
- return links;
1713
- }
1714
- const EXT_REGEX = /\.[\da-z]+$/;
1715
- function getExtension(link) {
1716
- const pathname = parseURL(link).pathname;
1717
- return (pathname.match(EXT_REGEX) || [])[0] || "";
1718
- }
1719
- function formatPrerenderRoute(route) {
1720
- let str = ` \u251C\u2500 ${route.route} (${route.generateTimeMS}ms)`;
1721
- if (route.error) {
1722
- const parents = linkParents$1.get(route.route);
1723
- const errorColor = colors[route.error.statusCode === 404 ? "yellow" : "red"];
1724
- const errorLead = parents?.size ? "\u251C\u2500\u2500" : "\u2514\u2500\u2500";
1725
- str += `
1726
- \u2502 ${errorLead} ${errorColor(route.error.message)}`;
1727
- if (parents?.size) {
1728
- str += `
1729
- ${[...parents.values()].map((link) => ` \u2502 \u2514\u2500\u2500 Linked from ${link}`).join("\n")}`;
1730
- }
1731
- }
1732
- if (route.skip) {
1733
- str += colors.gray(" (skipped)");
1734
- }
1735
- return colors.gray(str);
1736
- }
1737
- function matchesIgnorePattern(path, pattern) {
1738
- if (typeof pattern === "string") {
1739
- return path.startsWith(pattern);
1740
- }
1741
- if (typeof pattern === "function") {
1742
- return pattern(path) === true;
1743
- }
1744
- if (pattern instanceof RegExp) {
1745
- return pattern.test(path);
1746
- }
1747
- return false;
1748
- }
1749
-
1750
- const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
1751
- const linkParents = /* @__PURE__ */ new Map();
1752
- async function prerender(nitro) {
1753
- if (nitro.options.noPublicDir) {
1754
- console.warn(
1755
- "[nitro] Skipping prerender since `noPublicDir` option is enabled."
1756
- );
1757
- return;
1758
- }
1759
- const routes = new Set(nitro.options.prerender.routes);
1760
- const prerenderRulePaths = Object.entries(nitro.options.routeRules).filter(([path2, options]) => options.prerender && !path2.includes("*")).map((e) => e[0]);
1761
- for (const route of prerenderRulePaths) {
1762
- routes.add(route);
1763
- }
1764
- await nitro.hooks.callHook("prerender:routes", routes);
1765
- if (routes.size === 0) {
1766
- if (nitro.options.prerender.crawlLinks) {
1767
- routes.add("/");
1768
- } else {
1769
- return;
1770
- }
1771
- }
1772
- nitro.logger.info("Initializing prerenderer");
1773
- nitro._prerenderedRoutes = [];
1774
- nitro._prerenderMeta = nitro._prerenderMeta || {};
1775
- const prerendererConfig = {
1776
- ...nitro.options._config,
1777
- static: false,
1778
- rootDir: nitro.options.rootDir,
1779
- logLevel: 0,
1780
- preset: "nitro-prerender"
1781
- };
1782
- await nitro.hooks.callHook("prerender:config", prerendererConfig);
1783
- const nitroRenderer = await createNitro(prerendererConfig);
1784
- const prerenderStartTime = Date.now();
1785
- await nitro.hooks.callHook("prerender:init", nitroRenderer);
1786
- let path = relative(nitro.options.output.dir, nitro.options.output.publicDir);
1787
- if (!path.startsWith(".")) {
1788
- path = `./${path}`;
1789
- }
1790
- nitroRenderer.options.commands.preview = `npx serve ${path}`;
1791
- nitroRenderer.options.output.dir = nitro.options.output.dir;
1792
- await build(nitroRenderer);
1793
- const serverFilename = typeof nitroRenderer.options.rollupConfig?.output?.entryFileNames === "string" ? nitroRenderer.options.rollupConfig.output.entryFileNames : "index.mjs";
1794
- const serverEntrypoint = resolve(
1795
- nitroRenderer.options.output.serverDir,
1796
- serverFilename
1797
- );
1798
- const { closePrerenderer, localFetch } = await import(pathToFileURL(serverEntrypoint).href);
1799
- const _routeRulesMatcher = toRouteMatcher(
1800
- createRouter({ routes: nitro.options.routeRules })
1801
- );
1802
- const _getRouteRules = (path2) => defu({}, ..._routeRulesMatcher.matchAll(path2).reverse());
1803
- const generatedRoutes = /* @__PURE__ */ new Set();
1804
- const failedRoutes = /* @__PURE__ */ new Set();
1805
- const skippedRoutes = /* @__PURE__ */ new Set();
1806
- const displayedLengthWarns = /* @__PURE__ */ new Set();
1807
- const canPrerender = (route = "/") => {
1808
- if (generatedRoutes.has(route) || skippedRoutes.has(route)) {
1809
- return false;
1810
- }
1811
- for (const pattern of nitro.options.prerender.ignore) {
1812
- if (matchesIgnorePattern(route, pattern)) {
1813
- return false;
1814
- }
1815
- }
1816
- if (_getRouteRules(route).prerender === false) {
1817
- return false;
1818
- }
1819
- return true;
1820
- };
1821
- const canWriteToDisk = (route) => {
1822
- if (route.route.includes("?")) {
1823
- return false;
1824
- }
1825
- const FS_MAX_SEGMENT = 255;
1826
- const FS_MAX_PATH = 1024;
1827
- const FS_MAX_PATH_PUBLIC_HTML = FS_MAX_PATH - (nitro.options.output.publicDir.length + 10);
1828
- if ((route.route.length >= FS_MAX_PATH_PUBLIC_HTML || route.route.split("/").some((s) => s.length > FS_MAX_SEGMENT)) && !displayedLengthWarns.has(route)) {
1829
- displayedLengthWarns.add(route);
1830
- const _route = route.route.slice(0, 60) + "...";
1831
- if (route.route.length >= FS_MAX_PATH_PUBLIC_HTML) {
1832
- nitro.logger.warn(
1833
- `Prerendering long route "${_route}" (${route.route.length}) can cause filesystem issues since it exceeds ${FS_MAX_PATH_PUBLIC_HTML}-character limit when writing to \`${nitro.options.output.publicDir}\`.`
1834
- );
1835
- } else {
1836
- nitro.logger.warn(
1837
- `Skipping prerender of the route "${_route}" since it exceeds the ${FS_MAX_SEGMENT}-character limit in one of the path segments and can cause filesystem issues.`
1838
- );
1839
- return false;
1840
- }
1841
- }
1842
- return true;
1843
- };
1844
- const generateRoute = async (route) => {
1845
- const start = Date.now();
1846
- route = decodeURI(route);
1847
- if (!canPrerender(route)) {
1848
- skippedRoutes.add(route);
1849
- return;
1850
- }
1851
- generatedRoutes.add(route);
1852
- const _route = { route };
1853
- const encodedRoute = encodeURI(route);
1854
- const res = await localFetch(
1855
- withBase(encodedRoute, nitro.options.baseURL),
1856
- {
1857
- headers: { "x-nitro-prerender": encodedRoute },
1858
- retry: nitro.options.prerender.retry,
1859
- retryDelay: nitro.options.prerender.retryDelay
1860
- }
1861
- );
1862
- let dataBuff = Buffer.from(await res.arrayBuffer());
1863
- Object.defineProperty(_route, "contents", {
1864
- get: () => {
1865
- return dataBuff ? dataBuff.toString("utf8") : void 0;
1866
- },
1867
- set(value) {
1868
- if (dataBuff) {
1869
- dataBuff = Buffer.from(value);
1870
- }
1871
- }
1872
- });
1873
- Object.defineProperty(_route, "data", {
1874
- get: () => {
1875
- return dataBuff ? dataBuff.buffer : void 0;
1876
- },
1877
- set(value) {
1878
- if (dataBuff) {
1879
- dataBuff = Buffer.from(value);
1880
- }
1881
- }
1882
- });
1883
- const redirectCodes = [301, 302, 303, 304, 307, 308];
1884
- if (![200, ...redirectCodes].includes(res.status)) {
1885
- _route.error = new Error(`[${res.status}] ${res.statusText}`);
1886
- _route.error.statusCode = res.status;
1887
- _route.error.statusMessage = res.statusText;
1888
- }
1889
- _route.generateTimeMS = Date.now() - start;
1890
- const contentType = res.headers.get("content-type") || "";
1891
- const isImplicitHTML = !route.endsWith(".html") && contentType.includes("html") && !JsonSigRx.test(dataBuff.subarray(0, 32).toString("utf8"));
1892
- const routeWithIndex = route.endsWith("/") ? route + "index" : route;
1893
- const htmlPath = route.endsWith("/") || nitro.options.prerender.autoSubfolderIndex ? joinURL(route, "index.html") : route + ".html";
1894
- _route.fileName = withoutBase(
1895
- isImplicitHTML ? htmlPath : routeWithIndex,
1896
- nitro.options.baseURL
1897
- );
1898
- const inferredContentType = mime.getType(_route.fileName) || "text/plain";
1899
- _route.contentType = contentType || inferredContentType;
1900
- await nitro.hooks.callHook("prerender:generate", _route, nitro);
1901
- if (_route.contentType !== inferredContentType) {
1902
- nitro._prerenderMeta[_route.fileName] ||= {};
1903
- nitro._prerenderMeta[_route.fileName].contentType = _route.contentType;
1904
- }
1905
- if (_route.error) {
1906
- failedRoutes.add(_route);
1907
- }
1908
- if (_route.skip || _route.error) {
1909
- await nitro.hooks.callHook("prerender:route", _route);
1910
- nitro.logger.log(formatPrerenderRoute(_route));
1911
- dataBuff = void 0;
1912
- return _route;
1913
- }
1914
- if (canWriteToDisk(_route)) {
1915
- const filePath = join(nitro.options.output.publicDir, _route.fileName);
1916
- await writeFile(filePath, dataBuff);
1917
- nitro._prerenderedRoutes.push(_route);
1918
- } else {
1919
- _route.skip = true;
1920
- }
1921
- if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) {
1922
- const extractedLinks = extractLinks(
1923
- dataBuff.toString("utf8"),
1924
- route,
1925
- res,
1926
- nitro.options.prerender.crawlLinks
1927
- );
1928
- for (const _link of extractedLinks) {
1929
- if (canPrerender(_link)) {
1930
- routes.add(_link);
1931
- }
1932
- }
1933
- }
1934
- await nitro.hooks.callHook("prerender:route", _route);
1935
- nitro.logger.log(formatPrerenderRoute(_route));
1936
- dataBuff = void 0;
1937
- return _route;
1938
- };
1939
- nitro.logger.info(
1940
- nitro.options.prerender.crawlLinks ? `Prerendering ${routes.size} initial routes with crawler` : `Prerendering ${routes.size} routes`
1941
- );
1942
- await runParallel(routes, generateRoute, {
1943
- concurrency: nitro.options.prerender.concurrency,
1944
- interval: nitro.options.prerender.interval
1945
- });
1946
- await closePrerenderer();
1947
- await nitro.hooks.callHook("prerender:done", {
1948
- prerenderedRoutes: nitro._prerenderedRoutes,
1949
- failedRoutes: [...failedRoutes]
1950
- });
1951
- if (nitro.options.prerender.failOnError && failedRoutes.size > 0) {
1952
- nitro.logger.log("\nErrors prerendering:");
1953
- for (const route of failedRoutes) {
1954
- const parents = linkParents.get(route.route);
1955
- parents?.size ? `
1956
- ${[...parents.values()].map((link) => colors.gray(` \u2502 \u2514\u2500\u2500 Linked from ${link}`)).join("\n")}` : "";
1957
- nitro.logger.log(formatPrerenderRoute(route));
1958
- }
1959
- nitro.logger.log("");
1960
- throw new Error("Exiting due to prerender errors.");
1961
- }
1962
- const prerenderTimeInMs = Date.now() - prerenderStartTime;
1963
- nitro.logger.info(
1964
- `Prerendered ${nitro._prerenderedRoutes.length} routes in ${prerenderTimeInMs / 1e3} seconds`
1965
- );
1966
- if (nitro.options.compressPublicAssets) {
1967
- await compressPublicAssets(nitro);
1968
- }
1969
- }
1970
-
1971
- function errorHandler(error, event) {
1972
- setResponseHeader(event, "Content-Type", "text/html; charset=UTF-8");
1973
- setResponseStatus(event, 503, "Server Unavailable");
1974
- let body;
1975
- let title;
1976
- if (error) {
1977
- title = `${getResponseStatus(event)} ${getResponseStatusText(event)}`;
1978
- body = `<code><pre>${error.stack}</pre></code>`;
1979
- } else {
1980
- title = "Reloading server...";
1981
- body = "<progress></progress><script>document.querySelector('progress').indeterminate=true<\/script>";
1982
- }
1983
- return send(
1984
- event,
1985
- `<!DOCTYPE html>
1986
- <html lang="en">
1987
- <head>
1988
- <meta charset="utf-8">
1989
- <meta name="viewport" content="width=device-width, initial-scale=1">
1990
- ${error ? "" : '<meta http-equiv="refresh" content="2">'}
1991
- <title>${title}</title>
1992
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico/css/pico.min.css">
1993
- </head>
1994
- <body>
1995
- <main class="container">
1996
- <article>
1997
- <header>
1998
- <h2>${title}</h2>
1999
- </header>
2000
- ${body}
2001
- <footer>
2002
- Check console logs for more information.
2003
- </footer>
2004
- </article>
2005
- </main>
2006
- </body>
2007
- </html>
2008
- `
2009
- );
2010
- }
2011
-
2012
- function createVFSHandler(nitro) {
2013
- return eventHandler(async (event) => {
2014
- const vfsEntries = {
2015
- ...nitro.vfs,
2016
- ...nitro.options.virtual
2017
- };
2018
- const url = event.path || "";
2019
- const isJson = url.endsWith(".json") || getRequestHeader(event, "accept")?.includes("application/json");
2020
- const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || "");
2021
- if (id && !(id in vfsEntries)) {
2022
- throw createError({ message: "File not found", statusCode: 404 });
2023
- }
2024
- let content = id ? vfsEntries[id] : void 0;
2025
- if (typeof content === "function") {
2026
- content = await content();
2027
- }
2028
- if (isJson) {
2029
- return {
2030
- rootDir: nitro.options.rootDir,
2031
- entries: Object.keys(vfsEntries).map((id2) => ({
2032
- id: id2,
2033
- path: "/_vfs.json/" + encodeURIComponent(id2)
2034
- })),
2035
- current: id ? {
2036
- id,
2037
- content
2038
- } : null
2039
- };
2040
- }
2041
- const directories = { [nitro.options.rootDir]: {} };
2042
- const fpaths = Object.keys(vfsEntries);
2043
- for (const item of fpaths) {
2044
- const segments = item.replace(nitro.options.rootDir, "").split("/").filter(Boolean);
2045
- let currentDir = item.startsWith(nitro.options.rootDir) ? directories[nitro.options.rootDir] : directories;
2046
- for (const segment of segments) {
2047
- if (!currentDir[segment]) {
2048
- currentDir[segment] = {};
2049
- }
2050
- currentDir = currentDir[segment];
2051
- }
2052
- }
2053
- const generateHTML = (directory, path = []) => Object.entries(directory).map(([fname, value = {}]) => {
2054
- const subpath = [...path, fname];
2055
- const key = subpath.join("/");
2056
- const encodedUrl = encodeURIComponent(key);
2057
- const linkClass = url === `/${encodedUrl}` ? "bg-gray-700 text-white" : "hover:bg-gray-800 text-gray-200";
2058
- return Object.keys(value).length === 0 ? `
2059
- <li class="flex flex-nowrap">
2060
- <a href="/_vfs/${encodedUrl}" class="w-full text-sm px-2 py-1 border-b border-gray-10 ${linkClass}">
2061
- ${fname}
2062
- </a>
2063
- </li>
2064
- ` : `
2065
- <li>
2066
- <details ${url.startsWith(`/${encodedUrl}`) ? "open" : ""}>
2067
- <summary class="w-full text-sm px-2 py-1 border-b border-gray-10 hover:bg-gray-800 text-gray-200">
2068
- ${fname}
2069
- </summary>
2070
- <ul class="ml-4">
2071
- ${generateHTML(value, subpath)}
2072
- </ul>
2073
- </details>
2074
- </li>
2075
- `;
2076
- }).join("");
2077
- const rootDirectory = directories[nitro.options.rootDir];
2078
- delete directories[nitro.options.rootDir];
2079
- const items = generateHTML(rootDirectory, [nitro.options.rootDir]) + generateHTML(directories);
2080
- const files = `
2081
- <div class="h-full overflow-auto border-r border-gray:10">
2082
- <p class="text-white text-bold text-center py-1 opacity-50">Virtual Files</p>
2083
- <ul class="flex flex-col">${items}</ul>
2084
- </div>
2085
- `;
2086
- const file = id ? editorTemplate({
2087
- readOnly: true,
2088
- language: id.endsWith("html") ? "html" : "javascript",
2089
- theme: "vs-dark",
2090
- value: content,
2091
- wordWrap: "wordWrapColumn",
2092
- wordWrapColumn: 80
2093
- }) : `
2094
- <div class="w-full h-full flex opacity-50">
2095
- <h1 class="text-white m-auto">Select a virtual file to inspect</h1>
2096
- </div>
2097
- `;
2098
- return (
2099
- /* html */
2100
- `
2101
- <!doctype html>
2102
- <html>
2103
- <head>
2104
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" />
2105
- <link rel="stylesheet" data-name="vs/editor/editor.main" href="${vsUrl}/editor/editor.main.min.css">
2106
- <script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"><\/script>
2107
- <style>
2108
- html {
2109
- background: #1E1E1E;
2110
- color: white;
2111
- }
2112
- [un-cloak] {
2113
- display: none;
2114
- }
2115
- </style>
2116
- </head>
2117
- <body class="bg-[#1E1E1E]">
2118
- <div un-cloak class="h-screen grid grid-cols-[300px_1fr]">
2119
- ${files}
2120
- ${file}
2121
- </div>
2122
- </body>
2123
- </html>`
2124
- );
2125
- });
2126
- }
2127
- const monacoVersion = "0.30.0";
2128
- const monacoUrl = `https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/${monacoVersion}/min`;
2129
- const vsUrl = `${monacoUrl}/vs`;
2130
- const editorTemplate = (options) => `
2131
- <div id="editor" class="min-h-screen w-full h-full"></div>
2132
- <script src="${vsUrl}/loader.min.js"><\/script>
2133
- <script>
2134
- require.config({ paths: { vs: '${vsUrl}' } })
2135
-
2136
- const proxy = URL.createObjectURL(new Blob([\`
2137
- self.MonacoEnvironment = { baseUrl: '${monacoUrl}' }
2138
- importScripts('${vsUrl}/base/worker/workerMain.min.js')
2139
- \`], { type: 'text/javascript' }))
2140
- window.MonacoEnvironment = { getWorkerUrl: () => proxy }
2141
-
2142
- setTimeout(() => {
2143
- require(['vs/editor/editor.main'], function () {
2144
- monaco.editor.create(document.getElementById('editor'), ${JSON.stringify(
2145
- options
2146
- )})
2147
- })
2148
- }, 0);
2149
- <\/script>
2150
- `;
2151
-
2152
- function initWorker(filename) {
2153
- if (!existsSync(filename)) {
2154
- return;
2155
- }
2156
- return new Promise((resolve2, reject) => {
2157
- const worker = new Worker(filename);
2158
- worker.once("exit", (code) => {
2159
- reject(
2160
- new Error(
2161
- code ? "[worker] exited with code: " + code : "[worker] exited"
2162
- )
2163
- );
2164
- });
2165
- worker.once("error", (err) => {
2166
- const newErr = new Error("[worker init] " + err.message);
2167
- newErr.stack = err.stack;
2168
- reject(newErr);
2169
- });
2170
- const addressListener = (event) => {
2171
- if (!event || !event?.address) {
2172
- return;
2173
- }
2174
- worker.off("message", addressListener);
2175
- resolve2({
2176
- worker,
2177
- address: event.address
2178
- });
2179
- };
2180
- worker.on("message", addressListener);
2181
- });
2182
- }
2183
- async function killWorker(worker, nitro) {
2184
- if (!worker) {
2185
- return;
2186
- }
2187
- if (worker.worker) {
2188
- worker.worker.postMessage({ event: "shutdown" });
2189
- const gracefulShutdownTimeout = Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 3;
2190
- await new Promise((resolve2) => {
2191
- const timeout = setTimeout(() => {
2192
- nitro.logger.warn(
2193
- `[nitro] [dev] Force closing worker after ${gracefulShutdownTimeout} seconds...`
2194
- );
2195
- resolve2();
2196
- }, gracefulShutdownTimeout * 1e3);
2197
- worker.worker?.once("message", (message) => {
2198
- if (message.event === "exit") {
2199
- clearTimeout(timeout);
2200
- resolve2();
2201
- }
2202
- });
2203
- });
2204
- worker.worker.removeAllListeners();
2205
- await worker.worker.terminate();
2206
- worker.worker = null;
2207
- }
2208
- if (worker.address.socketPath && existsSync(worker.address.socketPath)) {
2209
- await promises.rm(worker.address.socketPath).catch(() => {
2210
- });
2211
- }
2212
- }
2213
- function createDevServer(nitro) {
2214
- const workerEntry = resolve(
2215
- nitro.options.output.dir,
2216
- nitro.options.output.serverDir,
2217
- "index.mjs"
2218
- );
2219
- const errorHandler$1 = nitro.options.devErrorHandler || errorHandler;
2220
- let lastError;
2221
- let reloadPromise;
2222
- let currentWorker;
2223
- async function _reload() {
2224
- const oldWorker = currentWorker;
2225
- currentWorker = void 0;
2226
- await killWorker(oldWorker, nitro);
2227
- currentWorker = await initWorker(workerEntry);
2228
- if (!currentWorker) {
2229
- return;
2230
- }
2231
- const buildInfoPath = resolve(nitro.options.buildDir, "nitro.json");
2232
- const buildInfo = {
2233
- date: (/* @__PURE__ */ new Date()).toJSON(),
2234
- preset: nitro.options.preset,
2235
- framework: nitro.options.framework,
2236
- versions: {
2237
- nitro: version
2238
- },
2239
- dev: {
2240
- pid: process.pid,
2241
- workerAddress: currentWorker?.address
2242
- }
2243
- };
2244
- await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2));
2245
- }
2246
- const reload = debounce(() => {
2247
- reloadPromise = _reload().then(() => {
2248
- lastError = void 0;
2249
- }).catch((error) => {
2250
- console.error("[worker reload]", error);
2251
- lastError = error;
2252
- }).finally(() => {
2253
- reloadPromise = void 0;
2254
- });
2255
- return reloadPromise;
2256
- });
2257
- nitro.hooks.hook("dev:reload", reload);
2258
- const app = createApp();
2259
- for (const handler of nitro.options.devHandlers) {
2260
- app.use(handler.route || "/", handler.handler);
2261
- }
2262
- app.use("/_vfs", createVFSHandler(nitro));
2263
- for (const asset of nitro.options.publicAssets) {
2264
- const url = joinURL(
2265
- nitro.options.runtimeConfig.app.baseURL,
2266
- asset.baseURL || "/"
2267
- );
2268
- app.use(url, fromNodeMiddleware(serveStatic(asset.dir)));
2269
- if (!asset.fallthrough) {
2270
- app.use(url, fromNodeMiddleware(servePlaceholder()));
2271
- }
2272
- }
2273
- for (const route of Object.keys(nitro.options.devProxy).sort().reverse()) {
2274
- let opts = nitro.options.devProxy[route];
2275
- if (typeof opts === "string") {
2276
- opts = { target: opts };
2277
- }
2278
- const proxy2 = createProxy(opts);
2279
- app.use(
2280
- route,
2281
- eventHandler(async (event) => {
2282
- await proxy2.handle(event);
2283
- })
2284
- );
2285
- }
2286
- const proxy = createProxy();
2287
- proxy.proxy.on("proxyReq", (proxyReq, req) => {
2288
- if (!proxyReq.hasHeader("x-forwarded-for")) {
2289
- const address = req.socket.remoteAddress;
2290
- if (address) {
2291
- proxyReq.appendHeader("x-forwarded-for", address);
2292
- }
2293
- }
2294
- if (!proxyReq.hasHeader("x-forwarded-port")) {
2295
- const localPort = req?.socket?.localPort;
2296
- if (localPort) {
2297
- proxyReq.setHeader("x-forwarded-port", req.socket.localPort);
2298
- }
2299
- }
2300
- if (!proxyReq.hasHeader("x-forwarded-Proto")) {
2301
- const encrypted = req?.connection?.encrypted;
2302
- proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http");
2303
- }
2304
- });
2305
- const getWorkerAddress = () => {
2306
- const address = currentWorker?.address;
2307
- if (!address) {
2308
- return;
2309
- }
2310
- if (address.socketPath) {
2311
- try {
2312
- accessSync(address.socketPath);
2313
- } catch (error) {
2314
- if (!lastError) {
2315
- lastError = error;
2316
- }
2317
- return;
2318
- }
2319
- }
2320
- return address;
2321
- };
2322
- app.use(
2323
- eventHandler(async (event) => {
2324
- await reloadPromise;
2325
- const address = getWorkerAddress();
2326
- if (!address) {
2327
- const error = lastError || createError("Worker not ready");
2328
- return errorHandler$1(error, event);
2329
- }
2330
- await proxy.handle(event, { target: address }).catch((error) => {
2331
- lastError = error;
2332
- throw error;
2333
- });
2334
- })
2335
- );
2336
- const upgrade = (req, socket, head) => {
2337
- return proxy.proxy.ws(
2338
- req,
2339
- // @ts-expect-error
2340
- socket,
2341
- {
2342
- target: getWorkerAddress(),
2343
- xfwd: true
2344
- },
2345
- head
2346
- );
2347
- };
2348
- let listeners = [];
2349
- const _listen = async (port, opts) => {
2350
- const listener = await listen(toNodeListener(app), { port, ...opts });
2351
- listener.server.on("upgrade", (req, sock, head) => {
2352
- upgrade(req, sock, head);
2353
- });
2354
- listeners.push(listener);
2355
- return listener;
2356
- };
2357
- let watcher;
2358
- if (nitro.options.devServer.watch.length > 0) {
2359
- watcher = watch(nitro.options.devServer.watch, nitro.options.watchOptions);
2360
- watcher.on("add", reload).on("change", reload);
2361
- }
2362
- async function close() {
2363
- if (watcher) {
2364
- await watcher.close();
2365
- }
2366
- await killWorker(currentWorker, nitro);
2367
- await Promise.all(listeners.map((l) => l.close()));
2368
- listeners = [];
2369
- }
2370
- nitro.hooks.hook("close", close);
2371
- return {
2372
- reload,
2373
- listen: _listen,
2374
- app,
2375
- close,
2376
- watcher,
2377
- upgrade
2378
- };
2379
- }
2380
- function createProxy(defaults = {}) {
2381
- const proxy = createProxyServer(defaults);
2382
- const handle = async (event, opts = {}) => {
2383
- try {
2384
- await proxy.web(event.node.req, event.node.res, opts);
2385
- } catch (error) {
2386
- if (error?.code !== "ECONNRESET") {
2387
- throw error;
2388
- }
2389
- }
2390
- };
2391
- return {
2392
- proxy,
2393
- handle
2394
- };
2395
- }
2396
-
2397
- const NEGATION_RE = /^(!?)(.*)$/;
2398
- const PARENT_DIR_GLOB_RE = /!?\.\.\//;
2399
- async function copyPublicAssets(nitro) {
2400
- if (nitro.options.noPublicDir) {
2401
- return;
2402
- }
2403
- for (const asset of nitro.options.publicAssets) {
2404
- const srcDir = asset.dir;
2405
- const dstDir = join(nitro.options.output.publicDir, asset.baseURL);
2406
- if (await isDirectory(srcDir)) {
2407
- const includePatterns = [
2408
- "**",
2409
- ...nitro.options.ignore.map((p) => {
2410
- const [_, negation, pattern] = p.match(NEGATION_RE) || [];
2411
- return (
2412
- // Convert ignore to include patterns
2413
- (negation ? "" : "!") + // Make non-glob patterns relative to publicAssetDir
2414
- (pattern.startsWith("*") ? pattern : relative(srcDir, resolve(nitro.options.srcDir, pattern)))
2415
- );
2416
- })
2417
- ].filter((p) => !PARENT_DIR_GLOB_RE.test(p));
2418
- const publicAssets = await globby(includePatterns, {
2419
- cwd: srcDir,
2420
- absolute: false,
2421
- dot: true
2422
- });
2423
- await Promise.all(
2424
- publicAssets.map(async (file) => {
2425
- const src = join(srcDir, file);
2426
- const dst = join(dstDir, file);
2427
- if (!existsSync(dst)) {
2428
- await promises.cp(src, dst);
2429
- }
2430
- })
2431
- );
2432
- }
2433
- }
2434
- if (nitro.options.compressPublicAssets) {
2435
- await compressPublicAssets(nitro);
2436
- }
2437
- nitro.logger.success(
2438
- "Generated public " + prettyPath(nitro.options.output.publicDir)
2439
- );
2440
- }
2441
-
2442
- async function prepare(nitro) {
2443
- await prepareDir(nitro.options.output.dir);
2444
- if (!nitro.options.noPublicDir) {
2445
- await prepareDir(nitro.options.output.publicDir);
2446
- }
2447
- if (!nitro.options.static) {
2448
- await prepareDir(nitro.options.output.serverDir);
2449
- }
2450
- }
2451
- async function prepareDir(dir) {
2452
- await fsp.mkdir(dir, { recursive: true });
2453
- await fse.emptyDir(dir);
2454
- }
2455
-
2456
- export { build, copyPublicAssets, createDevServer, createNitro, listTasks, loadOptions, prepare, prerender, runTask, writeTypes };