Skip to content

Commit 624d75a

Browse files
authored
refactor: patch getBuildId using ast-grep (#401)
1 parent 49a1377 commit 624d75a

File tree

8 files changed

+120
-16
lines changed

8 files changed

+120
-16
lines changed

packages/cloudflare/src/cli/build/bundle-server.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { build } from "esbuild";
99
import { patchVercelOgLibrary } from "./patches/ast/patch-vercel-og-library.js";
1010
import { patchWebpackRuntime } from "./patches/ast/webpack-runtime.js";
1111
import * as patches from "./patches/index.js";
12+
import { inlineBuildId } from "./patches/plugins/build-id.js";
1213
import { ContentUpdater } from "./patches/plugins/content-updater.js";
1314
import { inlineEvalManifest } from "./patches/plugins/eval-manifest.js";
1415
import { patchFetchCacheSetMissingWaitUntil } from "./patches/plugins/fetch-cache-wait-until.js";
@@ -95,6 +96,7 @@ export async function bundleServer(buildOpts: BuildOptions): Promise<void> {
9596
inlineEvalManifest(updater, buildOpts),
9697
inlineFindDir(updater, buildOpts),
9798
inlineLoadManifest(updater, buildOpts),
99+
inlineBuildId(updater),
98100
// Apply updater updaters, must be the last plugin
99101
updater.plugin,
100102
],
@@ -197,7 +199,6 @@ export async function updateWorkerBundledCode(
197199

198200
const patchedCode = await patchCodeWithValidations(code, [
199201
["require", patches.patchRequire],
200-
["`buildId` function", (code) => patches.patchBuildId(code, buildOpts)],
201202
["cacheHandler", (code) => patches.patchCache(code, buildOpts)],
202203
[
203204
"'require(this.middlewareManifestPath)'",
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
export * from "./investigated/index.js";
2-
export * from "./to-investigate/index.js";
2+
export * from "./to-investigate/inline-middleware-manifest.js";
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Inline `getBuildId` as it relies on `readFileSync` that is not supported by workerd.
3+
*/
4+
5+
import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";
6+
7+
import { patchCode } from "../ast/util.js";
8+
import type { ContentUpdater } from "./content-updater.js";
9+
10+
export function inlineBuildId(updater: ContentUpdater) {
11+
return updater.updateContent(
12+
"inline-build-id",
13+
{
14+
filter: getCrossPlatformPathRegex(String.raw`/next/dist/server/next-server\.js$`, { escape: false }),
15+
contentFilter: /getBuildId\(/,
16+
},
17+
async ({ contents }) => patchCode(contents, rule)
18+
);
19+
}
20+
21+
export const rule = `
22+
rule:
23+
kind: method_definition
24+
has:
25+
field: name
26+
regex: ^getBuildId$
27+
fix: |-
28+
getBuildId() {
29+
return process.env.NEXT_BUILD_ID;
30+
}
31+
`;
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { describe, expect, test } from "vitest";
2+
3+
import { patchCode } from "../ast/util.js";
4+
import { rule } from "./build-id.js";
5+
6+
describe("getBuildId", () => {
7+
test("patch", () => {
8+
const code = `
9+
class NextNodeServer extends _baseserver.default {
10+
constructor(options){
11+
// Initialize super class
12+
super(options);
13+
this.handleNextImageRequest = async (req, res, parsedUrl) => { /* ... */ };
14+
}
15+
async handleUpgrade() {
16+
// The web server does not support web sockets, it's only used for HMR in
17+
// development.
18+
}
19+
loadEnvConfig({ dev, forceReload, silent }) {
20+
(0, _env.loadEnvConfig)(this.dir, dev, silent ? {
21+
info: ()=>{},
22+
error: ()=>{}
23+
} : _log, forceReload);
24+
}
25+
async hasPage(pathname) {
26+
var _this_nextConfig_i18n;
27+
return !!(0, _require.getMaybePagePath)(pathname, this.distDir, (_this_nextConfig_i18n = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n.locales, this.enabledDirectories.app);
28+
}
29+
getBuildId() {
30+
const buildIdFile = (0, _path.join)(this.distDir, _constants.BUILD_ID_FILE);
31+
try {
32+
return _fs.default.readFileSync(buildIdFile, "utf8").trim();
33+
} catch (err) {
34+
if (err.code === "ENOENT") {
35+
throw new Error(\`Could not find a production build in the '\${this.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id\`);
36+
}
37+
throw err;
38+
}
39+
}
40+
getEnabledDirectories(dev) {
41+
const dir = dev ? this.dir : this.serverDistDir;
42+
return {
43+
app: (0, _findpagesdir.findDir)(dir, "app") ? true : false,
44+
pages: (0, _findpagesdir.findDir)(dir, "pages") ? true : false
45+
};
46+
}
47+
// ...
48+
}`;
49+
50+
expect(patchCode(code, rule)).toMatchInlineSnapshot(`
51+
"class NextNodeServer extends _baseserver.default {
52+
constructor(options){
53+
// Initialize super class
54+
super(options);
55+
this.handleNextImageRequest = async (req, res, parsedUrl) => { /* ... */ };
56+
}
57+
async handleUpgrade() {
58+
// The web server does not support web sockets, it's only used for HMR in
59+
// development.
60+
}
61+
loadEnvConfig({ dev, forceReload, silent }) {
62+
(0, _env.loadEnvConfig)(this.dir, dev, silent ? {
63+
info: ()=>{},
64+
error: ()=>{}
65+
} : _log, forceReload);
66+
}
67+
async hasPage(pathname) {
68+
var _this_nextConfig_i18n;
69+
return !!(0, _require.getMaybePagePath)(pathname, this.distDir, (_this_nextConfig_i18n = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n.locales, this.enabledDirectories.app);
70+
}
71+
getBuildId() {
72+
return process.env.NEXT_BUILD_ID;
73+
}
74+
getEnabledDirectories(dev) {
75+
const dir = dev ? this.dir : this.serverDistDir;
76+
return {
77+
app: (0, _findpagesdir.findDir)(dir, "app") ? true : false,
78+
pages: (0, _findpagesdir.findDir)(dir, "pages") ? true : false
79+
};
80+
}
81+
// ...
82+
}"
83+
`);
84+
});
85+
});

packages/cloudflare/src/cli/build/patches/plugins/load-manifest.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Inline `loadManifest` as it relies on `readFileSync`that is not supported by workerd.
2+
* Inline `loadManifest` as it relies on `readFileSync` that is not supported by workerd.
33
*/
44

55
import { readFile } from "node:fs/promises";

packages/cloudflare/src/cli/build/patches/to-investigate/index.ts

Lines changed: 0 additions & 2 deletions
This file was deleted.

packages/cloudflare/src/cli/build/patches/to-investigate/patch-read-file.ts

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)