Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions packages/open-next/src/build/patch/patches/patchEnvVar.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createPatchCode } from "../astCodePatcher.js";
import type { CodePatcher } from "../codePatcher";
import { createPatchCode, patchCode } from "../astCodePatcher.js";
import type { CodePatcher, PatchCodeFn } from "../codePatcher.js";

/**
* Creates a rule to replace `process.env.${envVar}` by `value` in the condition of if statements
Expand All @@ -21,6 +21,22 @@ fix:
'${value}'
`;

function isTurbopackBuild(tracedFiles: string[]): boolean {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be nice to extract this into an helper

  • so that it can be re-used across different files
  • and ultimately moved to Next.js

We use this check in the cloudflare adapter

const hasTurboRuntime = tracedFiles.some((file) =>
/-turbo[.-].*\.runtime\.(prod|dev)\.js$/.test(file),
);
const hasNonTurboRuntime = tracedFiles.some(
(file) =>
/\.runtime\.(prod|dev)\.js$/.test(file) && !/-turbo[.-]/.test(file),
);
return hasTurboRuntime && !hasNonTurboRuntime;
}

const createTurbopackPatch: PatchCodeFn = async ({ code, tracedFiles }) => {
const value = isTurbopackBuild(tracedFiles) ? "true" : "false";
return patchCode(code, envVarRuleCreator("TURBOPACK", value));
};

export const patchEnvVars: CodePatcher = {
name: "patch-env-vars",
patches: [
Expand All @@ -39,12 +55,12 @@ export const patchEnvVars: CodePatcher = {
contentFilter: /process\.env\.NODE_ENV/,
patchCode: createPatchCode(envVarRuleCreator("NODE_ENV", '"production"')),
},
// This patch will set `TURBOPACK` env to false to avoid loading turbopack related deps at runtime
// Turbopack builds only include *-turbo.runtime.prod.js files, so we detect and set accordingly
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I don't think we really care about how we detect a turbopack build in this comment?

Maybe revert to the inlined version of the code and remove the comment altogether when you add the helper?

{
versions: ">=15.0.0",
pathFilter: /module\.compiled\.js$/,
contentFilter: /process\.env\.TURBOPACK/,
patchCode: createPatchCode(envVarRuleCreator("TURBOPACK", "false")),
patchCode: createTurbopackPatch,
},
],
};
Loading