nitro 3.0.0 → 3.0.1-alpha.1

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 (293) hide show
  1. package/dist/_build/common.mjs +68 -0
  2. package/dist/_build/common2.mjs +772 -0
  3. package/dist/_build/rolldown.mjs +206 -0
  4. package/dist/_build/rollup.mjs +289 -0
  5. package/dist/_build/vite.build.mjs +56 -0
  6. package/dist/_build/vite.plugin.mjs +768 -0
  7. package/dist/_chunks/ANM1K1bE.mjs +304 -0
  8. package/dist/_chunks/B-D1JOIz.mjs +1355 -0
  9. package/dist/_chunks/BX9-zVkM.mjs +59 -0
  10. package/dist/_chunks/Bqks5huO.mjs +31 -0
  11. package/dist/_chunks/C7CbzoI1.mjs +39 -0
  12. package/dist/_dev.d.mts +12 -0
  13. package/dist/_dev.mjs +705 -0
  14. package/dist/_libs/acorn.mjs +5034 -0
  15. package/dist/_libs/c12.mjs +2858 -0
  16. package/dist/_libs/chokidar.mjs +1561 -0
  17. package/dist/_libs/citty.mjs +333 -0
  18. package/dist/_libs/commondir.mjs +22 -0
  19. package/dist/_libs/compatx.mjs +46 -0
  20. package/dist/_libs/confbox.mjs +2920 -0
  21. package/dist/_libs/deepmerge.mjs +86 -0
  22. package/dist/_libs/dot-prop.mjs +138 -0
  23. package/dist/_libs/duplexer.mjs +71 -0
  24. package/dist/_libs/escape-string-regexp.mjs +8 -0
  25. package/dist/_libs/estree-walker.mjs +330 -0
  26. package/dist/_libs/etag.mjs +80 -0
  27. package/dist/_libs/fdir.mjs +514 -0
  28. package/dist/_libs/function-bind.mjs +63 -0
  29. package/dist/_libs/gen-mapping.mjs +612 -0
  30. package/dist/_libs/giget.mjs +19289 -0
  31. package/dist/_libs/gzip-size.mjs +21 -0
  32. package/dist/_libs/hasown.mjs +14 -0
  33. package/dist/_libs/httpxy.mjs +410 -0
  34. package/dist/_libs/is-core-module.mjs +220 -0
  35. package/dist/_libs/is-module.mjs +13 -0
  36. package/dist/_libs/is-reference.mjs +32 -0
  37. package/dist/_libs/js-tokens.mjs +382 -0
  38. package/dist/_libs/klona.mjs +38 -0
  39. package/dist/_libs/knitwork.mjs +124 -0
  40. package/dist/_libs/local-pkg.mjs +1686 -0
  41. package/dist/_libs/magic-string.mjs +939 -0
  42. package/dist/_libs/mime.mjs +1391 -0
  43. package/dist/_libs/node-fetch-native.mjs +173 -0
  44. package/dist/_libs/path-parse.mjs +47 -0
  45. package/dist/_libs/pathe.mjs +41 -0
  46. package/dist/_libs/picomatch.mjs +1673 -0
  47. package/dist/_libs/plugin-alias.mjs +64 -0
  48. package/dist/_libs/plugin-commonjs.mjs +1491 -0
  49. package/dist/_libs/plugin-inject.mjs +135 -0
  50. package/dist/_libs/plugin-json.mjs +36 -0
  51. package/dist/_libs/plugin-node-resolve.mjs +1553 -0
  52. package/dist/_libs/plugin-replace.mjs +104 -0
  53. package/dist/_libs/pretty-bytes.mjs +116 -0
  54. package/dist/_libs/remapping.mjs +117 -0
  55. package/dist/_libs/rou3.mjs +319 -0
  56. package/dist/_libs/std-env.mjs +158 -0
  57. package/dist/_libs/strip-literal.mjs +51 -0
  58. package/dist/_libs/tinyglobby.mjs +292 -0
  59. package/dist/_libs/tsconfck.mjs +832 -0
  60. package/dist/_libs/ultrahtml.mjs +138 -0
  61. package/dist/_libs/unimport.mjs +3520 -0
  62. package/dist/_libs/untyped.mjs +271 -0
  63. package/dist/_libs/unwasm.mjs +5836 -0
  64. package/dist/_libs/vite-plugin-fullstack.mjs +561 -0
  65. package/dist/_presets.mjs +1752 -0
  66. package/dist/builder.d.mts +63 -0
  67. package/dist/builder.mjs +33 -0
  68. package/dist/cli/_chunks/build.mjs +48 -0
  69. package/dist/cli/_chunks/common.mjs +15 -0
  70. package/dist/cli/_chunks/detect-acorn.mjs +12 -0
  71. package/dist/cli/_chunks/dev.mjs +68 -0
  72. package/dist/cli/_chunks/dist.mjs +3 -0
  73. package/dist/cli/_chunks/dist2.mjs +3 -0
  74. package/dist/cli/_chunks/dist3.mjs +3 -0
  75. package/dist/cli/_chunks/dist4.mjs +4 -0
  76. package/dist/cli/_chunks/dist5.mjs +4 -0
  77. package/dist/cli/_chunks/esm.mjs +3 -0
  78. package/dist/cli/_chunks/json5.mjs +4 -0
  79. package/dist/cli/_chunks/jsonc.mjs +4 -0
  80. package/dist/cli/_chunks/list.mjs +27 -0
  81. package/dist/cli/_chunks/multipart-parser.mjs +6 -0
  82. package/dist/cli/_chunks/prepare.mjs +19 -0
  83. package/dist/cli/_chunks/run.mjs +55 -0
  84. package/dist/cli/_chunks/task.mjs +16 -0
  85. package/dist/cli/_chunks/toml.mjs +4 -0
  86. package/dist/cli/_chunks/yaml.mjs +4 -0
  87. package/dist/cli/index.d.mts +1 -1
  88. package/dist/cli/index.mjs +20 -476
  89. package/dist/node_modules/@poppinss/dumper/build/formatters/html/main.js +1 -1
  90. package/dist/node_modules/@poppinss/dumper/package.json +1 -1
  91. package/dist/node_modules/@sindresorhus/is/distribution/index.js +1 -1
  92. package/dist/node_modules/@sindresorhus/is/package.json +1 -1
  93. package/dist/node_modules/@speed-highlight/core/dist/index.js +2 -2
  94. package/dist/node_modules/@speed-highlight/core/dist/terminal.js +2 -2
  95. package/dist/node_modules/@speed-highlight/core/package.json +7 -3
  96. package/dist/node_modules/cookie-es/dist/index.mjs +262 -0
  97. package/dist/node_modules/cookie-es/package.json +37 -0
  98. package/dist/node_modules/hookable/dist/index.mjs +243 -266
  99. package/dist/node_modules/hookable/package.json +29 -26
  100. package/dist/node_modules/rendu/dist/index.mjs +380 -0
  101. package/dist/node_modules/rendu/package.json +47 -0
  102. package/dist/node_modules/youch/build/{chunk-VE4LENUR.js → chunk-F4I6KX4R.js} +2 -1
  103. package/dist/node_modules/youch/build/{chunk-JAN2TFI2.js → chunk-YYEJ3AGB.js} +4 -1
  104. package/dist/node_modules/youch/build/index.js +16 -8
  105. package/dist/node_modules/youch/build/public/error_stack/script.js +20 -22
  106. package/dist/node_modules/youch/build/public/header/script.js +0 -2
  107. package/dist/node_modules/youch/build/public/layout/script.js +0 -8
  108. package/dist/node_modules/youch/build/public/layout/style.css +4 -0
  109. package/dist/node_modules/youch/package.json +16 -17
  110. package/dist/presets/_nitro/runtime/nitro-dev.d.mts +1 -0
  111. package/dist/presets/_nitro/runtime/nitro-dev.mjs +48 -42
  112. package/dist/presets/_nitro/runtime/nitro-prerenderer.d.mts +2 -2
  113. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +10 -14
  114. package/dist/presets/_nitro/runtime/service-worker.d.mts +1 -0
  115. package/dist/presets/_nitro/runtime/service-worker.mjs +15 -12
  116. package/dist/presets/aws-amplify/runtime/aws-amplify.d.mts +1 -0
  117. package/dist/presets/aws-amplify/runtime/aws-amplify.mjs +7 -6
  118. package/dist/presets/aws-lambda/runtime/_utils.d.mts +8 -13
  119. package/dist/presets/aws-lambda/runtime/_utils.mjs +95 -81
  120. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.mts +1 -2
  121. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +26 -28
  122. package/dist/presets/aws-lambda/runtime/aws-lambda.mjs +8 -8
  123. package/dist/presets/azure/runtime/_utils.mjs +43 -43
  124. package/dist/presets/azure/runtime/azure-swa.d.mts +2 -2
  125. package/dist/presets/azure/runtime/azure-swa.mjs +24 -22
  126. package/dist/presets/bun/runtime/bun.d.mts +2 -0
  127. package/dist/presets/bun/runtime/bun.mjs +34 -21
  128. package/dist/presets/cloudflare/runtime/_module-handler.d.mts +10 -7
  129. package/dist/presets/cloudflare/runtime/_module-handler.mjs +80 -88
  130. package/dist/presets/cloudflare/runtime/cloudflare-durable.d.mts +6 -14
  131. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +60 -63
  132. package/dist/presets/cloudflare/runtime/cloudflare-module.d.mts +1 -7
  133. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +14 -16
  134. package/dist/presets/cloudflare/runtime/cloudflare-pages.d.mts +12 -12
  135. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +40 -42
  136. package/dist/presets/cloudflare/runtime/plugin.dev.d.mts +2 -2
  137. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +89 -82
  138. package/dist/presets/cloudflare/runtime/shims/workers.dev.mjs +27 -0
  139. package/dist/presets/deno/runtime/deno-deploy.d.mts +4 -0
  140. package/dist/presets/deno/runtime/deno-deploy.mjs +15 -12
  141. package/dist/presets/deno/runtime/deno-server.d.mts +0 -3
  142. package/dist/presets/deno/runtime/deno-server.mjs +32 -52
  143. package/dist/presets/netlify/runtime/netlify-edge.d.mts +2 -1
  144. package/dist/presets/netlify/runtime/netlify-edge.mjs +15 -12
  145. package/dist/presets/netlify/runtime/netlify.mjs +12 -18
  146. package/dist/presets/node/runtime/node-cluster.d.mts +3 -1
  147. package/dist/presets/node/runtime/node-cluster.mjs +50 -54
  148. package/dist/presets/node/runtime/node-middleware.d.mts +2 -3
  149. package/dist/presets/node/runtime/node-middleware.mjs +9 -8
  150. package/dist/presets/node/runtime/node-server.mjs +37 -34
  151. package/dist/presets/standard/runtime/server.d.mts +1 -3
  152. package/dist/presets/standard/runtime/server.mjs +2 -4
  153. package/dist/presets/stormkit/runtime/stormkit.d.mts +13 -13
  154. package/dist/presets/stormkit/runtime/stormkit.mjs +21 -21
  155. package/dist/presets/vercel/runtime/vercel.node.d.mts +3 -0
  156. package/dist/presets/vercel/runtime/vercel.node.mjs +15 -0
  157. package/dist/presets/vercel/runtime/{vercel.d.mts → vercel.web.d.mts} +3 -3
  158. package/dist/presets/vercel/runtime/vercel.web.mjs +20 -0
  159. package/dist/presets/winterjs/runtime/winterjs.d.mts +2 -0
  160. package/dist/presets/winterjs/runtime/winterjs.mjs +73 -69
  161. package/dist/presets/zeabur/runtime/zeabur.d.mts +1 -1
  162. package/dist/presets/zeabur/runtime/zeabur.mjs +1 -1
  163. package/dist/runtime/app.d.mts +1 -0
  164. package/dist/runtime/app.mjs +1 -0
  165. package/dist/runtime/cache.d.mts +1 -0
  166. package/dist/runtime/cache.mjs +1 -0
  167. package/dist/runtime/config.d.mts +3 -0
  168. package/dist/runtime/config.mjs +4 -0
  169. package/dist/runtime/context.d.mts +1 -0
  170. package/dist/runtime/context.mjs +1 -0
  171. package/dist/runtime/database.d.mts +1 -0
  172. package/dist/runtime/database.mjs +1 -0
  173. package/dist/runtime/internal/app.d.mts +11 -1
  174. package/dist/runtime/internal/app.mjs +188 -140
  175. package/dist/runtime/internal/cache.d.mts +9 -5
  176. package/dist/runtime/internal/cache.mjs +248 -219
  177. package/dist/runtime/internal/context.d.mts +9 -9
  178. package/dist/runtime/internal/context.mjs +17 -10
  179. package/dist/runtime/internal/database.mjs +8 -10
  180. package/dist/runtime/internal/error/dev.d.mts +5 -4
  181. package/dist/runtime/internal/error/dev.mjs +106 -105
  182. package/dist/runtime/internal/error/hooks.d.mts +1 -0
  183. package/dist/runtime/internal/error/hooks.mjs +9 -0
  184. package/dist/runtime/internal/error/prod.d.mts +5 -4
  185. package/dist/runtime/internal/error/prod.mjs +51 -59
  186. package/dist/runtime/internal/error/utils.d.mts +4 -4
  187. package/dist/runtime/internal/error/utils.mjs +1 -1
  188. package/dist/runtime/internal/meta.d.mts +1 -1
  189. package/dist/runtime/internal/meta.mjs +1 -1
  190. package/dist/runtime/internal/plugin.d.mts +2 -2
  191. package/dist/runtime/internal/plugin.mjs +1 -1
  192. package/dist/runtime/internal/route-rules.d.mts +8 -8
  193. package/dist/runtime/internal/route-rules.mjs +54 -52
  194. package/dist/runtime/internal/routes/dev-tasks.d.mts +1 -2
  195. package/dist/runtime/internal/routes/dev-tasks.mjs +16 -18
  196. package/dist/runtime/internal/routes/openapi.d.mts +1 -0
  197. package/dist/runtime/internal/routes/openapi.mjs +81 -87
  198. package/dist/runtime/internal/routes/renderer-template.d.mts +1 -1
  199. package/dist/runtime/internal/routes/renderer-template.dev.d.mts +1 -2
  200. package/dist/runtime/internal/routes/renderer-template.dev.mjs +15 -17
  201. package/dist/runtime/internal/routes/renderer-template.mjs +1 -1
  202. package/dist/runtime/internal/routes/scalar.d.mts +1 -0
  203. package/dist/runtime/internal/routes/scalar.mjs +22 -23
  204. package/dist/runtime/internal/routes/swagger.d.mts +1 -0
  205. package/dist/runtime/internal/routes/swagger.mjs +9 -11
  206. package/dist/runtime/internal/runtime-config.d.mts +4 -4
  207. package/dist/runtime/internal/runtime-config.mjs +40 -35
  208. package/dist/runtime/internal/static.mjs +63 -74
  209. package/dist/runtime/internal/storage.mjs +2 -2
  210. package/dist/runtime/internal/task.d.mts +6 -6
  211. package/dist/runtime/internal/task.mjs +56 -60
  212. package/dist/runtime/internal/vite/dev-entry.mjs +11 -1
  213. package/dist/runtime/internal/vite/dev-worker.mjs +9 -57
  214. package/dist/runtime/internal/vite/ssr-renderer.mjs +3 -1
  215. package/{lib/runtime-meta.d.mts → dist/runtime/meta.d.mts} +1 -1
  216. package/dist/runtime/meta.mjs +26 -0
  217. package/dist/runtime/nitro.d.mts +12 -0
  218. package/dist/runtime/nitro.mjs +32 -0
  219. package/dist/runtime/runtime-config.d.mts +1 -0
  220. package/dist/runtime/runtime-config.mjs +1 -0
  221. package/dist/runtime/storage.d.mts +1 -0
  222. package/dist/runtime/storage.mjs +1 -0
  223. package/dist/runtime/task.d.mts +1 -0
  224. package/dist/runtime/task.mjs +1 -0
  225. package/dist/runtime/vite-runtime.d.mts +8 -0
  226. package/dist/runtime/vite-runtime.mjs +9 -0
  227. package/dist/types/index.d.mts +2625 -2297
  228. package/dist/types/index.mjs +1 -1
  229. package/dist/vite.d.mts +49 -51
  230. package/dist/vite.mjs +44 -68
  231. package/lib/tsconfig.json +27 -0
  232. package/package.json +86 -76
  233. package/dist/_chunks/app.mjs +0 -19797
  234. package/dist/_chunks/build.mjs +0 -84
  235. package/dist/_chunks/build2.mjs +0 -318
  236. package/dist/_chunks/build3.mjs +0 -6452
  237. package/dist/_chunks/detect-acorn.mjs +0 -503
  238. package/dist/_chunks/index.mjs +0 -22242
  239. package/dist/_chunks/index2.mjs +0 -297
  240. package/dist/_chunks/index3.mjs +0 -1058
  241. package/dist/_chunks/index4.mjs +0 -1206
  242. package/dist/_chunks/info.mjs +0 -11157
  243. package/dist/_chunks/json5.mjs +0 -68
  244. package/dist/_chunks/jsonc.mjs +0 -51
  245. package/dist/_chunks/pathe.M-eThtNZ.mjs +0 -204
  246. package/dist/_chunks/plugin.mjs +0 -960
  247. package/dist/_chunks/server.mjs +0 -254
  248. package/dist/_chunks/snapshot.mjs +0 -284
  249. package/dist/_chunks/toml.mjs +0 -259
  250. package/dist/_chunks/yaml.mjs +0 -86
  251. package/dist/cli/build.mjs +0 -54
  252. package/dist/cli/common.mjs +0 -13
  253. package/dist/cli/dev.mjs +0 -95
  254. package/dist/cli/index2.mjs +0 -17
  255. package/dist/cli/list.mjs +0 -34
  256. package/dist/cli/prepare.mjs +0 -24
  257. package/dist/cli/run.mjs +0 -60
  258. package/dist/index.d.mts +0 -52
  259. package/dist/index.mjs +0 -55
  260. package/dist/node_modules/cookie/dist/index.js +0 -239
  261. package/dist/node_modules/cookie/package.json +0 -42
  262. package/dist/node_modules/klona/dist/index.mjs +0 -81
  263. package/dist/node_modules/klona/full/index.mjs +0 -53
  264. package/dist/node_modules/klona/package.json +0 -74
  265. package/dist/node_modules/std-env/dist/index.mjs +0 -1
  266. package/dist/node_modules/std-env/package.json +0 -46
  267. package/dist/presets/vercel/runtime/vercel.mjs +0 -17
  268. package/dist/presets.mjs +0 -2460
  269. package/dist/runtime/index.d.mts +0 -11
  270. package/dist/runtime/index.mjs +0 -17
  271. package/dist/runtime/internal/debug.d.mts +0 -2
  272. package/dist/runtime/internal/debug.mjs +0 -5
  273. package/dist/runtime/internal/empty.d.mts +0 -0
  274. package/dist/runtime/internal/index.d.mts +0 -3
  275. package/dist/runtime/internal/index.mjs +0 -3
  276. package/dist/runtime/internal/lib/http-graceful-shutdown.d.mts +0 -16
  277. package/dist/runtime/internal/lib/http-graceful-shutdown.mjs +0 -213
  278. package/dist/runtime/internal/renderer.d.mts +0 -3
  279. package/dist/runtime/internal/renderer.mjs +0 -36
  280. package/dist/runtime/internal/shutdown.d.mts +0 -9
  281. package/dist/runtime/internal/shutdown.mjs +0 -34
  282. package/dist/runtime/internal/utils.d.mts +0 -1
  283. package/dist/runtime/internal/utils.mjs +0 -15
  284. package/dist/runtime/internal/vite/dev-entry.d.mts +0 -1
  285. package/dist/runtime/internal/vite/dev-worker.d.mts +0 -1
  286. package/dist/runtime/internal/vite/prod-setup.d.mts +0 -4
  287. package/dist/runtime/internal/vite/prod-setup.mjs +0 -55
  288. package/dist/runtime/internal/vite/ssr-renderer.d.mts +0 -4
  289. package/lib/config.d.mts +0 -9
  290. package/lib/config.mjs +0 -5
  291. package/lib/meta.d.mts +0 -5
  292. package/lib/meta.mjs +0 -21
  293. package/lib/runtime-meta.mjs +0 -38
@@ -5,232 +5,261 @@ import { hash } from "ohash";
5
5
  import { useNitroApp } from "./app.mjs";
6
6
  import { useStorage } from "./storage.mjs";
7
7
  function defaultCacheOptions() {
8
- return {
9
- name: "_",
10
- base: "/cache",
11
- swr: true,
12
- maxAge: 1
13
- };
8
+ return {
9
+ name: "_",
10
+ base: "/cache",
11
+ swr: true,
12
+ maxAge: 1
13
+ };
14
14
  }
15
15
  export function defineCachedFunction(fn, opts = {}) {
16
- opts = { ...defaultCacheOptions(), ...opts };
17
- const pending = {};
18
- const group = opts.group || "nitro/functions";
19
- const name = opts.name || fn.name || "_";
20
- const integrity = opts.integrity || hash([fn, opts]);
21
- const validate = opts.validate || ((entry) => entry.value !== void 0);
22
- async function get(key, resolver, shouldInvalidateCache, event) {
23
- const cacheKey = [opts.base, group, name, key + ".json"].filter(Boolean).join(":").replace(/:\/$/, ":index");
24
- let entry = await useStorage().getItem(cacheKey).catch((error) => {
25
- console.error(`[cache] Cache read error.`, error);
26
- useNitroApp().captureError(error, { event, tags: ["cache"] });
27
- }) || {};
28
- if (typeof entry !== "object") {
29
- entry = {};
30
- const error = new Error("Malformed data read from cache.");
31
- console.error("[cache]", error);
32
- useNitroApp().captureError(error, { event, tags: ["cache"] });
33
- }
34
- const ttl = (opts.maxAge ?? 0) * 1e3;
35
- if (ttl) {
36
- entry.expires = Date.now() + ttl;
37
- }
38
- const expired = shouldInvalidateCache || entry.integrity !== integrity || ttl && Date.now() - (entry.mtime || 0) > ttl || validate(entry) === false;
39
- const _resolve = async () => {
40
- const isPending = pending[key];
41
- if (!isPending) {
42
- if (entry.value !== void 0 && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
43
- entry.value = void 0;
44
- entry.integrity = void 0;
45
- entry.mtime = void 0;
46
- entry.expires = void 0;
47
- }
48
- pending[key] = Promise.resolve(resolver());
49
- }
50
- try {
51
- entry.value = await pending[key];
52
- } catch (error) {
53
- if (!isPending) {
54
- delete pending[key];
55
- }
56
- throw error;
57
- }
58
- if (!isPending) {
59
- entry.mtime = Date.now();
60
- entry.integrity = integrity;
61
- delete pending[key];
62
- if (validate(entry) !== false) {
63
- let setOpts;
64
- if (opts.maxAge && !opts.swr) {
65
- setOpts = { ttl: opts.maxAge };
66
- }
67
- const promise = useStorage().setItem(cacheKey, entry, setOpts).catch((error) => {
68
- console.error(`[cache] Cache write error.`, error);
69
- useNitroApp().captureError(error, { event, tags: ["cache"] });
70
- });
71
- if (typeof event?.req?.waitUntil === "function") {
72
- event.req.waitUntil(promise);
73
- }
74
- }
75
- }
76
- };
77
- const _resolvePromise = expired ? _resolve() : Promise.resolve();
78
- if (entry.value === void 0) {
79
- await _resolvePromise;
80
- } else if (expired && event && event.req.waitUntil) {
81
- event.req.waitUntil(_resolvePromise);
82
- }
83
- if (opts.swr && validate(entry) !== false) {
84
- _resolvePromise.catch((error) => {
85
- console.error(`[cache] SWR handler error.`, error);
86
- useNitroApp().captureError(error, { event, tags: ["cache"] });
87
- });
88
- return entry;
89
- }
90
- return _resolvePromise.then(() => entry);
91
- }
92
- return async (...args) => {
93
- const shouldBypassCache = await opts.shouldBypassCache?.(...args);
94
- if (shouldBypassCache) {
95
- return fn(...args);
96
- }
97
- const key = await (opts.getKey || getKey)(...args);
98
- const shouldInvalidateCache = await opts.shouldInvalidateCache?.(...args);
99
- const entry = await get(
100
- key,
101
- () => fn(...args),
102
- shouldInvalidateCache,
103
- args[0] && isHTTPEvent(args[0]) ? args[0] : void 0
104
- );
105
- let value = entry.value;
106
- if (opts.transform) {
107
- value = await opts.transform(entry, ...args) || value;
108
- }
109
- return value;
110
- };
16
+ opts = {
17
+ ...defaultCacheOptions(),
18
+ ...opts
19
+ };
20
+ const pending = {};
21
+ // Normalize cache params
22
+ const group = opts.group || "nitro/functions";
23
+ const name = opts.name || fn.name || "_";
24
+ const integrity = opts.integrity || hash([fn, opts]);
25
+ const validate = opts.validate || ((entry) => entry.value !== undefined);
26
+ async function get(key, resolver, shouldInvalidateCache, event) {
27
+ // Use extension for key to avoid conflicting with parent namespace (foo/bar and foo/bar/baz)
28
+ const cacheKey = [
29
+ opts.base,
30
+ group,
31
+ name,
32
+ key + ".json"
33
+ ].filter(Boolean).join(":").replace(/:\/$/, ":index");
34
+ let entry = await useStorage().getItem(cacheKey).catch((error) => {
35
+ console.error(`[cache] Cache read error.`, error);
36
+ useNitroApp().captureError?.(error, {
37
+ event,
38
+ tags: ["cache"]
39
+ });
40
+ }) || {};
41
+ // https://github.com/nitrojs/nitro/issues/2160
42
+ if (typeof entry !== "object") {
43
+ entry = {};
44
+ const error = new Error("Malformed data read from cache.");
45
+ console.error("[cache]", error);
46
+ useNitroApp().captureError?.(error, {
47
+ event,
48
+ tags: ["cache"]
49
+ });
50
+ }
51
+ const ttl = (opts.maxAge ?? 0) * 1e3;
52
+ if (ttl) {
53
+ entry.expires = Date.now() + ttl;
54
+ }
55
+ const expired = shouldInvalidateCache || entry.integrity !== integrity || ttl && Date.now() - (entry.mtime || 0) > ttl || validate(entry) === false;
56
+ const _resolve = async () => {
57
+ const isPending = pending[key];
58
+ if (!isPending) {
59
+ if (entry.value !== undefined && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
60
+ // Remove cached entry to prevent using expired cache on concurrent requests
61
+ entry.value = undefined;
62
+ entry.integrity = undefined;
63
+ entry.mtime = undefined;
64
+ entry.expires = undefined;
65
+ }
66
+ pending[key] = Promise.resolve(resolver());
67
+ }
68
+ try {
69
+ entry.value = await pending[key];
70
+ } catch (error) {
71
+ // Make sure entries that reject get removed.
72
+ if (!isPending) {
73
+ delete pending[key];
74
+ }
75
+ // Re-throw error to make sure the caller knows the task failed.
76
+ throw error;
77
+ }
78
+ if (!isPending) {
79
+ // Update mtime, integrity + validate and set the value in cache only the first time the request is made.
80
+ entry.mtime = Date.now();
81
+ entry.integrity = integrity;
82
+ delete pending[key];
83
+ if (validate(entry) !== false) {
84
+ let setOpts;
85
+ if (opts.maxAge && !opts.swr) {
86
+ setOpts = { ttl: opts.maxAge };
87
+ }
88
+ const promise = useStorage().setItem(cacheKey, entry, setOpts).catch((error) => {
89
+ console.error(`[cache] Cache write error.`, error);
90
+ useNitroApp().captureError?.(error, {
91
+ event,
92
+ tags: ["cache"]
93
+ });
94
+ });
95
+ if (typeof event?.req?.waitUntil === "function") {
96
+ event.req.waitUntil(promise);
97
+ }
98
+ }
99
+ }
100
+ };
101
+ const _resolvePromise = expired ? _resolve() : Promise.resolve();
102
+ if (entry.value === undefined) {
103
+ await _resolvePromise;
104
+ } else if (expired && event && event.req.waitUntil) {
105
+ event.req.waitUntil(_resolvePromise);
106
+ }
107
+ if (opts.swr && validate(entry) !== false) {
108
+ _resolvePromise.catch((error) => {
109
+ console.error(`[cache] SWR handler error.`, error);
110
+ useNitroApp().captureError?.(error, {
111
+ event,
112
+ tags: ["cache"]
113
+ });
114
+ });
115
+ return entry;
116
+ }
117
+ return _resolvePromise.then(() => entry);
118
+ }
119
+ return async (...args) => {
120
+ const shouldBypassCache = await opts.shouldBypassCache?.(...args);
121
+ if (shouldBypassCache) {
122
+ return fn(...args);
123
+ }
124
+ const key = await (opts.getKey || getKey)(...args);
125
+ const shouldInvalidateCache = await opts.shouldInvalidateCache?.(...args);
126
+ const entry = await get(key, () => fn(...args), shouldInvalidateCache, args[0] && isHTTPEvent(args[0]) ? args[0] : undefined);
127
+ let value = entry.value;
128
+ if (opts.transform) {
129
+ value = await opts.transform(entry, ...args) || value;
130
+ }
131
+ return value;
132
+ };
111
133
  }
112
134
  export function cachedFunction(fn, opts = {}) {
113
- return defineCachedFunction(fn, opts);
135
+ return defineCachedFunction(fn, opts);
114
136
  }
115
137
  function getKey(...args) {
116
- return args.length > 0 ? hash(args) : "";
138
+ return args.length > 0 ? hash(args) : "";
117
139
  }
118
140
  function escapeKey(key) {
119
- return String(key).replace(/\W/g, "");
141
+ return String(key).replace(/\W/g, "");
120
142
  }
121
- export function defineCachedEventHandler(handler, opts = defaultCacheOptions()) {
122
- const variableHeaderNames = (opts.varies || []).filter(Boolean).map((h) => h.toLowerCase()).sort();
123
- const _opts = {
124
- ...opts,
125
- shouldBypassCache: (event) => {
126
- return event.req.method !== "GET" && event.req.method !== "HEAD";
127
- },
128
- getKey: async (event) => {
129
- const customKey = await opts.getKey?.(event);
130
- if (customKey) {
131
- return escapeKey(customKey);
132
- }
133
- const _path = event.url.pathname + event.url.search;
134
- let _pathname;
135
- try {
136
- _pathname = escapeKey(decodeURI(parseURL(_path).pathname)).slice(0, 16) || "index";
137
- } catch {
138
- _pathname = "-";
139
- }
140
- const _hashedPath = `${_pathname}.${hash(_path)}`;
141
- const _headers = variableHeaderNames.map((header) => [header, event.req.headers.get(header)]).map(([name, value]) => `${escapeKey(name)}.${hash(value)}`);
142
- return [_hashedPath, ..._headers].join(":");
143
- },
144
- validate: (entry) => {
145
- if (!entry.value) {
146
- return false;
147
- }
148
- if (entry.value.status >= 400) {
149
- return false;
150
- }
151
- if (entry.value.body === void 0) {
152
- return false;
153
- }
154
- if (entry.value.headers.etag === "undefined" || entry.value.headers["last-modified"] === "undefined") {
155
- return false;
156
- }
157
- return true;
158
- },
159
- group: opts.group || "nitro/handlers",
160
- integrity: opts.integrity || hash([handler, opts])
161
- };
162
- const _cachedHandler = cachedFunction(
163
- async (event) => {
164
- const filteredHeaders = [...event.req.headers.entries()].filter(
165
- ([key]) => !variableHeaderNames.includes(key.toLowerCase())
166
- );
167
- try {
168
- const originalReq = event.req;
169
- event.req = new Request(event.req.url, {
170
- method: event.req.method,
171
- headers: filteredHeaders
172
- });
173
- event.req.runtime = originalReq.runtime;
174
- event.req.waitUntil = originalReq.waitUntil;
175
- } catch (error) {
176
- console.error("[cache] Failed to filter headers:", error);
177
- }
178
- const rawValue = await handler(event);
179
- const res = await toResponse(rawValue, event);
180
- const body = await res.text();
181
- if (!res.headers.has("etag")) {
182
- res.headers.set("etag", `W/"${hash(body)}"`);
183
- }
184
- if (!res.headers.has("last-modified")) {
185
- res.headers.set("last-modified", (/* @__PURE__ */ new Date()).toUTCString());
186
- }
187
- const cacheControl = [];
188
- if (opts.swr) {
189
- if (opts.maxAge) {
190
- cacheControl.push(`s-maxage=${opts.maxAge}`);
191
- }
192
- if (opts.staleMaxAge) {
193
- cacheControl.push(`stale-while-revalidate=${opts.staleMaxAge}`);
194
- } else {
195
- cacheControl.push("stale-while-revalidate");
196
- }
197
- } else if (opts.maxAge) {
198
- cacheControl.push(`max-age=${opts.maxAge}`);
199
- }
200
- if (cacheControl.length > 0) {
201
- res.headers.set("cache-control", cacheControl.join(", "));
202
- }
203
- const cacheEntry = {
204
- status: res.status,
205
- statusText: res.statusText,
206
- headers: Object.fromEntries(res.headers.entries()),
207
- body
208
- };
209
- return cacheEntry;
210
- },
211
- _opts
212
- );
213
- return defineHandler(async (event) => {
214
- if (opts.headersOnly) {
215
- if (handleCacheHeaders(event, { maxAge: opts.maxAge })) {
216
- return;
217
- }
218
- return handler(event);
219
- }
220
- const response = await _cachedHandler(event);
221
- if (handleCacheHeaders(event, {
222
- modifiedTime: new Date(response.headers["last-modified"]),
223
- etag: response.headers.etag,
224
- maxAge: opts.maxAge
225
- })) {
226
- return;
227
- }
228
- return new FastResponse(response.body, {
229
- status: response.status,
230
- statusText: response.statusText,
231
- headers: response.headers
232
- });
233
- });
143
+ export function defineCachedHandler(handler, opts = defaultCacheOptions()) {
144
+ const variableHeaderNames = (opts.varies || []).filter(Boolean).map((h) => h.toLowerCase()).sort();
145
+ const _opts = {
146
+ ...opts,
147
+ shouldBypassCache: (event) => {
148
+ return event.req.method !== "GET" && event.req.method !== "HEAD";
149
+ },
150
+ getKey: async (event) => {
151
+ // Custom user-defined key
152
+ const customKey = await opts.getKey?.(event);
153
+ if (customKey) {
154
+ return escapeKey(customKey);
155
+ }
156
+ // Auto-generated key
157
+ const _path = event.url.pathname + event.url.search;
158
+ let _pathname;
159
+ try {
160
+ _pathname = escapeKey(decodeURI(parseURL(_path).pathname)).slice(0, 16) || "index";
161
+ } catch {
162
+ _pathname = "-";
163
+ }
164
+ const _hashedPath = `${_pathname}.${hash(_path)}`;
165
+ const _headers = variableHeaderNames.map((header) => [header, event.req.headers.get(header)]).map(([name, value]) => `${escapeKey(name)}.${hash(value)}`);
166
+ return [_hashedPath, ..._headers].join(":");
167
+ },
168
+ validate: (entry) => {
169
+ if (!entry.value) {
170
+ return false;
171
+ }
172
+ if (entry.value.status >= 400) {
173
+ return false;
174
+ }
175
+ if (entry.value.body === undefined) {
176
+ return false;
177
+ }
178
+ // https://github.com/nitrojs/nitro/pull/1857
179
+ if (entry.value.headers.etag === "undefined" || entry.value.headers["last-modified"] === "undefined") {
180
+ return false;
181
+ }
182
+ return true;
183
+ },
184
+ group: opts.group || "nitro/handlers",
185
+ integrity: opts.integrity || hash([handler, opts])
186
+ };
187
+ const _cachedHandler = cachedFunction(async (event) => {
188
+ // Filter non variable headers
189
+ const filteredHeaders = [...event.req.headers.entries()].filter(([key]) => !variableHeaderNames.includes(key.toLowerCase()));
190
+ try {
191
+ const originalReq = event.req;
192
+ // @ts-expect-error assigning to publicly readonly property
193
+ event.req = new Request(event.req.url, {
194
+ method: event.req.method,
195
+ headers: filteredHeaders
196
+ });
197
+ // Inherit srvx context
198
+ event.req.runtime = originalReq.runtime;
199
+ event.req.waitUntil = originalReq.waitUntil;
200
+ } catch (error) {
201
+ console.error("[cache] Failed to filter headers:", error);
202
+ }
203
+ // Call handler
204
+ const rawValue = await handler(event);
205
+ const res = await toResponse(rawValue, event);
206
+ // Stringified body
207
+ // TODO: support binary responses
208
+ const body = await res.text();
209
+ if (!res.headers.has("etag")) {
210
+ res.headers.set("etag", `W/"${hash(body)}"`);
211
+ }
212
+ if (!res.headers.has("last-modified")) {
213
+ res.headers.set("last-modified", new Date().toUTCString());
214
+ }
215
+ const cacheControl = [];
216
+ if (opts.swr) {
217
+ if (opts.maxAge) {
218
+ cacheControl.push(`s-maxage=${opts.maxAge}`);
219
+ }
220
+ if (opts.staleMaxAge) {
221
+ cacheControl.push(`stale-while-revalidate=${opts.staleMaxAge}`);
222
+ } else {
223
+ cacheControl.push("stale-while-revalidate");
224
+ }
225
+ } else if (opts.maxAge) {
226
+ cacheControl.push(`max-age=${opts.maxAge}`);
227
+ }
228
+ if (cacheControl.length > 0) {
229
+ res.headers.set("cache-control", cacheControl.join(", "));
230
+ }
231
+ const cacheEntry = {
232
+ status: res.status,
233
+ statusText: res.statusText,
234
+ headers: Object.fromEntries(res.headers.entries()),
235
+ body
236
+ };
237
+ return cacheEntry;
238
+ }, _opts);
239
+ return defineHandler(async (event) => {
240
+ // Headers-only mode
241
+ if (opts.headersOnly) {
242
+ // TODO: Send SWR too
243
+ if (handleCacheHeaders(event, { maxAge: opts.maxAge })) {
244
+ return;
245
+ }
246
+ return handler(event);
247
+ }
248
+ // Call with cache
249
+ const response = await _cachedHandler(event);
250
+ // Check for cache headers
251
+ if (handleCacheHeaders(event, {
252
+ modifiedTime: new Date(response.headers["last-modified"]),
253
+ etag: response.headers.etag,
254
+ maxAge: opts.maxAge
255
+ })) {
256
+ return;
257
+ }
258
+ // Send Response
259
+ return new FastResponse(response.body, {
260
+ status: response.status,
261
+ statusText: response.statusText,
262
+ headers: response.headers
263
+ });
264
+ });
234
265
  }
235
- export const cachedEventHandler = defineCachedEventHandler;
236
- export const defineCachedHandler = defineCachedEventHandler;
@@ -1,12 +1,12 @@
1
1
  import type { ServerRequest } from "srvx";
2
- export declare const nitroAsyncContext: import("unctx/index").UseContext<NitroAsyncContext>;
2
+ export declare const nitroAsyncContext: unknown;
3
3
  /**
4
- *
5
- * Access to the current Nitro request.
6
- *
7
- * @experimental
8
- * - Requires `experimental.asyncContext: true` config to work.
9
- * - Works in Node.js and limited runtimes only
10
- *
11
- */
4
+ *
5
+ * Access to the current Nitro request.
6
+ *
7
+ * @experimental
8
+ * - Requires `experimental.asyncContext: true` config to work.
9
+ * - Works in Node.js and limited runtimes only
10
+ *
11
+ */
12
12
  export declare function useRequest(): ServerRequest;
@@ -2,16 +2,23 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { HTTPError } from "h3";
3
3
  import { getContext } from "unctx";
4
4
  export const nitroAsyncContext = /* @__PURE__ */ (() => getContext("nitro-app", {
5
- asyncContext: import.meta._asyncContext,
6
- AsyncLocalStorage: import.meta._asyncContext ? AsyncLocalStorage : void 0
5
+ asyncContext: import.meta._asyncContext,
6
+ AsyncLocalStorage: import.meta._asyncContext ? AsyncLocalStorage : undefined
7
7
  }))();
8
+ /**
9
+ *
10
+ * Access to the current Nitro request.
11
+ *
12
+ * @experimental
13
+ * - Requires `experimental.asyncContext: true` config to work.
14
+ * - Works in Node.js and limited runtimes only
15
+ *
16
+ */
8
17
  export function useRequest() {
9
- try {
10
- return nitroAsyncContext.use().request;
11
- } catch {
12
- const hint = import.meta._asyncContext ? "Note: This is an experimental feature and might be broken on non-Node.js environments." : "Enable the experimental flag using `experimental.asyncContext: true`.";
13
- throw new HTTPError({
14
- message: `Nitro request context is not available. ${hint}`
15
- });
16
- }
18
+ try {
19
+ return nitroAsyncContext.use().request;
20
+ } catch {
21
+ const hint = import.meta._asyncContext ? "Note: This is an experimental feature and might be broken on non-Node.js environments." : "Enable the experimental flag using `experimental.asyncContext: true`.";
22
+ throw new HTTPError({ message: `Nitro request context is not available. ${hint}` });
23
+ }
17
24
  }
@@ -1,14 +1,12 @@
1
1
  import { createDatabase } from "db0";
2
2
  import { connectionConfigs } from "#nitro-internal-virtual/database";
3
- const instances = /* @__PURE__ */ Object.create(null);
3
+ const instances = Object.create(null);
4
4
  export function useDatabase(name = "default") {
5
- if (instances[name]) {
6
- return instances[name];
7
- }
8
- if (!connectionConfigs[name]) {
9
- throw new Error(`Database connection "${name}" not configured.`);
10
- }
11
- return instances[name] = createDatabase(
12
- connectionConfigs[name].connector(connectionConfigs[name].options || {})
13
- );
5
+ if (instances[name]) {
6
+ return instances[name];
7
+ }
8
+ if (!connectionConfigs[name]) {
9
+ throw new Error(`Database connection "${name}" not configured.`);
10
+ }
11
+ return instances[name] = createDatabase(connectionConfigs[name].connector(connectionConfigs[name].options || {}));
14
12
  }
@@ -1,9 +1,10 @@
1
1
  import type { HTTPError, HTTPEvent } from "h3";
2
2
  import type { InternalHandlerResponse } from "./utils.mjs";
3
- declare const _default: NitroErrorHandler;
3
+ declare const _default;
4
4
  export default _default;
5
5
  export declare function defaultHandler(error: HTTPError, event: HTTPEvent, opts?: {
6
- silent?: boolean;
7
- json?: boolean;
6
+ silent?: boolean;
7
+ json?: boolean;
8
8
  }): Promise<InternalHandlerResponse>;
9
- export declare function loadStackTrace(error: any): Promise<void>;
9
+ // ---- Source Map support ----
10
+ export declare function loadStackTrace(error: any);