@netlify/plugin-nextjs 5.1.2 → 5.2.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 (43) hide show
  1. package/dist/build/advanced-api-routes.js +121 -4
  2. package/dist/build/cache.js +25 -4
  3. package/dist/build/content/prerendered.js +237 -8
  4. package/dist/build/content/server.js +259 -14
  5. package/dist/build/content/static.js +96 -11
  6. package/dist/build/functions/edge.js +511 -5
  7. package/dist/build/functions/server.js +131 -12
  8. package/dist/build/image-cdn.js +1615 -3
  9. package/dist/build/plugin-context.js +236 -5
  10. package/dist/build/templates/handler-monorepo.tmpl.js +3 -0
  11. package/dist/build/templates/handler.tmpl.js +3 -0
  12. package/dist/build/verification.js +81 -8
  13. package/dist/esm-chunks/{package-RVJOBSMH.js → package-SCUAWNXR.js} +23 -23
  14. package/dist/index.js +25 -36
  15. package/dist/run/config.js +25 -6
  16. package/dist/run/constants.js +7 -5
  17. package/dist/run/handlers/cache.cjs +6 -567
  18. package/dist/run/handlers/request-context.cjs +8 -1
  19. package/dist/run/handlers/server.js +20 -22
  20. package/dist/run/handlers/tracing.js +27022 -10456
  21. package/dist/run/headers.js +198 -8
  22. package/dist/run/next.cjs +106 -655
  23. package/dist/{esm-chunks/chunk-PMRBBOBY.js → run/regional-blob-store.cjs} +117 -263
  24. package/dist/run/revalidate.js +17 -3
  25. package/dist/run/systemlog.js +94 -3
  26. package/dist/shared/blobkey.js +15 -3
  27. package/edge-runtime/lib/response.ts +3 -2
  28. package/package.json +1 -1
  29. package/dist/esm-chunks/chunk-3SUDZQ7L.js +0 -40
  30. package/dist/esm-chunks/chunk-4BNHE6TP.js +0 -278
  31. package/dist/esm-chunks/chunk-72ZI2IVI.js +0 -36
  32. package/dist/esm-chunks/chunk-BG455SFE.js +0 -133
  33. package/dist/esm-chunks/chunk-HESS57SH.js +0 -127
  34. package/dist/esm-chunks/chunk-HYBEXB2Z.js +0 -105
  35. package/dist/esm-chunks/chunk-K7BTUM7O.js +0 -97
  36. package/dist/esm-chunks/chunk-L6OM53B6.js +0 -238
  37. package/dist/esm-chunks/chunk-MCEOSJH6.js +0 -1637
  38. package/dist/esm-chunks/chunk-MRD3XSKD.js +0 -248
  39. package/dist/esm-chunks/chunk-RL4K4CVH.js +0 -27
  40. package/dist/esm-chunks/chunk-TYCYFZ22.js +0 -25
  41. package/dist/esm-chunks/chunk-UTQSBE5O.js +0 -524
  42. package/dist/esm-chunks/chunk-UYKENJEU.js +0 -19
  43. package/dist/esm-chunks/chunk-V2T6NUOM.js +0 -113
@@ -5,17 +5,102 @@
5
5
  })();
6
6
 
7
7
  import {
8
- copyStaticAssets,
9
- copyStaticContent,
10
- copyStaticExport,
11
- publishStaticDir,
12
- unpublishStaticDir
13
- } from "../../esm-chunks/chunk-V2T6NUOM.js";
14
- import "../../esm-chunks/chunk-TYCYFZ22.js";
15
- import "../../esm-chunks/chunk-PDPDW32D.js";
16
- import "../../esm-chunks/chunk-Y3K5Q6FP.js";
17
- import "../../esm-chunks/chunk-VZNKO4OO.js";
18
- import "../../esm-chunks/chunk-5JVNISGM.js";
8
+ require_out
9
+ } from "../../esm-chunks/chunk-VZNKO4OO.js";
10
+ import {
11
+ wrapTracer
12
+ } from "../../esm-chunks/chunk-PDPDW32D.js";
13
+ import {
14
+ init_esm,
15
+ trace
16
+ } from "../../esm-chunks/chunk-Y3K5Q6FP.js";
17
+ import {
18
+ __toESM
19
+ } from "../../esm-chunks/chunk-5JVNISGM.js";
20
+
21
+ // src/build/content/static.ts
22
+ init_esm();
23
+ import { existsSync } from "node:fs";
24
+ import { cp, mkdir, rename, rm } from "node:fs/promises";
25
+ import { basename, join } from "node:path";
26
+ var import_fast_glob = __toESM(require_out(), 1);
27
+ import { encodeBlobKey } from "../../shared/blobkey.js";
28
+ var tracer = wrapTracer(trace.getTracer("Next runtime"));
29
+ var copyStaticContent = async (ctx) => {
30
+ return tracer.withActiveSpan("copyStaticContent", async () => {
31
+ const srcDir = join(ctx.publishDir, "server/pages");
32
+ const destDir = ctx.blobDir;
33
+ const paths = await (0, import_fast_glob.default)("**/*.+(html|json)", {
34
+ cwd: srcDir,
35
+ extglob: true
36
+ });
37
+ try {
38
+ await Promise.all(
39
+ paths.filter((path) => !paths.includes(`${path.slice(0, -5)}.json`)).map(async (path) => {
40
+ await cp(join(srcDir, path), join(destDir, await encodeBlobKey(path)), {
41
+ recursive: true,
42
+ force: true
43
+ });
44
+ })
45
+ );
46
+ } catch (error) {
47
+ ctx.failBuild("Failed assembling static pages for upload", error);
48
+ }
49
+ });
50
+ };
51
+ var copyStaticAssets = async (ctx) => {
52
+ return tracer.withActiveSpan("copyStaticAssets", async (span) => {
53
+ try {
54
+ await rm(ctx.staticDir, { recursive: true, force: true });
55
+ const { basePath } = await ctx.getRoutesManifest();
56
+ if (existsSync(ctx.resolveFromSiteDir("public"))) {
57
+ await cp(ctx.resolveFromSiteDir("public"), join(ctx.staticDir, basePath), {
58
+ recursive: true
59
+ });
60
+ }
61
+ if (existsSync(join(ctx.publishDir, "static"))) {
62
+ await cp(join(ctx.publishDir, "static"), join(ctx.staticDir, basePath, "_next/static"), {
63
+ recursive: true
64
+ });
65
+ }
66
+ } catch (error) {
67
+ span.end();
68
+ ctx.failBuild("Failed copying static assets", error);
69
+ }
70
+ });
71
+ };
72
+ var copyStaticExport = async (ctx) => {
73
+ await tracer.withActiveSpan("copyStaticExport", async () => {
74
+ if (!ctx.exportDetail?.outDirectory) {
75
+ ctx.failBuild("Export directory not found");
76
+ }
77
+ try {
78
+ await rm(ctx.staticDir, { recursive: true, force: true });
79
+ await cp(ctx.exportDetail.outDirectory, ctx.staticDir, { recursive: true });
80
+ } catch (error) {
81
+ ctx.failBuild("Failed copying static export", error);
82
+ }
83
+ });
84
+ };
85
+ var publishStaticDir = async (ctx) => {
86
+ try {
87
+ await rm(ctx.tempPublishDir, { recursive: true, force: true });
88
+ await mkdir(basename(ctx.tempPublishDir), { recursive: true });
89
+ await rename(ctx.publishDir, ctx.tempPublishDir);
90
+ await rename(ctx.staticDir, ctx.publishDir);
91
+ } catch (error) {
92
+ ctx.failBuild("Failed publishing static content", error instanceof Error ? { error } : {});
93
+ }
94
+ };
95
+ var unpublishStaticDir = async (ctx) => {
96
+ try {
97
+ if (existsSync(ctx.tempPublishDir)) {
98
+ await rename(ctx.publishDir, ctx.staticDir);
99
+ await rename(ctx.tempPublishDir, ctx.publishDir);
100
+ }
101
+ } catch {
102
+ }
103
+ };
19
104
  export {
20
105
  copyStaticAssets,
21
106
  copyStaticContent,
@@ -5,11 +5,517 @@
5
5
  })();
6
6
 
7
7
  import {
8
- createEdgeHandlers
9
- } from "../../esm-chunks/chunk-UTQSBE5O.js";
10
- import "../../esm-chunks/chunk-VZNKO4OO.js";
11
- import "../../esm-chunks/chunk-L6OM53B6.js";
12
- import "../../esm-chunks/chunk-5JVNISGM.js";
8
+ require_out
9
+ } from "../../esm-chunks/chunk-VZNKO4OO.js";
10
+ import {
11
+ __commonJS,
12
+ __toESM
13
+ } from "../../esm-chunks/chunk-5JVNISGM.js";
14
+
15
+ // node_modules/path-to-regexp/dist/index.js
16
+ var require_dist = __commonJS({
17
+ "node_modules/path-to-regexp/dist/index.js"(exports) {
18
+ "use strict";
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.pathToRegexp = exports.tokensToRegexp = exports.regexpToFunction = exports.match = exports.tokensToFunction = exports.compile = exports.parse = void 0;
21
+ function lexer(str) {
22
+ var tokens = [];
23
+ var i = 0;
24
+ while (i < str.length) {
25
+ var char = str[i];
26
+ if (char === "*" || char === "+" || char === "?") {
27
+ tokens.push({ type: "MODIFIER", index: i, value: str[i++] });
28
+ continue;
29
+ }
30
+ if (char === "\\") {
31
+ tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
32
+ continue;
33
+ }
34
+ if (char === "{") {
35
+ tokens.push({ type: "OPEN", index: i, value: str[i++] });
36
+ continue;
37
+ }
38
+ if (char === "}") {
39
+ tokens.push({ type: "CLOSE", index: i, value: str[i++] });
40
+ continue;
41
+ }
42
+ if (char === ":") {
43
+ var name = "";
44
+ var j = i + 1;
45
+ while (j < str.length) {
46
+ var code = str.charCodeAt(j);
47
+ if (
48
+ // `0-9`
49
+ code >= 48 && code <= 57 || // `A-Z`
50
+ code >= 65 && code <= 90 || // `a-z`
51
+ code >= 97 && code <= 122 || // `_`
52
+ code === 95
53
+ ) {
54
+ name += str[j++];
55
+ continue;
56
+ }
57
+ break;
58
+ }
59
+ if (!name)
60
+ throw new TypeError("Missing parameter name at ".concat(i));
61
+ tokens.push({ type: "NAME", index: i, value: name });
62
+ i = j;
63
+ continue;
64
+ }
65
+ if (char === "(") {
66
+ var count = 1;
67
+ var pattern = "";
68
+ var j = i + 1;
69
+ if (str[j] === "?") {
70
+ throw new TypeError('Pattern cannot start with "?" at '.concat(j));
71
+ }
72
+ while (j < str.length) {
73
+ if (str[j] === "\\") {
74
+ pattern += str[j++] + str[j++];
75
+ continue;
76
+ }
77
+ if (str[j] === ")") {
78
+ count--;
79
+ if (count === 0) {
80
+ j++;
81
+ break;
82
+ }
83
+ } else if (str[j] === "(") {
84
+ count++;
85
+ if (str[j + 1] !== "?") {
86
+ throw new TypeError("Capturing groups are not allowed at ".concat(j));
87
+ }
88
+ }
89
+ pattern += str[j++];
90
+ }
91
+ if (count)
92
+ throw new TypeError("Unbalanced pattern at ".concat(i));
93
+ if (!pattern)
94
+ throw new TypeError("Missing pattern at ".concat(i));
95
+ tokens.push({ type: "PATTERN", index: i, value: pattern });
96
+ i = j;
97
+ continue;
98
+ }
99
+ tokens.push({ type: "CHAR", index: i, value: str[i++] });
100
+ }
101
+ tokens.push({ type: "END", index: i, value: "" });
102
+ return tokens;
103
+ }
104
+ function parse(str, options) {
105
+ if (options === void 0) {
106
+ options = {};
107
+ }
108
+ var tokens = lexer(str);
109
+ var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a;
110
+ var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
111
+ var result = [];
112
+ var key = 0;
113
+ var i = 0;
114
+ var path = "";
115
+ var tryConsume = function(type) {
116
+ if (i < tokens.length && tokens[i].type === type)
117
+ return tokens[i++].value;
118
+ };
119
+ var mustConsume = function(type) {
120
+ var value2 = tryConsume(type);
121
+ if (value2 !== void 0)
122
+ return value2;
123
+ var _a2 = tokens[i], nextType = _a2.type, index = _a2.index;
124
+ throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
125
+ };
126
+ var consumeText = function() {
127
+ var result2 = "";
128
+ var value2;
129
+ while (value2 = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR")) {
130
+ result2 += value2;
131
+ }
132
+ return result2;
133
+ };
134
+ while (i < tokens.length) {
135
+ var char = tryConsume("CHAR");
136
+ var name = tryConsume("NAME");
137
+ var pattern = tryConsume("PATTERN");
138
+ if (name || pattern) {
139
+ var prefix = char || "";
140
+ if (prefixes.indexOf(prefix) === -1) {
141
+ path += prefix;
142
+ prefix = "";
143
+ }
144
+ if (path) {
145
+ result.push(path);
146
+ path = "";
147
+ }
148
+ result.push({
149
+ name: name || key++,
150
+ prefix,
151
+ suffix: "",
152
+ pattern: pattern || defaultPattern,
153
+ modifier: tryConsume("MODIFIER") || ""
154
+ });
155
+ continue;
156
+ }
157
+ var value = char || tryConsume("ESCAPED_CHAR");
158
+ if (value) {
159
+ path += value;
160
+ continue;
161
+ }
162
+ if (path) {
163
+ result.push(path);
164
+ path = "";
165
+ }
166
+ var open = tryConsume("OPEN");
167
+ if (open) {
168
+ var prefix = consumeText();
169
+ var name_1 = tryConsume("NAME") || "";
170
+ var pattern_1 = tryConsume("PATTERN") || "";
171
+ var suffix = consumeText();
172
+ mustConsume("CLOSE");
173
+ result.push({
174
+ name: name_1 || (pattern_1 ? key++ : ""),
175
+ pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
176
+ prefix,
177
+ suffix,
178
+ modifier: tryConsume("MODIFIER") || ""
179
+ });
180
+ continue;
181
+ }
182
+ mustConsume("END");
183
+ }
184
+ return result;
185
+ }
186
+ exports.parse = parse;
187
+ function compile(str, options) {
188
+ return tokensToFunction(parse(str, options), options);
189
+ }
190
+ exports.compile = compile;
191
+ function tokensToFunction(tokens, options) {
192
+ if (options === void 0) {
193
+ options = {};
194
+ }
195
+ var reFlags = flags(options);
196
+ var _a = options.encode, encode = _a === void 0 ? function(x) {
197
+ return x;
198
+ } : _a, _b = options.validate, validate = _b === void 0 ? true : _b;
199
+ var matches = tokens.map(function(token) {
200
+ if (typeof token === "object") {
201
+ return new RegExp("^(?:".concat(token.pattern, ")$"), reFlags);
202
+ }
203
+ });
204
+ return function(data) {
205
+ var path = "";
206
+ for (var i = 0; i < tokens.length; i++) {
207
+ var token = tokens[i];
208
+ if (typeof token === "string") {
209
+ path += token;
210
+ continue;
211
+ }
212
+ var value = data ? data[token.name] : void 0;
213
+ var optional = token.modifier === "?" || token.modifier === "*";
214
+ var repeat = token.modifier === "*" || token.modifier === "+";
215
+ if (Array.isArray(value)) {
216
+ if (!repeat) {
217
+ throw new TypeError('Expected "'.concat(token.name, '" to not repeat, but got an array'));
218
+ }
219
+ if (value.length === 0) {
220
+ if (optional)
221
+ continue;
222
+ throw new TypeError('Expected "'.concat(token.name, '" to not be empty'));
223
+ }
224
+ for (var j = 0; j < value.length; j++) {
225
+ var segment = encode(value[j], token);
226
+ if (validate && !matches[i].test(segment)) {
227
+ throw new TypeError('Expected all "'.concat(token.name, '" to match "').concat(token.pattern, '", but got "').concat(segment, '"'));
228
+ }
229
+ path += token.prefix + segment + token.suffix;
230
+ }
231
+ continue;
232
+ }
233
+ if (typeof value === "string" || typeof value === "number") {
234
+ var segment = encode(String(value), token);
235
+ if (validate && !matches[i].test(segment)) {
236
+ throw new TypeError('Expected "'.concat(token.name, '" to match "').concat(token.pattern, '", but got "').concat(segment, '"'));
237
+ }
238
+ path += token.prefix + segment + token.suffix;
239
+ continue;
240
+ }
241
+ if (optional)
242
+ continue;
243
+ var typeOfMessage = repeat ? "an array" : "a string";
244
+ throw new TypeError('Expected "'.concat(token.name, '" to be ').concat(typeOfMessage));
245
+ }
246
+ return path;
247
+ };
248
+ }
249
+ exports.tokensToFunction = tokensToFunction;
250
+ function match(str, options) {
251
+ var keys = [];
252
+ var re = pathToRegexp2(str, keys, options);
253
+ return regexpToFunction(re, keys, options);
254
+ }
255
+ exports.match = match;
256
+ function regexpToFunction(re, keys, options) {
257
+ if (options === void 0) {
258
+ options = {};
259
+ }
260
+ var _a = options.decode, decode = _a === void 0 ? function(x) {
261
+ return x;
262
+ } : _a;
263
+ return function(pathname) {
264
+ var m = re.exec(pathname);
265
+ if (!m)
266
+ return false;
267
+ var path = m[0], index = m.index;
268
+ var params = /* @__PURE__ */ Object.create(null);
269
+ var _loop_1 = function(i2) {
270
+ if (m[i2] === void 0)
271
+ return "continue";
272
+ var key = keys[i2 - 1];
273
+ if (key.modifier === "*" || key.modifier === "+") {
274
+ params[key.name] = m[i2].split(key.prefix + key.suffix).map(function(value) {
275
+ return decode(value, key);
276
+ });
277
+ } else {
278
+ params[key.name] = decode(m[i2], key);
279
+ }
280
+ };
281
+ for (var i = 1; i < m.length; i++) {
282
+ _loop_1(i);
283
+ }
284
+ return { path, index, params };
285
+ };
286
+ }
287
+ exports.regexpToFunction = regexpToFunction;
288
+ function escapeString(str) {
289
+ return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
290
+ }
291
+ function flags(options) {
292
+ return options && options.sensitive ? "" : "i";
293
+ }
294
+ function regexpToRegexp(path, keys) {
295
+ if (!keys)
296
+ return path;
297
+ var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
298
+ var index = 0;
299
+ var execResult = groupsRegex.exec(path.source);
300
+ while (execResult) {
301
+ keys.push({
302
+ // Use parenthesized substring match if available, index otherwise
303
+ name: execResult[1] || index++,
304
+ prefix: "",
305
+ suffix: "",
306
+ modifier: "",
307
+ pattern: ""
308
+ });
309
+ execResult = groupsRegex.exec(path.source);
310
+ }
311
+ return path;
312
+ }
313
+ function arrayToRegexp(paths, keys, options) {
314
+ var parts = paths.map(function(path) {
315
+ return pathToRegexp2(path, keys, options).source;
316
+ });
317
+ return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options));
318
+ }
319
+ function stringToRegexp(path, keys, options) {
320
+ return tokensToRegexp(parse(path, options), keys, options);
321
+ }
322
+ function tokensToRegexp(tokens, keys, options) {
323
+ if (options === void 0) {
324
+ options = {};
325
+ }
326
+ var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function(x) {
327
+ return x;
328
+ } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
329
+ var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
330
+ var delimiterRe = "[".concat(escapeString(delimiter), "]");
331
+ var route = start ? "^" : "";
332
+ for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
333
+ var token = tokens_1[_i];
334
+ if (typeof token === "string") {
335
+ route += escapeString(encode(token));
336
+ } else {
337
+ var prefix = escapeString(encode(token.prefix));
338
+ var suffix = escapeString(encode(token.suffix));
339
+ if (token.pattern) {
340
+ if (keys)
341
+ keys.push(token);
342
+ if (prefix || suffix) {
343
+ if (token.modifier === "+" || token.modifier === "*") {
344
+ var mod = token.modifier === "*" ? "?" : "";
345
+ route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod);
346
+ } else {
347
+ route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier);
348
+ }
349
+ } else {
350
+ if (token.modifier === "+" || token.modifier === "*") {
351
+ route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")");
352
+ } else {
353
+ route += "(".concat(token.pattern, ")").concat(token.modifier);
354
+ }
355
+ }
356
+ } else {
357
+ route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier);
358
+ }
359
+ }
360
+ }
361
+ if (end) {
362
+ if (!strict)
363
+ route += "".concat(delimiterRe, "?");
364
+ route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")");
365
+ } else {
366
+ var endToken = tokens[tokens.length - 1];
367
+ var isEndDelimited = typeof endToken === "string" ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1 : endToken === void 0;
368
+ if (!strict) {
369
+ route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?");
370
+ }
371
+ if (!isEndDelimited) {
372
+ route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")");
373
+ }
374
+ }
375
+ return new RegExp(route, flags(options));
376
+ }
377
+ exports.tokensToRegexp = tokensToRegexp;
378
+ function pathToRegexp2(path, keys, options) {
379
+ if (path instanceof RegExp)
380
+ return regexpToRegexp(path, keys);
381
+ if (Array.isArray(path))
382
+ return arrayToRegexp(path, keys, options);
383
+ return stringToRegexp(path, keys, options);
384
+ }
385
+ exports.pathToRegexp = pathToRegexp2;
386
+ }
387
+ });
388
+
389
+ // src/build/functions/edge.ts
390
+ var import_fast_glob = __toESM(require_out(), 1);
391
+ var import_path_to_regexp = __toESM(require_dist(), 1);
392
+ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
393
+ import { dirname, join } from "node:path";
394
+ import { EDGE_HANDLER_NAME } from "../plugin-context.js";
395
+ var writeEdgeManifest = async (ctx, manifest) => {
396
+ await mkdir(ctx.edgeFunctionsDir, { recursive: true });
397
+ await writeFile(join(ctx.edgeFunctionsDir, "manifest.json"), JSON.stringify(manifest, null, 2));
398
+ };
399
+ var copyRuntime = async (ctx, handlerDirectory) => {
400
+ const files = await (0, import_fast_glob.glob)("edge-runtime/**/*", {
401
+ cwd: ctx.pluginDir,
402
+ ignore: ["**/*.test.ts"],
403
+ dot: true
404
+ });
405
+ await Promise.all(
406
+ files.map(
407
+ (path) => cp(join(ctx.pluginDir, path), join(handlerDirectory, path), { recursive: true })
408
+ )
409
+ );
410
+ };
411
+ var augmentMatchers = (matchers, ctx) => {
412
+ if (!ctx.buildConfig.i18n) {
413
+ return matchers;
414
+ }
415
+ return matchers.flatMap((matcher) => {
416
+ if (matcher.originalSource && matcher.locale !== false) {
417
+ return [
418
+ matcher,
419
+ {
420
+ ...matcher,
421
+ regexp: (0, import_path_to_regexp.pathToRegexp)(matcher.originalSource).source
422
+ }
423
+ ];
424
+ }
425
+ return matcher;
426
+ });
427
+ };
428
+ var writeHandlerFile = async (ctx, { matchers, name }) => {
429
+ const nextConfig = ctx.buildConfig;
430
+ const handlerName = getHandlerName({ name });
431
+ const handlerDirectory = join(ctx.edgeFunctionsDir, handlerName);
432
+ const handlerRuntimeDirectory = join(handlerDirectory, "edge-runtime");
433
+ await copyRuntime(ctx, handlerDirectory);
434
+ await writeFile(
435
+ join(handlerRuntimeDirectory, "matchers.json"),
436
+ JSON.stringify(augmentMatchers(matchers, ctx))
437
+ );
438
+ const minimalNextConfig = {
439
+ basePath: nextConfig.basePath,
440
+ i18n: nextConfig.i18n,
441
+ trailingSlash: nextConfig.trailingSlash,
442
+ skipMiddlewareUrlNormalize: nextConfig.skipMiddlewareUrlNormalize
443
+ };
444
+ await writeFile(
445
+ join(handlerRuntimeDirectory, "next.config.json"),
446
+ JSON.stringify(minimalNextConfig)
447
+ );
448
+ await writeFile(
449
+ join(handlerDirectory, `${handlerName}.js`),
450
+ `
451
+ import {handleMiddleware} from './edge-runtime/middleware.ts';
452
+ import handler from './server/${name}.js';
453
+ export default (req, context) => handleMiddleware(req, context, handler);
454
+ `
455
+ );
456
+ };
457
+ var copyHandlerDependencies = async (ctx, { name, files, wasm }) => {
458
+ const srcDir = join(ctx.standaloneDir, ctx.nextDistDir);
459
+ const destDir = join(ctx.edgeFunctionsDir, getHandlerName({ name }));
460
+ const edgeRuntimeDir = join(ctx.pluginDir, "edge-runtime");
461
+ const shimPath = join(edgeRuntimeDir, "shim/index.js");
462
+ const shim = await readFile(shimPath, "utf8");
463
+ const parts = [shim];
464
+ if (wasm?.length) {
465
+ parts.push(
466
+ `import { decode as _base64Decode } from "../edge-runtime/vendor/deno.land/std@0.175.0/encoding/base64.ts";`
467
+ );
468
+ for (const wasmChunk of wasm ?? []) {
469
+ const data = await readFile(join(srcDir, wasmChunk.filePath));
470
+ parts.push(
471
+ `const ${wasmChunk.name} = _base64Decode(${JSON.stringify(
472
+ data.toString("base64")
473
+ )}).buffer`
474
+ );
475
+ }
476
+ }
477
+ for (const file of files) {
478
+ const entrypoint = await readFile(join(srcDir, file), "utf8");
479
+ parts.push(`;// Concatenated file: ${file}
480
+ `, entrypoint);
481
+ }
482
+ const exports = `export default _ENTRIES["middleware_${name}"].default;`;
483
+ await mkdir(dirname(join(destDir, `server/${name}.js`)), { recursive: true });
484
+ await writeFile(join(destDir, `server/${name}.js`), [...parts, exports].join("\n"));
485
+ };
486
+ var createEdgeHandler = async (ctx, definition) => {
487
+ await copyHandlerDependencies(ctx, definition);
488
+ await writeHandlerFile(ctx, definition);
489
+ };
490
+ var getHandlerName = ({ name }) => `${EDGE_HANDLER_NAME}-${name.replace(/\W/g, "-")}`;
491
+ var buildHandlerDefinition = (ctx, { name, matchers, page }) => {
492
+ const fun = getHandlerName({ name });
493
+ const funName = name.endsWith("middleware") ? "Next.js Middleware Handler" : `Next.js Edge Handler: ${page}`;
494
+ const cache = name.endsWith("middleware") ? void 0 : "manual";
495
+ const generator = `${ctx.pluginName}@${ctx.pluginVersion}`;
496
+ return augmentMatchers(matchers, ctx).map((matcher) => ({
497
+ function: fun,
498
+ name: funName,
499
+ pattern: matcher.regexp,
500
+ cache,
501
+ generator
502
+ }));
503
+ };
504
+ var createEdgeHandlers = async (ctx) => {
505
+ await rm(ctx.edgeFunctionsDir, { recursive: true, force: true });
506
+ const nextManifest = await ctx.getMiddlewareManifest();
507
+ const nextDefinitions = [
508
+ ...Object.values(nextManifest.middleware)
509
+ // ...Object.values(nextManifest.functions)
510
+ ];
511
+ await Promise.all(nextDefinitions.map((def) => createEdgeHandler(ctx, def)));
512
+ const netlifyDefinitions = nextDefinitions.flatMap((def) => buildHandlerDefinition(ctx, def));
513
+ const netlifyManifest = {
514
+ version: 1,
515
+ functions: netlifyDefinitions
516
+ };
517
+ await writeEdgeManifest(ctx, netlifyManifest);
518
+ };
13
519
  export {
14
520
  createEdgeHandlers
15
521
  };