-
Notifications
You must be signed in to change notification settings - Fork 458
/
netlify.ts
243 lines (223 loc) · 6.71 KB
/
netlify.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
import { existsSync, promises as fsp } from "node:fs";
import { join, dirname } from "pathe";
import { defineNitroPreset } from "../preset";
import type { Nitro } from "../types";
import nitroPkg from "../../package.json";
// Netlify functions
export const netlify = defineNitroPreset({
extends: "aws-lambda",
entry: "#internal/nitro/entries/netlify",
output: {
dir: "{{ rootDir }}/.netlify/functions-internal",
publicDir: "{{ rootDir }}/dist",
},
rollupConfig: {
output: {
entryFileNames: "server.mjs",
},
},
hooks: {
"rollup:before": (nitro: Nitro) => {
deprecateSWR(nitro);
},
async compiled(nitro: Nitro) {
await writeHeaders(nitro);
await writeRedirects(nitro);
const functionConfig = {
config: { nodeModuleFormat: "esm" },
version: 1,
};
const functionConfigPath = join(
nitro.options.output.serverDir,
"server.json"
);
await fsp.writeFile(functionConfigPath, JSON.stringify(functionConfig));
},
},
});
// Netlify builder
export const netlifyBuilder = defineNitroPreset({
extends: "netlify",
entry: "#internal/nitro/entries/netlify-builder",
hooks: {
"rollup:before": (nitro: Nitro) => {
deprecateSWR(nitro);
},
},
});
// Netlify edge
export const netlifyEdge = defineNitroPreset({
extends: "base-worker",
entry: "#internal/nitro/entries/netlify-edge",
exportConditions: ["netlify"],
output: {
serverDir: "{{ rootDir }}/.netlify/edge-functions/server",
publicDir: "{{ rootDir }}/dist",
},
rollupConfig: {
output: {
entryFileNames: "server.js",
format: "esm",
},
},
unenv: {
polyfill: ["#internal/nitro/polyfill/deno-env"],
},
hooks: {
"rollup:before": (nitro: Nitro) => {
deprecateSWR(nitro);
},
async compiled(nitro: Nitro) {
await writeHeaders(nitro);
await writeRedirects(nitro);
// https://docs.netlify.com/edge-functions/create-integration/
const manifest = {
version: 1,
functions: [
{
path: "/*",
name: "nitro server handler",
function: "server",
generator: `${nitroPkg.name}@${nitroPkg.version}`,
},
],
};
const manifestPath = join(
nitro.options.rootDir,
".netlify/edge-functions/manifest.json"
);
await fsp.mkdir(dirname(manifestPath), { recursive: true });
await fsp.writeFile(manifestPath, JSON.stringify(manifest, null, 2));
},
},
});
export const netlifyStatic = defineNitroPreset({
extends: "static",
output: {
publicDir: "{{ rootDir }}/dist",
},
commands: {
preview: "npx serve ./static",
},
hooks: {
"rollup:before": (nitro: Nitro) => {
deprecateSWR(nitro);
},
async compiled(nitro: Nitro) {
await writeHeaders(nitro);
await writeRedirects(nitro);
},
},
});
async function writeRedirects(nitro: Nitro) {
const redirectsPath = join(nitro.options.output.publicDir, "_redirects");
const staticFallback = existsSync(
join(nitro.options.output.publicDir, "404.html")
)
? "/* /404.html 404"
: "";
let contents = nitro.options.static
? staticFallback
: "/* /.netlify/functions/server 200";
const rules = Object.entries(nitro.options.routeRules).sort(
(a, b) => a[0].split(/\/(?!\*)/).length - b[0].split(/\/(?!\*)/).length
);
if (!nitro.options.static) {
// Rewrite static ISR paths to builder functions
for (const [key, value] of rules.filter(
([_, value]) => value.isr !== undefined
)) {
contents = value.isr
? `${key.replace("/**", "/*")}\t/.netlify/builders/server 200\n` +
contents
: `${key.replace("/**", "/*")}\t/.netlify/functions/server 200\n` +
contents;
}
}
for (const [key, routeRules] of rules.filter(
([_, routeRules]) => routeRules.redirect
)) {
// TODO: Remove map when netlify support 307/308
let code = routeRules.redirect.statusCode;
code = { 307: 302, 308: 301 }[code] || code;
contents =
`${key.replace("/**", "/*")}\t${routeRules.redirect.to.replace("/**", "/:splat")}\t${code}\n` +
contents;
}
if (existsSync(redirectsPath)) {
const currentRedirects = await fsp.readFile(redirectsPath, "utf8");
if (/^\/\* /m.test(currentRedirects)) {
nitro.logger.info(
"Not adding Nitro fallback to `_redirects` (as an existing fallback was found)."
);
return;
}
nitro.logger.info(
"Adding Nitro fallback to `_redirects` to handle all unmatched routes."
);
contents = currentRedirects + "\n" + contents;
}
await fsp.writeFile(redirectsPath, contents);
}
async function writeHeaders(nitro: Nitro) {
const headersPath = join(nitro.options.output.publicDir, "_headers");
let contents = "";
const rules = Object.entries(nitro.options.routeRules).sort(
(a, b) => b[0].split(/\/(?!\*)/).length - a[0].split(/\/(?!\*)/).length
);
for (const [path, routeRules] of rules.filter(
([_, routeRules]) => routeRules.headers
)) {
const headers = [
path.replace("/**", "/*"),
...Object.entries({ ...routeRules.headers }).map(
([header, value]) => ` ${header}: ${value}`
),
].join("\n");
contents += headers + "\n";
}
if (existsSync(headersPath)) {
const currentHeaders = await fsp.readFile(headersPath, "utf8");
if (/^\/\* /m.test(currentHeaders)) {
nitro.logger.info(
"Not adding Nitro fallback to `_headers` (as an existing fallback was found)."
);
return;
}
nitro.logger.info(
"Adding Nitro fallback to `_headers` to handle all unmatched routes."
);
contents = currentHeaders + "\n" + contents;
}
await fsp.writeFile(headersPath, contents);
}
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 && value.cache && _hasProp(value.cache, "swr")) {
value.isr = value.cache.swr;
hasLegacyOptions = true;
}
}
if (hasLegacyOptions) {
console.warn(
"[nitro] Nitro now uses `isr` option to configure ISR behavior on Netlify. Backwards-compatible support for `static` and `swr` support with Builder Functions will be removed in the future versions. Set `future.nativeSWR: true` nitro config disable this warning."
);
}
}
function _hasProp(obj: any, prop: string) {
return obj && typeof obj === "object" && prop in obj;
}