@netlify/plugin-nextjs 5.10.0-fetch-patch-logs → 5.10.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 +136 -4
  2. package/dist/build/cache.js +25 -4
  3. package/dist/build/content/prerendered.js +293 -11
  4. package/dist/build/content/server.js +219 -11
  5. package/dist/build/content/static.js +112 -15
  6. package/dist/build/functions/edge.js +540 -7
  7. package/dist/build/functions/server.js +130 -11
  8. package/dist/build/image-cdn.js +1599 -3
  9. package/dist/build/plugin-context.js +292 -6
  10. package/dist/build/verification.js +104 -9
  11. package/dist/esm-chunks/{package-F536DQ6H.js → package-UN6EVEHD.js} +1 -1
  12. package/dist/index.js +18 -39
  13. package/dist/run/config.js +1 -4
  14. package/dist/run/constants.js +7 -5
  15. package/dist/run/handlers/cache.cjs +44 -1655
  16. package/dist/run/handlers/server.js +14 -33
  17. package/dist/run/handlers/tracer.cjs +2 -114
  18. package/dist/run/handlers/tracing.js +2 -4
  19. package/dist/run/handlers/wait-until.cjs +2 -116
  20. package/dist/run/headers.js +198 -10
  21. package/dist/run/next.cjs +11 -1624
  22. package/dist/run/regional-blob-store.cjs +37 -5
  23. package/dist/run/revalidate.js +24 -3
  24. package/dist/shared/blobkey.js +15 -3
  25. package/package.json +1 -1
  26. package/dist/esm-chunks/chunk-3RQSTU2O.js +0 -554
  27. package/dist/esm-chunks/chunk-72ZI2IVI.js +0 -36
  28. package/dist/esm-chunks/chunk-AMY4NOT5.js +0 -1610
  29. package/dist/esm-chunks/chunk-DLVROEVU.js +0 -144
  30. package/dist/esm-chunks/chunk-GFYWJNQR.js +0 -305
  31. package/dist/esm-chunks/chunk-HXVWGXWM.js +0 -218
  32. package/dist/esm-chunks/chunk-IJZEDP6B.js +0 -235
  33. package/dist/esm-chunks/chunk-JPTD4GEB.js +0 -309
  34. package/dist/esm-chunks/chunk-MKMK7FBF.js +0 -132
  35. package/dist/esm-chunks/chunk-RYJYZQ4X.js +0 -610
  36. package/dist/esm-chunks/chunk-SGXRYMYQ.js +0 -127
  37. package/dist/esm-chunks/chunk-TYCYFZ22.js +0 -25
  38. package/dist/esm-chunks/chunk-UYKENJEU.js +0 -19
  39. package/dist/esm-chunks/chunk-WHUPSPWV.js +0 -73
  40. package/dist/esm-chunks/chunk-XS27YRA5.js +0 -34
  41. package/dist/esm-chunks/chunk-ZENB67PD.js +0 -148
  42. package/dist/esm-chunks/chunk-ZSVHJNNY.js +0 -120
  43. package/dist/esm-chunks/next-LDOXJ7XH.js +0 -567
@@ -5,13 +5,546 @@
5
5
  })();
6
6
 
7
7
  import {
8
- clearStaleEdgeHandlers,
9
- createEdgeHandlers
10
- } from "../../esm-chunks/chunk-3RQSTU2O.js";
11
- import "../../esm-chunks/chunk-GFYWJNQR.js";
12
- import "../../esm-chunks/chunk-KGYJQ2U2.js";
13
- import "../../esm-chunks/chunk-APO262HE.js";
14
- import "../../esm-chunks/chunk-OEQOKJGE.js";
8
+ require_out
9
+ } from "../../esm-chunks/chunk-KGYJQ2U2.js";
10
+ import {
11
+ __commonJS,
12
+ __toESM
13
+ } from "../../esm-chunks/chunk-OEQOKJGE.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, _b = options.delimiter, delimiter = _b === void 0 ? "/#?" : _b;
110
+ var result = [];
111
+ var key = 0;
112
+ var i = 0;
113
+ var path = "";
114
+ var tryConsume = function(type) {
115
+ if (i < tokens.length && tokens[i].type === type)
116
+ return tokens[i++].value;
117
+ };
118
+ var mustConsume = function(type) {
119
+ var value2 = tryConsume(type);
120
+ if (value2 !== void 0)
121
+ return value2;
122
+ var _a2 = tokens[i], nextType = _a2.type, index = _a2.index;
123
+ throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
124
+ };
125
+ var consumeText = function() {
126
+ var result2 = "";
127
+ var value2;
128
+ while (value2 = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR")) {
129
+ result2 += value2;
130
+ }
131
+ return result2;
132
+ };
133
+ var isSafe = function(value2) {
134
+ for (var _i = 0, delimiter_1 = delimiter; _i < delimiter_1.length; _i++) {
135
+ var char2 = delimiter_1[_i];
136
+ if (value2.indexOf(char2) > -1)
137
+ return true;
138
+ }
139
+ return false;
140
+ };
141
+ var safePattern = function(prefix2) {
142
+ var prev = result[result.length - 1];
143
+ var prevText = prefix2 || (prev && typeof prev === "string" ? prev : "");
144
+ if (prev && !prevText) {
145
+ throw new TypeError('Must have text between two parameters, missing text after "'.concat(prev.name, '"'));
146
+ }
147
+ if (!prevText || isSafe(prevText))
148
+ return "[^".concat(escapeString(delimiter), "]+?");
149
+ return "(?:(?!".concat(escapeString(prevText), ")[^").concat(escapeString(delimiter), "])+?");
150
+ };
151
+ while (i < tokens.length) {
152
+ var char = tryConsume("CHAR");
153
+ var name = tryConsume("NAME");
154
+ var pattern = tryConsume("PATTERN");
155
+ if (name || pattern) {
156
+ var prefix = char || "";
157
+ if (prefixes.indexOf(prefix) === -1) {
158
+ path += prefix;
159
+ prefix = "";
160
+ }
161
+ if (path) {
162
+ result.push(path);
163
+ path = "";
164
+ }
165
+ result.push({
166
+ name: name || key++,
167
+ prefix,
168
+ suffix: "",
169
+ pattern: pattern || safePattern(prefix),
170
+ modifier: tryConsume("MODIFIER") || ""
171
+ });
172
+ continue;
173
+ }
174
+ var value = char || tryConsume("ESCAPED_CHAR");
175
+ if (value) {
176
+ path += value;
177
+ continue;
178
+ }
179
+ if (path) {
180
+ result.push(path);
181
+ path = "";
182
+ }
183
+ var open = tryConsume("OPEN");
184
+ if (open) {
185
+ var prefix = consumeText();
186
+ var name_1 = tryConsume("NAME") || "";
187
+ var pattern_1 = tryConsume("PATTERN") || "";
188
+ var suffix = consumeText();
189
+ mustConsume("CLOSE");
190
+ result.push({
191
+ name: name_1 || (pattern_1 ? key++ : ""),
192
+ pattern: name_1 && !pattern_1 ? safePattern(prefix) : pattern_1,
193
+ prefix,
194
+ suffix,
195
+ modifier: tryConsume("MODIFIER") || ""
196
+ });
197
+ continue;
198
+ }
199
+ mustConsume("END");
200
+ }
201
+ return result;
202
+ }
203
+ exports.parse = parse;
204
+ function compile(str, options) {
205
+ return tokensToFunction(parse(str, options), options);
206
+ }
207
+ exports.compile = compile;
208
+ function tokensToFunction(tokens, options) {
209
+ if (options === void 0) {
210
+ options = {};
211
+ }
212
+ var reFlags = flags(options);
213
+ var _a = options.encode, encode = _a === void 0 ? function(x) {
214
+ return x;
215
+ } : _a, _b = options.validate, validate = _b === void 0 ? true : _b;
216
+ var matches = tokens.map(function(token) {
217
+ if (typeof token === "object") {
218
+ return new RegExp("^(?:".concat(token.pattern, ")$"), reFlags);
219
+ }
220
+ });
221
+ return function(data) {
222
+ var path = "";
223
+ for (var i = 0; i < tokens.length; i++) {
224
+ var token = tokens[i];
225
+ if (typeof token === "string") {
226
+ path += token;
227
+ continue;
228
+ }
229
+ var value = data ? data[token.name] : void 0;
230
+ var optional = token.modifier === "?" || token.modifier === "*";
231
+ var repeat = token.modifier === "*" || token.modifier === "+";
232
+ if (Array.isArray(value)) {
233
+ if (!repeat) {
234
+ throw new TypeError('Expected "'.concat(token.name, '" to not repeat, but got an array'));
235
+ }
236
+ if (value.length === 0) {
237
+ if (optional)
238
+ continue;
239
+ throw new TypeError('Expected "'.concat(token.name, '" to not be empty'));
240
+ }
241
+ for (var j = 0; j < value.length; j++) {
242
+ var segment = encode(value[j], token);
243
+ if (validate && !matches[i].test(segment)) {
244
+ throw new TypeError('Expected all "'.concat(token.name, '" to match "').concat(token.pattern, '", but got "').concat(segment, '"'));
245
+ }
246
+ path += token.prefix + segment + token.suffix;
247
+ }
248
+ continue;
249
+ }
250
+ if (typeof value === "string" || typeof value === "number") {
251
+ var segment = encode(String(value), token);
252
+ if (validate && !matches[i].test(segment)) {
253
+ throw new TypeError('Expected "'.concat(token.name, '" to match "').concat(token.pattern, '", but got "').concat(segment, '"'));
254
+ }
255
+ path += token.prefix + segment + token.suffix;
256
+ continue;
257
+ }
258
+ if (optional)
259
+ continue;
260
+ var typeOfMessage = repeat ? "an array" : "a string";
261
+ throw new TypeError('Expected "'.concat(token.name, '" to be ').concat(typeOfMessage));
262
+ }
263
+ return path;
264
+ };
265
+ }
266
+ exports.tokensToFunction = tokensToFunction;
267
+ function match(str, options) {
268
+ var keys = [];
269
+ var re = pathToRegexp2(str, keys, options);
270
+ return regexpToFunction(re, keys, options);
271
+ }
272
+ exports.match = match;
273
+ function regexpToFunction(re, keys, options) {
274
+ if (options === void 0) {
275
+ options = {};
276
+ }
277
+ var _a = options.decode, decode = _a === void 0 ? function(x) {
278
+ return x;
279
+ } : _a;
280
+ return function(pathname) {
281
+ var m = re.exec(pathname);
282
+ if (!m)
283
+ return false;
284
+ var path = m[0], index = m.index;
285
+ var params = /* @__PURE__ */ Object.create(null);
286
+ var _loop_1 = function(i2) {
287
+ if (m[i2] === void 0)
288
+ return "continue";
289
+ var key = keys[i2 - 1];
290
+ if (key.modifier === "*" || key.modifier === "+") {
291
+ params[key.name] = m[i2].split(key.prefix + key.suffix).map(function(value) {
292
+ return decode(value, key);
293
+ });
294
+ } else {
295
+ params[key.name] = decode(m[i2], key);
296
+ }
297
+ };
298
+ for (var i = 1; i < m.length; i++) {
299
+ _loop_1(i);
300
+ }
301
+ return { path, index, params };
302
+ };
303
+ }
304
+ exports.regexpToFunction = regexpToFunction;
305
+ function escapeString(str) {
306
+ return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
307
+ }
308
+ function flags(options) {
309
+ return options && options.sensitive ? "" : "i";
310
+ }
311
+ function regexpToRegexp(path, keys) {
312
+ if (!keys)
313
+ return path;
314
+ var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
315
+ var index = 0;
316
+ var execResult = groupsRegex.exec(path.source);
317
+ while (execResult) {
318
+ keys.push({
319
+ // Use parenthesized substring match if available, index otherwise
320
+ name: execResult[1] || index++,
321
+ prefix: "",
322
+ suffix: "",
323
+ modifier: "",
324
+ pattern: ""
325
+ });
326
+ execResult = groupsRegex.exec(path.source);
327
+ }
328
+ return path;
329
+ }
330
+ function arrayToRegexp(paths, keys, options) {
331
+ var parts = paths.map(function(path) {
332
+ return pathToRegexp2(path, keys, options).source;
333
+ });
334
+ return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options));
335
+ }
336
+ function stringToRegexp(path, keys, options) {
337
+ return tokensToRegexp(parse(path, options), keys, options);
338
+ }
339
+ function tokensToRegexp(tokens, keys, options) {
340
+ if (options === void 0) {
341
+ options = {};
342
+ }
343
+ 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) {
344
+ return x;
345
+ } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
346
+ var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
347
+ var delimiterRe = "[".concat(escapeString(delimiter), "]");
348
+ var route = start ? "^" : "";
349
+ for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
350
+ var token = tokens_1[_i];
351
+ if (typeof token === "string") {
352
+ route += escapeString(encode(token));
353
+ } else {
354
+ var prefix = escapeString(encode(token.prefix));
355
+ var suffix = escapeString(encode(token.suffix));
356
+ if (token.pattern) {
357
+ if (keys)
358
+ keys.push(token);
359
+ if (prefix || suffix) {
360
+ if (token.modifier === "+" || token.modifier === "*") {
361
+ var mod = token.modifier === "*" ? "?" : "";
362
+ route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod);
363
+ } else {
364
+ route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier);
365
+ }
366
+ } else {
367
+ if (token.modifier === "+" || token.modifier === "*") {
368
+ throw new TypeError('Can not repeat "'.concat(token.name, '" without a prefix and suffix'));
369
+ }
370
+ route += "(".concat(token.pattern, ")").concat(token.modifier);
371
+ }
372
+ } else {
373
+ route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier);
374
+ }
375
+ }
376
+ }
377
+ if (end) {
378
+ if (!strict)
379
+ route += "".concat(delimiterRe, "?");
380
+ route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")");
381
+ } else {
382
+ var endToken = tokens[tokens.length - 1];
383
+ var isEndDelimited = typeof endToken === "string" ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1 : endToken === void 0;
384
+ if (!strict) {
385
+ route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?");
386
+ }
387
+ if (!isEndDelimited) {
388
+ route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")");
389
+ }
390
+ }
391
+ return new RegExp(route, flags(options));
392
+ }
393
+ exports.tokensToRegexp = tokensToRegexp;
394
+ function pathToRegexp2(path, keys, options) {
395
+ if (path instanceof RegExp)
396
+ return regexpToRegexp(path, keys);
397
+ if (Array.isArray(path))
398
+ return arrayToRegexp(path, keys, options);
399
+ return stringToRegexp(path, keys, options);
400
+ }
401
+ exports.pathToRegexp = pathToRegexp2;
402
+ }
403
+ });
404
+
405
+ // src/build/functions/edge.ts
406
+ var import_fast_glob = __toESM(require_out(), 1);
407
+ var import_path_to_regexp = __toESM(require_dist(), 1);
408
+ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
409
+ import { dirname, join } from "node:path";
410
+ import { EDGE_HANDLER_NAME } from "../plugin-context.js";
411
+ var writeEdgeManifest = async (ctx, manifest) => {
412
+ await mkdir(ctx.edgeFunctionsDir, { recursive: true });
413
+ await writeFile(join(ctx.edgeFunctionsDir, "manifest.json"), JSON.stringify(manifest, null, 2));
414
+ };
415
+ var copyRuntime = async (ctx, handlerDirectory) => {
416
+ const files = await (0, import_fast_glob.glob)("edge-runtime/**/*", {
417
+ cwd: ctx.pluginDir,
418
+ ignore: ["**/*.test.ts"],
419
+ dot: true
420
+ });
421
+ await Promise.all(
422
+ files.map(
423
+ (path) => cp(join(ctx.pluginDir, path), join(handlerDirectory, path), { recursive: true })
424
+ )
425
+ );
426
+ };
427
+ var augmentMatchers = (matchers, ctx) => {
428
+ const i18NConfig = ctx.buildConfig.i18n;
429
+ if (!i18NConfig) {
430
+ return matchers;
431
+ }
432
+ return matchers.flatMap((matcher) => {
433
+ if (matcher.originalSource && matcher.locale !== false) {
434
+ return [
435
+ matcher.regexp ? {
436
+ ...matcher,
437
+ // https://github.com/vercel/next.js/blob/5e236c9909a768dc93856fdfad53d4f4adc2db99/packages/next/src/build/analysis/get-page-static-info.ts#L332-L336
438
+ // Next is producing pretty broad matcher for i18n locale. Presumably rest of their infrastructure protects this broad matcher
439
+ // from matching on non-locale paths. For us this becomes request entry point, so we need to narrow it down to just defined locales
440
+ // otherwise users might get unexpected matches on paths like `/api*`
441
+ regexp: matcher.regexp.replace(/\[\^\/\.]+/g, `(${i18NConfig.locales.join("|")})`)
442
+ } : matcher,
443
+ {
444
+ ...matcher,
445
+ regexp: (0, import_path_to_regexp.pathToRegexp)(matcher.originalSource).source
446
+ }
447
+ ];
448
+ }
449
+ return matcher;
450
+ });
451
+ };
452
+ var writeHandlerFile = async (ctx, { matchers, name }) => {
453
+ const nextConfig = ctx.buildConfig;
454
+ const handlerName = getHandlerName({ name });
455
+ const handlerDirectory = join(ctx.edgeFunctionsDir, handlerName);
456
+ const handlerRuntimeDirectory = join(handlerDirectory, "edge-runtime");
457
+ await copyRuntime(ctx, handlerDirectory);
458
+ await writeFile(join(handlerRuntimeDirectory, "matchers.json"), JSON.stringify(matchers));
459
+ const minimalNextConfig = {
460
+ basePath: nextConfig.basePath,
461
+ i18n: nextConfig.i18n,
462
+ trailingSlash: nextConfig.trailingSlash,
463
+ skipMiddlewareUrlNormalize: nextConfig.skipMiddlewareUrlNormalize
464
+ };
465
+ await writeFile(
466
+ join(handlerRuntimeDirectory, "next.config.json"),
467
+ JSON.stringify(minimalNextConfig)
468
+ );
469
+ const htmlRewriterWasm = await readFile(
470
+ join(
471
+ ctx.pluginDir,
472
+ "edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/pkg/htmlrewriter_bg.wasm"
473
+ )
474
+ );
475
+ await writeFile(
476
+ join(handlerDirectory, `${handlerName}.js`),
477
+ `
478
+ import { init as htmlRewriterInit } from './edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/src/index.ts'
479
+ import { handleMiddleware } from './edge-runtime/middleware.ts';
480
+ import handler from './server/${name}.js';
481
+
482
+ await htmlRewriterInit({ module_or_path: Uint8Array.from(${JSON.stringify([
483
+ ...htmlRewriterWasm
484
+ ])}) });
485
+
486
+ export default (req, context) => handleMiddleware(req, context, handler);
487
+ `
488
+ );
489
+ };
490
+ var copyHandlerDependencies = async (ctx, { name, files, wasm }) => {
491
+ const srcDir = join(ctx.standaloneDir, ctx.nextDistDir);
492
+ const destDir = join(ctx.edgeFunctionsDir, getHandlerName({ name }));
493
+ const edgeRuntimeDir = join(ctx.pluginDir, "edge-runtime");
494
+ const shimPath = join(edgeRuntimeDir, "shim/index.js");
495
+ const shim = await readFile(shimPath, "utf8");
496
+ const parts = [shim];
497
+ const outputFile = join(destDir, `server/${name}.js`);
498
+ if (wasm?.length) {
499
+ for (const wasmChunk of wasm ?? []) {
500
+ const data = await readFile(join(srcDir, wasmChunk.filePath));
501
+ parts.push(`const ${wasmChunk.name} = Uint8Array.from(${JSON.stringify([...data])})`);
502
+ }
503
+ }
504
+ for (const file of files) {
505
+ const entrypoint = await readFile(join(srcDir, file), "utf8");
506
+ parts.push(`;// Concatenated file: ${file}
507
+ `, entrypoint);
508
+ }
509
+ const exports = `const middlewareEntryKey = Object.keys(_ENTRIES).find(entryKey => entryKey.startsWith("middleware_${name}")); export default _ENTRIES[middlewareEntryKey].default;`;
510
+ await mkdir(dirname(outputFile), { recursive: true });
511
+ await writeFile(outputFile, [...parts, exports].join("\n"));
512
+ };
513
+ var createEdgeHandler = async (ctx, definition) => {
514
+ await copyHandlerDependencies(ctx, definition);
515
+ await writeHandlerFile(ctx, definition);
516
+ };
517
+ var getHandlerName = ({ name }) => `${EDGE_HANDLER_NAME}-${name.replace(/\W/g, "-")}`;
518
+ var buildHandlerDefinition = (ctx, { name, matchers, page }) => {
519
+ const fun = getHandlerName({ name });
520
+ const funName = name.endsWith("middleware") ? "Next.js Middleware Handler" : `Next.js Edge Handler: ${page}`;
521
+ const cache = name.endsWith("middleware") ? void 0 : "manual";
522
+ const generator = `${ctx.pluginName}@${ctx.pluginVersion}`;
523
+ return augmentMatchers(matchers, ctx).map((matcher) => ({
524
+ function: fun,
525
+ name: funName,
526
+ pattern: matcher.regexp,
527
+ cache,
528
+ generator
529
+ }));
530
+ };
531
+ var clearStaleEdgeHandlers = async (ctx) => {
532
+ await rm(ctx.edgeFunctionsDir, { recursive: true, force: true });
533
+ };
534
+ var createEdgeHandlers = async (ctx) => {
535
+ const nextManifest = await ctx.getMiddlewareManifest();
536
+ const nextDefinitions = [
537
+ ...Object.values(nextManifest.middleware)
538
+ // ...Object.values(nextManifest.functions)
539
+ ];
540
+ await Promise.all(nextDefinitions.map((def) => createEdgeHandler(ctx, def)));
541
+ const netlifyDefinitions = nextDefinitions.flatMap((def) => buildHandlerDefinition(ctx, def));
542
+ const netlifyManifest = {
543
+ version: 1,
544
+ functions: netlifyDefinitions
545
+ };
546
+ await writeEdgeManifest(ctx, netlifyManifest);
547
+ };
15
548
  export {
16
549
  clearStaleEdgeHandlers,
17
550
  createEdgeHandlers
@@ -5,17 +5,136 @@
5
5
  })();
6
6
 
7
7
  import {
8
- clearStaleServerHandlers,
9
- createServerHandler
10
- } from "../../esm-chunks/chunk-DLVROEVU.js";
11
- import "../../esm-chunks/chunk-IJZEDP6B.js";
12
- import "../../esm-chunks/chunk-5QSXBV7L.js";
13
- import "../../esm-chunks/chunk-GNGHTHMQ.js";
14
- import "../../esm-chunks/chunk-GFYWJNQR.js";
15
- import "../../esm-chunks/chunk-KGYJQ2U2.js";
16
- import "../../esm-chunks/chunk-APO262HE.js";
17
- import "../../esm-chunks/chunk-UYKENJEU.js";
18
- import "../../esm-chunks/chunk-OEQOKJGE.js";
8
+ wrapTracer
9
+ } from "../../esm-chunks/chunk-5QSXBV7L.js";
10
+ import {
11
+ init_esm,
12
+ trace
13
+ } from "../../esm-chunks/chunk-GNGHTHMQ.js";
14
+ import {
15
+ require_out
16
+ } from "../../esm-chunks/chunk-KGYJQ2U2.js";
17
+ import {
18
+ __toESM
19
+ } from "../../esm-chunks/chunk-OEQOKJGE.js";
20
+
21
+ // src/build/functions/server.ts
22
+ init_esm();
23
+ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
24
+ import { join, relative } from "node:path";
25
+ import { join as posixJoin } from "node:path/posix";
26
+ var import_fast_glob = __toESM(require_out(), 1);
27
+ import {
28
+ copyNextDependencies,
29
+ copyNextServerCode,
30
+ verifyHandlerDirStructure
31
+ } from "../content/server.js";
32
+ import { SERVER_HANDLER_NAME } from "../plugin-context.js";
33
+ var tracer = wrapTracer(trace.getTracer("Next runtime"));
34
+ var copyHandlerDependencies = async (ctx) => {
35
+ await tracer.withActiveSpan("copyHandlerDependencies", async (span) => {
36
+ const promises = [];
37
+ const { included_files: includedFiles = [] } = ctx.netlifyConfig.functions?.["*"] || {};
38
+ includedFiles.push(
39
+ posixJoin(ctx.relativeAppDir, ".env"),
40
+ posixJoin(ctx.relativeAppDir, ".env.production"),
41
+ posixJoin(ctx.relativeAppDir, ".env.local"),
42
+ posixJoin(ctx.relativeAppDir, ".env.production.local")
43
+ );
44
+ span.setAttribute("next.includedFiles", includedFiles.join(","));
45
+ const resolvedFiles = await Promise.all(
46
+ includedFiles.map((globPattern) => (0, import_fast_glob.glob)(globPattern, { cwd: process.cwd() }))
47
+ );
48
+ for (const filePath of resolvedFiles.flat()) {
49
+ promises.push(
50
+ cp(
51
+ join(process.cwd(), filePath),
52
+ // the serverHandlerDir is aware of the dist dir.
53
+ // The distDir must not be the package path therefore we need to rely on the
54
+ // serverHandlerDir instead of the serverHandlerRootDir
55
+ // therefore we need to remove the package path from the filePath
56
+ join(ctx.serverHandlerDir, relative(ctx.relativeAppDir, filePath)),
57
+ {
58
+ recursive: true,
59
+ force: true
60
+ }
61
+ )
62
+ );
63
+ }
64
+ promises.push(
65
+ writeFile(
66
+ join(ctx.serverHandlerRuntimeModulesDir, "package.json"),
67
+ JSON.stringify({ type: "module" })
68
+ )
69
+ );
70
+ const fileList = await (0, import_fast_glob.glob)("dist/**/*", { cwd: ctx.pluginDir });
71
+ for (const filePath of fileList) {
72
+ promises.push(
73
+ cp(join(ctx.pluginDir, filePath), join(ctx.serverHandlerRuntimeModulesDir, filePath), {
74
+ recursive: true,
75
+ force: true
76
+ })
77
+ );
78
+ }
79
+ await Promise.all(promises);
80
+ });
81
+ };
82
+ var writeHandlerManifest = async (ctx) => {
83
+ await writeFile(
84
+ join(ctx.serverHandlerRootDir, `${SERVER_HANDLER_NAME}.json`),
85
+ JSON.stringify({
86
+ config: {
87
+ name: "Next.js Server Handler",
88
+ generator: `${ctx.pluginName}@${ctx.pluginVersion}`,
89
+ nodeBundler: "none",
90
+ // the folders can vary in monorepos based on the folder structure of the user so we have to glob all
91
+ includedFiles: ["**"],
92
+ includedFilesBasePath: ctx.serverHandlerRootDir
93
+ },
94
+ version: 1
95
+ }),
96
+ "utf-8"
97
+ );
98
+ };
99
+ var applyTemplateVariables = (template, variables) => {
100
+ return Object.entries(variables).reduce((acc, [key, value]) => {
101
+ return acc.replaceAll(key, value);
102
+ }, template);
103
+ };
104
+ var getHandlerFile = async (ctx) => {
105
+ const templatesDir = join(ctx.pluginDir, "dist/build/templates");
106
+ const templateVariables = {
107
+ "{{useRegionalBlobs}}": ctx.useRegionalBlobs.toString()
108
+ };
109
+ if (ctx.relativeAppDir.length !== 0) {
110
+ const template = await readFile(join(templatesDir, "handler-monorepo.tmpl.js"), "utf-8");
111
+ templateVariables["{{cwd}}"] = posixJoin(ctx.lambdaWorkingDirectory);
112
+ templateVariables["{{nextServerHandler}}"] = posixJoin(ctx.nextServerHandler);
113
+ return applyTemplateVariables(template, templateVariables);
114
+ }
115
+ return applyTemplateVariables(
116
+ await readFile(join(templatesDir, "handler.tmpl.js"), "utf-8"),
117
+ templateVariables
118
+ );
119
+ };
120
+ var writeHandlerFile = async (ctx) => {
121
+ const handler = await getHandlerFile(ctx);
122
+ await writeFile(join(ctx.serverHandlerRootDir, `${SERVER_HANDLER_NAME}.mjs`), handler);
123
+ };
124
+ var clearStaleServerHandlers = async (ctx) => {
125
+ await rm(ctx.serverFunctionsDir, { recursive: true, force: true });
126
+ };
127
+ var createServerHandler = async (ctx) => {
128
+ await tracer.withActiveSpan("createServerHandler", async () => {
129
+ await mkdir(join(ctx.serverHandlerRuntimeModulesDir), { recursive: true });
130
+ await copyNextServerCode(ctx);
131
+ await copyNextDependencies(ctx);
132
+ await copyHandlerDependencies(ctx);
133
+ await writeHandlerManifest(ctx);
134
+ await writeHandlerFile(ctx);
135
+ await verifyHandlerDirStructure(ctx);
136
+ });
137
+ };
19
138
  export {
20
139
  clearStaleServerHandlers,
21
140
  createServerHandler