Skip to content

Commit 50cb0d6

Browse files
wm0018steipete
andauthored
fix(ai): replace raw require(node:fs) with loadNodeBuiltinModule in getProcEnv (#102947)
* fix(ai): replace raw require(node:fs) with loadNodeBuiltinModule in getProcEnv * test(ai): cover browser-safe env key bundle --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent fe24862 commit 50cb0d6

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { fileURLToPath } from "node:url";
2+
import { build } from "esbuild";
3+
import { describe, expect, it } from "vitest";
4+
5+
describe("env API key browser bundle", () => {
6+
it("does not emit a static node:fs require", async () => {
7+
const result = await build({
8+
entryPoints: [fileURLToPath(new URL("./env-api-keys.ts", import.meta.url))],
9+
bundle: true,
10+
format: "esm",
11+
logLevel: "silent",
12+
platform: "browser",
13+
write: false,
14+
});
15+
16+
const output = result.outputFiles[0]?.text ?? "";
17+
expect(output).not.toMatch(/(?:__)?require\(\s*["']node:fs["']\s*\)/u);
18+
});
19+
});

packages/ai/src/env-api-keys.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,11 @@ function getProcEnv(key: string): string | undefined {
8989
if (procEnvCache === null) {
9090
procEnvCache = new Map();
9191
try {
92-
const { readFileSync } = require("node:fs") as typeof import("node:fs");
93-
const data = readFileSync("/proc/self/environ", "utf-8");
92+
const fsModule = loadNodeBuiltinModule(NODE_FS_SPECIFIER) as typeof import("node:fs") | null;
93+
if (!fsModule) {
94+
return undefined;
95+
}
96+
const data = fsModule.readFileSync("/proc/self/environ", "utf-8");
9497
for (const entry of data.split("\0")) {
9598
const idx = entry.indexOf("=");
9699
if (idx > 0) {

0 commit comments

Comments
 (0)