@netlify/plugin-nextjs 5.8.1 → 5.9.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 (61) hide show
  1. package/README.md +3 -2
  2. package/dist/build/advanced-api-routes.js +4 -136
  3. package/dist/build/cache.js +4 -25
  4. package/dist/build/content/prerendered.js +11 -290
  5. package/dist/build/content/server.js +11 -219
  6. package/dist/build/content/static.js +14 -103
  7. package/dist/build/functions/edge.js +7 -534
  8. package/dist/build/functions/server.js +11 -130
  9. package/dist/build/image-cdn.js +3 -1599
  10. package/dist/build/plugin-context.js +6 -292
  11. package/dist/build/templates/handler-monorepo.tmpl.js +1 -1
  12. package/dist/build/templates/handler.tmpl.js +1 -1
  13. package/dist/build/verification.js +9 -104
  14. package/dist/esm-chunks/chunk-72ZI2IVI.js +36 -0
  15. package/dist/esm-chunks/chunk-AMY4NOT5.js +1610 -0
  16. package/dist/esm-chunks/chunk-BEIUVQZK.js +212 -0
  17. package/dist/esm-chunks/chunk-BVYZSEV6.js +306 -0
  18. package/dist/esm-chunks/chunk-DLVROEVU.js +144 -0
  19. package/dist/esm-chunks/chunk-GFYWJNQR.js +305 -0
  20. package/dist/esm-chunks/chunk-HGXG447M.js +561 -0
  21. package/dist/esm-chunks/chunk-HWMLYAVP.js +122 -0
  22. package/dist/esm-chunks/chunk-IJZEDP6B.js +235 -0
  23. package/dist/esm-chunks/chunk-K4RDUZYO.js +609 -0
  24. package/dist/esm-chunks/chunk-KBX7SJLC.js +73 -0
  25. package/dist/esm-chunks/chunk-NDSDIXRD.js +122 -0
  26. package/dist/esm-chunks/chunk-TYCYFZ22.js +25 -0
  27. package/dist/esm-chunks/chunk-UYKENJEU.js +19 -0
  28. package/dist/esm-chunks/chunk-XS27YRA5.js +34 -0
  29. package/dist/esm-chunks/chunk-ZENB67PD.js +148 -0
  30. package/dist/esm-chunks/chunk-ZSVHJNNY.js +120 -0
  31. package/dist/esm-chunks/next-4L47PQSM.js +569 -0
  32. package/dist/esm-chunks/{package-AOKLDA5E.js → package-BD57IC76.js} +5 -5
  33. package/dist/index.js +39 -18
  34. package/dist/run/config.js +4 -1
  35. package/dist/run/constants.js +5 -7
  36. package/dist/run/handlers/cache.cjs +1618 -31
  37. package/dist/run/handlers/request-context.cjs +6 -2
  38. package/dist/run/handlers/server.js +40 -20
  39. package/dist/run/handlers/tracer.cjs +83 -2
  40. package/dist/run/handlers/tracing.js +4 -2
  41. package/dist/run/handlers/wait-until.cjs +122 -0
  42. package/dist/run/headers.js +9 -194
  43. package/dist/run/next.cjs +1597 -15
  44. package/dist/run/revalidate.js +3 -24
  45. package/dist/shared/blobkey.js +3 -15
  46. package/edge-runtime/lib/middleware.ts +1 -1
  47. package/edge-runtime/lib/response.ts +5 -2
  48. package/edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/pkg/htmlrewriter.js +1218 -0
  49. package/edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/pkg/htmlrewriter_bg.wasm +0 -0
  50. package/edge-runtime/vendor/deno.land/x/htmlrewriter@v1.0.0/src/index.ts +80 -0
  51. package/edge-runtime/vendor/deno.land/x/{html_rewriter@v0.1.0-pre.17/vendor/html_rewriter.d.ts → htmlrewriter@v1.0.0/src/types.d.ts} +8 -25
  52. package/edge-runtime/vendor/import_map.json +0 -2
  53. package/edge-runtime/vendor.ts +1 -1
  54. package/package.json +4 -4
  55. package/edge-runtime/vendor/deno.land/std@0.134.0/fmt/colors.ts +0 -536
  56. package/edge-runtime/vendor/deno.land/std@0.134.0/testing/_diff.ts +0 -360
  57. package/edge-runtime/vendor/deno.land/std@0.134.0/testing/asserts.ts +0 -866
  58. package/edge-runtime/vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/index.ts +0 -133
  59. package/edge-runtime/vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/vendor/asyncify.js +0 -112
  60. package/edge-runtime/vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/vendor/html_rewriter.js +0 -974
  61. package/edge-runtime/vendor/raw.githubusercontent.com/worker-tools/resolvable-promise/master/index.ts +0 -50
@@ -0,0 +1,212 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import {
8
+ getRegionalBlobStore
9
+ } from "./chunk-K4RDUZYO.js";
10
+ import {
11
+ encodeBlobKey
12
+ } from "./chunk-TYCYFZ22.js";
13
+
14
+ // src/run/headers.ts
15
+ var ALL_VARIATIONS = Symbol.for("ALL_VARIATIONS");
16
+ var NetlifyVaryKeys = /* @__PURE__ */ new Set(["header", "language", "cookie", "query", "country"]);
17
+ var isNetlifyVaryKey = (key) => NetlifyVaryKeys.has(key);
18
+ var generateNetlifyVaryValues = ({
19
+ header,
20
+ language,
21
+ cookie,
22
+ query,
23
+ country
24
+ }) => {
25
+ const values = [];
26
+ if (query.length !== 0) {
27
+ if (query.includes(ALL_VARIATIONS)) {
28
+ values.push(`query`);
29
+ } else {
30
+ values.push(`query=${query.join(`|`)}`);
31
+ }
32
+ }
33
+ if (header.length !== 0) {
34
+ values.push(`header=${header.join(`|`)}`);
35
+ }
36
+ if (language.length !== 0) {
37
+ values.push(`language=${language.join(`|`)}`);
38
+ }
39
+ if (cookie.length !== 0) {
40
+ values.push(`cookie=${cookie.join(`|`)}`);
41
+ }
42
+ if (country.length !== 0) {
43
+ values.push(`country=${country.join(`|`)}`);
44
+ }
45
+ return values.join(",");
46
+ };
47
+ var getHeaderValueArray = (header) => {
48
+ return header.split(",").map((value) => value.trim()).filter(Boolean);
49
+ };
50
+ var omitHeaderValues = (header, values) => {
51
+ const headerValues = getHeaderValueArray(header);
52
+ const filteredValues = headerValues.filter(
53
+ (value) => !values.some((val) => value.startsWith(val))
54
+ );
55
+ return filteredValues.join(", ");
56
+ };
57
+ var setVaryHeaders = (headers, request, { basePath, i18n }) => {
58
+ const netlifyVaryValues = {
59
+ header: ["x-nextjs-data", "x-next-debug-logging"],
60
+ language: [],
61
+ cookie: ["__prerender_bypass", "__next_preview_data"],
62
+ query: ["__nextDataReq"],
63
+ country: []
64
+ };
65
+ const vary = headers.get("vary");
66
+ if (vary !== null) {
67
+ netlifyVaryValues.header.push(...getHeaderValueArray(vary));
68
+ }
69
+ const path = new URL(request.url).pathname;
70
+ const locales = i18n && i18n.localeDetection !== false ? i18n.locales : [];
71
+ if (locales.length > 1 && (path === "/" || path === basePath)) {
72
+ netlifyVaryValues.language.push(...locales);
73
+ netlifyVaryValues.cookie.push(`NEXT_LOCALE`);
74
+ }
75
+ const userNetlifyVary = headers.get("netlify-vary");
76
+ if (userNetlifyVary) {
77
+ const directives = getHeaderValueArray(userNetlifyVary);
78
+ for (const directive of directives) {
79
+ const [key, value] = directive.split("=");
80
+ if (key === "query" && !value) {
81
+ netlifyVaryValues.query.push(ALL_VARIATIONS);
82
+ } else if (value && isNetlifyVaryKey(key)) {
83
+ netlifyVaryValues[key].push(...value.split("|"));
84
+ }
85
+ }
86
+ }
87
+ headers.set(`netlify-vary`, generateNetlifyVaryValues(netlifyVaryValues));
88
+ };
89
+ var adjustDateHeader = async ({
90
+ headers,
91
+ request,
92
+ span,
93
+ tracer,
94
+ requestContext
95
+ }) => {
96
+ const cacheState = headers.get("x-nextjs-cache");
97
+ const isServedFromCache = cacheState === "HIT" || cacheState === "STALE";
98
+ span.setAttributes({
99
+ "x-nextjs-cache": cacheState ?? void 0,
100
+ isServedFromCache
101
+ });
102
+ if (!isServedFromCache) {
103
+ return;
104
+ }
105
+ const key = new URL(request.url).pathname;
106
+ let lastModified;
107
+ if (requestContext.responseCacheGetLastModified) {
108
+ lastModified = requestContext.responseCacheGetLastModified;
109
+ } else {
110
+ span.recordException(
111
+ new Error("lastModified not found in requestContext, falling back to trying blobs")
112
+ );
113
+ span.setAttributes({
114
+ severity: "alert",
115
+ warning: true
116
+ });
117
+ const blobStore = getRegionalBlobStore({ consistency: "strong" });
118
+ const blobKey = await encodeBlobKey(key);
119
+ lastModified = await tracer.withActiveSpan(
120
+ "get cache to calculate date header",
121
+ async (getBlobForDateSpan) => {
122
+ getBlobForDateSpan.setAttributes({
123
+ key,
124
+ blobKey
125
+ });
126
+ const blob = await blobStore.get(blobKey, { type: "json" }) ?? {};
127
+ getBlobForDateSpan.addEvent(blob ? "Cache hit" : "Cache miss");
128
+ return blob.lastModified;
129
+ }
130
+ );
131
+ }
132
+ if (!lastModified) {
133
+ span.recordException(
134
+ new Error(
135
+ "lastModified not found in either requestContext or blobs, date header for cached response is not set"
136
+ )
137
+ );
138
+ span.setAttributes({
139
+ severity: "alert",
140
+ warning: true
141
+ });
142
+ return;
143
+ }
144
+ const lastModifiedDate = new Date(lastModified);
145
+ headers.set("x-nextjs-date", headers.get("date") ?? lastModifiedDate.toUTCString());
146
+ headers.set("date", lastModifiedDate.toUTCString());
147
+ };
148
+ var setCacheControlHeaders = ({ headers, status }, request, requestContext) => {
149
+ if (typeof requestContext.routeHandlerRevalidate !== "undefined" && ["GET", "HEAD"].includes(request.method) && !headers.has("cdn-cache-control") && !headers.has("netlify-cdn-cache-control")) {
150
+ const cdnCacheControl = (
151
+ // if we are serving already stale response, instruct edge to not attempt to cache that response
152
+ headers.get("x-nextjs-cache") === "STALE" ? "public, max-age=0, must-revalidate, durable" : `s-maxage=${requestContext.routeHandlerRevalidate === false ? 31536e3 : requestContext.routeHandlerRevalidate}, stale-while-revalidate=31536000, durable`
153
+ );
154
+ headers.set("netlify-cdn-cache-control", cdnCacheControl);
155
+ return;
156
+ }
157
+ if (status === 404 && request.url.endsWith(".php")) {
158
+ headers.set("cache-control", "public, max-age=0, must-revalidate");
159
+ headers.set("netlify-cdn-cache-control", `max-age=31536000, durable`);
160
+ }
161
+ const cacheControl = headers.get("cache-control");
162
+ if (cacheControl !== null && ["GET", "HEAD"].includes(request.method) && !headers.has("cdn-cache-control") && !headers.has("netlify-cdn-cache-control")) {
163
+ const browserCacheControl = omitHeaderValues(cacheControl, [
164
+ "s-maxage",
165
+ "stale-while-revalidate"
166
+ ]);
167
+ const cdnCacheControl = (
168
+ // if we are serving already stale response, instruct edge to not attempt to cache that response
169
+ headers.get("x-nextjs-cache") === "STALE" ? "public, max-age=0, must-revalidate, durable" : [
170
+ ...getHeaderValueArray(cacheControl).map(
171
+ (value) => value === "stale-while-revalidate" ? "stale-while-revalidate=31536000" : value
172
+ ),
173
+ "durable"
174
+ ].join(", ")
175
+ );
176
+ headers.set("cache-control", browserCacheControl || "public, max-age=0, must-revalidate");
177
+ headers.set("netlify-cdn-cache-control", cdnCacheControl);
178
+ return;
179
+ }
180
+ if (cacheControl === null && !headers.has("cdn-cache-control") && !headers.has("netlify-cdn-cache-control") && requestContext.usedFsReadForNonFallback) {
181
+ headers.set("cache-control", "public, max-age=0, must-revalidate");
182
+ headers.set("netlify-cdn-cache-control", `max-age=31536000, durable`);
183
+ }
184
+ };
185
+ var setCacheTagsHeaders = (headers, requestContext) => {
186
+ if (requestContext.responseCacheTags && (headers.has("cache-control") || headers.has("netlify-cdn-cache-control"))) {
187
+ headers.set("netlify-cache-tag", requestContext.responseCacheTags.join(","));
188
+ }
189
+ };
190
+ var NEXT_CACHE_TO_CACHE_STATUS = {
191
+ HIT: `hit`,
192
+ MISS: `fwd=miss`,
193
+ STALE: `hit; fwd=stale`
194
+ };
195
+ var setCacheStatusHeader = (headers) => {
196
+ const nextCache = headers.get("x-nextjs-cache");
197
+ if (typeof nextCache === "string") {
198
+ if (nextCache in NEXT_CACHE_TO_CACHE_STATUS) {
199
+ const cacheStatus = NEXT_CACHE_TO_CACHE_STATUS[nextCache];
200
+ headers.set("cache-status", `"Next.js"; ${cacheStatus}`);
201
+ }
202
+ headers.delete("x-nextjs-cache");
203
+ }
204
+ };
205
+
206
+ export {
207
+ setVaryHeaders,
208
+ adjustDateHeader,
209
+ setCacheControlHeaders,
210
+ setCacheTagsHeaders,
211
+ setCacheStatusHeader
212
+ };
@@ -0,0 +1,306 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import {
8
+ encodeBlobKey
9
+ } from "./chunk-TYCYFZ22.js";
10
+ import {
11
+ wrapTracer
12
+ } from "./chunk-5QSXBV7L.js";
13
+ import {
14
+ init_esm,
15
+ trace
16
+ } from "./chunk-GNGHTHMQ.js";
17
+ import {
18
+ verifyNetlifyForms
19
+ } from "./chunk-ZSVHJNNY.js";
20
+ import {
21
+ require_out
22
+ } from "./chunk-KGYJQ2U2.js";
23
+ import {
24
+ require_semver
25
+ } from "./chunk-APO262HE.js";
26
+ import {
27
+ __toESM
28
+ } from "./chunk-OEQOKJGE.js";
29
+
30
+ // src/build/content/prerendered.ts
31
+ init_esm();
32
+ import { existsSync } from "node:fs";
33
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
34
+ import { join } from "node:path";
35
+ var import_fast_glob = __toESM(require_out(), 1);
36
+
37
+ // node_modules/yocto-queue/index.js
38
+ var Node = class {
39
+ value;
40
+ next;
41
+ constructor(value) {
42
+ this.value = value;
43
+ }
44
+ };
45
+ var Queue = class {
46
+ #head;
47
+ #tail;
48
+ #size;
49
+ constructor() {
50
+ this.clear();
51
+ }
52
+ enqueue(value) {
53
+ const node = new Node(value);
54
+ if (this.#head) {
55
+ this.#tail.next = node;
56
+ this.#tail = node;
57
+ } else {
58
+ this.#head = node;
59
+ this.#tail = node;
60
+ }
61
+ this.#size++;
62
+ }
63
+ dequeue() {
64
+ const current = this.#head;
65
+ if (!current) {
66
+ return;
67
+ }
68
+ this.#head = this.#head.next;
69
+ this.#size--;
70
+ return current.value;
71
+ }
72
+ clear() {
73
+ this.#head = void 0;
74
+ this.#tail = void 0;
75
+ this.#size = 0;
76
+ }
77
+ get size() {
78
+ return this.#size;
79
+ }
80
+ *[Symbol.iterator]() {
81
+ let current = this.#head;
82
+ while (current) {
83
+ yield current.value;
84
+ current = current.next;
85
+ }
86
+ }
87
+ };
88
+
89
+ // node_modules/p-limit/index.js
90
+ import { AsyncResource } from "async_hooks";
91
+ function pLimit(concurrency) {
92
+ if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
93
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
94
+ }
95
+ const queue = new Queue();
96
+ let activeCount = 0;
97
+ const next = () => {
98
+ activeCount--;
99
+ if (queue.size > 0) {
100
+ queue.dequeue()();
101
+ }
102
+ };
103
+ const run = async (function_, resolve, arguments_) => {
104
+ activeCount++;
105
+ const result = (async () => function_(...arguments_))();
106
+ resolve(result);
107
+ try {
108
+ await result;
109
+ } catch {
110
+ }
111
+ next();
112
+ };
113
+ const enqueue = (function_, resolve, arguments_) => {
114
+ queue.enqueue(
115
+ AsyncResource.bind(run.bind(void 0, function_, resolve, arguments_))
116
+ );
117
+ (async () => {
118
+ await Promise.resolve();
119
+ if (activeCount < concurrency && queue.size > 0) {
120
+ queue.dequeue()();
121
+ }
122
+ })();
123
+ };
124
+ const generator = (function_, ...arguments_) => new Promise((resolve) => {
125
+ enqueue(function_, resolve, arguments_);
126
+ });
127
+ Object.defineProperties(generator, {
128
+ activeCount: {
129
+ get: () => activeCount
130
+ },
131
+ pendingCount: {
132
+ get: () => queue.size
133
+ },
134
+ clearQueue: {
135
+ value() {
136
+ queue.clear();
137
+ }
138
+ }
139
+ });
140
+ return generator;
141
+ }
142
+
143
+ // src/build/content/prerendered.ts
144
+ var import_semver = __toESM(require_semver(), 1);
145
+ var tracer = wrapTracer(trace.getTracer("Next runtime"));
146
+ var writeCacheEntry = async (route, value, lastModified, ctx) => {
147
+ const path = join(ctx.blobDir, await encodeBlobKey(route));
148
+ const entry = JSON.stringify({
149
+ lastModified,
150
+ value
151
+ });
152
+ await writeFile(path, entry, "utf-8");
153
+ };
154
+ var routeToFilePath = (path) => {
155
+ if (path === "/") {
156
+ return "/index";
157
+ }
158
+ if (path.startsWith("/")) {
159
+ return path;
160
+ }
161
+ return `/${path}`;
162
+ };
163
+ var buildPagesCacheValue = async (path, shouldUseEnumKind, shouldSkipJson = false) => ({
164
+ kind: shouldUseEnumKind ? "PAGES" : "PAGE",
165
+ html: await readFile(`${path}.html`, "utf-8"),
166
+ pageData: shouldSkipJson ? {} : JSON.parse(await readFile(`${path}.json`, "utf-8")),
167
+ headers: void 0,
168
+ status: void 0
169
+ });
170
+ var buildAppCacheValue = async (path, shouldUseAppPageKind) => {
171
+ const meta = JSON.parse(await readFile(`${path}.meta`, "utf-8"));
172
+ const html = await readFile(`${path}.html`, "utf-8");
173
+ if (shouldUseAppPageKind) {
174
+ return {
175
+ kind: "APP_PAGE",
176
+ html,
177
+ rscData: await readFile(`${path}.rsc`, "base64").catch(
178
+ () => readFile(`${path}.prefetch.rsc`, "base64")
179
+ ),
180
+ ...meta
181
+ };
182
+ }
183
+ const rsc = await readFile(`${path}.rsc`, "utf-8").catch(
184
+ () => readFile(`${path}.prefetch.rsc`, "utf-8")
185
+ );
186
+ if (!meta.status && rsc.includes("NEXT_NOT_FOUND") && !meta.headers["x-next-cache-tags"].includes("/@")) {
187
+ meta.status = 404;
188
+ }
189
+ return {
190
+ kind: "PAGE",
191
+ html,
192
+ pageData: rsc,
193
+ ...meta
194
+ };
195
+ };
196
+ var buildRouteCacheValue = async (path, initialRevalidateSeconds, shouldUseEnumKind) => ({
197
+ kind: shouldUseEnumKind ? "APP_ROUTE" : "ROUTE",
198
+ body: await readFile(`${path}.body`, "base64"),
199
+ ...JSON.parse(await readFile(`${path}.meta`, "utf-8")),
200
+ revalidate: initialRevalidateSeconds
201
+ });
202
+ var buildFetchCacheValue = async (path) => ({
203
+ kind: "FETCH",
204
+ ...JSON.parse(await readFile(path, "utf-8"))
205
+ });
206
+ var copyPrerenderedContent = async (ctx) => {
207
+ return tracer.withActiveSpan("copyPrerenderedContent", async () => {
208
+ try {
209
+ await mkdir(ctx.blobDir, { recursive: true });
210
+ const manifest = await ctx.getPrerenderManifest();
211
+ const limitConcurrentPrerenderContentHandling = pLimit(10);
212
+ const shouldUseAppPageKind = ctx.nextVersion ? (0, import_semver.satisfies)(ctx.nextVersion, ">=15.0.0-canary.13 <15.0.0-d || >15.0.0-rc.0", {
213
+ includePrerelease: true
214
+ }) : false;
215
+ const shouldUseEnumKind = ctx.nextVersion ? (0, import_semver.satisfies)(ctx.nextVersion, ">=15.0.0-canary.114 <15.0.0-d || >15.0.0-rc.0", {
216
+ includePrerelease: true
217
+ }) : false;
218
+ await Promise.all([
219
+ ...Object.entries(manifest.routes).map(
220
+ ([route, meta]) => limitConcurrentPrerenderContentHandling(async () => {
221
+ const lastModified = meta.initialRevalidateSeconds ? Date.now() - 31536e6 : Date.now();
222
+ const key = routeToFilePath(route);
223
+ let value;
224
+ switch (true) {
225
+ // Parallel route default layout has no prerendered page
226
+ case (meta.dataRoute?.endsWith("/default.rsc") && !existsSync(join(ctx.publishDir, "server/app", `${key}.html`))):
227
+ return;
228
+ case meta.dataRoute?.endsWith(".json"):
229
+ if (manifest.notFoundRoutes.includes(route)) {
230
+ return;
231
+ }
232
+ value = await buildPagesCacheValue(
233
+ join(ctx.publishDir, "server/pages", key),
234
+ shouldUseEnumKind
235
+ );
236
+ break;
237
+ case meta.dataRoute?.endsWith(".rsc"):
238
+ value = await buildAppCacheValue(
239
+ join(ctx.publishDir, "server/app", key),
240
+ shouldUseAppPageKind
241
+ );
242
+ break;
243
+ case meta.dataRoute === null:
244
+ value = await buildRouteCacheValue(
245
+ join(ctx.publishDir, "server/app", key),
246
+ meta.initialRevalidateSeconds,
247
+ shouldUseEnumKind
248
+ );
249
+ break;
250
+ default:
251
+ throw new Error(`Unrecognized content: ${route}`);
252
+ }
253
+ if (value.kind === "PAGE" || value.kind === "PAGES" || value.kind === "APP_PAGE") {
254
+ verifyNetlifyForms(ctx, value.html);
255
+ }
256
+ await writeCacheEntry(key, value, lastModified, ctx);
257
+ })
258
+ ),
259
+ ...ctx.getFallbacks(manifest).map(async (route) => {
260
+ const key = routeToFilePath(route);
261
+ const value = await buildPagesCacheValue(
262
+ join(ctx.publishDir, "server/pages", key),
263
+ shouldUseEnumKind,
264
+ true
265
+ // there is no corresponding json file for fallback, so we are skipping it for this entry
266
+ );
267
+ await writeCacheEntry(key, value, Date.now(), ctx);
268
+ })
269
+ ]);
270
+ if (existsSync(join(ctx.publishDir, `server/app/_not-found.html`))) {
271
+ const lastModified = Date.now();
272
+ const key = "/404";
273
+ const value = await buildAppCacheValue(
274
+ join(ctx.publishDir, "server/app/_not-found"),
275
+ shouldUseAppPageKind
276
+ );
277
+ await writeCacheEntry(key, value, lastModified, ctx);
278
+ }
279
+ } catch (error) {
280
+ ctx.failBuild("Failed assembling prerendered content for upload", error);
281
+ }
282
+ });
283
+ };
284
+ var copyFetchContent = async (ctx) => {
285
+ try {
286
+ const paths = await (0, import_fast_glob.glob)(["!(*.*)"], {
287
+ cwd: join(ctx.publishDir, "cache/fetch-cache"),
288
+ extglob: true
289
+ });
290
+ await Promise.all(
291
+ paths.map(async (key) => {
292
+ const lastModified = Date.now() - 31536e6;
293
+ const path = join(ctx.publishDir, "cache/fetch-cache", key);
294
+ const value = await buildFetchCacheValue(path);
295
+ await writeCacheEntry(key, value, lastModified, ctx);
296
+ })
297
+ );
298
+ } catch (error) {
299
+ ctx.failBuild("Failed assembling fetch content for upload", error);
300
+ }
301
+ };
302
+
303
+ export {
304
+ copyPrerenderedContent,
305
+ copyFetchContent
306
+ };
@@ -0,0 +1,144 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import {
8
+ copyNextDependencies,
9
+ copyNextServerCode,
10
+ verifyHandlerDirStructure
11
+ } from "./chunk-IJZEDP6B.js";
12
+ import {
13
+ wrapTracer
14
+ } from "./chunk-5QSXBV7L.js";
15
+ import {
16
+ init_esm,
17
+ trace
18
+ } from "./chunk-GNGHTHMQ.js";
19
+ import {
20
+ SERVER_HANDLER_NAME
21
+ } from "./chunk-GFYWJNQR.js";
22
+ import {
23
+ require_out
24
+ } from "./chunk-KGYJQ2U2.js";
25
+ import {
26
+ __toESM
27
+ } from "./chunk-OEQOKJGE.js";
28
+
29
+ // src/build/functions/server.ts
30
+ init_esm();
31
+ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
32
+ import { join, relative } from "node:path";
33
+ import { join as posixJoin } from "node:path/posix";
34
+ var import_fast_glob = __toESM(require_out(), 1);
35
+ var tracer = wrapTracer(trace.getTracer("Next runtime"));
36
+ var copyHandlerDependencies = async (ctx) => {
37
+ await tracer.withActiveSpan("copyHandlerDependencies", async (span) => {
38
+ const promises = [];
39
+ const { included_files: includedFiles = [] } = ctx.netlifyConfig.functions?.["*"] || {};
40
+ includedFiles.push(
41
+ posixJoin(ctx.relativeAppDir, ".env"),
42
+ posixJoin(ctx.relativeAppDir, ".env.production"),
43
+ posixJoin(ctx.relativeAppDir, ".env.local"),
44
+ posixJoin(ctx.relativeAppDir, ".env.production.local")
45
+ );
46
+ span.setAttribute("next.includedFiles", includedFiles.join(","));
47
+ const resolvedFiles = await Promise.all(
48
+ includedFiles.map((globPattern) => (0, import_fast_glob.glob)(globPattern, { cwd: process.cwd() }))
49
+ );
50
+ for (const filePath of resolvedFiles.flat()) {
51
+ promises.push(
52
+ cp(
53
+ join(process.cwd(), filePath),
54
+ // the serverHandlerDir is aware of the dist dir.
55
+ // The distDir must not be the package path therefore we need to rely on the
56
+ // serverHandlerDir instead of the serverHandlerRootDir
57
+ // therefore we need to remove the package path from the filePath
58
+ join(ctx.serverHandlerDir, relative(ctx.relativeAppDir, filePath)),
59
+ {
60
+ recursive: true,
61
+ force: true
62
+ }
63
+ )
64
+ );
65
+ }
66
+ promises.push(
67
+ writeFile(
68
+ join(ctx.serverHandlerRuntimeModulesDir, "package.json"),
69
+ JSON.stringify({ type: "module" })
70
+ )
71
+ );
72
+ const fileList = await (0, import_fast_glob.glob)("dist/**/*", { cwd: ctx.pluginDir });
73
+ for (const filePath of fileList) {
74
+ promises.push(
75
+ cp(join(ctx.pluginDir, filePath), join(ctx.serverHandlerRuntimeModulesDir, filePath), {
76
+ recursive: true,
77
+ force: true
78
+ })
79
+ );
80
+ }
81
+ await Promise.all(promises);
82
+ });
83
+ };
84
+ var writeHandlerManifest = async (ctx) => {
85
+ await writeFile(
86
+ join(ctx.serverHandlerRootDir, `${SERVER_HANDLER_NAME}.json`),
87
+ JSON.stringify({
88
+ config: {
89
+ name: "Next.js Server Handler",
90
+ generator: `${ctx.pluginName}@${ctx.pluginVersion}`,
91
+ nodeBundler: "none",
92
+ // the folders can vary in monorepos based on the folder structure of the user so we have to glob all
93
+ includedFiles: ["**"],
94
+ includedFilesBasePath: ctx.serverHandlerRootDir
95
+ },
96
+ version: 1
97
+ }),
98
+ "utf-8"
99
+ );
100
+ };
101
+ var applyTemplateVariables = (template, variables) => {
102
+ return Object.entries(variables).reduce((acc, [key, value]) => {
103
+ return acc.replaceAll(key, value);
104
+ }, template);
105
+ };
106
+ var getHandlerFile = async (ctx) => {
107
+ const templatesDir = join(ctx.pluginDir, "dist/build/templates");
108
+ const templateVariables = {
109
+ "{{useRegionalBlobs}}": ctx.useRegionalBlobs.toString()
110
+ };
111
+ if (ctx.relativeAppDir.length !== 0) {
112
+ const template = await readFile(join(templatesDir, "handler-monorepo.tmpl.js"), "utf-8");
113
+ templateVariables["{{cwd}}"] = posixJoin(ctx.lambdaWorkingDirectory);
114
+ templateVariables["{{nextServerHandler}}"] = posixJoin(ctx.nextServerHandler);
115
+ return applyTemplateVariables(template, templateVariables);
116
+ }
117
+ return applyTemplateVariables(
118
+ await readFile(join(templatesDir, "handler.tmpl.js"), "utf-8"),
119
+ templateVariables
120
+ );
121
+ };
122
+ var writeHandlerFile = async (ctx) => {
123
+ const handler = await getHandlerFile(ctx);
124
+ await writeFile(join(ctx.serverHandlerRootDir, `${SERVER_HANDLER_NAME}.mjs`), handler);
125
+ };
126
+ var clearStaleServerHandlers = async (ctx) => {
127
+ await rm(ctx.serverFunctionsDir, { recursive: true, force: true });
128
+ };
129
+ var createServerHandler = async (ctx) => {
130
+ await tracer.withActiveSpan("createServerHandler", async () => {
131
+ await mkdir(join(ctx.serverHandlerRuntimeModulesDir), { recursive: true });
132
+ await copyNextServerCode(ctx);
133
+ await copyNextDependencies(ctx);
134
+ await copyHandlerDependencies(ctx);
135
+ await writeHandlerManifest(ctx);
136
+ await writeHandlerFile(ctx);
137
+ await verifyHandlerDirStructure(ctx);
138
+ });
139
+ };
140
+
141
+ export {
142
+ clearStaleServerHandlers,
143
+ createServerHandler
144
+ };