-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathpatch-read-file.ts
45 lines (42 loc) · 1.86 KB
/
patch-read-file.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
import { join, posix } from "node:path";
import { Config } from "../../../config";
import { globSync } from "glob";
import { normalizePath } from "../../utils";
import { readFileSync } from "node:fs";
export function patchReadFile(code: string, config: Config): string {
console.log("# patchReadFile");
// The next-server code gets the buildId from the filesystem, resulting in a `[unenv] fs.readFileSync is not implemented yet!` error
// so we add an early return to the `getBuildId` function so that the `readyFileSync` is never encountered
// (source: https://github.com/vercel/next.js/blob/15aeb92efb34c09a36/packages/next/src/server/next-server.ts#L438-L451)
// Note: we could/should probably just patch readFileSync here or something!
code = code.replace(
"getBuildId() {",
`getBuildId() {
return ${JSON.stringify(readFileSync(join(config.paths.output.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
`
);
// Same as above, the next-server code loads the manifests with `readFileSync` and we want to avoid that
// (source: https://github.com/vercel/next.js/blob/15aeb92e/packages/next/src/server/load-manifest.ts#L34-L56)
// Note: we could/should probably just patch readFileSync here or something!
const manifestJsons = globSync(
normalizePath(join(config.paths.output.standaloneAppDotNext, "**", "*-manifest.json"))
).map((file) =>
normalizePath(file).replace(normalizePath(config.paths.output.standaloneApp) + posix.sep, "")
);
code = code.replace(
/function loadManifest\((.+?), .+?\) {/,
`$&
${manifestJsons
.map(
(manifestJson) => `
if ($1.endsWith("${manifestJson}")) {
return ${readFileSync(join(config.paths.output.standaloneApp, manifestJson), "utf-8")};
}
`
)
.join("\n")}
throw new Error("Unknown loadManifest: " + $1);
`
);
return code;
}