@netlify/plugin-nextjs 5.0.0-beta.8 → 5.0.0-beta.9

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 (33) hide show
  1. package/README.md +23 -0
  2. package/dist/build/cache.js +1 -1
  3. package/dist/build/content/prerendered.js +2 -1
  4. package/dist/build/content/server.js +2 -1
  5. package/dist/build/functions/edge.js +2 -3
  6. package/dist/build/functions/server.js +4 -4
  7. package/dist/build/image-cdn.js +1 -1
  8. package/dist/build/plugin-context.js +1 -2
  9. package/dist/build/templates/handler-monorepo.tmpl.js +33 -30
  10. package/dist/build/templates/handler.tmpl.js +31 -25
  11. package/dist/esm-chunks/{chunk-YMFYCTRI.js → chunk-4J4A5OE2.js} +23 -3
  12. package/dist/esm-chunks/{chunk-XFDUV7DP.js → chunk-67EWAGDQ.js} +29 -20
  13. package/dist/esm-chunks/chunk-72ZI2IVI.js +36 -0
  14. package/dist/esm-chunks/{chunk-N23TUUXK.js → chunk-AU7XDLZH.js} +58 -26
  15. package/dist/esm-chunks/{chunk-IZ2AVCVF.js → chunk-DWC6JSN7.js} +48 -24
  16. package/dist/esm-chunks/{chunk-XIP2W57K.js → chunk-NL5YH5N6.js} +5 -4
  17. package/dist/esm-chunks/{chunk-WSPFUAK4.js → chunk-T6AZTXZF.js} +6 -6
  18. package/dist/esm-chunks/{chunk-EPSI5TTB.js → chunk-TOK7TKP3.js} +1 -1
  19. package/dist/esm-chunks/{chunk-K233JI4O.js → chunk-UYKENJEU.js} +4 -2
  20. package/dist/esm-chunks/{chunk-ETPYUOBQ.js → chunk-YIE34LVX.js} +5 -5
  21. package/dist/esm-chunks/{package-2CI3IXK3.js → package-6DFWHFJA.js} +8 -6
  22. package/dist/index.js +12 -13
  23. package/dist/run/config.js +2 -2
  24. package/dist/run/constants.js +5 -3
  25. package/dist/run/handlers/cache.cjs +155 -79
  26. package/dist/run/handlers/request-context.cjs +56 -0
  27. package/dist/run/handlers/server.js +30 -16
  28. package/dist/run/handlers/tracing.js +1 -1
  29. package/dist/run/headers.js +3 -3
  30. package/edge-runtime/lib/response.ts +24 -20
  31. package/edge-runtime/lib/util.ts +6 -1
  32. package/package.json +1 -1
  33. package/dist/esm-chunks/chunk-XA2CZH5Y.js +0 -32
@@ -4,17 +4,15 @@
4
4
  return createRequire(import.meta.url);
5
5
  })();
6
6
 
7
- import {
8
- encodeBlobKey
9
- } from "./chunk-TYCYFZ22.js";
10
7
 
11
8
  // src/build/plugin-context.ts
12
9
  import { readFileSync } from "node:fs";
13
- import { mkdir, readFile, writeFile, stat } from "node:fs/promises";
14
- import { dirname, join, resolve } from "node:path";
10
+ import { readFile } from "node:fs/promises";
11
+ import { join, relative, resolve } from "node:path";
15
12
  import { fileURLToPath } from "node:url";
16
13
  var MODULE_DIR = fileURLToPath(new URL(".", import.meta.url));
17
14
  var PLUGIN_DIR = join(MODULE_DIR, "../..");
15
+ var DEFAULT_PUBLISH_DIR = ".next";
18
16
  var SERVER_HANDLER_NAME = "___netlify-server-handler";
19
17
  var EDGE_HANDLER_NAME = "___netlify-edge-handler";
20
18
  var PluginContext = class {
@@ -26,9 +24,12 @@ var PluginContext = class {
26
24
  packageJSON;
27
25
  /** Absolute path of the next runtime plugin directory */
28
26
  pluginDir = PLUGIN_DIR;
27
+ get relPublishDir() {
28
+ return this.constants.PUBLISH_DIR ?? join(this.packagePath, DEFAULT_PUBLISH_DIR);
29
+ }
29
30
  /** Absolute path of the publish directory */
30
31
  get publishDir() {
31
- return resolve(this.constants.PUBLISH_DIR);
32
+ return resolve(this.relPublishDir);
32
33
  }
33
34
  /**
34
35
  * Relative package path in non monorepo setups this is an empty string
@@ -38,15 +39,38 @@ var PluginContext = class {
38
39
  get packagePath() {
39
40
  return this.constants.PACKAGE_PATH || "";
40
41
  }
42
+ /**
43
+ * The working directory inside the lambda that is used for monorepos to execute the serverless function
44
+ */
45
+ get lambdaWorkingDirectory() {
46
+ return join("/var/task", this.distFolder);
47
+ }
41
48
  /**
42
49
  * Retrieves the root of the `.next/standalone` directory
43
50
  */
44
51
  get standaloneRootDir() {
45
52
  return join(this.publishDir, "standalone");
46
53
  }
54
+ /**
55
+ * The resolved relative next dist directory defaults to `.next`,
56
+ * but can be configured through the next.config.js. For monorepos this will include the packagePath
57
+ * If we need just the plain dist dir use the `nextDistDir`
58
+ */
59
+ get distDir() {
60
+ const dir = this.buildConfig.distDir ?? DEFAULT_PUBLISH_DIR;
61
+ return relative(process.cwd(), resolve(this.packagePath, dir));
62
+ }
63
+ /** The dist folder represents the parent directory of the .next folder or custom distDir */
64
+ get distFolder() {
65
+ return join(this.distDir, "..");
66
+ }
67
+ /** The `.next` folder or what the custom dist dir is set to */
68
+ get nextDistDir() {
69
+ return relative(this.distFolder, this.distDir);
70
+ }
47
71
  /** Retrieves the `.next/standalone/` directory monorepo aware */
48
72
  get standaloneDir() {
49
- return join(this.standaloneRootDir, this.constants.PACKAGE_PATH || "");
73
+ return join(this.standaloneRootDir, this.distFolder);
50
74
  }
51
75
  /**
52
76
  * Absolute path of the directory that is published and deployed to the Netlify CDN
@@ -75,10 +99,16 @@ var PluginContext = class {
75
99
  return join(this.serverFunctionsDir, SERVER_HANDLER_NAME);
76
100
  }
77
101
  get serverHandlerDir() {
78
- return join(this.serverHandlerRootDir, this.constants.PACKAGE_PATH || "");
102
+ if (this.packagePath.length === 0) {
103
+ return this.serverHandlerRootDir;
104
+ }
105
+ return join(this.serverHandlerRootDir, this.distFolder);
79
106
  }
80
107
  get nextServerHandler() {
81
- return join(this.constants.PACKAGE_PATH || "", "dist/run/handlers/server.js");
108
+ if (this.packagePath.length !== 0) {
109
+ return join(this.lambdaWorkingDirectory, ".netlify/dist/run/handlers/server.js");
110
+ }
111
+ return "./.netlify/dist/run/handlers/server.js";
82
112
  }
83
113
  /**
84
114
  * Absolute path of the directory containing the files for deno edge functions
@@ -115,9 +145,16 @@ var PluginContext = class {
115
145
  await readFile(join(this.publishDir, "server/middleware-manifest.json"), "utf-8")
116
146
  );
117
147
  }
148
+ // don't make private as it is handy inside testing to override the config
149
+ _buildConfig = null;
118
150
  /** Get Next Config from build output **/
119
- async getBuildConfig() {
120
- return JSON.parse(await readFile(join(this.publishDir, "required-server-files.json"), "utf-8")).config;
151
+ get buildConfig() {
152
+ if (!this._buildConfig) {
153
+ this._buildConfig = JSON.parse(
154
+ readFileSync(join(this.publishDir, "required-server-files.json"), "utf-8")
155
+ ).config;
156
+ }
157
+ return this._buildConfig;
121
158
  }
122
159
  /**
123
160
  * Get Next.js routes manifest from the build output
@@ -125,19 +162,6 @@ var PluginContext = class {
125
162
  async getRoutesManifest() {
126
163
  return JSON.parse(await readFile(join(this.publishDir, "routes-manifest.json"), "utf-8"));
127
164
  }
128
- /**
129
- * Write a cache entry to the blob upload directory.
130
- */
131
- async writeCacheEntry(route, value, filePath) {
132
- const { mtime } = await stat(filePath);
133
- const path = join(this.blobDir, await encodeBlobKey(route));
134
- const entry = JSON.stringify({
135
- lastModified: mtime.getTime(),
136
- value
137
- });
138
- await mkdir(dirname(path), { recursive: true });
139
- await writeFile(path, entry, "utf-8");
140
- }
141
165
  /** Fails a build with a message and an optional error */
142
166
  failBuild(message, error) {
143
167
  return this.utils.build.failBuild(message, error instanceof Error ? { error } : void 0);
@@ -5,18 +5,19 @@
5
5
  })();
6
6
 
7
7
  import {
8
- PLUGIN_DIR
9
- } from "./chunk-K233JI4O.js";
8
+ PLUGIN_DIR,
9
+ RUN_CONFIG
10
+ } from "./chunk-UYKENJEU.js";
10
11
 
11
12
  // src/run/config.ts
12
13
  import { existsSync } from "node:fs";
13
14
  import { readFile } from "node:fs/promises";
14
15
  import { join, resolve } from "node:path";
15
16
  var getRunConfig = async () => {
16
- return JSON.parse(await readFile(resolve(".next/required-server-files.json"), "utf-8")).config;
17
+ return JSON.parse(await readFile(resolve(RUN_CONFIG), "utf-8"));
17
18
  };
18
19
  var setRunConfig = (config) => {
19
- const cacheHandler = join(PLUGIN_DIR, "dist/run/handlers/cache.cjs");
20
+ const cacheHandler = join(PLUGIN_DIR, ".netlify/dist/run/handlers/cache.cjs");
20
21
  if (!existsSync(cacheHandler)) {
21
22
  throw new Error(`Cache handler not found at ${cacheHandler}`);
22
23
  }
@@ -8,13 +8,13 @@ import {
8
8
  copyNextDependencies,
9
9
  copyNextServerCode,
10
10
  writeTagsManifest
11
- } from "./chunk-YMFYCTRI.js";
12
- import {
13
- SERVER_HANDLER_NAME
14
- } from "./chunk-IZ2AVCVF.js";
11
+ } from "./chunk-4J4A5OE2.js";
15
12
  import {
16
13
  require_out
17
14
  } from "./chunk-VZNKO4OO.js";
15
+ import {
16
+ SERVER_HANDLER_NAME
17
+ } from "./chunk-DWC6JSN7.js";
18
18
  import {
19
19
  __toESM
20
20
  } from "./chunk-5JVNISGM.js";
@@ -27,7 +27,7 @@ var copyHandlerDependencies = async (ctx) => {
27
27
  const fileList = await (0, import_fast_glob.glob)("dist/**/*", { cwd: ctx.pluginDir });
28
28
  await Promise.all(
29
29
  [...fileList].map(
30
- (path) => cp(join(ctx.pluginDir, path), join(ctx.serverHandlerDir, path), {
30
+ (path) => cp(join(ctx.pluginDir, path), join(ctx.serverHandlerDir, ".netlify", path), {
31
31
  recursive: true,
32
32
  force: true
33
33
  })
@@ -61,7 +61,7 @@ var getHandlerFile = async (ctx) => {
61
61
  const templatesDir = join(ctx.pluginDir, "dist/build/templates");
62
62
  if (ctx.packagePath.length !== 0) {
63
63
  const template = await readFile(join(templatesDir, "handler-monorepo.tmpl.js"), "utf-8");
64
- return template.replaceAll("{{cwd}}", join("/var/task", ctx.packagePath)).replace("{{nextServerHandler}}", ctx.nextServerHandler);
64
+ return template.replaceAll("{{cwd}}", ctx.lambdaWorkingDirectory).replace("{{nextServerHandler}}", ctx.nextServerHandler);
65
65
  }
66
66
  return await readFile(join(templatesDir, "handler.tmpl.js"), "utf-8");
67
67
  };
@@ -9,7 +9,7 @@
9
9
  var setImageConfig = async (ctx) => {
10
10
  const {
11
11
  images: { path: imageEndpointPath, loader: imageLoader }
12
- } = await ctx.getBuildConfig();
12
+ } = ctx.buildConfig;
13
13
  if (imageLoader === "default") {
14
14
  ctx.netlifyConfig.redirects.push({
15
15
  from: imageEndpointPath,
@@ -9,9 +9,11 @@
9
9
  import { resolve } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  var MODULE_DIR = fileURLToPath(new URL(".", import.meta.url));
12
- var PLUGIN_DIR = resolve(`${MODULE_DIR}../..`);
12
+ var PLUGIN_DIR = resolve(`${MODULE_DIR}../../..`);
13
+ var RUN_CONFIG = "run-config.json";
13
14
 
14
15
  export {
15
16
  MODULE_DIR,
16
- PLUGIN_DIR
17
+ PLUGIN_DIR,
18
+ RUN_CONFIG
17
19
  };
@@ -4,12 +4,12 @@
4
4
  return createRequire(import.meta.url);
5
5
  })();
6
6
 
7
- import {
8
- EDGE_HANDLER_NAME
9
- } from "./chunk-IZ2AVCVF.js";
10
7
  import {
11
8
  require_out
12
9
  } from "./chunk-VZNKO4OO.js";
10
+ import {
11
+ EDGE_HANDLER_NAME
12
+ } from "./chunk-DWC6JSN7.js";
13
13
  import {
14
14
  __toESM
15
15
  } from "./chunk-5JVNISGM.js";
@@ -35,7 +35,7 @@ var copyRuntime = async (ctx, handlerDirectory) => {
35
35
  );
36
36
  };
37
37
  var writeHandlerFile = async (ctx, { matchers, name }) => {
38
- const nextConfig = await ctx.getBuildConfig();
38
+ const nextConfig = ctx.buildConfig;
39
39
  const handlerName = getHandlerName({ name });
40
40
  const handlerDirectory = join(ctx.edgeFunctionsDir, handlerName);
41
41
  const handlerRuntimeDirectory = join(handlerDirectory, "edge-runtime");
@@ -60,7 +60,7 @@ var writeHandlerFile = async (ctx, { matchers, name }) => {
60
60
  );
61
61
  };
62
62
  var copyHandlerDependencies = async (ctx, { name, files, wasm }) => {
63
- const srcDir = join(ctx.standaloneDir, ".next");
63
+ const srcDir = join(ctx.standaloneDir, ctx.nextDistDir);
64
64
  const destDir = join(ctx.edgeFunctionsDir, getHandlerName({ name }));
65
65
  await Promise.all(
66
66
  files.map(async (file) => {
@@ -8,7 +8,7 @@ import "./chunk-5JVNISGM.js";
8
8
 
9
9
  // package.json
10
10
  var name = "@netlify/plugin-nextjs";
11
- var version = "5.0.0-beta.8";
11
+ var version = "5.0.0-beta.9";
12
12
  var description = "Run Next.js seamlessly on Netlify";
13
13
  var main = "./dist/index.js";
14
14
  var type = "module";
@@ -26,9 +26,10 @@ var scripts = {
26
26
  pretest: "node tests/prepare.mjs",
27
27
  build: "node ./tools/build.js",
28
28
  "build:watch": "node ./tools/build.js --watch",
29
- lint: "eslint --cache --format=codeframe --max-warnings=0 src/**/*.ts",
29
+ lint: "eslint --cache --format=codeframe --max-warnings=0 --ext .ts,.cts,.js src",
30
30
  test: "vitest",
31
31
  "test:ci": "vitest run --reporter=default --retry=3",
32
+ typecheck: "tsc --noEmit",
32
33
  e2e: "playwright test",
33
34
  "e2e:ci": "playwright test"
34
35
  };
@@ -50,13 +51,13 @@ var homepage = "https://github.com/netlify/next-runtime-minimal#readme";
50
51
  var devDependencies = {
51
52
  "@fastly/http-compute-js": "1.1.4",
52
53
  "@netlify/blobs": "^6.5.0",
53
- "@netlify/build": "^29.33.5",
54
+ "@netlify/build": "^29.35.1",
54
55
  "@netlify/edge-bundler": "^11.2.2",
55
- "@netlify/edge-functions": "^2.3.0",
56
+ "@netlify/edge-functions": "^2.3.1",
56
57
  "@netlify/eslint-config-node": "^7.0.1",
57
58
  "@netlify/functions": "^2.5.1",
58
59
  "@netlify/serverless-functions-api": "^1.10.1",
59
- "@netlify/zip-it-and-ship-it": "^9.29.1",
60
+ "@netlify/zip-it-and-ship-it": "^9.29.2",
60
61
  "@opentelemetry/api": "^1.7.0",
61
62
  "@opentelemetry/sdk-node": "^0.48.0",
62
63
  "@opentelemetry/exporter-trace-otlp-http": "^0.48.0",
@@ -76,6 +77,7 @@ var devDependencies = {
76
77
  "get-port": "^7.0.0",
77
78
  "lambda-local": "^2.1.2",
78
79
  memfs: "^4.6.0",
80
+ "mock-require": "^3.0.3",
79
81
  msw: "^2.0.7",
80
82
  next: "^14.0.4",
81
83
  os: "^0.1.2",
@@ -84,7 +86,7 @@ var devDependencies = {
84
86
  typescript: "^5.1.6",
85
87
  unionfs: "^4.5.1",
86
88
  uuid: "^9.0.1",
87
- vitest: "^0.34.6"
89
+ vitest: "^1.2.2"
88
90
  };
89
91
  var clean_package = {
90
92
  indent: 2,
package/dist/index.js CHANGED
@@ -5,13 +5,8 @@
5
5
  })();
6
6
 
7
7
  import {
8
- createServerHandler
9
- } from "./esm-chunks/chunk-WSPFUAK4.js";
10
- import {
11
- copyFetchContent,
12
8
  copyPrerenderedContent
13
- } from "./esm-chunks/chunk-XFDUV7DP.js";
14
- import "./esm-chunks/chunk-YMFYCTRI.js";
9
+ } from "./esm-chunks/chunk-67EWAGDQ.js";
15
10
  import {
16
11
  copyStaticAssets,
17
12
  copyStaticContent,
@@ -20,19 +15,24 @@ import {
20
15
  } from "./esm-chunks/chunk-ZWFKLYLH.js";
21
16
  import {
22
17
  createEdgeHandlers
23
- } from "./esm-chunks/chunk-ETPYUOBQ.js";
18
+ } from "./esm-chunks/chunk-YIE34LVX.js";
24
19
  import {
25
- PluginContext
26
- } from "./esm-chunks/chunk-IZ2AVCVF.js";
20
+ createServerHandler
21
+ } from "./esm-chunks/chunk-T6AZTXZF.js";
22
+ import "./esm-chunks/chunk-4J4A5OE2.js";
27
23
  import "./esm-chunks/chunk-VZNKO4OO.js";
28
- import "./esm-chunks/chunk-TYCYFZ22.js";
29
24
  import {
30
25
  restoreBuildCache,
31
26
  saveBuildCache
32
- } from "./esm-chunks/chunk-XA2CZH5Y.js";
27
+ } from "./esm-chunks/chunk-72ZI2IVI.js";
33
28
  import {
34
29
  setImageConfig
35
- } from "./esm-chunks/chunk-EPSI5TTB.js";
30
+ } from "./esm-chunks/chunk-TOK7TKP3.js";
31
+ import {
32
+ PluginContext
33
+ } from "./esm-chunks/chunk-DWC6JSN7.js";
34
+ import "./esm-chunks/chunk-UYKENJEU.js";
35
+ import "./esm-chunks/chunk-TYCYFZ22.js";
36
36
  import "./esm-chunks/chunk-5JVNISGM.js";
37
37
 
38
38
  // src/index.ts
@@ -58,7 +58,6 @@ var onBuild = async (options) => {
58
58
  copyStaticAssets(ctx),
59
59
  copyStaticContent(ctx),
60
60
  copyPrerenderedContent(ctx),
61
- copyFetchContent(ctx),
62
61
  createServerHandler(ctx),
63
62
  createEdgeHandlers(ctx)
64
63
  ]);
@@ -8,8 +8,8 @@ import {
8
8
  getRunConfig,
9
9
  getTagsManifest,
10
10
  setRunConfig
11
- } from "../esm-chunks/chunk-XIP2W57K.js";
12
- import "../esm-chunks/chunk-K233JI4O.js";
11
+ } from "../esm-chunks/chunk-NL5YH5N6.js";
12
+ import "../esm-chunks/chunk-UYKENJEU.js";
13
13
  import "../esm-chunks/chunk-5JVNISGM.js";
14
14
  export {
15
15
  getRunConfig,
@@ -6,10 +6,12 @@
6
6
 
7
7
  import {
8
8
  MODULE_DIR,
9
- PLUGIN_DIR
10
- } from "../esm-chunks/chunk-K233JI4O.js";
9
+ PLUGIN_DIR,
10
+ RUN_CONFIG
11
+ } from "../esm-chunks/chunk-UYKENJEU.js";
11
12
  import "../esm-chunks/chunk-5JVNISGM.js";
12
13
  export {
13
14
  MODULE_DIR,
14
- PLUGIN_DIR
15
+ PLUGIN_DIR,
16
+ RUN_CONFIG
15
17
  };
@@ -1347,12 +1347,12 @@ var require_status = __commonJS({
1347
1347
  "use strict";
1348
1348
  Object.defineProperty(exports2, "__esModule", { value: true });
1349
1349
  exports2.SpanStatusCode = void 0;
1350
- var SpanStatusCode;
1351
- (function(SpanStatusCode2) {
1352
- SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
1353
- SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
1354
- SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
1355
- })(SpanStatusCode = exports2.SpanStatusCode || (exports2.SpanStatusCode = {}));
1350
+ var SpanStatusCode2;
1351
+ (function(SpanStatusCode3) {
1352
+ SpanStatusCode3[SpanStatusCode3["UNSET"] = 0] = "UNSET";
1353
+ SpanStatusCode3[SpanStatusCode3["OK"] = 1] = "OK";
1354
+ SpanStatusCode3[SpanStatusCode3["ERROR"] = 2] = "ERROR";
1355
+ })(SpanStatusCode2 = exports2.SpanStatusCode || (exports2.SpanStatusCode = {}));
1356
1356
  }
1357
1357
  });
1358
1358
 
@@ -2431,81 +2431,115 @@ var pipeline = (0, import_util.promisify)(import_stream.default.pipeline);
2431
2431
  var import_functions = __toESM(require_main());
2432
2432
  var import_api = __toESM(require_src());
2433
2433
  var import_constants = require("next/dist/lib/constants.js");
2434
+ var import_request_context = require("./request-context.cjs");
2434
2435
  var fetchBeforeNextPatchedIt = globalThis.fetch;
2435
2436
  var NetlifyCacheHandler = class {
2436
2437
  options;
2437
2438
  revalidatedTags;
2438
2439
  blobStore;
2439
2440
  tracer = import_api.trace.getTracer("Netlify Cache Handler");
2441
+ tagManifestsFetchedFromBlobStoreInCurrentRequest;
2440
2442
  constructor(options) {
2441
2443
  this.options = options;
2442
2444
  this.revalidatedTags = options.revalidatedTags;
2443
- this.blobStore = getDeployStore({ fetch: fetchBeforeNextPatchedIt });
2445
+ this.blobStore = getDeployStore({ fetch: fetchBeforeNextPatchedIt, consistency: "strong" });
2446
+ this.tagManifestsFetchedFromBlobStoreInCurrentRequest = {};
2444
2447
  }
2445
2448
  async encodeBlobKey(key) {
2446
2449
  const { encodeBlobKey: encodeBlobKey2 } = await Promise.resolve().then(() => (init_blobkey(), blobkey_exports));
2447
2450
  return await encodeBlobKey2(key);
2448
2451
  }
2452
+ captureResponseCacheLastModified(cacheValue, key, getCacheKeySpan) {
2453
+ if (cacheValue.value?.kind === "FETCH") {
2454
+ return;
2455
+ }
2456
+ const requestContext = (0, import_request_context.getRequestContext)();
2457
+ if (!requestContext) {
2458
+ getCacheKeySpan.recordException(
2459
+ new Error("CacheHandler was called without a request context")
2460
+ );
2461
+ getCacheKeySpan.setAttributes({
2462
+ severity: "alert",
2463
+ warning: true
2464
+ });
2465
+ return;
2466
+ }
2467
+ if (requestContext.responseCacheKey && requestContext.responseCacheKey !== key) {
2468
+ requestContext.responseCacheGetLastModified = void 0;
2469
+ getCacheKeySpan.recordException(
2470
+ new Error(
2471
+ `Multiple response cache keys used in single request: ["${requestContext.responseCacheKey}, "${key}"]`
2472
+ )
2473
+ );
2474
+ getCacheKeySpan.setAttributes({
2475
+ severity: "alert",
2476
+ warning: true
2477
+ });
2478
+ return;
2479
+ }
2480
+ requestContext.responseCacheKey = key;
2481
+ if (cacheValue.lastModified) {
2482
+ requestContext.responseCacheGetLastModified = cacheValue.lastModified;
2483
+ }
2484
+ }
2449
2485
  async get(...args) {
2450
2486
  return this.tracer.startActiveSpan("get cache key", async (span) => {
2451
- const [key, ctx = {}] = args;
2452
- console.debug(`[NetlifyCacheHandler.get]: ${key}`);
2453
- const blobKey = await this.encodeBlobKey(key);
2454
- span.setAttributes({ key, blobKey });
2455
- const blob = await this.blobStore.get(blobKey, {
2456
- type: "json"
2457
- });
2458
- if (!blob) {
2459
- span.addEvent("Cache miss", { key, blobKey });
2460
- span.end();
2487
+ try {
2488
+ const [key, ctx = {}] = args;
2489
+ console.debug(`[NetlifyCacheHandler.get]: ${key}`);
2490
+ const blobKey = await this.encodeBlobKey(key);
2491
+ span.setAttributes({ key, blobKey });
2492
+ const blob = await this.blobStore.get(blobKey, {
2493
+ type: "json"
2494
+ });
2495
+ if (!blob) {
2496
+ span.addEvent("Cache miss", { key, blobKey });
2497
+ return null;
2498
+ }
2499
+ const staleByTags = await this.checkCacheEntryStaleByTags(blob, ctx.tags, ctx.softTags);
2500
+ if (staleByTags) {
2501
+ span.addEvent("Stale", { staleByTags });
2502
+ return null;
2503
+ }
2504
+ this.captureResponseCacheLastModified(blob, key, span);
2505
+ switch (blob.value?.kind) {
2506
+ case "FETCH":
2507
+ span.addEvent("FETCH", { lastModified: blob.lastModified, revalidate: ctx.revalidate });
2508
+ return {
2509
+ lastModified: blob.lastModified,
2510
+ value: blob.value
2511
+ };
2512
+ case "ROUTE":
2513
+ span.addEvent("ROUTE", { lastModified: blob.lastModified, status: blob.value.status });
2514
+ return {
2515
+ lastModified: blob.lastModified,
2516
+ value: {
2517
+ ...blob.value,
2518
+ body: import_node_buffer2.Buffer.from(blob.value.body, "base64")
2519
+ }
2520
+ };
2521
+ case "PAGE":
2522
+ span.addEvent("PAGE", { lastModified: blob.lastModified });
2523
+ return {
2524
+ lastModified: blob.lastModified,
2525
+ value: blob.value
2526
+ };
2527
+ default:
2528
+ span.recordException(new Error(`Unknown cache entry kind: ${blob.value?.kind}`));
2529
+ }
2461
2530
  return null;
2462
- }
2463
- const staleByTags = await this.checkCacheEntryStaleByTags(blob, ctx.softTags);
2464
- if (staleByTags) {
2465
- span.addEvent("Stale", { staleByTags });
2531
+ } catch (error) {
2532
+ if (error instanceof Error) {
2533
+ span.recordException(error);
2534
+ }
2535
+ span.setStatus({
2536
+ code: import_api.SpanStatusCode.ERROR,
2537
+ message: error instanceof Error ? error.message : String(error)
2538
+ });
2539
+ throw error;
2540
+ } finally {
2466
2541
  span.end();
2467
- return null;
2468
2542
  }
2469
- switch (blob.value.kind) {
2470
- case "FETCH":
2471
- span.addEvent("FETCH", { lastModified: blob.lastModified, revalidate: ctx.revalidate });
2472
- span.end();
2473
- return {
2474
- lastModified: blob.lastModified,
2475
- value: {
2476
- kind: blob.value.kind,
2477
- data: blob.value.data,
2478
- revalidate: blob.value.revalidate
2479
- }
2480
- };
2481
- case "ROUTE":
2482
- span.addEvent("ROUTE", {
2483
- lastModified: blob.lastModified,
2484
- kind: blob.value.kind,
2485
- status: blob.value.status
2486
- });
2487
- span.end();
2488
- return {
2489
- lastModified: blob.lastModified,
2490
- value: {
2491
- body: import_node_buffer2.Buffer.from(blob.value.body, "base64"),
2492
- kind: blob.value.kind,
2493
- status: blob.value.status,
2494
- headers: blob.value.headers
2495
- }
2496
- };
2497
- case "PAGE":
2498
- span.addEvent("PAGE", { lastModified: blob.lastModified });
2499
- span.end();
2500
- return {
2501
- lastModified: blob.lastModified,
2502
- value: blob.value
2503
- };
2504
- default:
2505
- span.recordException(new Error(`Unknown cache entry kind: ${blob.value.kind}`));
2506
- }
2507
- span.end();
2508
- return null;
2509
2543
  });
2510
2544
  }
2511
2545
  async set(...args) {
@@ -2540,27 +2574,69 @@ var NetlifyCacheHandler = class {
2540
2574
  console.error(`[NetlifyCacheHandler]: Purging the cache for tag ${tag} failed`, error);
2541
2575
  });
2542
2576
  }
2577
+ resetRequestCache() {
2578
+ this.tagManifestsFetchedFromBlobStoreInCurrentRequest = {};
2579
+ }
2543
2580
  /**
2544
- * Checks if a page is stale through on demand revalidated tags
2581
+ * Checks if a cache entry is stale through on demand revalidated tags
2545
2582
  */
2546
- async checkCacheEntryStaleByTags(cacheEntry, softTags = []) {
2547
- const tags = "headers" in cacheEntry.value ? cacheEntry.value.headers?.[import_constants.NEXT_CACHE_TAGS_HEADER]?.split(",") || [] : [];
2548
- const cacheTags = [...tags, ...softTags];
2549
- const allManifests = await Promise.all(
2550
- cacheTags.map(async (tag) => {
2551
- const res = await this.blobStore.get(await this.encodeBlobKey(tag), { type: "json" }).then((value) => ({ [tag]: value })).catch(console.error);
2552
- return res || { [tag]: null };
2553
- })
2554
- );
2555
- const tagsManifest = Object.assign({}, ...allManifests);
2556
- const isStale = cacheTags.some((tag) => {
2557
- if (this.revalidatedTags?.includes(tag)) {
2558
- return true;
2583
+ async checkCacheEntryStaleByTags(cacheEntry, tags = [], softTags = []) {
2584
+ let cacheTags = [];
2585
+ if (cacheEntry.value?.kind === "FETCH") {
2586
+ cacheTags = [...tags, ...softTags];
2587
+ } else if (cacheEntry.value?.kind === "PAGE" || cacheEntry.value?.kind === "ROUTE") {
2588
+ cacheTags = cacheEntry.value.headers?.[import_constants.NEXT_CACHE_TAGS_HEADER]?.split(",") || [];
2589
+ } else {
2590
+ return false;
2591
+ }
2592
+ if (this.revalidatedTags && this.revalidatedTags.length !== 0) {
2593
+ for (const tag of this.revalidatedTags) {
2594
+ if (cacheTags.includes(tag)) {
2595
+ return true;
2596
+ }
2597
+ }
2598
+ }
2599
+ return new Promise((resolve, reject) => {
2600
+ const tagManifestPromises = [];
2601
+ for (const tag of cacheTags) {
2602
+ let tagManifestPromise = this.tagManifestsFetchedFromBlobStoreInCurrentRequest[tag];
2603
+ if (!tagManifestPromise) {
2604
+ tagManifestPromise = this.encodeBlobKey(tag).then((blobKey) => {
2605
+ return this.tracer.startActiveSpan(`get tag manifest`, async (span) => {
2606
+ span.setAttributes({ tag, blobKey });
2607
+ try {
2608
+ return await this.blobStore.get(blobKey, { type: "json" });
2609
+ } catch (error) {
2610
+ if (error instanceof Error) {
2611
+ span.recordException(error);
2612
+ }
2613
+ span.setStatus({
2614
+ code: import_api.SpanStatusCode.ERROR,
2615
+ message: error instanceof Error ? error.message : String(error)
2616
+ });
2617
+ throw error;
2618
+ } finally {
2619
+ span.end();
2620
+ }
2621
+ });
2622
+ });
2623
+ this.tagManifestsFetchedFromBlobStoreInCurrentRequest[tag] = tagManifestPromise;
2624
+ }
2625
+ tagManifestPromises.push(
2626
+ tagManifestPromise.then((tagManifest) => {
2627
+ const isStale = tagManifest?.revalidatedAt >= (cacheEntry.lastModified || Date.now());
2628
+ if (isStale) {
2629
+ resolve(true);
2630
+ return true;
2631
+ }
2632
+ return false;
2633
+ })
2634
+ );
2559
2635
  }
2560
- const { revalidatedAt } = tagsManifest[tag] || {};
2561
- return revalidatedAt && revalidatedAt >= (cacheEntry.lastModified || Date.now());
2636
+ Promise.all(tagManifestPromises).then((tagManifestAreStale) => {
2637
+ resolve(tagManifestAreStale.some((tagIsStale) => tagIsStale));
2638
+ }).catch(reject);
2562
2639
  });
2563
- return isStale;
2564
2640
  }
2565
2641
  };
2566
2642
  var cache_default = NetlifyCacheHandler;