@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,10 +5,127 @@
5
5
  })();
6
6
 
7
7
  import {
8
- ApiRouteType,
9
- getAPIRoutesConfigs
10
- } from "../esm-chunks/chunk-BG455SFE.js";
11
- import "../esm-chunks/chunk-5JVNISGM.js";
8
+ __require
9
+ } from "../esm-chunks/chunk-5JVNISGM.js";
10
+
11
+ // src/build/advanced-api-routes.ts
12
+ import { existsSync } from "node:fs";
13
+ import { readFile } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+ var ApiRouteType = /* @__PURE__ */ ((ApiRouteType2) => {
16
+ ApiRouteType2["SCHEDULED"] = "experimental-scheduled";
17
+ ApiRouteType2["BACKGROUND"] = "experimental-background";
18
+ return ApiRouteType2;
19
+ })(ApiRouteType || {});
20
+ async function getAPIRoutesConfigs(ctx) {
21
+ const functionsConfigManifestPath = join(
22
+ ctx.publishDir,
23
+ "server",
24
+ "functions-config-manifest.json"
25
+ );
26
+ if (!existsSync(functionsConfigManifestPath)) {
27
+ return [];
28
+ }
29
+ const functionsConfigManifest = JSON.parse(
30
+ await readFile(functionsConfigManifestPath, "utf-8")
31
+ );
32
+ const appDir = ctx.resolveFromSiteDir(".");
33
+ const pagesDir = join(appDir, "pages");
34
+ const srcPagesDir = join(appDir, "src", "pages");
35
+ const { pageExtensions } = ctx.requiredServerFiles.config;
36
+ return Promise.all(
37
+ Object.keys(functionsConfigManifest.functions).map(async (apiRoute) => {
38
+ const filePath = getSourceFileForPage(apiRoute, [pagesDir, srcPagesDir], pageExtensions);
39
+ const sharedFields = {
40
+ apiRoute,
41
+ filePath,
42
+ config: {}
43
+ };
44
+ if (filePath) {
45
+ const config = await extractConfigFromFile(filePath, appDir);
46
+ return {
47
+ ...sharedFields,
48
+ config
49
+ };
50
+ }
51
+ return sharedFields;
52
+ })
53
+ );
54
+ }
55
+ var SOURCE_FILE_EXTENSIONS = ["js", "jsx", "ts", "tsx"];
56
+ var getSourceFileForPage = (page, roots, pageExtensions = SOURCE_FILE_EXTENSIONS) => {
57
+ for (const root of roots) {
58
+ for (const extension of pageExtensions) {
59
+ const file = join(root, `${page}.${extension}`);
60
+ if (existsSync(file)) {
61
+ return file;
62
+ }
63
+ const fileAtFolderIndex = join(root, page, `index.${extension}`);
64
+ if (existsSync(fileAtFolderIndex)) {
65
+ return fileAtFolderIndex;
66
+ }
67
+ }
68
+ }
69
+ };
70
+ var findModuleFromBase = ({
71
+ paths,
72
+ candidates
73
+ }) => {
74
+ for (const candidate of candidates) {
75
+ try {
76
+ const modulePath = __require.resolve(candidate, { paths });
77
+ if (modulePath) {
78
+ return modulePath;
79
+ }
80
+ } catch {
81
+ }
82
+ }
83
+ for (const candidate of candidates) {
84
+ try {
85
+ const modulePath = __require.resolve(candidate);
86
+ if (modulePath) {
87
+ return modulePath;
88
+ }
89
+ } catch {
90
+ }
91
+ }
92
+ return null;
93
+ };
94
+ var extractConstValue;
95
+ var parseModule;
96
+ var extractConfigFromFile = async (apiFilePath, appDir) => {
97
+ if (!apiFilePath || !existsSync(apiFilePath)) {
98
+ return {};
99
+ }
100
+ const extractConstValueModulePath = findModuleFromBase({
101
+ paths: [appDir],
102
+ candidates: ["next/dist/build/analysis/extract-const-value"]
103
+ });
104
+ const parseModulePath = findModuleFromBase({
105
+ paths: [appDir],
106
+ candidates: ["next/dist/build/analysis/parse-module"]
107
+ });
108
+ if (!extractConstValueModulePath || !parseModulePath) {
109
+ return {};
110
+ }
111
+ if (!extractConstValue && extractConstValueModulePath) {
112
+ extractConstValue = __require(extractConstValueModulePath);
113
+ }
114
+ if (!parseModule && parseModulePath) {
115
+ parseModule = __require(parseModulePath).parseModule;
116
+ }
117
+ const { extractExportedConstValue } = extractConstValue;
118
+ const fileContent = await readFile(apiFilePath, "utf8");
119
+ if (!fileContent.includes("config")) {
120
+ return {};
121
+ }
122
+ const ast = await parseModule(apiFilePath, fileContent);
123
+ try {
124
+ return extractExportedConstValue(ast, "config");
125
+ } catch {
126
+ return {};
127
+ }
128
+ };
12
129
  export {
13
130
  ApiRouteType,
14
131
  getAPIRoutesConfigs
@@ -4,11 +4,32 @@
4
4
  return createRequire(import.meta.url);
5
5
  })();
6
6
 
7
- import {
8
- restoreBuildCache,
9
- saveBuildCache
10
- } from "../esm-chunks/chunk-72ZI2IVI.js";
11
7
  import "../esm-chunks/chunk-5JVNISGM.js";
8
+
9
+ // src/build/cache.ts
10
+ import { existsSync } from "node:fs";
11
+ import { rm } from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ var saveBuildCache = async (ctx) => {
14
+ const { cache } = ctx.utils;
15
+ const cacheDir = join(ctx.publishDir, "cache");
16
+ if (existsSync(cacheDir)) {
17
+ await rm(join(cacheDir, "fetch-cache"), { recursive: true, force: true });
18
+ await cache.save(cacheDir);
19
+ console.log("Next.js cache saved");
20
+ } else {
21
+ console.log("No Next.js cache to save");
22
+ }
23
+ };
24
+ var restoreBuildCache = async (ctx) => {
25
+ const { cache } = ctx.utils;
26
+ const cacheDir = join(ctx.publishDir, "cache");
27
+ if (await cache.restore(cacheDir)) {
28
+ console.log("Next.js cache restored");
29
+ } else {
30
+ console.log("No Next.js cache to restore");
31
+ }
32
+ };
12
33
  export {
13
34
  restoreBuildCache,
14
35
  saveBuildCache
@@ -5,14 +5,243 @@
5
5
  })();
6
6
 
7
7
  import {
8
- copyFetchContent,
9
- copyPrerenderedContent
10
- } from "../../esm-chunks/chunk-MRD3XSKD.js";
11
- import "../../esm-chunks/chunk-TYCYFZ22.js";
12
- import "../../esm-chunks/chunk-PDPDW32D.js";
13
- import "../../esm-chunks/chunk-Y3K5Q6FP.js";
14
- import "../../esm-chunks/chunk-VZNKO4OO.js";
15
- 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/prerendered.ts
22
+ init_esm();
23
+ import { existsSync } from "node:fs";
24
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
25
+ import { join } from "node:path";
26
+ var import_fast_glob = __toESM(require_out(), 1);
27
+
28
+ // node_modules/yocto-queue/index.js
29
+ var Node = class {
30
+ value;
31
+ next;
32
+ constructor(value) {
33
+ this.value = value;
34
+ }
35
+ };
36
+ var Queue = class {
37
+ #head;
38
+ #tail;
39
+ #size;
40
+ constructor() {
41
+ this.clear();
42
+ }
43
+ enqueue(value) {
44
+ const node = new Node(value);
45
+ if (this.#head) {
46
+ this.#tail.next = node;
47
+ this.#tail = node;
48
+ } else {
49
+ this.#head = node;
50
+ this.#tail = node;
51
+ }
52
+ this.#size++;
53
+ }
54
+ dequeue() {
55
+ const current = this.#head;
56
+ if (!current) {
57
+ return;
58
+ }
59
+ this.#head = this.#head.next;
60
+ this.#size--;
61
+ return current.value;
62
+ }
63
+ clear() {
64
+ this.#head = void 0;
65
+ this.#tail = void 0;
66
+ this.#size = 0;
67
+ }
68
+ get size() {
69
+ return this.#size;
70
+ }
71
+ *[Symbol.iterator]() {
72
+ let current = this.#head;
73
+ while (current) {
74
+ yield current.value;
75
+ current = current.next;
76
+ }
77
+ }
78
+ };
79
+
80
+ // node_modules/p-limit/index.js
81
+ import { AsyncResource } from "async_hooks";
82
+ function pLimit(concurrency) {
83
+ if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
84
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
85
+ }
86
+ const queue = new Queue();
87
+ let activeCount = 0;
88
+ const next = () => {
89
+ activeCount--;
90
+ if (queue.size > 0) {
91
+ queue.dequeue()();
92
+ }
93
+ };
94
+ const run = async (function_, resolve, arguments_) => {
95
+ activeCount++;
96
+ const result = (async () => function_(...arguments_))();
97
+ resolve(result);
98
+ try {
99
+ await result;
100
+ } catch {
101
+ }
102
+ next();
103
+ };
104
+ const enqueue = (function_, resolve, arguments_) => {
105
+ queue.enqueue(
106
+ AsyncResource.bind(run.bind(void 0, function_, resolve, arguments_))
107
+ );
108
+ (async () => {
109
+ await Promise.resolve();
110
+ if (activeCount < concurrency && queue.size > 0) {
111
+ queue.dequeue()();
112
+ }
113
+ })();
114
+ };
115
+ const generator = (function_, ...arguments_) => new Promise((resolve) => {
116
+ enqueue(function_, resolve, arguments_);
117
+ });
118
+ Object.defineProperties(generator, {
119
+ activeCount: {
120
+ get: () => activeCount
121
+ },
122
+ pendingCount: {
123
+ get: () => queue.size
124
+ },
125
+ clearQueue: {
126
+ value() {
127
+ queue.clear();
128
+ }
129
+ }
130
+ });
131
+ return generator;
132
+ }
133
+
134
+ // src/build/content/prerendered.ts
135
+ import { encodeBlobKey } from "../../shared/blobkey.js";
136
+ var tracer = wrapTracer(trace.getTracer("Next runtime"));
137
+ var writeCacheEntry = async (route, value, lastModified, ctx) => {
138
+ const path = join(ctx.blobDir, await encodeBlobKey(route));
139
+ const entry = JSON.stringify({
140
+ lastModified,
141
+ value
142
+ });
143
+ await writeFile(path, entry, "utf-8");
144
+ };
145
+ var routeToFilePath = (path) => path === "/" ? "/index" : path;
146
+ var buildPagesCacheValue = async (path) => ({
147
+ kind: "PAGE",
148
+ html: await readFile(`${path}.html`, "utf-8"),
149
+ pageData: JSON.parse(await readFile(`${path}.json`, "utf-8")),
150
+ postponed: void 0,
151
+ headers: void 0,
152
+ status: void 0
153
+ });
154
+ var buildAppCacheValue = async (path) => {
155
+ const meta = JSON.parse(await readFile(`${path}.meta`, "utf-8"));
156
+ const rsc = await readFile(`${path}.rsc`, "utf-8").catch(
157
+ () => readFile(`${path}.prefetch.rsc`, "utf-8")
158
+ );
159
+ if (!meta.status && rsc.includes("NEXT_NOT_FOUND")) {
160
+ meta.status = 404;
161
+ }
162
+ return {
163
+ kind: "PAGE",
164
+ html: await readFile(`${path}.html`, "utf-8"),
165
+ pageData: rsc,
166
+ ...meta
167
+ };
168
+ };
169
+ var buildRouteCacheValue = async (path, initialRevalidateSeconds) => ({
170
+ kind: "ROUTE",
171
+ body: await readFile(`${path}.body`, "base64"),
172
+ ...JSON.parse(await readFile(`${path}.meta`, "utf-8")),
173
+ revalidate: initialRevalidateSeconds
174
+ });
175
+ var buildFetchCacheValue = async (path) => ({
176
+ kind: "FETCH",
177
+ ...JSON.parse(await readFile(path, "utf-8"))
178
+ });
179
+ var copyPrerenderedContent = async (ctx) => {
180
+ return tracer.withActiveSpan("copyPrerenderedContent", async () => {
181
+ try {
182
+ await mkdir(ctx.blobDir, { recursive: true });
183
+ const manifest = await ctx.getPrerenderManifest();
184
+ const limitConcurrentPrerenderContentHandling = pLimit(10);
185
+ await Promise.all(
186
+ Object.entries(manifest.routes).map(
187
+ ([route, meta]) => limitConcurrentPrerenderContentHandling(async () => {
188
+ const lastModified = meta.initialRevalidateSeconds ? Date.now() - 31536e6 : Date.now();
189
+ const key = routeToFilePath(route);
190
+ let value;
191
+ switch (true) {
192
+ case (meta.dataRoute?.endsWith("/default.rsc") && !existsSync(join(ctx.publishDir, "server/app", `${key}.html`))):
193
+ return;
194
+ case meta.dataRoute?.endsWith(".json"):
195
+ if (manifest.notFoundRoutes.includes(route)) {
196
+ return;
197
+ }
198
+ value = await buildPagesCacheValue(join(ctx.publishDir, "server/pages", key));
199
+ break;
200
+ case meta.dataRoute?.endsWith(".rsc"):
201
+ value = await buildAppCacheValue(join(ctx.publishDir, "server/app", key));
202
+ break;
203
+ case meta.dataRoute === null:
204
+ value = await buildRouteCacheValue(
205
+ join(ctx.publishDir, "server/app", key),
206
+ meta.initialRevalidateSeconds
207
+ );
208
+ break;
209
+ default:
210
+ throw new Error(`Unrecognized content: ${route}`);
211
+ }
212
+ await writeCacheEntry(key, value, lastModified, ctx);
213
+ })
214
+ )
215
+ );
216
+ if (existsSync(join(ctx.publishDir, `server/app/_not-found.html`))) {
217
+ const lastModified = Date.now();
218
+ const key = "/404";
219
+ const value = await buildAppCacheValue(join(ctx.publishDir, "server/app/_not-found"));
220
+ await writeCacheEntry(key, value, lastModified, ctx);
221
+ }
222
+ } catch (error) {
223
+ ctx.failBuild("Failed assembling prerendered content for upload", error);
224
+ }
225
+ });
226
+ };
227
+ var copyFetchContent = async (ctx) => {
228
+ try {
229
+ const paths = await (0, import_fast_glob.glob)(["!(*.*)"], {
230
+ cwd: join(ctx.publishDir, "cache/fetch-cache"),
231
+ extglob: true
232
+ });
233
+ await Promise.all(
234
+ paths.map(async (key) => {
235
+ const lastModified = Date.now() - 31536e6;
236
+ const path = join(ctx.publishDir, "cache/fetch-cache", key);
237
+ const value = await buildFetchCacheValue(path);
238
+ await writeCacheEntry(key, value, lastModified, ctx);
239
+ })
240
+ );
241
+ } catch (error) {
242
+ ctx.failBuild("Failed assembling fetch content for upload", error);
243
+ }
244
+ };
16
245
  export {
17
246
  copyFetchContent,
18
247
  copyPrerenderedContent
@@ -5,20 +5,265 @@
5
5
  })();
6
6
 
7
7
  import {
8
- copyNextDependencies,
9
- copyNextServerCode,
10
- getPatchesToApply,
11
- verifyHandlerDirStructure,
12
- writeTagsManifest
13
- } from "../../esm-chunks/chunk-4BNHE6TP.js";
14
- import "../../esm-chunks/chunk-PDPDW32D.js";
15
- import "../../esm-chunks/chunk-Y3K5Q6FP.js";
16
- import "../../esm-chunks/chunk-VZNKO4OO.js";
17
- import "../../esm-chunks/chunk-K7BTUM7O.js";
18
- import "../../esm-chunks/chunk-PJG75HGC.js";
19
- import "../../esm-chunks/chunk-BG455SFE.js";
20
- import "../../esm-chunks/chunk-UYKENJEU.js";
21
- 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
+ require_semver
19
+ } from "../../esm-chunks/chunk-PJG75HGC.js";
20
+ import {
21
+ __toESM
22
+ } from "../../esm-chunks/chunk-5JVNISGM.js";
23
+
24
+ // src/build/content/server.ts
25
+ init_esm();
26
+ import { existsSync } from "node:fs";
27
+ import {
28
+ cp,
29
+ mkdir,
30
+ readFile,
31
+ readdir,
32
+ readlink,
33
+ symlink,
34
+ writeFile,
35
+ access
36
+ } from "node:fs/promises";
37
+ import { createRequire } from "node:module";
38
+ import { dirname, join, resolve, sep } from "node:path";
39
+ import { sep as posixSep, join as posixJoin } from "node:path/posix";
40
+ var import_fast_glob = __toESM(require_out(), 1);
41
+ var import_semver = __toESM(require_semver(), 1);
42
+ import { RUN_CONFIG } from "../../run/constants.js";
43
+ import { verifyNextVersion } from "../verification.js";
44
+ var tracer = wrapTracer(trace.getTracer("Next runtime"));
45
+ var toPosixPath = (path) => path.split(sep).join(posixSep);
46
+ function isError(error) {
47
+ return error instanceof Error;
48
+ }
49
+ var copyNextServerCode = async (ctx) => {
50
+ await tracer.withActiveSpan("copyNextServerCode", async () => {
51
+ const reqServerFilesPath = join(
52
+ ctx.standaloneRootDir,
53
+ ctx.relativeAppDir,
54
+ ctx.requiredServerFiles.config.distDir,
55
+ "required-server-files.json"
56
+ );
57
+ try {
58
+ await access(reqServerFilesPath);
59
+ } catch (error) {
60
+ if (isError(error) && error.code === "ENOENT") {
61
+ ctx.failBuild(
62
+ `Failed creating server handler. required-server-files.json file not found at expected location "${reqServerFilesPath}". Your repository setup is currently not yet supported.`
63
+ );
64
+ } else {
65
+ throw error;
66
+ }
67
+ }
68
+ const reqServerFiles = JSON.parse(await readFile(reqServerFilesPath, "utf-8"));
69
+ if (toPosixPath(ctx.distDir).replace(new RegExp(`^${ctx.relativeAppDir}/?`), "") !== reqServerFiles.config.distDir) {
70
+ reqServerFiles.config.distDir = ctx.nextDistDir;
71
+ await writeFile(reqServerFilesPath, JSON.stringify(reqServerFiles));
72
+ }
73
+ await mkdir(ctx.serverHandlerDir, { recursive: true });
74
+ await writeFile(
75
+ join(ctx.serverHandlerDir, RUN_CONFIG),
76
+ JSON.stringify(reqServerFiles.config),
77
+ "utf-8"
78
+ );
79
+ const srcDir = join(ctx.standaloneDir, ctx.nextDistDir);
80
+ const nextFolder = toPosixPath(ctx.distDir) === toPosixPath(ctx.buildConfig.distDir) ? ctx.distDir : ctx.nextDistDir;
81
+ const destDir = join(ctx.serverHandlerDir, nextFolder);
82
+ const paths = await (0, import_fast_glob.default)(
83
+ [`*`, `server/*`, `server/chunks/*`, `server/edge-chunks/*`, `server/+(app|pages)/**/*.js`],
84
+ {
85
+ cwd: srcDir,
86
+ extglob: true
87
+ }
88
+ );
89
+ await Promise.all(
90
+ paths.map(async (path) => {
91
+ const srcPath = join(srcDir, path);
92
+ const destPath = join(destDir, path);
93
+ if (path === "server/middleware-manifest.json") {
94
+ try {
95
+ await replaceMiddlewareManifest(srcPath, destPath);
96
+ } catch (error) {
97
+ throw new Error("Could not patch middleware manifest file", { cause: error });
98
+ }
99
+ return;
100
+ }
101
+ await cp(srcPath, destPath, { recursive: true, force: true });
102
+ })
103
+ );
104
+ });
105
+ };
106
+ async function recreateNodeModuleSymlinks(src, dest, org) {
107
+ const dirents = await readdir(join(src, org || ""), { withFileTypes: true });
108
+ await Promise.all(
109
+ dirents.map(async (dirent) => {
110
+ if (dirent.name.startsWith("@")) {
111
+ return recreateNodeModuleSymlinks(src, dest, dirent.name);
112
+ }
113
+ if (dirent.isSymbolicLink()) {
114
+ const symlinkSrc = join(dest, org || "", dirent.name);
115
+ const symlinkTarget = await readlink(join(src, org || "", dirent.name));
116
+ const symlinkDest = join(dest, org || "", symlinkTarget);
117
+ if (existsSync(symlinkDest) && !existsSync(symlinkSrc)) {
118
+ if (org) {
119
+ await mkdir(join(dest, org), { recursive: true });
120
+ }
121
+ await symlink(symlinkTarget, symlinkSrc);
122
+ }
123
+ }
124
+ })
125
+ );
126
+ }
127
+ var nextInternalModuleReplacements = [
128
+ {
129
+ // standalone is loading expensive Telemetry module that is not actually used
130
+ // so this replace that module with lightweight no-op shim that doesn't load additional modules
131
+ // see https://github.com/vercel/next.js/pull/63574 that removed need for this shim
132
+ ongoing: false,
133
+ minVersion: "13.5.0-canary.0",
134
+ // perf released in https://github.com/vercel/next.js/releases/tag/v14.2.0-canary.43
135
+ maxVersion: "14.2.0-canary.42",
136
+ nextModule: "next/dist/telemetry/storage.js",
137
+ shimModule: "./next-shims/telemetry-storage.cjs"
138
+ }
139
+ ];
140
+ function getPatchesToApply(nextVersion, patches = nextInternalModuleReplacements) {
141
+ return patches.filter((patch) => {
142
+ if ((0, import_semver.lt)(nextVersion, patch.minVersion)) {
143
+ return false;
144
+ }
145
+ if (patch.ongoing) {
146
+ if ((0, import_semver.prerelease)(nextVersion) || process.env.NETLIFY_NEXT_FORCE_APPLY_ONGOING_PATCHES) {
147
+ return true;
148
+ }
149
+ return (0, import_semver.lte)(nextVersion, patch.maxStableVersion);
150
+ }
151
+ return (0, import_semver.lte)(nextVersion, patch.maxVersion);
152
+ });
153
+ }
154
+ async function patchNextModules(ctx, nextVersion, serverHandlerRequireResolve) {
155
+ const moduleReplacementsToApply = getPatchesToApply(nextVersion);
156
+ if (moduleReplacementsToApply.length !== 0) {
157
+ await Promise.all(
158
+ moduleReplacementsToApply.map(async ({ nextModule, shimModule }) => {
159
+ try {
160
+ const nextModulePath = serverHandlerRequireResolve(nextModule);
161
+ const shimModulePath = posixJoin(ctx.pluginDir, "dist", "build", "content", shimModule);
162
+ await cp(shimModulePath, nextModulePath, { force: true });
163
+ } catch {
164
+ }
165
+ })
166
+ );
167
+ }
168
+ }
169
+ var copyNextDependencies = async (ctx) => {
170
+ await tracer.withActiveSpan("copyNextDependencies", async () => {
171
+ const entries = await readdir(ctx.standaloneDir);
172
+ const promises = entries.map(async (entry) => {
173
+ if (entry === "package.json" || entry === ctx.nextDistDir) {
174
+ return;
175
+ }
176
+ const src = join(ctx.standaloneDir, entry);
177
+ const dest = join(ctx.serverHandlerDir, entry);
178
+ await cp(src, dest, { recursive: true, verbatimSymlinks: true, force: true });
179
+ if (entry === "node_modules") {
180
+ await recreateNodeModuleSymlinks(ctx.resolveFromSiteDir("node_modules"), dest);
181
+ }
182
+ });
183
+ const rootSrcDir = join(ctx.standaloneRootDir, "node_modules");
184
+ const rootDestDir = join(ctx.serverHandlerRootDir, "node_modules");
185
+ if (existsSync(rootSrcDir) && ctx.standaloneRootDir !== ctx.standaloneDir) {
186
+ promises.push(
187
+ cp(rootSrcDir, rootDestDir, { recursive: true, verbatimSymlinks: true }).then(
188
+ () => recreateNodeModuleSymlinks(resolve("node_modules"), rootDestDir)
189
+ )
190
+ );
191
+ }
192
+ await Promise.all(promises);
193
+ const serverHandlerRequire = createRequire(posixJoin(ctx.serverHandlerDir, ":internal:"));
194
+ let nextVersion;
195
+ try {
196
+ const { version } = serverHandlerRequire("next/package.json");
197
+ if (version) {
198
+ nextVersion = version;
199
+ }
200
+ } catch {
201
+ }
202
+ if (nextVersion) {
203
+ verifyNextVersion(ctx, nextVersion);
204
+ await patchNextModules(ctx, nextVersion, serverHandlerRequire.resolve);
205
+ }
206
+ try {
207
+ const nextEntryAbsolutePath = serverHandlerRequire.resolve("next");
208
+ const nextRequire = createRequire(nextEntryAbsolutePath);
209
+ nextRequire.resolve("styled-jsx");
210
+ } catch {
211
+ throw new Error(
212
+ "node_modules are not installed correctly, if you are using pnpm please set the public hoist pattern to: `public-hoist-pattern[]=*`.\nRefer to your docs for more details: https://docs.netlify.com/integrations/frameworks/next-js/overview/#pnpm-support"
213
+ );
214
+ }
215
+ });
216
+ };
217
+ var writeTagsManifest = async (ctx) => {
218
+ const manifest = await ctx.getPrerenderManifest();
219
+ const routes = Object.entries(manifest.routes).map(async ([route, definition]) => {
220
+ let tags;
221
+ if (definition.dataRoute?.endsWith(".rsc")) {
222
+ const path = join(ctx.publishDir, `server/app/${route === "/" ? "/index" : route}.meta`);
223
+ try {
224
+ const file = await readFile(path, "utf-8");
225
+ const meta = JSON.parse(file);
226
+ tags = meta.headers["x-next-cache-tags"];
227
+ } catch {
228
+ if (!definition.dataRoute?.endsWith("/default.rsc")) {
229
+ console.log(`Unable to read cache tags for: ${path}`);
230
+ }
231
+ }
232
+ }
233
+ if (definition.dataRoute?.endsWith(".json")) {
234
+ tags = `_N_T_${route}`;
235
+ }
236
+ if (definition.dataRoute === null) {
237
+ tags = definition.initialHeaders?.["x-next-cache-tags"];
238
+ }
239
+ return [route, tags];
240
+ });
241
+ await writeFile(
242
+ join(ctx.serverHandlerDir, ".netlify/tags-manifest.json"),
243
+ JSON.stringify(Object.fromEntries(await Promise.all(routes))),
244
+ "utf-8"
245
+ );
246
+ };
247
+ var replaceMiddlewareManifest = async (sourcePath, destPath) => {
248
+ await mkdir(dirname(destPath), { recursive: true });
249
+ const data = await readFile(sourcePath, "utf8");
250
+ const manifest = JSON.parse(data);
251
+ const newManifest = {
252
+ ...manifest,
253
+ middleware: {}
254
+ };
255
+ const newData = JSON.stringify(newManifest);
256
+ await writeFile(destPath, newData);
257
+ };
258
+ var verifyHandlerDirStructure = async (ctx) => {
259
+ const runConfig = JSON.parse(await readFile(join(ctx.serverHandlerDir, RUN_CONFIG), "utf-8"));
260
+ const expectedBuildIDPath = join(ctx.serverHandlerDir, runConfig.distDir, "BUILD_ID");
261
+ if (!existsSync(expectedBuildIDPath)) {
262
+ ctx.failBuild(
263
+ `Failed creating server handler. BUILD_ID file not found at expected location "${expectedBuildIDPath}".`
264
+ );
265
+ }
266
+ };
22
267
  export {
23
268
  copyNextDependencies,
24
269
  copyNextServerCode,