Skip to content

Commit 96cf4b5

Browse files
committed
fix(next): Don't inject into the raw Next.js config
Turbopack's config validation loads the config with rawConfig, in which mode next returns the config module's namespace object rather than a resolved configuration. Assigning webpack to it threw, since a namespace object is not extensible, and every `next dev` reported ⨯ Unexpected error occurred while checking config TypeError: Cannot add property webpack, object is not extensible Recording was unaffected — next catches the exception — but it silently loses the validation, so the user no longer gets told about the config options Turbopack ignores. Worse, had the object been extensible we would have made next believe the user wrote a webpack config, which it refuses to combine with the default bundler. Skip the injection there. Skip it for any other non-extensible config as well: nothing can be injected into one, and throwing is worse than not instrumenting. The Next.js tests now assert that nothing was thrown out of the hook, which they can do incidentally: next reports it with an injectConfig frame in the stack, and they already collect the output. Assisted-by: Claude:claude-opus-5[1m]
1 parent 6a4f340 commit 96cf4b5

2 files changed

Lines changed: 42 additions & 9 deletions

File tree

‎src/hooks/next.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ interface NextConfig {
2020
webpack?: (config: WebpackConfiguration, context: WebpackContext) => WebpackConfiguration;
2121
}
2222

23+
// The third argument of next's loadConfig(phase, dir, opts).
24+
interface LoadConfigOptions {
25+
rawConfig?: boolean;
26+
}
27+
2328
import { call_, identifier, literal, member, ret } from "../generate";
2429
import { warn } from "../message";
2530

@@ -47,16 +52,36 @@ export function transform(program: ESTree.Program): ESTree.Program {
4752
};
4853
const thisFile = call_(identifier("require"), literal(__filename));
4954
const injectConfig = member(thisFile, "injectConfig");
50-
fun.body.body = [ret(call_(injectConfig, orig))];
55+
// Forward the arguments rather than the declared parameters, so that we
56+
// don't depend on how a given version of next happens to name them.
57+
fun.body.body = [ret(call_(injectConfig, orig, identifier("arguments")))];
5158
},
5259
});
5360
return program;
5461
}
5562

5663
const jsExtensions = ["tsx", "ts", "js", "cjs", "mjs", "jsx"];
5764

58-
export async function injectConfig(loadConfig: () => Promise<NextConfig>): Promise<NextConfig> {
65+
export async function injectConfig(
66+
loadConfig: () => Promise<NextConfig>,
67+
args?: IArguments,
68+
): Promise<NextConfig> {
5969
const result = await loadConfig();
70+
71+
// With rawConfig next asks for the config module's exports rather than the
72+
// resolved configuration, to validate what the user configured. That object
73+
// is a module namespace and hence not extensible, and injecting a webpack
74+
// config into it would in any case make next believe the user has one.
75+
const opts = args?.[2] as LoadConfigOptions | undefined;
76+
if (opts?.rawConfig) return result;
77+
78+
// Any other config we can't extend is unexpected. Don't throw, the caller
79+
// handles it poorly, but do say so: nothing would be instrumented otherwise.
80+
if (!Object.isExtensible(result)) {
81+
warn("The Next.js configuration cannot be modified, AppMap will not be injected into it.");
82+
return result;
83+
}
84+
6085
const loaderPath = resolve(__dirname, "../webpack.js");
6186

6287
// Webpack loader injection (Next.js with --webpack or older Next.js)

‎test/nextApp.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { detachOutput, getFreePort, readAppmaps, resolveTarget, spawnAppmapNode
1010
*/
1111
export default async function testNextApp() {
1212
const port = await getFreePort();
13-
const { app, waitForOutput } = await spawnNextJsApp(port);
13+
const { app, waitForOutput, errorOutput } = await spawnNextJsApp(port);
1414
const response = await makeRequest(port, "/hello");
1515
console.log("Response", response);
1616
const { pid } = JSON.parse(response) as { pid: number };
@@ -30,6 +30,10 @@ export default async function testNextApp() {
3030
await new Promise((r) => app.once("exit", r));
3131
detachOutput(app);
3232

33+
// next reports an exception thrown out of the config hooks with this frame in
34+
// the stack and then carries on regardless, so nothing else would notice.
35+
expect(errorOutput()).not.toContain("injectConfig");
36+
3337
const appMaps = readAppmaps();
3438
// Delete response body captures because they will be different in every run
3539
Object.values(appMaps).forEach(
@@ -53,30 +57,32 @@ async function spawnNextJsApp(port: number) {
5357
? spawnAppmapNode("node", nextBin, "dev", "-p", String(port))
5458
: spawnAppmapNode(nextBin, "dev", "-p", String(port));
5559

56-
const waitForOutput = watchOutput(app);
60+
const { waitForOutput, errorOutput } = watchOutput(app);
5761
await waitForOutput("Ready");
58-
return { app, waitForOutput };
62+
return { app, waitForOutput, errorOutput };
5963
}
6064

6165
/**
62-
* Watch the process' stdout, returning a function which waits for a fragment of
63-
* it to appear.
66+
* Watch the process' output, returning a function which waits for a fragment of
67+
* its stdout to appear, and one giving everything it has said on stderr.
6468
*
65-
* Matching is against everything seen so far rather than individual chunks:
69+
* Waiting matches against everything seen so far rather than individual chunks:
6670
* next dev interleaves spinner frames and escape sequences with its output, so
6771
* a message can both be split across chunk boundaries and have arrived before
6872
* we start waiting for it.
6973
*/
7074
function watchOutput(app: ChildProcessWithoutNullStreams, timeout = 30000) {
7175
let output = "";
76+
let errors = "";
7277
const waiters = new Set<() => void>();
7378

7479
app.stdout.on("data", (chunk: Buffer) => {
7580
output += chunk.toString();
7681
for (const check of waiters) check();
7782
});
83+
app.stderr.on("data", (chunk: Buffer) => (errors += chunk.toString()));
7884

79-
return (needle: string) =>
85+
const waitForOutput = (needle: string) =>
8086
new Promise<void>((resolve, reject) => {
8187
// Fail before the test times out, so that we get to say what we waited for.
8288
const timer = setTimeout(() => {
@@ -92,6 +98,8 @@ function watchOutput(app: ChildProcessWithoutNullStreams, timeout = 30000) {
9298
waiters.add(check);
9399
check();
94100
});
101+
102+
return { waitForOutput, errorOutput: () => errors };
95103
}
96104

97105
async function makeRequest(port: number, path: string, method = "GET") {

0 commit comments

Comments
 (0)