-
Notifications
You must be signed in to change notification settings - Fork 511
/
build.ts
512 lines (461 loc) · 14.2 KB
/
build.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import { existsSync, promises as fsp } from "node:fs";
import { relative, resolve, join, dirname, isAbsolute } from "pathe";
import { resolveAlias } from "pathe/utils";
import * as rollup from "rollup";
import fse from "fs-extra";
import { defu } from "defu";
import { watch } from "chokidar";
import { genTypeImport } from "knitwork";
import { debounce } from "perfect-debounce";
import type { TSConfig } from "pkg-types";
import type { RollupError } from "rollup";
import type { OnResolveResult, PartialMessage } from "esbuild";
import type { RouterMethod } from "h3";
import { globby } from "globby";
import {
lookupNodeModuleSubpath,
parseNodeModulePath,
resolvePath,
} from "mlly";
import { generateFSTree } from "./utils/tree";
import { getRollupConfig, RollupConfig } from "./rollup/config";
import { prettyPath, writeFile, isDirectory } from "./utils";
import { GLOB_SCAN_PATTERN, scanHandlers } from "./scan";
import type { Nitro } from "./types";
import { runtimeDir } from "./dirs";
import { snapshotStorage } from "./storage";
import { compressPublicAssets } from "./compress";
export async function prepare(nitro: Nitro) {
await prepareDir(nitro.options.output.dir);
if (!nitro.options.noPublicDir) {
await prepareDir(nitro.options.output.publicDir);
}
if (!nitro.options.static) {
await prepareDir(nitro.options.output.serverDir);
}
}
async function prepareDir(dir: string) {
await fsp.mkdir(dir, { recursive: true });
await fse.emptyDir(dir);
}
export async function copyPublicAssets(nitro: Nitro) {
if (nitro.options.noPublicDir) {
return;
}
for (const asset of nitro.options.publicAssets) {
const srcDir = asset.dir;
const dstDir = join(nitro.options.output.publicDir, asset.baseURL!);
if (await isDirectory(srcDir)) {
const publicAssets = await globby("**", {
cwd: srcDir,
absolute: false,
dot: true,
ignore: nitro.options.ignore,
});
await Promise.all(
publicAssets.map(async (file) => {
const src = join(srcDir, file);
const dst = join(dstDir, file);
if (!existsSync(dst)) {
await fsp.cp(src, dst);
}
})
);
}
}
if (nitro.options.compressPublicAssets) {
await compressPublicAssets(nitro);
}
nitro.logger.success(
"Generated public " + prettyPath(nitro.options.output.publicDir)
);
}
export async function build(nitro: Nitro) {
const rollupConfig = getRollupConfig(nitro);
await nitro.hooks.callHook("rollup:before", nitro, rollupConfig);
return nitro.options.dev
? _watch(nitro, rollupConfig)
: _build(nitro, rollupConfig);
}
export async function writeTypes(nitro: Nitro) {
const routeTypes: Record<
string,
Partial<Record<RouterMethod | "default", string[]>>
> = {};
const typesDir = resolve(nitro.options.buildDir, "types");
const middleware = [...nitro.scannedHandlers, ...nitro.options.handlers];
for (const mw of middleware) {
if (typeof mw.handler !== "string" || !mw.route) {
continue;
}
const relativePath = relative(typesDir, mw.handler).replace(
/\.[a-z]+$/,
""
);
if (!routeTypes[mw.route]) {
routeTypes[mw.route] = {};
}
const method = mw.method || "default";
if (!routeTypes[mw.route][method]) {
routeTypes[mw.route][method] = [];
}
routeTypes[mw.route][method].push(
`Simplify<Serialize<Awaited<ReturnType<typeof import('${relativePath}').default>>>>`
);
}
let autoImportedTypes: string[] = [];
let autoImportExports: string;
if (nitro.unimport) {
await nitro.unimport.init();
// TODO: fully resolve utils exported from `#imports`
autoImportExports = await nitro.unimport
.toExports(typesDir)
.then((r) => r.replace(/#internal\/nitro/g, runtimeDir));
const resolvedImportPathMap = new Map<string, string>();
const imports = await nitro.unimport
.getImports()
.then((r) => r.filter((i) => !i.type));
for (const i of imports) {
if (resolvedImportPathMap.has(i.from)) {
continue;
}
let path = resolveAlias(i.from, nitro.options.alias);
if (!isAbsolute(path)) {
const resolvedPath = await resolvePath(i.from, {
url: nitro.options.nodeModulesDirs,
}).catch(() => null);
if (resolvedPath) {
const { dir, name } = parseNodeModulePath(resolvedPath);
if (!dir || !name) {
path = resolvedPath;
} else {
const subpath = await lookupNodeModuleSubpath(resolvedPath);
path = join(dir, name, subpath || "");
}
}
}
if (existsSync(path) && !isDirectory(path)) {
path = path.replace(/\.[a-z]+$/, "");
}
if (isAbsolute(path)) {
path = relative(typesDir, path);
}
resolvedImportPathMap.set(i.from, path);
}
autoImportedTypes = [
(
await nitro.unimport.generateTypeDeclarations({
exportHelper: false,
resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from,
})
).trim(),
];
}
const routes = [
"// Generated by nitro",
"import type { Serialize, Simplify } from 'nitropack'",
"declare module 'nitropack' {",
" type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T",
" interface InternalApi {",
...Object.entries(routeTypes).map(([path, methods]) =>
[
` '${path}': {`,
...Object.entries(methods).map(
([method, types]) => ` '${method}': ${types.join(" | ")}`
),
" }",
].join("\n")
),
" }",
"}",
// Makes this a module for augmentation purposes
"export {}",
];
const config = [
"// Generated by nitro",
`
// App Config
import type { Defu } from 'defu'
${nitro.options.appConfigFiles
.map((file, index) =>
genTypeImport(file.replace(/\.\w+$/, ""), [
{ name: "default", as: `appConfig${index}` },
])
)
.join("\n")}
type UserAppConfig = Defu<{}, [${nitro.options.appConfigFiles
.map((_, index: number) => `typeof appConfig${index}`)
.join(", ")}]>
declare module 'nitropack' {
interface AppConfig extends UserAppConfig {}
}
`,
// Makes this a module for augmentation purposes
"export {}",
];
const declarations = [
// local nitropack augmentations
'/// <reference path="./nitro-routes.d.ts" />',
'/// <reference path="./nitro-config.d.ts" />',
// global server auto-imports
'/// <reference path="./nitro-imports.d.ts" />',
];
const buildFiles: { path: string; contents: string }[] = [];
buildFiles.push({
path: join(typesDir, "nitro-routes.d.ts"),
contents: routes.join("\n"),
});
buildFiles.push({
path: join(typesDir, "nitro-config.d.ts"),
contents: config.join("\n"),
});
buildFiles.push({
path: join(typesDir, "nitro-imports.d.ts"),
contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
"\n"
),
});
buildFiles.push({
path: join(typesDir, "nitro.d.ts"),
contents: declarations.join("\n"),
});
if (nitro.options.typescript.generateTsConfig) {
const tsConfigPath = resolve(
nitro.options.buildDir,
nitro.options.typescript.tsconfigPath
);
const tsconfigDir = dirname(tsConfigPath);
const tsConfig: TSConfig = defu(nitro.options.typescript.tsConfig, {
compilerOptions: {
forceConsistentCasingInFileNames: true,
strict: nitro.options.typescript.strict,
target: "ESNext",
module: "ESNext",
moduleResolution: nitro.options.experimental.typescriptBundlerResolution
? "Bundler"
: "Node",
allowJs: true,
resolveJsonModule: true,
jsx: "preserve",
allowSyntheticDefaultImports: true,
jsxFactory: "h",
jsxFragmentFactory: "Fragment",
paths: {
"#imports": [
relativeWithDot(tsconfigDir, join(typesDir, "nitro-imports")),
],
...(nitro.options.typescript.internalPaths
? {
"#internal/nitro": [
relativeWithDot(tsconfigDir, join(runtimeDir, "index")),
],
"#internal/nitro/*": [
relativeWithDot(tsconfigDir, join(runtimeDir, "*")),
],
}
: {}),
},
},
include: [
relativeWithDot(tsconfigDir, join(typesDir, "nitro.d.ts")).replace(
/^(?=[^.])/,
"./"
),
join(relativeWithDot(tsconfigDir, nitro.options.rootDir), "**/*"),
...(nitro.options.srcDir === nitro.options.rootDir
? []
: [join(relativeWithDot(tsconfigDir, nitro.options.srcDir), "**/*")]),
],
});
buildFiles.push({
path: tsConfigPath,
contents: JSON.stringify(tsConfig, null, 2),
});
}
await Promise.all(
buildFiles.map(async (file) => {
await writeFile(
resolve(nitro.options.buildDir, file.path),
file.contents
);
})
);
}
async function _snapshot(nitro: Nitro) {
if (
nitro.options.bundledStorage.length === 0 ||
nitro.options.preset === "nitro-prerender"
) {
return;
}
// TODO: Use virtual storage for server assets
const storageDir = resolve(nitro.options.buildDir, "snapshot");
nitro.options.serverAssets.push({
baseName: "nitro:bundled",
dir: storageDir,
});
const data = await snapshotStorage(nitro);
await Promise.all(
Object.entries(data).map(async ([path, contents]) => {
if (typeof contents !== "string") {
contents = JSON.stringify(contents);
}
const fsPath = join(storageDir, path.replace(/:/g, "/"));
await fsp.mkdir(dirname(fsPath), { recursive: true });
await fsp.writeFile(fsPath, contents, "utf8");
})
);
}
async function _build(nitro: Nitro, rollupConfig: RollupConfig) {
await scanHandlers(nitro);
await writeTypes(nitro);
await _snapshot(nitro);
if (!nitro.options.static) {
nitro.logger.info(
`Building Nitro Server (preset: \`${nitro.options.preset}\`)`
);
const build = await rollup.rollup(rollupConfig).catch((error) => {
nitro.logger.error(formatRollupError(error));
throw error;
});
await build.write(rollupConfig.output);
}
// Write build info
const nitroConfigPath = resolve(nitro.options.output.dir, "nitro.json");
const buildInfo = {
date: new Date(),
preset: nitro.options.preset,
commands: {
preview: nitro.options.commands.preview,
deploy: nitro.options.commands.deploy,
},
};
await writeFile(nitroConfigPath, JSON.stringify(buildInfo, null, 2));
if (!nitro.options.static) {
nitro.logger.success("Nitro server built");
if (nitro.options.logLevel > 1) {
process.stdout.write(
await generateFSTree(nitro.options.output.serverDir)
);
}
}
await nitro.hooks.callHook("compiled", nitro);
// Show deploy and preview hints
const rOutput = relative(process.cwd(), nitro.options.output.dir);
const rewriteRelativePaths = (input: string) => {
return input.replace(/\s\.\/(\S*)/g, ` ${rOutput}/$1`);
};
if (buildInfo.commands.preview) {
nitro.logger.success(
`You can preview this build using \`${rewriteRelativePaths(
buildInfo.commands.preview
)}\``
);
}
if (buildInfo.commands.deploy) {
nitro.logger.success(
`You can deploy this build using \`${rewriteRelativePaths(
buildInfo.commands.deploy
)}\``
);
}
}
function startRollupWatcher(nitro: Nitro, rollupConfig: RollupConfig) {
const watcher = rollup.watch(
defu(rollupConfig, {
watch: {
chokidar: nitro.options.watchOptions,
},
})
);
let start: number;
watcher.on("event", (event) => {
switch (event.code) {
// The watcher is (re)starting
case "START": {
return;
}
// Building an individual bundle
case "BUNDLE_START": {
start = Date.now();
return;
}
// Finished building all bundles
case "END": {
nitro.hooks.callHook("compiled", nitro);
nitro.logger.success(
"Nitro built",
start ? `in ${Date.now() - start} ms` : ""
);
nitro.hooks.callHook("dev:reload");
return;
}
// Encountered an error while bundling
case "ERROR": {
nitro.logger.error(formatRollupError(event.error));
}
}
});
return watcher;
}
async function _watch(nitro: Nitro, rollupConfig: RollupConfig) {
let rollupWatcher: rollup.RollupWatcher;
async function load() {
if (rollupWatcher) {
await rollupWatcher.close();
}
await scanHandlers(nitro);
rollupWatcher = startRollupWatcher(nitro, rollupConfig);
await writeTypes(nitro);
}
const reload = debounce(load);
const watchPatterns = nitro.options.scanDirs.flatMap((dir) => [
join(dir, "api"),
join(dir, "routes"),
join(dir, "middleware", GLOB_SCAN_PATTERN),
]);
const watchReloadEvents = new Set(["add", "addDir", "unlink", "unlinkDir"]);
const reloadWacher = watch(watchPatterns, { ignoreInitial: true }).on(
"all",
(event) => {
if (watchReloadEvents.has(event)) {
reload();
}
}
);
nitro.hooks.hook("close", () => {
rollupWatcher.close();
reloadWacher.close();
});
nitro.hooks.hook("rollup:reload", () => reload());
await load();
}
function formatRollupError(_error: RollupError | OnResolveResult) {
try {
const logs: string[] = [_error.toString()];
for (const error of "errors" in _error
? _error.errors
: [_error as RollupError]) {
const id = (error as any).path || error.id || (_error as RollupError).id;
let path = isAbsolute(id) ? relative(process.cwd(), id) : id;
const location =
(error as RollupError).loc || (error as PartialMessage).location;
if (location) {
path += `:${location.line}:${location.column}`;
}
const text =
(error as PartialMessage).text || (error as RollupError).frame;
logs.push(
`Rollup error while processing \`${path}\`` + text ? "\n\n" + text : ""
);
}
return logs.join("\n");
} catch {
return _error?.toString();
}
}
const RELATIVE_RE = /^\.{1,2}\//;
function relativeWithDot(from: string, to: string) {
const rel = relative(from, to);
return RELATIVE_RE.test(rel) ? rel : "./" + rel;
}