-
-
Notifications
You must be signed in to change notification settings - Fork 886
Expand file tree
/
Copy pathutils.ts
More file actions
490 lines (448 loc) · 14.4 KB
/
Copy pathutils.ts
File metadata and controls
490 lines (448 loc) · 14.4 KB
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
import fsp from "node:fs/promises";
import { defu } from "defu";
import { writeFile } from "nitropack/kit";
import type { Nitro, NitroRouteRules } from "nitropack/types";
import { dirname, relative, resolve } from "pathe";
import { joinURL, withLeadingSlash, withoutLeadingSlash } from "ufo";
import type {
PrerenderFunctionConfig,
VercelBuildConfigV3,
VercelServerlessFunctionConfig,
} from "./types";
import { isTest } from "std-env";
import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
import { ISR_URL_PARAM } from "./runtime/consts";
// https://vercel.com/docs/build-output-api/configuration
// https://vercel.com/docs/functions/runtimes/node-js/node-js-versions
const SUPPORTED_NODE_VERSIONS = [18, 20, 22];
const FALLBACK_ROUTE = "/__fallback";
const ISR_SUFFIX = "-isr"; // Avoid using . as it can conflict with routing
const SAFE_FS_CHAR_RE = /[^a-zA-Z0-9_.[\]/]/g;
function getSystemNodeVersion() {
const systemNodeVersion = Number.parseInt(
process.versions.node.split(".")[0]
);
return Number.isNaN(systemNodeVersion) ? 22 : systemNodeVersion;
}
export async function generateFunctionFiles(nitro: Nitro) {
const o11Routes = getObservabilityRoutes(nitro);
const buildConfigPath = resolve(nitro.options.output.dir, "config.json");
const buildConfig = generateBuildConfig(nitro, o11Routes);
await writeFile(buildConfigPath, JSON.stringify(buildConfig, null, 2));
// Runtime
// 1. Respect explicit runtime from nitro config
let runtime: VercelServerlessFunctionConfig["runtime"] =
nitro.options.vercel?.functions?.runtime;
// 2. Read runtime from vercel.json if specified
if (!runtime) {
const vercelConfig = await readVercelConfig(nitro.options.rootDir);
// Use bun runtime if bunVersion is specified or bun used to build
if (vercelConfig.bunVersion || "Bun" in globalThis) {
runtime = `bun${vercelConfig.bunVersion || "1.x"}`;
} else {
// 3. Auto-detect runtime based on system Node.js version
const systemNodeVersion = getSystemNodeVersion();
const usedNodeVersion =
SUPPORTED_NODE_VERSIONS.find(
(version) => version >= systemNodeVersion
) ?? SUPPORTED_NODE_VERSIONS.at(-1);
runtime = `nodejs${usedNodeVersion}.x`;
}
}
const functionConfigPath = resolve(
nitro.options.output.serverDir,
".vc-config.json"
);
const functionConfig: VercelServerlessFunctionConfig = {
runtime,
...nitro.options.vercel?.functions,
handler: "index.mjs",
launcherType: "Nodejs",
shouldAddHelpers: false,
supportsResponseStreaming: true,
};
await writeFile(functionConfigPath, JSON.stringify(functionConfig, null, 2));
// Write ISR functions
for (const [key, value] of Object.entries(nitro.options.routeRules)) {
if (!value.isr) {
continue;
}
const funcPrefix = resolve(
nitro.options.output.serverDir,
"..",
normalizeRouteDest(key) + ISR_SUFFIX
);
await fsp.mkdir(dirname(funcPrefix), { recursive: true });
await fsp.symlink(
"./" + relative(dirname(funcPrefix), nitro.options.output.serverDir),
funcPrefix + ".func",
"junction"
);
await writePrerenderConfig(
funcPrefix + ".prerender-config.json",
value.isr,
nitro.options.vercel?.config?.bypassToken
);
}
// Write observability routes
if (o11Routes.length === 0) {
return;
}
const _routeRulesMatcher = toRouteMatcher(
createRadixRouter({ routes: nitro.options.routeRules })
);
const _getRouteRules = (path: string) =>
defu({}, ..._routeRulesMatcher.matchAll(path).reverse()) as NitroRouteRules;
for (const route of o11Routes) {
const routeRules = _getRouteRules(route.src);
if (routeRules.isr) {
continue; // #3563
}
const funcPrefix = resolve(
nitro.options.output.serverDir,
"..",
route.dest
);
await fsp.mkdir(dirname(funcPrefix), { recursive: true });
await fsp.symlink(
"./" + relative(dirname(funcPrefix), nitro.options.output.serverDir),
funcPrefix + ".func",
"junction"
);
}
}
export async function generateEdgeFunctionFiles(nitro: Nitro) {
const buildConfigPath = resolve(nitro.options.output.dir, "config.json");
const buildConfig = generateBuildConfig(nitro);
await writeFile(buildConfigPath, JSON.stringify(buildConfig, null, 2));
const functionConfigPath = resolve(
nitro.options.output.serverDir,
".vc-config.json"
);
const functionConfig = {
runtime: "edge",
entrypoint: "index.mjs",
regions: nitro.options.vercel?.regions,
};
await writeFile(functionConfigPath, JSON.stringify(functionConfig, null, 2));
}
export async function generateStaticFiles(nitro: Nitro) {
const buildConfigPath = resolve(nitro.options.output.dir, "config.json");
const buildConfig = generateBuildConfig(nitro);
await writeFile(buildConfigPath, JSON.stringify(buildConfig, null, 2));
}
function generateBuildConfig(nitro: Nitro, o11Routes?: ObservabilityRoute[]) {
const rules = Object.entries(nitro.options.routeRules).sort(
(a, b) => b[0].split(/\/(?!\*)/).length - a[0].split(/\/(?!\*)/).length
);
const config = defu(nitro.options.vercel?.config, <VercelBuildConfigV3>{
version: 3,
framework: {
name: nitro.options.framework.name,
version: nitro.options.framework.version,
},
overrides: {
// Nitro static prerendered route overrides
...Object.fromEntries(
(
nitro._prerenderedRoutes?.filter((r) => r.fileName !== r.route) || []
).map(({ route, fileName }) => [
withoutLeadingSlash(fileName),
{ path: route.replace(/^\//, "") },
])
),
},
routes: [
// Redirect and header rules
...rules
.filter(([_, routeRules]) => routeRules.redirect || routeRules.headers)
.map(([path, routeRules]) => {
let route = {
src: path.replace("/**", "/(.*)"),
};
if (routeRules.redirect) {
route = defu(route, {
status: routeRules.redirect.statusCode,
headers: {
Location: routeRules.redirect.to.replace("/**", "/$1"),
},
});
}
if (routeRules.headers) {
route = defu(route, { headers: routeRules.headers });
}
return route;
}),
// Skew protection
...(nitro.options.vercel?.skewProtection &&
process.env.VERCEL_DEPLOYMENT_ID
? [
{
src: "/.*",
has: [
{
type: "header",
key: "Sec-Fetch-Dest",
value: "document",
},
],
headers: {
"Set-Cookie": `__vdpl=${process.env.VERCEL_DEPLOYMENT_ID}; Path=${nitro.options.baseURL}; SameSite=Strict; Secure; HttpOnly`,
},
continue: true,
},
]
: []),
// Public asset rules
...nitro.options.publicAssets
.filter((asset) => !asset.fallthrough)
.map((asset) => joinURL(nitro.options.baseURL, asset.baseURL || "/"))
.map((baseURL) => ({
src: baseURL + "(.*)",
headers: {
"cache-control": "public,max-age=31536000,immutable",
},
continue: true,
})),
{ handle: "filesystem" },
],
});
// Early return if we are building a static site
if (nitro.options.static) {
return config;
}
config.routes!.push(
// ISR rules
// ...If we are using an ISR function for /, then we need to write this explicitly
...(nitro.options.routeRules["/"]?.isr
? [
{
src: `(?<${ISR_URL_PARAM}>/)`,
dest: `/index${ISR_SUFFIX}?${ISR_URL_PARAM}=$${ISR_URL_PARAM}`,
},
]
: []),
// ...Add rest of the ISR routes
...rules
.filter(([key, value]) => value.isr !== undefined && key !== "/")
.map(([key, value]) => {
const src = `(?<${ISR_URL_PARAM}>${normalizeRouteSrc(key)})`;
if (value.isr === false) {
// We need to write a rule to avoid route being shadowed by another cache rule elsewhere
return {
src,
dest: FALLBACK_ROUTE,
};
}
return {
src,
dest:
nitro.options.preset === "vercel-edge"
? FALLBACK_ROUTE + `?${ISR_URL_PARAM}=$${ISR_URL_PARAM}`
: withLeadingSlash(
normalizeRouteDest(key) +
ISR_SUFFIX +
`?${ISR_URL_PARAM}=$${ISR_URL_PARAM}`
),
};
}),
// Observability routes
...(o11Routes || []).map((route) => ({
src: joinURL(nitro.options.baseURL, route.src),
dest: withLeadingSlash(route.dest),
})),
// If we are using an ISR function as a fallback
// then we do not need to output the below fallback route as well
...(nitro.options.routeRules["/**"]?.isr
? []
: [
{
src: "/(.*)",
dest: FALLBACK_ROUTE,
},
])
);
return config;
}
export function deprecateSWR(nitro: Nitro) {
if (nitro.options.future.nativeSWR) {
return;
}
let hasLegacyOptions = false;
for (const [key, value] of Object.entries(nitro.options.routeRules)) {
if (_hasProp(value, "isr")) {
continue;
}
if (value.cache === false) {
value.isr = false;
}
if (_hasProp(value, "static")) {
value.isr = !(value as { static: boolean }).static;
hasLegacyOptions = true;
}
if (value.cache && _hasProp(value.cache, "swr")) {
value.isr = value.cache.swr;
hasLegacyOptions = true;
}
}
if (hasLegacyOptions && !isTest) {
nitro.logger.warn(
"Nitro now uses `isr` option to configure ISR behavior on Vercel. Backwards-compatible support for `static` and `swr` options within the Vercel Build Options API will be removed in the future versions. Set `future.nativeSWR: true` nitro config disable this warning."
);
}
}
// --- vercel.json ---
// https://vercel.com/docs/project-configuration
// https://openapi.vercel.sh/vercel.json
export interface VercelConfig {
bunVersion?: string;
}
export async function readVercelConfig(rootDir: string): Promise<VercelConfig> {
const vercelConfigPath = resolve(rootDir, "vercel.json");
const vercelConfig = await fsp
.readFile(vercelConfigPath)
.then((config) => JSON.parse(config.toString()))
.catch(() => ({}));
return vercelConfig as VercelConfig;
}
function _hasProp(obj: any, prop: string) {
return obj && typeof obj === "object" && prop in obj;
}
// --- utils for observability ---
type ObservabilityRoute = {
src: string; // route pattern
dest: string; // function name
};
function getObservabilityRoutes(nitro: Nitro): ObservabilityRoute[] {
const compatDate =
nitro.options.compatibilityDate.vercel ||
nitro.options.compatibilityDate.default;
if (compatDate < "2025-07-15") {
return [];
}
// Sort routes by how much specific they are
const routePatterns = [
...new Set([
...(nitro.options.ssrRoutes || []),
...[...nitro.scannedHandlers, ...nitro.options.handlers]
.filter((h) => !h.middleware && h.route)
.map((h) => h.route!),
]),
];
const staticRoutes: string[] = [];
const dynamicRoutes: string[] = [];
const catchAllRoutes: string[] = [];
for (const route of routePatterns) {
if (route.includes("**")) {
catchAllRoutes.push(route);
} else if (route.includes(":") || route.includes("*")) {
dynamicRoutes.push(route);
} else {
staticRoutes.push(route);
}
}
const prerendered = nitro._prerenderedRoutes || [];
return [
...normalizeRoutes(staticRoutes),
...normalizeRoutes(dynamicRoutes),
...normalizeRoutes(catchAllRoutes),
].filter((route) => {
return !prerendered.some((r) => route.src === r.route);
});
}
function normalizeRoutes(routes: string[]) {
return routes
.sort((a, b) =>
// a.split("/").length - b.split("/").length ||
b.localeCompare(a)
)
.map((route) => ({
src: normalizeRouteSrc(route),
dest: normalizeRouteDest(route),
}));
}
// Input is a rou3/radix3 compatible route pattern
// Output is a PCRE-compatible regular expression that matches each incoming pathname
// Reference: https://github.com/h3js/rou3/blob/main/src/regexp.ts
function normalizeRouteSrc(route: string): string {
let idCtr = 0;
return route
.split("/")
.map((segment) => {
if (segment.startsWith("**")) {
return segment === "**"
? "(?:.*)"
: `?(?<${namedGroup(segment.slice(3))}>.+)`;
}
if (segment === "*") {
return `(?<_${idCtr++}>[^/]*)`;
}
if (segment.includes(":")) {
return segment
.replace(/:(\w+)/g, (_, id) => `(?<${namedGroup(id)}>[^/]+)`)
.replace(/\./g, String.raw`\.`);
}
return segment;
})
.join("/");
}
// Valid PCRE capture group name
function namedGroup(input = "") {
if (/\d/.test(input[0])) {
input = `_${input}`;
}
return input.replace(/[^a-zA-Z0-9_]/g, "") || "_";
}
// Output is a destination pathname to function name
function normalizeRouteDest(route: string) {
return (
route
.split("/")
.slice(1)
.map((segment) => {
if (segment.startsWith("**")) {
return `[...${segment.replace(/[*:]/g, "")}]`;
}
if (segment === "*") {
return "[-]";
}
if (segment.startsWith(":")) {
return `[${segment.slice(1)}]`;
}
if (segment.includes(":")) {
return `[${segment.replace(/:/g, "_")}]`;
}
return segment;
})
// Only use filesystem-safe characters
.map((segment) => segment.replace(SAFE_FS_CHAR_RE, "-"))
.join("/") || "index"
);
}
async function writePrerenderConfig(
filename: string,
isrConfig: NitroRouteRules["isr"],
bypassToken?: string
) {
// Normalize route rule
if (typeof isrConfig === "number") {
isrConfig = { expiration: isrConfig };
} else if (isrConfig === true) {
isrConfig = { expiration: false };
} else {
isrConfig = { ...isrConfig };
}
// Generate prerender config
const prerenderConfig: PrerenderFunctionConfig = {
expiration: isrConfig.expiration ?? false,
bypassToken,
...isrConfig,
};
if (
prerenderConfig.allowQuery &&
!prerenderConfig.allowQuery.includes(ISR_URL_PARAM)
) {
prerenderConfig.allowQuery.push(ISR_URL_PARAM);
}
await writeFile(filename, JSON.stringify(prerenderConfig, null, 2));
}