@netlify/plugin-nextjs 5.0.0-beta.5 → 5.0.0-beta.7

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.
@@ -7,7 +7,7 @@
7
7
  import {
8
8
  copyFetchContent,
9
9
  copyPrerenderedContent
10
- } from "../../esm-chunks/chunk-BPBL55OP.js";
10
+ } from "../../esm-chunks/chunk-UDWVXRI2.js";
11
11
  import "../../esm-chunks/chunk-MFN4GH7U.js";
12
12
  import "../../esm-chunks/chunk-WELZ7LFO.js";
13
13
  export {
@@ -6,9 +6,9 @@
6
6
 
7
7
  import {
8
8
  createEdgeHandlers
9
- } from "../../esm-chunks/chunk-HFQPUU7P.js";
9
+ } from "../../esm-chunks/chunk-PCJY2SS7.js";
10
10
  import "../../esm-chunks/chunk-MFN4GH7U.js";
11
- import "../../esm-chunks/chunk-5OSUYKC4.js";
11
+ import "../../esm-chunks/chunk-IZ2AVCVF.js";
12
12
  import "../../esm-chunks/chunk-TYCYFZ22.js";
13
13
  import "../../esm-chunks/chunk-WELZ7LFO.js";
14
14
  export {
@@ -6,10 +6,10 @@
6
6
 
7
7
  import {
8
8
  createServerHandler
9
- } from "../../esm-chunks/chunk-CFYLTWDR.js";
9
+ } from "../../esm-chunks/chunk-KDRFBPAR.js";
10
10
  import "../../esm-chunks/chunk-COJ526HO.js";
11
11
  import "../../esm-chunks/chunk-MFN4GH7U.js";
12
- import "../../esm-chunks/chunk-5OSUYKC4.js";
12
+ import "../../esm-chunks/chunk-IZ2AVCVF.js";
13
13
  import "../../esm-chunks/chunk-TYCYFZ22.js";
14
14
  import "../../esm-chunks/chunk-WELZ7LFO.js";
15
15
  export {
@@ -8,7 +8,7 @@ import {
8
8
  EDGE_HANDLER_NAME,
9
9
  PluginContext,
10
10
  SERVER_HANDLER_NAME
11
- } from "../esm-chunks/chunk-5OSUYKC4.js";
11
+ } from "../esm-chunks/chunk-IZ2AVCVF.js";
12
12
  import "../esm-chunks/chunk-TYCYFZ22.js";
13
13
  import "../esm-chunks/chunk-WELZ7LFO.js";
14
14
  export {
@@ -10,7 +10,7 @@ import {
10
10
 
11
11
  // src/build/plugin-context.ts
12
12
  import { readFileSync } from "node:fs";
13
- import { mkdir, readFile, writeFile } from "node:fs/promises";
13
+ import { mkdir, readFile, writeFile, stat } from "node:fs/promises";
14
14
  import { dirname, join, resolve } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  var MODULE_DIR = fileURLToPath(new URL(".", import.meta.url));
@@ -128,10 +128,11 @@ var PluginContext = class {
128
128
  /**
129
129
  * Write a cache entry to the blob upload directory.
130
130
  */
131
- async writeCacheEntry(route, value) {
131
+ async writeCacheEntry(route, value, filePath) {
132
+ const { mtime } = await stat(filePath);
132
133
  const path = join(this.blobDir, await encodeBlobKey(route));
133
134
  const entry = JSON.stringify({
134
- lastModified: Date.now(),
135
+ lastModified: mtime.getTime(),
135
136
  value
136
137
  });
137
138
  await mkdir(dirname(path), { recursive: true });
@@ -14,7 +14,7 @@ import {
14
14
  } from "./chunk-MFN4GH7U.js";
15
15
  import {
16
16
  SERVER_HANDLER_NAME
17
- } from "./chunk-5OSUYKC4.js";
17
+ } from "./chunk-IZ2AVCVF.js";
18
18
  import {
19
19
  __toESM
20
20
  } from "./chunk-WELZ7LFO.js";
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-MFN4GH7U.js";
10
10
  import {
11
11
  EDGE_HANDLER_NAME
12
- } from "./chunk-5OSUYKC4.js";
12
+ } from "./chunk-IZ2AVCVF.js";
13
13
  import {
14
14
  __toESM
15
15
  } from "./chunk-WELZ7LFO.js";
@@ -17,7 +17,7 @@ import {
17
17
  // src/build/functions/edge.ts
18
18
  var import_fast_glob = __toESM(require_out(), 1);
19
19
  import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
20
- import { dirname, join } from "node:path";
20
+ import { dirname, join, relative } from "node:path";
21
21
  var writeEdgeManifest = async (ctx, manifest) => {
22
22
  await mkdir(ctx.edgeFunctionsDir, { recursive: true });
23
23
  await writeFile(join(ctx.edgeFunctionsDir, "manifest.json"), JSON.stringify(manifest, null, 2));
@@ -60,36 +60,38 @@ var writeHandlerFile = async (ctx, { matchers, name }) => {
60
60
  );
61
61
  };
62
62
  var copyHandlerDependencies = async (ctx, { name, files, wasm }) => {
63
- const edgeRuntimePath = join(ctx.pluginDir, "edge-runtime");
64
63
  const srcDir = join(ctx.standaloneDir, ".next");
65
- const shimPath = join(edgeRuntimePath, "shim/index.js");
66
- const shim = await readFile(shimPath, "utf8");
67
- const imports = `import './edge-runtime-webpack.js';`;
68
- const exports = `export default _ENTRIES["middleware_${name}"].default;`;
69
- const parts = [shim, imports];
70
- if (wasm?.length) {
71
- parts.push(
72
- `import { decode as _base64Decode } from "../edge-runtime/vendor/deno.land/std@0.175.0/encoding/base64.ts";`
73
- );
74
- for (const wasmChunk of wasm ?? []) {
75
- const data = await readFile(join(srcDir, wasmChunk.filePath));
76
- parts.push(
77
- `const ${wasmChunk.name} = _base64Decode(${JSON.stringify(
78
- data.toString("base64")
79
- )}).buffer`
80
- );
81
- }
82
- }
64
+ const destDir = join(ctx.edgeFunctionsDir, getHandlerName({ name }));
83
65
  await Promise.all(
84
66
  files.map(async (file) => {
85
- const destDir = join(ctx.edgeFunctionsDir, getHandlerName({ name }));
86
67
  if (file === `server/${name}.js`) {
68
+ const edgeRuntimeDir = join(ctx.pluginDir, "edge-runtime");
69
+ const shimPath = join(edgeRuntimeDir, "shim/index.js");
70
+ const shim = await readFile(shimPath, "utf8");
71
+ const importsDir = relative(dirname(join(srcDir, file)), join(srcDir, "server"));
72
+ const importsSrc = `${importsDir || "."}/edge-runtime-webpack.js`;
73
+ const imports = `import '${importsSrc}';`;
74
+ const exports = `export default _ENTRIES["middleware_${name}"].default;`;
75
+ const parts = [shim, imports];
76
+ if (wasm?.length) {
77
+ parts.push(
78
+ `import { decode as _base64Decode } from "../edge-runtime/vendor/deno.land/std@0.175.0/encoding/base64.ts";`
79
+ );
80
+ for (const wasmChunk of wasm ?? []) {
81
+ const data = await readFile(join(srcDir, wasmChunk.filePath));
82
+ parts.push(
83
+ `const ${wasmChunk.name} = _base64Decode(${JSON.stringify(
84
+ data.toString("base64")
85
+ )}).buffer`
86
+ );
87
+ }
88
+ }
87
89
  const entrypoint = await readFile(join(srcDir, file), "utf8");
88
90
  await mkdir(dirname(join(destDir, file)), { recursive: true });
89
91
  await writeFile(join(destDir, file), [...parts, entrypoint, exports].join("\n;"));
90
- return;
92
+ } else {
93
+ await cp(join(srcDir, file), join(destDir, file));
91
94
  }
92
- await cp(join(srcDir, file), join(destDir, file));
93
95
  })
94
96
  );
95
97
  };
@@ -100,8 +102,8 @@ var createEdgeHandler = async (ctx, definition) => {
100
102
  var getHandlerName = ({ name }) => `${EDGE_HANDLER_NAME}-${name.replace(/\W/g, "-")}`;
101
103
  var buildHandlerDefinition = (ctx, { name, matchers, page }) => {
102
104
  const fun = getHandlerName({ name });
103
- const funName = name === "middleware" ? "Next.js Middleware Handler" : `Next.js Edge Handler: ${page}`;
104
- const cache = name === "middleware" ? void 0 : "manual";
105
+ const funName = name.endsWith("middleware") ? "Next.js Middleware Handler" : `Next.js Edge Handler: ${page}`;
106
+ const cache = name.endsWith("middleware") ? void 0 : "manual";
105
107
  const generator = `${ctx.pluginName}@${ctx.pluginVersion}`;
106
108
  return matchers.map((matcher) => ({
107
109
  function: fun,
@@ -44,28 +44,37 @@ var copyPrerenderedContent = async (ctx) => {
44
44
  Object.entries(manifest.routes).map(async ([route, meta]) => {
45
45
  const key = routeToFilePath(route);
46
46
  let value;
47
+ let path;
47
48
  switch (true) {
48
49
  case (meta.dataRoute?.endsWith("/default.rsc") && !existsSync(join(ctx.publishDir, "server/app", `${key}.html`))):
49
50
  return;
50
51
  case meta.dataRoute?.endsWith(".json"):
51
- value = await buildPagesCacheValue(join(ctx.publishDir, "server/pages", key));
52
+ path = join(ctx.publishDir, "server/pages", key);
53
+ value = await buildPagesCacheValue(path);
52
54
  break;
53
55
  case meta.dataRoute?.endsWith(".rsc"):
54
- value = await buildAppCacheValue(join(ctx.publishDir, "server/app", key));
56
+ path = join(ctx.publishDir, "server/app", key);
57
+ value = await buildAppCacheValue(path);
55
58
  break;
56
59
  case meta.dataRoute === null:
57
- value = await buildRouteCacheValue(join(ctx.publishDir, "server/app", key));
60
+ path = join(ctx.publishDir, "server/app", key);
61
+ value = await buildRouteCacheValue(path);
58
62
  break;
59
63
  default:
60
64
  throw new Error(`Unrecognized content: ${route}`);
61
65
  }
62
- await ctx.writeCacheEntry(key, value);
66
+ await ctx.writeCacheEntry(
67
+ key,
68
+ value,
69
+ meta.dataRoute === null ? `${path}.body` : `${path}.html`
70
+ );
63
71
  })
64
72
  );
65
73
  if (existsSync(join(ctx.publishDir, `server/app/_not-found.html`))) {
66
74
  const key = "/404";
67
- const value = await buildAppCacheValue(join(ctx.publishDir, "server/app/_not-found"));
68
- await ctx.writeCacheEntry(key, value);
75
+ const path = join(ctx.publishDir, "server/app/_not-found");
76
+ const value = await buildAppCacheValue(path);
77
+ await ctx.writeCacheEntry(key, value, `${path}.html`);
69
78
  }
70
79
  } catch (error) {
71
80
  ctx.failBuild("Failed assembling prerendered content for upload", error);
@@ -79,8 +88,9 @@ var copyFetchContent = async (ctx) => {
79
88
  });
80
89
  await Promise.all(
81
90
  paths.map(async (key) => {
82
- const value = await buildFetchCacheValue(join(ctx.publishDir, "cache/fetch-cache", key));
83
- await ctx.writeCacheEntry(key, value);
91
+ const path = join(ctx.publishDir, "cache/fetch-cache", key);
92
+ const value = await buildFetchCacheValue(path);
93
+ await ctx.writeCacheEntry(key, value, path);
84
94
  })
85
95
  );
86
96
  } catch (error) {
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  import {
8
8
  copyFetchContent,
9
9
  copyPrerenderedContent
10
- } from "./esm-chunks/chunk-BPBL55OP.js";
10
+ } from "./esm-chunks/chunk-UDWVXRI2.js";
11
11
  import {
12
12
  copyStaticAssets,
13
13
  copyStaticContent,
@@ -16,10 +16,10 @@ import {
16
16
  } from "./esm-chunks/chunk-AMJYZZKR.js";
17
17
  import {
18
18
  createEdgeHandlers
19
- } from "./esm-chunks/chunk-HFQPUU7P.js";
19
+ } from "./esm-chunks/chunk-PCJY2SS7.js";
20
20
  import {
21
21
  createServerHandler
22
- } from "./esm-chunks/chunk-CFYLTWDR.js";
22
+ } from "./esm-chunks/chunk-KDRFBPAR.js";
23
23
  import "./esm-chunks/chunk-COJ526HO.js";
24
24
  import "./esm-chunks/chunk-MFN4GH7U.js";
25
25
  import {
@@ -31,7 +31,7 @@ import {
31
31
  } from "./esm-chunks/chunk-EPSI5TTB.js";
32
32
  import {
33
33
  PluginContext
34
- } from "./esm-chunks/chunk-5OSUYKC4.js";
34
+ } from "./esm-chunks/chunk-IZ2AVCVF.js";
35
35
  import "./esm-chunks/chunk-TYCYFZ22.js";
36
36
  import "./esm-chunks/chunk-WELZ7LFO.js";
37
37
 
@@ -12,20 +12,34 @@ export const InternalHeaders = {
12
12
  // * https://github.com/vercel/next.js/blob/43c9d8940dc42337dd2f7d66aa90e6abf952278e/packages/next/server/web/spec-extension/response.ts#L10-L27
13
13
  export function updateModifiedHeaders(requestHeaders: Headers, responseHeaders: Headers) {
14
14
  const overriddenHeaders = responseHeaders.get('x-middleware-override-headers')
15
-
16
15
  if (!overriddenHeaders) {
17
16
  return
18
17
  }
19
18
 
20
- const headersToUpdate = overriddenHeaders.split(',').map((header) => header.trim())
19
+ const headersToUpdate = new Set(overriddenHeaders.split(',').map((header) => header.trim()))
20
+
21
+ // We can't iterate this directly, because we modify the headers in the loop.
22
+ // This was causing values to be skipped. By spreading them first we avoid that.
23
+ for (const key of [...requestHeaders.keys()]) {
24
+ if (!headersToUpdate.has(key)) {
25
+ requestHeaders.delete(key)
26
+ }
27
+ }
21
28
 
22
29
  for (const header of headersToUpdate) {
23
30
  const oldHeaderKey = 'x-middleware-request-' + header
24
31
  const headerValue = responseHeaders.get(oldHeaderKey) || ''
25
32
 
26
- requestHeaders.set(header, headerValue)
33
+ const oldValue = requestHeaders.get(header) || ''
34
+
35
+ if (oldValue !== headerValue) {
36
+ if (headerValue) {
37
+ requestHeaders.set(header, headerValue)
38
+ } else {
39
+ requestHeaders.delete(header)
40
+ }
41
+ }
27
42
  responseHeaders.delete(oldHeaderKey)
28
43
  }
29
-
30
44
  responseHeaders.delete('x-middleware-override-headers')
31
45
  }
@@ -1,6 +1,6 @@
1
1
  import type { Context } from '@netlify/edge-functions'
2
2
 
3
- import { normalizeDataUrl, removeBasePath, normalizeLocalePath } from './util.ts'
3
+ import { normalizeDataUrl, removeBasePath, normalizeLocalePath, addBasePath } from './util.ts'
4
4
 
5
5
  interface I18NConfig {
6
6
  defaultLocale: string
@@ -41,6 +41,7 @@ const normalizeRequestURL = (
41
41
  const url = new URL(originalURL)
42
42
 
43
43
  url.pathname = removeBasePath(url.pathname, nextConfig?.basePath)
44
+ const didRemoveBasePath = url.toString() !== originalURL
44
45
 
45
46
  let detectedLocale: string | undefined
46
47
 
@@ -64,6 +65,10 @@ const normalizeRequestURL = (
64
65
  url.pathname = `${url.pathname}/`
65
66
  }
66
67
 
68
+ if (didRemoveBasePath) {
69
+ url.pathname = addBasePath(url.pathname, nextConfig?.basePath)
70
+ }
71
+
67
72
  return {
68
73
  url: url.toString(),
69
74
  detectedLocale,
@@ -3,7 +3,13 @@ import { HTMLRewriter } from '../vendor/deno.land/x/html_rewriter@v0.1.0-pre.17/
3
3
 
4
4
  import { updateModifiedHeaders } from './headers.ts'
5
5
  import type { StructuredLogger } from './logging.ts'
6
- import { normalizeDataUrl, normalizeLocalePath, relativizeURL, rewriteDataPath } from './util.ts'
6
+ import {
7
+ addBasePath,
8
+ normalizeDataUrl,
9
+ normalizeLocalePath,
10
+ relativizeURL,
11
+ rewriteDataPath,
12
+ } from './util.ts'
7
13
  import { addMiddlewareHeaders, isMiddlewareRequest, isMiddlewareResponse } from './middleware.ts'
8
14
  import { RequestData } from './next-request.ts'
9
15
 
@@ -164,27 +170,33 @@ export const buildResponse = async ({
164
170
  newRoute: rewriteUrl.pathname,
165
171
  basePath: nextConfig?.basePath,
166
172
  })
173
+ if (rewriteUrl.toString() === request.url) {
174
+ logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url')
175
+ return
176
+ }
177
+ res.headers.set('x-middleware-rewrite', relativeUrl)
178
+ return addMiddlewareHeaders(fetch(new Request(rewriteUrl, request)), res)
179
+ }
180
+ const target = normalizeLocalizedTarget({ target: rewrite, request, nextConfig })
181
+ if (target === request.url) {
182
+ logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url')
183
+ return
167
184
  }
168
185
  res.headers.set('x-middleware-rewrite', relativeUrl)
169
- request.headers.set('x-middleware-rewrite', rewrite)
170
- return addMiddlewareHeaders(fetch(new Request(rewriteUrl, request)), res)
186
+ request.headers.set('x-middleware-rewrite', target)
187
+ return addMiddlewareHeaders(fetch(new Request(target, request)), res)
171
188
  }
172
189
 
173
190
  let redirect = res.headers.get('location')
174
191
 
175
192
  // If we are redirecting a request that had a locale in the URL, we need to add it back in
176
193
  if (redirect && requestLocale) {
177
- const redirectUrl = new URL(redirect, request.url)
178
-
179
- const normalizedRedirect = normalizeLocalePath(redirectUrl.pathname, nextConfig?.i18n?.locales)
180
-
181
- const locale = normalizedRedirect.detectedLocale ?? requestLocale
182
- // Pages router API routes don't have a locale in the URL
183
- if (locale && !redirectUrl.pathname.startsWith(`/api/`)) {
184
- redirectUrl.pathname = `/${locale}${normalizedRedirect.pathname}`
185
- redirect = redirectUrl.toString()
186
- res.headers.set('location', redirect)
194
+ redirect = normalizeLocalizedTarget({ target: redirect, request, nextConfig })
195
+ if (redirect === request.url) {
196
+ logger.withFields({ rewrite_url: rewrite }).debug('Rewrite url is same as original url')
197
+ return
187
198
  }
199
+ res.headers.set('location', redirect)
188
200
  }
189
201
 
190
202
  // Data requests shouldn't automatically redirect in the browser (they might be HTML pages): they're handled by the router
@@ -206,3 +218,34 @@ export const buildResponse = async ({
206
218
 
207
219
  return res
208
220
  }
221
+
222
+ /**
223
+ * Normalizes the locale in a URL.
224
+ */
225
+ function normalizeLocalizedTarget({
226
+ target,
227
+ request,
228
+ nextConfig,
229
+ requestLocale,
230
+ }: {
231
+ target: string
232
+ request: Request
233
+ nextConfig?: RequestData['nextConfig']
234
+ requestLocale?: string
235
+ }) {
236
+ const targetUrl = new URL(target, request.url)
237
+
238
+ const normalizedTarget = normalizeLocalePath(targetUrl.pathname, nextConfig?.i18n?.locales)
239
+
240
+ const locale = normalizedTarget.detectedLocale ?? requestLocale
241
+ if (
242
+ locale &&
243
+ !normalizedTarget.pathname.startsWith(`/api/`) &&
244
+ !normalizedTarget.pathname.startsWith(`/_next/static/`)
245
+ ) {
246
+ targetUrl.pathname = addBasePath(`/${locale}${normalizedTarget.pathname}`, nextConfig?.basePath)
247
+ } else {
248
+ targetUrl.pathname = addBasePath(normalizedTarget.pathname, nextConfig?.basePath)
249
+ }
250
+ return targetUrl.toString()
251
+ }
@@ -24,6 +24,13 @@ export const removeBasePath = (path: string, basePath?: string) => {
24
24
  return path
25
25
  }
26
26
 
27
+ export const addBasePath = (path: string, basePath?: string) => {
28
+ if (basePath && !path.startsWith(basePath)) {
29
+ return `${basePath}${path}`
30
+ }
31
+ return path
32
+ }
33
+
27
34
  // https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/i18n/normalize-locale-path.ts
28
35
 
29
36
  export interface PathLocale {
@@ -91,8 +98,11 @@ export function rewriteDataPath({
91
98
  }) {
92
99
  const normalizedDataUrl = normalizeDataUrl(removeBasePath(dataUrl, basePath))
93
100
 
94
- return dataUrl.replace(
95
- normalizeIndex(normalizedDataUrl),
96
- stripTrailingSlash(normalizeIndex(newRoute)),
101
+ return addBasePath(
102
+ dataUrl.replace(
103
+ normalizeIndex(normalizedDataUrl),
104
+ stripTrailingSlash(normalizeIndex(newRoute)),
105
+ ),
106
+ basePath,
97
107
  )
98
108
  }
@@ -59,6 +59,7 @@ export async function handleMiddleware(
59
59
  request,
60
60
  result,
61
61
  requestLocale: nextRequest.detectedLocale,
62
+ nextConfig,
62
63
  })
63
64
 
64
65
  return response
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netlify/plugin-nextjs",
3
- "version": "5.0.0-beta.5",
3
+ "version": "5.0.0-beta.7",
4
4
  "description": "Run Next.js seamlessly on Netlify",
5
5
  "main": "./dist/index.js",
6
6
  "type": "module",