-
Notifications
You must be signed in to change notification settings - Fork 126
/
edge.ts
201 lines (180 loc) · 6.18 KB
/
edge.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { readFileSync } from "node:fs";
import path from "node:path";
import type { Plugin } from "esbuild";
import type { MiddlewareInfo } from "types/next-types.js";
import {
loadAppPathsManifestKeys,
loadBuildId,
loadConfig,
loadConfigHeaders,
loadHtmlPages,
loadMiddlewareManifest,
loadPrerenderManifest,
loadRoutesManifest,
} from "../adapters/config/util.js";
export interface IPluginSettings {
nextDir: string;
edgeFunctionHandlerPath?: string;
middlewareInfo?: MiddlewareInfo;
isInCloudfare?: boolean;
}
/**
* @param opts.nextDir - The path to the .next directory
* @param opts.edgeFunctionHandlerPath - The path to the edgeFunctionHandler.js file that we'll use to bundle the routing
* @param opts.middlewareInfo - The entry files that we'll inject into the edgeFunctionHandler.js file
* @returns
*/
export function openNextEdgePlugins({
nextDir,
edgeFunctionHandlerPath,
middlewareInfo,
isInCloudfare,
}: IPluginSettings): Plugin {
const entryFiles =
middlewareInfo?.files.map((file: string) => path.join(nextDir, file)) ?? [];
const routes = middlewareInfo
? [
{
name: middlewareInfo.name || "/",
page: middlewareInfo.page,
regex: middlewareInfo.matchers.map((m) => m.regexp),
},
]
: [];
const wasmFiles = middlewareInfo?.wasm ?? [];
return {
name: "opennext-edge",
setup(build) {
if (edgeFunctionHandlerPath) {
// If we bundle the routing, we need to resolve the middleware
build.onResolve({ filter: /\.\/middleware.mjs/g }, () => {
return {
path: edgeFunctionHandlerPath,
};
});
}
build.onResolve({ filter: /\.(mjs|wasm)$/g }, () => {
return {
external: true,
};
});
//Copied from https://github.com/cloudflare/next-on-pages/blob/7a18efb5cab4d86c8e3e222fc94ea88ac05baffd/packages/next-on-pages/src/buildApplication/processVercelFunctions/build.ts#L86-L112
build.onResolve({ filter: /^node:/ }, ({ kind, path }) => {
// this plugin converts `require("node:*")` calls, those are the only ones that
// need updating (esm imports to "node:*" are totally valid), so here we tag with the
// node-buffer namespace only imports that are require calls
return kind === "require-call"
? { path, namespace: "node-built-in-modules" }
: undefined;
});
// we convert the imports we tagged with the node-built-in-modules namespace so that instead of `require("node:*")`
// they import from `export * from "node:*";`
build.onLoad(
{ filter: /.*/, namespace: "node-built-in-modules" },
({ path }) => {
return {
contents: `export * from '${path}'`,
loader: "js",
};
},
);
// We inject the entry files into the edgeFunctionHandler
build.onLoad({ filter: /\/edgeFunctionHandler.js/g }, async (args) => {
let contents = readFileSync(args.path, "utf-8");
contents = `
globalThis._ENTRIES = {};
globalThis.self = globalThis;
globalThis._ROUTES = ${JSON.stringify(routes)};
${
isInCloudfare
? ``
: `
import {readFileSync} from "node:fs";
import path from "node:path";
function addDuplexToInit(init) {
return typeof init === 'undefined' ||
(typeof init === 'object' && init.duplex === undefined)
? { duplex: 'half', ...init }
: init
}
// We need to override Request to add duplex to the init, it seems Next expects it to work like this
class OverrideRequest extends Request {
constructor(input, init) {
super(input, addDuplexToInit(init))
}
}
globalThis.Request = OverrideRequest;
// If we're not in cloudflare, we polyfill crypto
// https://github.com/vercel/edge-runtime/blob/main/packages/primitives/src/primitives/crypto.js
import { webcrypto } from 'node:crypto'
if(!globalThis.crypto){
globalThis.crypto = new webcrypto.Crypto()
}
if(!globalThis.CryptoKey){
globalThis.CryptoKey = webcrypto.CryptoKey
}
function SubtleCrypto() {
if (!(this instanceof SubtleCrypto)) return new SubtleCrypto()
throw TypeError('Illegal constructor')
}
if(!globalThis.SubtleCrypto) {
globalThis.SubtleCrypto = SubtleCrypto
}
if(!globalThis.Crypto) {
globalThis.Crypto = webcrypto.Crypto
}
// We also need to polyfill URLPattern
if (!globalThis.URLPattern) {
await import("urlpattern-polyfill");
}
`
}
${wasmFiles
.map((file) =>
isInCloudfare
? `import ${file.name} from './wasm/${file.name}.wasm';`
: `const ${file.name} = readFileSync(path.join(__dirname,'/wasm/${file.name}.wasm'));`,
)
.join("\n")}
${entryFiles.map((file) => `require("${file}");`).join("\n")}
${contents}
`;
return {
contents,
};
});
build.onLoad({ filter: /adapters\/config\/index/g }, async () => {
const NextConfig = loadConfig(nextDir);
const BuildId = loadBuildId(nextDir);
const HtmlPages = loadHtmlPages(nextDir);
const RoutesManifest = loadRoutesManifest(nextDir);
const ConfigHeaders = loadConfigHeaders(nextDir);
const PrerenderManifest = loadPrerenderManifest(nextDir);
const AppPathsManifestKeys = loadAppPathsManifestKeys(nextDir);
const MiddlewareManifest = loadMiddlewareManifest(nextDir);
const contents = `
import path from "path";
import { debug } from "../logger";
if(!globalThis.__dirname) {
globalThis.__dirname = ""
}
export const NEXT_DIR = path.join(__dirname, ".next");
export const OPEN_NEXT_DIR = path.join(__dirname, ".open-next");
debug({ NEXT_DIR, OPEN_NEXT_DIR });
export const NextConfig = ${JSON.stringify(NextConfig)};
export const BuildId = ${JSON.stringify(BuildId)};
export const HtmlPages = ${JSON.stringify(HtmlPages)};
export const RoutesManifest = ${JSON.stringify(RoutesManifest)};
export const ConfigHeaders = ${JSON.stringify(ConfigHeaders)};
export const PrerenderManifest = ${JSON.stringify(PrerenderManifest)};
export const AppPathsManifestKeys = ${JSON.stringify(AppPathsManifestKeys)};
export const MiddlewareManifest = ${JSON.stringify(MiddlewareManifest)};
process.env.NEXT_BUILD_ID = BuildId;
`;
return {
contents,
};
});
},
};
}