nitro-nightly 3.0.1-20251108-180447-f148172c → 3.0.1-20251108-185438-04c7fe99

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.
@@ -1,712 +1,68 @@
1
- import { i as __toESM } from "../_chunks/Bqks5huO.mjs";
2
- import { C as join, D as relative, O as resolve, b as dirname, x as extname } from "../_libs/c12.mjs";
3
- import { i as unplugin } from "../_libs/unimport.mjs";
4
- import { t as glob } from "../_libs/tinyglobby.mjs";
5
- import { t as src_default } from "../_libs/mime.mjs";
6
- import { i as genSafeVariableName, t as genImport } from "../_libs/knitwork.mjs";
7
- import { t as replace } from "../_libs/plugin-replace.mjs";
8
- import { t as unwasm } from "../_libs/unwasm.mjs";
9
- import { t as require_etag } from "../_libs/etag.mjs";
10
- import { camelCase } from "scule";
11
- import { promises } from "node:fs";
12
- import { joinURL, withTrailingSlash } from "ufo";
13
- import { readFile } from "node:fs/promises";
14
- import { defu } from "defu";
15
- import { pkgDir, runtimeDependencies, runtimeDir } from "nitro/meta";
16
- import { hash } from "ohash";
17
- import { defineEnv } from "unenv";
18
- import { connectors } from "db0";
19
- import { transform } from "esbuild";
20
- import { builtinDrivers, normalizeKey } from "unstorage";
21
- import { rollupNodeFileTrace } from "nf3";
22
- import { RENDER_CONTEXT_KEYS, compileTemplateToString, hasTemplateSyntax } from "rendu";
23
-
24
- //#region src/build/plugins/replace.ts
25
- const NO_REPLACE_RE = /ROLLUP_NO_REPLACE|\\0raw:/;
26
- function replace$1(options) {
27
- const _plugin = replace(options);
28
- return {
29
- ..._plugin,
30
- renderChunk(code, chunk, options$1) {
31
- if (!NO_REPLACE_RE.test(code)) return _plugin.renderChunk.call(this, code, chunk, options$1);
32
- }
33
- };
34
- }
35
-
36
- //#endregion
37
- //#region src/build/config.ts
38
- function baseBuildConfig(nitro) {
39
- const presetsDir$1 = resolve(runtimeDir, "../presets");
40
- const extensions = [
41
- ".ts",
42
- ".mjs",
43
- ".js",
44
- ".json",
45
- ".node",
46
- ".tsx",
47
- ".jsx"
48
- ];
49
- const isNodeless = nitro.options.node === false;
50
- let NODE_ENV = nitro.options.dev ? "development" : "production";
51
- if (nitro.options.preset === "nitro-prerender") NODE_ENV = "prerender";
52
- const buildEnvVars = {
53
- NODE_ENV,
54
- prerender: nitro.options.preset === "nitro-prerender",
55
- server: true,
56
- client: false,
57
- dev: String(nitro.options.dev),
58
- DEBUG: nitro.options.dev
59
- };
60
- const staticFlags = {
61
- dev: nitro.options.dev,
62
- preset: nitro.options.preset,
63
- prerender: nitro.options.preset === "nitro-prerender",
64
- server: true,
65
- client: false,
66
- nitro: true,
67
- baseURL: nitro.options.baseURL,
68
- "versions.nitro": "",
69
- "versions?.nitro": "",
70
- _asyncContext: nitro.options.experimental.asyncContext,
71
- _websocket: nitro.options.experimental.websocket,
72
- _tasks: nitro.options.experimental.tasks
73
- };
74
- const replacements = {
75
- "typeof window": "\"undefined\"",
76
- _import_meta_url_: "import.meta.url",
77
- "globalThis.process.": "process.",
78
- "process.env.RUNTIME_CONFIG": () => JSON.stringify(nitro.options.runtimeConfig, null, 2),
79
- ...Object.fromEntries(Object.entries(buildEnvVars).map(([key, val]) => [`process.env.${key}`, JSON.stringify(val)])),
80
- ...Object.fromEntries(Object.entries(buildEnvVars).map(([key, val]) => [`import.meta.env.${key}`, JSON.stringify(val)])),
81
- ...Object.fromEntries(Object.entries(staticFlags).map(([key, val]) => [`process.${key}`, JSON.stringify(val)])),
82
- ...Object.fromEntries(Object.entries(staticFlags).map(([key, val]) => [`import.meta.${key}`, JSON.stringify(val)])),
83
- ...nitro.options.replace
84
- };
85
- const noExternal = [
86
- "#",
87
- "~",
88
- "@/",
89
- "~~",
90
- "@@/",
91
- "virtual:",
92
- "nitro",
93
- pkgDir,
94
- nitro.options.serverDir,
95
- dirname(nitro.options.entry),
96
- ...nitro.options.experimental.wasm ? [(id) => id?.endsWith(".wasm")] : [],
97
- ...nitro.options.handlers.map((m) => m.handler).filter((i) => typeof i === "string"),
98
- ...nitro.options.dev || nitro.options.preset === "nitro-prerender" ? [] : runtimeDependencies
99
- ].filter(Boolean);
100
- const { env } = defineEnv({
101
- nodeCompat: isNodeless,
102
- npmShims: true,
103
- resolve: true,
104
- presets: nitro.options.unenv,
105
- overrides: { alias: nitro.options.alias }
106
- });
107
- return {
108
- presetsDir: presetsDir$1,
109
- extensions,
110
- isNodeless,
111
- buildEnvVars,
112
- staticFlags,
113
- replacements,
114
- env,
115
- aliases: resolveAliases({ ...env.alias }),
116
- noExternal
117
- };
118
- }
119
- function resolveAliases(_aliases) {
120
- const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => b.split("/").length - a.split("/").length || b.length - a.length));
121
- for (const key in aliases) for (const alias in aliases) {
122
- if (![
123
- "~",
124
- "@",
125
- "#"
126
- ].includes(alias[0])) continue;
127
- if (alias === "@" && !aliases[key].startsWith("@/")) continue;
128
- if (aliases[key].startsWith(alias)) aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
129
- }
130
- return aliases;
131
- }
132
-
133
- //#endregion
134
- //#region src/build/plugins/virtual.ts
135
- const PREFIX = "\0virtual:";
136
- function virtual(modules, cache = {}, opts) {
137
- const _modules = /* @__PURE__ */ new Map();
138
- for (const [id, mod] of Object.entries(modules)) {
139
- cache[id] = mod;
140
- _modules.set(id, mod);
141
- _modules.set(resolve(id), mod);
142
- }
143
- return {
144
- name: "virtual",
145
- resolveId(id, importer) {
146
- if (id in modules) return {
147
- id: PREFIX + id,
148
- ...opts
149
- };
150
- if (importer) {
151
- const resolved = resolve(dirname(importer.startsWith(PREFIX) ? importer.slice(9) : importer), id);
152
- if (_modules.has(resolved)) return PREFIX + resolved;
153
- }
154
- return null;
155
- },
156
- async load(id) {
157
- if (!id.startsWith(PREFIX)) return null;
158
- const idNoPrefix = id.slice(9);
159
- if (!_modules.has(idNoPrefix)) return null;
160
- let m = _modules.get(idNoPrefix);
161
- if (typeof m === "function") m = await m();
162
- if (!m) return null;
163
- cache[id.replace(PREFIX, "")] = m;
164
- return {
165
- code: m,
166
- map: null
167
- };
168
- }
169
- };
170
- }
171
-
172
- //#endregion
173
- //#region src/build/plugins/database.ts
174
- function database(nitro) {
175
- if (!nitro.options.experimental.database) return virtual({ "#nitro-internal-virtual/database": () => {
176
- return `export const connectionConfigs = {};`;
177
- } }, nitro.vfs);
178
- const dbConfigs = nitro.options.dev && nitro.options.devDatabase || nitro.options.database;
179
- const connectorsNames = [...new Set(Object.values(dbConfigs || {}).map((config) => config?.connector))].filter(Boolean);
180
- for (const name of connectorsNames) if (!connectors[name]) throw new Error(`Database connector "${name}" is invalid.`);
181
- return virtual({ "#nitro-internal-virtual/database": () => {
182
- return `
183
- ${connectorsNames.map((name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`).join("\n")}
184
-
185
- export const connectionConfigs = {
186
- ${Object.entries(dbConfigs || {}).map(([name, { connector, options }]) => `${name}: {
187
- connector: ${camelCase(connector)}Connector,
188
- options: ${JSON.stringify(options)}
189
- }`).join(",\n")}
190
- };
191
- `;
192
- } }, nitro.vfs);
193
- }
194
-
195
- //#endregion
196
- //#region src/build/plugins/routing.ts
197
- const RuntimeRouteRules = [
198
- "headers",
199
- "redirect",
200
- "proxy",
201
- "cache"
1
+ import { C as join$1, D as relative$1, O as resolve$1 } from "../_libs/c12.mjs";
2
+ import { i as writeFile$1 } from "../_chunks/DTJoprWj.mjs";
3
+ import { dirname } from "node:path";
4
+ import { mkdir, readFile, stat } from "node:fs/promises";
5
+ import { version } from "nitro/meta";
6
+
7
+ //#region src/presets/_types.gen.ts
8
+ const presetsWithConfig = [
9
+ "awsAmplify",
10
+ "awsLambda",
11
+ "azure",
12
+ "cloudflare",
13
+ "firebase",
14
+ "netlify",
15
+ "vercel"
202
16
  ];
203
- function routing(nitro) {
204
- return virtual({
205
- "#nitro-internal-virtual/routing": () => {
206
- const allHandlers = uniqueBy([
207
- ...Object.values(nitro.routing.routes.routes).flatMap((h) => h.data),
208
- ...Object.values(nitro.routing.routedMiddleware.routes).map((h) => h.data),
209
- ...nitro.routing.globalMiddleware
210
- ], "_importHash");
211
- return `
212
- import * as __routeRules__ from "nitro/~internal/runtime/route-rules";
213
- import * as srvxNode from "srvx/node"
214
- import * as h3 from "h3";
215
-
216
- export const findRouteRules = ${nitro.routing.routeRules.compileToString({
217
- serialize: serializeRouteRule,
218
- matchAll: true
219
- })}
220
-
221
- const multiHandler = (...handlers) => {
222
- const final = handlers.pop()
223
- const middleware = handlers.filter(Boolean).map(h => h3.toMiddleware(h));
224
- return (ev) => h3.callMiddleware(ev, middleware, final);
225
- }
226
-
227
- ${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "${h.handler}";`).join("\n")}
228
-
229
- ${allHandlers.filter((h) => h.lazy).map((h) => `const ${h._importHash} = h3.defineLazyEventHandler(() => import("${h.handler}")${h.format === "node" ? ".then(m => srvxNode.toFetchHandler(m.default))" : ""});`).join("\n")}
230
-
231
- export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })}
232
-
233
- export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({
234
- serialize: serializeHandler,
235
- matchAll: true
236
- })};
237
-
238
- export const globalMiddleware = [
239
- ${nitro.routing.globalMiddleware.map((h) => h.lazy ? h._importHash : `h3.toEventHandler(${h._importHash})`).join(",")}
240
- ].filter(Boolean);
241
- `;
242
- },
243
- "#nitro-internal-virtual/routing-meta": () => {
244
- const routeHandlers = uniqueBy(Object.values(nitro.routing.routes.routes).flatMap((h) => h.data), "_importHash");
245
- return `
246
- ${routeHandlers.map((h) => `import ${h._importHash}Meta from "${h.handler}?meta";`).join("\n")}
247
- export const handlersMeta = [
248
- ${routeHandlers.map((h) => `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(h.method?.toLowerCase())}, meta: ${h._importHash}Meta }`).join(",\n")}
249
- ];
250
- `.trim();
251
- }
252
- }, nitro.vfs);
253
- }
254
- function uniqueBy(arr, key) {
255
- return [...new Map(arr.map((item) => [item[key], item])).values()];
256
- }
257
- function serializeHandler(h) {
258
- const meta = Array.isArray(h) ? h[0] : h;
259
- return `{${[
260
- `route:${JSON.stringify(meta.route)}`,
261
- meta.method && `method:${JSON.stringify(meta.method)}`,
262
- meta.meta && `meta:${JSON.stringify(meta.meta)}`,
263
- `handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}`
264
- ].filter(Boolean).join(",")}}`;
265
- }
266
- function serializeHandlerFn(h) {
267
- let code = h._importHash;
268
- if (!h.lazy) {
269
- if (h.format === "node") code = `srvxNode.toFetchHandler(${code})`;
270
- code = `h3.toEventHandler(${code})`;
271
- }
272
- return code;
273
- }
274
- function serializeRouteRule(h) {
275
- return `[${Object.entries(h).filter(([name, options]) => options !== void 0 && name[0] !== "_").map(([name, options]) => {
276
- return `{${[
277
- `name:${JSON.stringify(name)}`,
278
- `route:${JSON.stringify(h._route)}`,
279
- h._method && `method:${JSON.stringify(h._method)}`,
280
- RuntimeRouteRules.includes(name) && `handler:__routeRules__.${name}`,
281
- `options:${JSON.stringify(options)}`
282
- ].filter(Boolean).join(",")}}`;
283
- }).join(",")}]`;
284
- }
285
17
 
286
18
  //#endregion
287
- //#region src/build/plugins/route-meta.ts
288
- const virtualPrefix = "\0nitro-handler-meta:";
289
- const esbuildLoaders = {
290
- ".ts": "ts",
291
- ".js": "js",
292
- ".tsx": "tsx",
293
- ".jsx": "jsx"
294
- };
295
- function routeMeta(nitro) {
19
+ //#region src/build/info.ts
20
+ const NITRO_WELLKNOWN_DIR = "node_modules/.nitro";
21
+ async function getBuildInfo(root) {
22
+ const outputDir = await findLastBuildDir(root);
23
+ if (!await stat(outputDir).then((s) => s.isDirectory()).catch(() => false)) return {};
296
24
  return {
297
- name: "nitro:route-meta",
298
- async resolveId(id, importer, resolveOpts) {
299
- if (id.startsWith("\0")) return;
300
- if (id.endsWith(`?meta`)) {
301
- const resolved = await this.resolve(id.replace(`?meta`, ``), importer, resolveOpts);
302
- if (!resolved) return;
303
- return virtualPrefix + resolved.id;
304
- }
305
- },
306
- load(id) {
307
- if (id.startsWith(virtualPrefix)) return readFile(id.slice(20), { encoding: "utf8" });
308
- },
309
- async transform(code, id) {
310
- if (!id.startsWith(virtualPrefix)) return;
311
- let meta = null;
312
- try {
313
- const jsCode = await transform(code, { loader: esbuildLoaders[extname(id)] }).then((r) => r.code);
314
- const ast = this.parse(jsCode);
315
- for (const node of ast.body) if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "defineRouteMeta" && node.expression.arguments.length === 1) {
316
- meta = astToObject(node.expression.arguments[0]);
317
- break;
318
- }
319
- } catch (error) {
320
- nitro.logger.warn(`[handlers-meta] Cannot extra route meta for: ${id}: ${error}`);
321
- }
322
- return {
323
- code: `export default ${JSON.stringify(meta)};`,
324
- map: null
325
- };
326
- }
25
+ outputDir,
26
+ buildInfo: await readFile(resolve$1(outputDir, "nitro.json"), "utf8").then(JSON.parse).catch(() => void 0)
327
27
  };
328
28
  }
329
- function astToObject(node) {
330
- switch (node.type) {
331
- case "ObjectExpression": {
332
- const obj = {};
333
- for (const prop of node.properties) if (prop.type === "Property") {
334
- const key = prop.key.name ?? prop.key.value;
335
- obj[key] = astToObject(prop.value);
336
- }
337
- return obj;
338
- }
339
- case "ArrayExpression": return node.elements.map((el) => astToObject(el)).filter(Boolean);
340
- case "Literal": return node.value;
341
- }
342
- }
343
-
344
- //#endregion
345
- //#region src/build/plugins/server-main.ts
346
- function serverMain(nitro) {
347
- return {
348
- name: "nitro:server-main",
349
- renderChunk(code, chunk) {
350
- if (chunk.isEntry) return {
351
- code: `globalThis.__nitro_main__ = import.meta.url; ${code}`,
352
- map: null
353
- };
354
- }
355
- };
29
+ async function findLastBuildDir(root) {
30
+ const lastBuildLink = join$1(root, NITRO_WELLKNOWN_DIR, "last-build.json");
31
+ return await readFile(lastBuildLink, "utf8").then(JSON.parse).then((data) => resolve$1(lastBuildLink, data.outputDir || "../../../.output")).catch(() => resolve$1(root, ".output"));
356
32
  }
357
-
358
- //#endregion
359
- //#region src/build/plugins/public-assets.ts
360
- var import_etag$1 = /* @__PURE__ */ __toESM(require_etag(), 1);
361
- const readAssetHandler = {
362
- true: "node",
363
- node: "node",
364
- false: "null",
365
- deno: "deno",
366
- inline: "inline"
367
- };
368
- function publicAssets(nitro) {
369
- return virtual({
370
- "#nitro-internal-virtual/public-assets-data": async () => {
371
- const assets = {};
372
- const files = await glob("**", {
373
- cwd: nitro.options.output.publicDir,
374
- absolute: false,
375
- dot: true
376
- });
377
- for (const id of files) {
378
- let mimeType = src_default.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
379
- if (mimeType.startsWith("text")) mimeType += "; charset=utf-8";
380
- const fullPath = resolve(nitro.options.output.publicDir, id);
381
- const assetData = await promises.readFile(fullPath);
382
- const etag = (0, import_etag$1.default)(assetData);
383
- const stat$1 = await promises.stat(fullPath);
384
- const assetId = joinURL(nitro.options.baseURL, decodeURIComponent(id));
385
- let encoding;
386
- if (id.endsWith(".gz")) encoding = "gzip";
387
- else if (id.endsWith(".br")) encoding = "br";
388
- assets[assetId] = {
389
- type: nitro._prerenderMeta?.[assetId]?.contentType || mimeType,
390
- encoding,
391
- etag,
392
- mtime: stat$1.mtime.toJSON(),
393
- size: stat$1.size,
394
- path: relative(nitro.options.output.serverDir, fullPath),
395
- data: nitro.options.serveStatic === "inline" ? assetData.toString("base64") : void 0
396
- };
397
- }
398
- return `export default ${JSON.stringify(assets, null, 2)};`;
399
- },
400
- "#nitro-internal-virtual/public-assets-node": () => {
401
- return `
402
- import { promises as fsp } from 'node:fs'
403
- import { fileURLToPath } from 'node:url'
404
- import { resolve, dirname } from 'node:path'
405
- import assets from '#nitro-internal-virtual/public-assets-data'
406
- export function readAsset (id) {
407
- const serverDir = dirname(fileURLToPath(globalThis.__nitro_main__))
408
- return fsp.readFile(resolve(serverDir, assets[id].path))
409
- }`;
410
- },
411
- "#nitro-internal-virtual/public-assets-deno": () => {
412
- return `
413
- import assets from '#nitro-internal-virtual/public-assets-data'
414
- export function readAsset (id) {
415
- // https://deno.com/deploy/docs/serve-static-assets
416
- const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname)
417
- return Deno.readFile(path);
418
- }`;
419
- },
420
- "#nitro-internal-virtual/public-assets-null": () => {
421
- return `
422
- export function readAsset (id) {
423
- return Promise.resolve(null);
424
- }`;
425
- },
426
- "#nitro-internal-virtual/public-assets-inline": () => {
427
- return `
428
- import assets from '#nitro-internal-virtual/public-assets-data'
429
- export function readAsset (id) {
430
- if (!assets[id]) { return undefined }
431
- if (assets[id]._data) { return assets[id]._data }
432
- if (!assets[id].data) { return assets[id].data }
433
- assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0))
434
- return assets[id]._data
435
- }`;
33
+ async function writeBuildInfo(nitro) {
34
+ const buildInfoPath = resolve$1(nitro.options.output.dir, "nitro.json");
35
+ const buildInfo = {
36
+ date: (/* @__PURE__ */ new Date()).toJSON(),
37
+ preset: nitro.options.preset,
38
+ framework: nitro.options.framework,
39
+ versions: { nitro: version },
40
+ commands: {
41
+ preview: nitro.options.commands.preview,
42
+ deploy: nitro.options.commands.deploy
436
43
  },
437
- "#nitro-internal-virtual/public-assets": () => {
438
- const publicAssetBases = Object.fromEntries(nitro.options.publicAssets.filter((dir) => !dir.fallthrough && dir.baseURL !== "/").map((dir) => [withTrailingSlash(joinURL(nitro.options.baseURL, dir.baseURL || "/")), { maxAge: dir.maxAge }]));
439
- return `
440
- import assets from '#nitro-internal-virtual/public-assets-data'
441
- export { readAsset } from "${`#nitro-internal-virtual/public-assets-${readAssetHandler[nitro.options.serveStatic] || "null"}`}"
442
- export const publicAssetBases = ${JSON.stringify(publicAssetBases)}
443
-
444
- export function isPublicAssetURL(id = '') {
445
- if (assets[id]) {
446
- return true
447
- }
448
- for (const base in publicAssetBases) {
449
- if (id.startsWith(base)) { return true }
450
- }
451
- return false
452
- }
453
-
454
- export function getPublicAssetMeta(id = '') {
455
- for (const base in publicAssetBases) {
456
- if (id.startsWith(base)) { return publicAssetBases[base] }
457
- }
458
- return {}
459
- }
460
-
461
- export function getAsset (id) {
462
- return assets[id]
463
- }
464
- `;
465
- }
466
- }, nitro.vfs);
467
- }
468
-
469
- //#endregion
470
- //#region src/build/plugins/server-assets.ts
471
- var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
472
- function serverAssets(nitro) {
473
- if (nitro.options.dev || nitro.options.preset === "nitro-prerender") return virtual({ "#nitro-internal-virtual/server-assets": getAssetsDev(nitro) }, nitro.vfs);
474
- return virtual({ "#nitro-internal-virtual/server-assets": async () => {
475
- const assets = {};
476
- for (const asset of nitro.options.serverAssets) {
477
- const files = await glob(asset.pattern || "**/*", {
478
- cwd: asset.dir,
479
- absolute: false,
480
- ignore: asset.ignore
481
- });
482
- for (const _id of files) {
483
- const fsPath = resolve(asset.dir, _id);
484
- const id = asset.baseName + "/" + _id;
485
- assets[id] = {
486
- fsPath,
487
- meta: {}
488
- };
489
- let type = src_default.getType(id) || "text/plain";
490
- if (type.startsWith("text")) type += "; charset=utf-8";
491
- const etag = (0, import_etag.default)(await promises.readFile(fsPath));
492
- const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON());
493
- assets[id].meta = {
494
- type,
495
- etag,
496
- mtime
497
- };
498
- }
499
- }
500
- return getAssetProd(assets);
501
- } }, nitro.vfs);
502
- }
503
- function getAssetsDev(nitro) {
504
- return `
505
- import { createStorage } from 'unstorage'
506
- import fsDriver from 'unstorage/drivers/fs'
507
-
508
- const serverAssets = ${JSON.stringify(nitro.options.serverAssets)}
509
-
510
- export const assets = createStorage()
511
-
512
- for (const asset of serverAssets) {
513
- assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) }))
514
- }`;
515
- }
516
- function getAssetProd(assets) {
517
- return `
518
- const _assets = {\n${Object.entries(assets).map(([id, asset]) => ` [${JSON.stringify(normalizeKey(id))}]: {\n import: () => import(${JSON.stringify("raw:" + asset.fsPath)}).then(r => r.default || r),\n meta: ${JSON.stringify(asset.meta)}\n }`).join(",\n")}\n}
519
-
520
- const normalizeKey = ${normalizeKey.toString()}
521
-
522
- export const assets = {
523
- getKeys() {
524
- return Promise.resolve(Object.keys(_assets))
525
- },
526
- hasItem (id) {
527
- id = normalizeKey(id)
528
- return Promise.resolve(id in _assets)
529
- },
530
- getItem (id) {
531
- id = normalizeKey(id)
532
- return Promise.resolve(_assets[id] ? _assets[id].import() : null)
533
- },
534
- getMeta (id) {
535
- id = normalizeKey(id)
536
- return Promise.resolve(_assets[id] ? _assets[id].meta : {})
537
- }
538
- }
539
- `;
540
- }
541
-
542
- //#endregion
543
- //#region src/build/plugins/storage.ts
544
- function storage(nitro) {
545
- const mounts = [];
546
- const storageMounts = nitro.options.dev || nitro.options.preset === "nitro-prerender" ? {
547
- ...nitro.options.storage,
548
- ...nitro.options.devStorage
549
- } : nitro.options.storage;
550
- for (const path in storageMounts) {
551
- const mount = storageMounts[path];
552
- mounts.push({
553
- path,
554
- driver: builtinDrivers[mount.driver] || mount.driver,
555
- opts: mount
556
- });
557
- }
558
- const driverImports = [...new Set(mounts.map((m) => m.driver))];
559
- return virtual({ "#nitro-internal-virtual/storage": `
560
- import { createStorage } from 'unstorage'
561
- import { assets } from '#nitro-internal-virtual/server-assets'
562
-
563
- ${driverImports.map((i) => genImport(i, genSafeVariableName(i))).join("\n")}
564
-
565
- export function initStorage() {
566
- const storage = createStorage({})
567
- storage.mount('/assets', assets)
568
- ${mounts.map((m) => `storage.mount('${m.path}', ${genSafeVariableName(m.driver)}(${JSON.stringify(m.opts)}))`).join("\n")}
569
- return storage
570
- }
571
- ` }, nitro.vfs);
572
- }
573
-
574
- //#endregion
575
- //#region src/build/plugins/error-handler.ts
576
- function errorHandler(nitro) {
577
- return virtual({ "#nitro-internal-virtual/error-handler": () => {
578
- const errorHandlers = Array.isArray(nitro.options.errorHandler) ? nitro.options.errorHandler : [nitro.options.errorHandler];
579
- const builtinHandler = join(runtimeDir, `internal/error/${nitro.options.dev ? "dev" : "prod"}`);
580
- return `
581
- ${errorHandlers.map((h, i) => `import errorHandler$${i} from "${h}";`).join("\n")}
582
-
583
- const errorHandlers = [${errorHandlers.map((_, i) => `errorHandler$${i}`).join(", ")}];
584
-
585
- import { defaultHandler } from "${builtinHandler}";
586
-
587
- export default async function(error, event) {
588
- for (const handler of errorHandlers) {
589
- try {
590
- const response = await handler(error, event, { defaultHandler });
591
- if (response) {
592
- return response;
593
- }
594
- } catch(error) {
595
- // Handler itself thrown, log and continue
596
- console.error(error);
597
- }
598
- }
599
- // H3 will handle fallback
600
- }
601
- `;
602
- } }, nitro.vfs);
603
- }
604
-
605
- //#endregion
606
- //#region src/build/plugins/renderer-template.ts
607
- function rendererTemplate(nitro) {
608
- return virtual({ "#nitro-internal-virtual/renderer-template": async () => {
609
- if (typeof nitro.options.renderer?.template !== "string") return `export const rendererTemplate = () => '<!-- renderer.template is not set -->'; export const rendererTemplateFile = undefined;`;
610
- if (nitro.options.dev) return `import { readFile } from 'node:fs/promises';export const rendererTemplate = () => readFile(${JSON.stringify(nitro.options.renderer?.template)}, "utf8"); export const rendererTemplateFile = ${JSON.stringify(nitro.options.renderer?.template)};`;
611
- else {
612
- const html = await readFile(nitro.options.renderer?.template, "utf8");
613
- if (hasTemplateSyntax(html)) return `
614
- import { renderToResponse } from 'rendu'
615
- import { serverFetch } from 'nitro/app'
616
- const template = ${compileTemplateToString(html, { contextKeys: [...RENDER_CONTEXT_KEYS] })};
617
- export const rendererTemplate = (request) => renderToResponse(template, { request, context: { serverFetch } })
618
- `;
619
- else return `
620
- import { HTTPResponse } from "h3";
621
- export const rendererTemplate = () => new HTTPResponse(${JSON.stringify(html)}, { headers: { "content-type": "text/html; charset=utf-8" } });
622
- `;
623
- }
624
- } }, nitro.vfs);
625
- }
626
-
627
- //#endregion
628
- //#region src/build/plugins/feature-flags.ts
629
- function featureFlags(nitro) {
630
- return virtual({ "#nitro-internal-virtual/feature-flags": () => {
631
- const featureFlags$1 = {
632
- hasRoutes: nitro.routing.routes.hasRoutes(),
633
- hasRouteRules: nitro.routing.routeRules.hasRoutes(),
634
- hasRoutedMiddleware: nitro.routing.routedMiddleware.hasRoutes(),
635
- hasGlobalMiddleware: nitro.routing.globalMiddleware.length > 0,
636
- hasPlugins: nitro.options.plugins.length > 0,
637
- hasHooks: nitro.options.features?.runtimeHooks ?? nitro.options.plugins.length > 0
638
- };
639
- return Object.entries(featureFlags$1).map(([key, value]) => `export const ${key} = ${Boolean(value)};`).join("\n");
640
- } }, nitro.vfs);
641
- }
642
-
643
- //#endregion
644
- //#region src/build/plugins/resolve.ts
645
- const subpathMap = {
646
- "nitro/h3": "h3",
647
- "nitro/deps/h3": "h3",
648
- "nitro/deps/ofetch": "ofetch"
649
- };
650
- function nitroResolveIds() {
651
- return {
652
- name: "nitro:resolve-ids",
653
- resolveId: {
654
- order: "pre",
655
- handler(id, importer, rOpts) {
656
- if (importer && importer.startsWith("\0virtual:#nitro-internal-virtual")) return this.resolve(id, runtimeDir, { skipSelf: true });
657
- const mappedId = subpathMap[id];
658
- if (mappedId) return this.resolve(mappedId, runtimeDir, { skipSelf: true });
659
- }
44
+ config: { ...Object.fromEntries(presetsWithConfig.map((key) => [key, nitro.options[key]])) }
45
+ };
46
+ await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2), true);
47
+ const lastBuild = join$1(nitro.options.rootDir, NITRO_WELLKNOWN_DIR, "last-build.json");
48
+ await mkdir(dirname(lastBuild), { recursive: true });
49
+ await writeFile$1(lastBuild, JSON.stringify({ outputDir: relative$1(lastBuild, nitro.options.output.dir) }));
50
+ return buildInfo;
51
+ }
52
+ async function writeDevBuildInfo(nitro, addr) {
53
+ const buildInfoPath = join$1(nitro.options.rootDir, NITRO_WELLKNOWN_DIR, "nitro.dev.json");
54
+ const buildInfo = {
55
+ date: (/* @__PURE__ */ new Date()).toJSON(),
56
+ preset: nitro.options.preset,
57
+ framework: nitro.options.framework,
58
+ versions: { nitro: version },
59
+ dev: {
60
+ pid: process.pid,
61
+ workerAddress: addr
660
62
  }
661
63
  };
64
+ await writeFile$1(buildInfoPath, JSON.stringify(buildInfo, null, 2));
662
65
  }
663
66
 
664
67
  //#endregion
665
- //#region src/build/plugins.ts
666
- function baseBuildPlugins(nitro, base) {
667
- const plugins = [];
668
- if (nitro.options.imports) plugins.push(unplugin.rollup(nitro.options.imports));
669
- if (nitro.options.experimental.wasm) plugins.push(unwasm(nitro.options.wasm || {}));
670
- plugins.push(serverMain(nitro));
671
- const nitroPlugins = [...new Set(nitro.options.plugins)];
672
- plugins.push(virtual({ "#nitro-internal-virtual/plugins": `
673
- ${nitroPlugins.map((plugin) => `import _${hash(plugin).replace(/-/g, "")} from '${plugin}';`).join("\n")}
674
-
675
- export const plugins = [
676
- ${nitroPlugins.map((plugin) => `_${hash(plugin).replace(/-/g, "")}`).join(",\n")}
677
- ]
678
- ` }, nitro.vfs));
679
- plugins.push(featureFlags(nitro));
680
- plugins.push(nitroResolveIds());
681
- plugins.push(serverAssets(nitro));
682
- plugins.push(publicAssets(nitro));
683
- plugins.push(storage(nitro));
684
- plugins.push(database(nitro));
685
- plugins.push(routing(nitro));
686
- if (nitro.options.experimental.openAPI) plugins.push(routeMeta(nitro));
687
- plugins.push(errorHandler(nitro));
688
- plugins.push(virtual({ "#nitro-internal-pollyfills": base.env.polyfill.map((p) => `import '${p}';`).join("\n") || `/* No polyfills */` }, nitro.vfs, { moduleSideEffects: true }));
689
- plugins.push(virtual(nitro.options.virtual, nitro.vfs));
690
- if (nitro.options.renderer?.template) plugins.push(rendererTemplate(nitro));
691
- if (!nitro.options.noExternals) plugins.push(rollupNodeFileTrace(defu(nitro.options.externals, {
692
- outDir: nitro.options.output.serverDir,
693
- moduleDirectories: nitro.options.nodeModulesDirs,
694
- external: nitro.options.nodeModulesDirs,
695
- inline: [...base.noExternal],
696
- traceOptions: {
697
- base: "/",
698
- processCwd: nitro.options.rootDir,
699
- exportsOnly: true
700
- },
701
- traceAlias: {
702
- "h3-nightly": "h3",
703
- ...nitro.options.externals?.traceAlias
704
- },
705
- exportConditions: nitro.options.exportConditions,
706
- writePackageJson: true
707
- })));
708
- return plugins;
709
- }
710
-
711
- //#endregion
712
- export { baseBuildConfig as n, replace$1 as r, baseBuildPlugins as t };
68
+ export { writeBuildInfo as n, writeDevBuildInfo as r, getBuildInfo as t };