Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 4 additions & 2 deletions src/js_parser/visit/visit_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2455,8 +2455,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
break 'check_for_usestate false;
} {
debug_assert!(p.options.features.server_components.is_server_side());
if !strings::starts_with(p.source.path.pretty, b"node_modules")
&& original_name == b"useState"
if original_name == b"useState"
&& !bun_paths::strings::path_contains_node_modules_folder(
p.source.path.text,
)
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
{
p.log()
.add_error(
Expand Down
28 changes: 28 additions & 0 deletions test/bake/dev/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,34 @@ devTest("build error in a file imported by a 'use client' component", {
await dev.fetch("/").equals("object");
},
});
// The SSR graph bundles its own copy of what a client component imports. The parser reads only the
// local name `useState`, and this route does not render with React, so a stand-in for `react` is enough.
devTest("useState in a package is not a build error in the server graph or in the SSR graph", {
framework: { ...minimalFramework, serverComponents: separateSSRGraph },
files: {
"node_modules/react/index.js": `export const useState = initial => [initial, () => {}];`,
"node_modules/some-lib/index.js": `
import { useState } from "react";
export const useCounter = () => useState(0);
export const label = () => "some-lib";
`,
"Counter.ts": `
"use client";
import { useCounter } from "some-lib";
export const Counter = () => "count=" + useCounter()[0];
`,
"routes/index.ts": `
import { label } from "some-lib";
import { Counter } from "../Counter" with { bunBakeGraph: "ssr" };
export default function () {
return new Response(label() + " " + Counter());
}
`,
},
async test(dev) {
await dev.fetch("/").equals("some-lib count=0");
},
});
devTest("deinit with a free-list slot in DirectoryWatchStore.dependencies", {
files: {
"index.html": emptyHtmlFile({ scripts: ["index.ts"] }),
Expand Down
170 changes: 169 additions & 1 deletion test/bake/dev/production.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { existsSync } from "fs";
import { existsSync, symlinkSync } from "fs";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";
import path from "path";
import { minimalFramework, tempDirWithBakeDeps } from "../bake-harness";
Expand Down Expand Up @@ -612,6 +612,174 @@ export default function IndexPage() {
expect(exitCode).toBe(1);
});

// The files that get the server-component `useState` error, relative to `root`.
const filesWithUseStateError = (stderr: string, root: string) =>
Array.from(stderr.matchAll(/"useState" is not available in a server component.*\n\s+at (.+):\d+:\d+/g), match =>
normalizePath(path.relative(root, match[1])),
).sort();

test("importing useState server-side from a project path that holds the letters node_modules", async () => {
Comment thread
robobun marked this conversation as resolved.
Resolved
const widget = `import { useState } from 'react';

export default function Widget() {
const [count] = useState(0);
return <button>{count}</button>;
}`;
const dir = await tempDirWithBakeDeps("bake-production-node-modules-letters", {
"src/index.tsx": `export default { app: { framework: "react" } };`,
"pages/index.tsx": `import Tools from "../node_modules-tools/Widget";
import Local from "../node_modules_local/Widget";
import RootFile from "../node_modules_widget";
import Old from "../old_node_modules/Widget";

export default function IndexPage() {
return (
<div>
<Tools />
<Local />
<RootFile />
<Old />
</div>
);
}`,
"node_modules-tools/Widget.tsx": widget,
"node_modules_local/Widget.tsx": widget,
"node_modules_widget.tsx": widget,
"old_node_modules/Widget.tsx": widget,
"package.json": JSON.stringify({
"name": "test-app",
"version": "1.0.0",
"devDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
},
}),
});

const { exitCode, stderr } = await Bun.$`${bunExe()} build --app ./src/index.tsx`.cwd(dir).throws(false);
Comment thread
robobun marked this conversation as resolved.
Resolved

expect({ useStateErrors: filesWithUseStateError(stderr.toString(), dir), exitCode }).toEqual({
useStateErrors: [
"node_modules-tools/Widget.tsx",
"node_modules_local/Widget.tsx",
"node_modules_widget.tsx",
"old_node_modules/Widget.tsx",
],
exitCode: 1,
});
});

// A package module with a hook that calls `useState` and an export that uses no hook.
const libWithHook = (label: string) => `import { useState } from 'react';

export function useCounter() {
return useState(0);
}

export function ${label}() {
return ${JSON.stringify(label)};
}`;
const libPackageJson = (name: string) => JSON.stringify({ name, version: "1.0.0", type: "module", main: "index.js" });

test("useState in a package is not a server-component error, wherever node_modules is", async () => {
// The app is in apps/web. React and most of the packages are in the node_modules folder two levels above it.
const dir = await tempDirWithBakeDeps("bake-production-package-useState", {
"node_modules/hoisted-lib/package.json": libPackageJson("hoisted-lib"),
"node_modules/hoisted-lib/index.js": libWithHook("hoistedLabel"),
// A file directly inside node_modules.
"node_modules/loose-lib.js": libWithHook("looseLabel"),
// The store of the isolated linker. node_modules/iso-lib is a link to it.
"node_modules/.bun/iso-lib@1.0.0/node_modules/iso-lib/package.json": libPackageJson("iso-lib"),
"node_modules/.bun/iso-lib@1.0.0/node_modules/iso-lib/index.js": libWithHook("isoLabel"),
"node_modules/cjs-lib/package.json": JSON.stringify({ name: "cjs-lib", version: "1.0.0", main: "index.js" }),
"node_modules/cjs-lib/index.js": `const React = require("react");

exports.useCounter = function useCounter() {
return React.useState(0);
};

exports.cjsLabel = function cjsLabel() {
return "cjsLabel";
};`,
"apps/web/packages/x/node_modules/nested-lib/package.json": libPackageJson("nested-lib"),
"apps/web/packages/x/node_modules/nested-lib/index.js": libWithHook("nestedLabel"),
"apps/web/packages/x/index.ts": `export { nestedLabel } from "nested-lib";`,
"apps/web/src/index.tsx": `export default { app: { framework: "react" } };`,
"apps/web/pages/index.tsx": `import { hoistedLabel } from "hoisted-lib";
import { looseLabel } from "loose-lib.js";
import { isoLabel } from "iso-lib";
import { cjsLabel } from "cjs-lib";
import { nestedLabel } from "../packages/x";
import Counter from "../components/Counter";

export default function IndexPage() {
return (
<ul>
<li>{hoistedLabel()}</li>
<li>{looseLabel()}</li>
<li>{isoLabel()}</li>
<li>{cjsLabel()}</li>
<li>{nestedLabel()}</li>
<li>
<Counter />
</li>
</ul>
);
}`,
"apps/web/components/Counter.tsx": `"use client";
import { useCounter } from "hoisted-lib";

export default function Counter() {
const [count] = useCounter();
return <p>{"count=" + count}</p>;
}`,
"apps/web/package.json": JSON.stringify({ name: "web", version: "1.0.0" }),
});
symlinkSync(
path.join(dir, "node_modules", ".bun", "iso-lib@1.0.0", "node_modules", "iso-lib"),
path.join(dir, "node_modules", "iso-lib"),
"junction",
);
const appDir = path.join(dir, "apps", "web");

const { exitCode, stderr } = await Bun.$`${bunExe()} build --app ./src/index.tsx`.cwd(appDir).throws(false);

expect({ useStateErrors: filesWithUseStateError(stderr.toString(), dir), exitCode }).toEqual({
useStateErrors: [],
exitCode: 0,
});
// The server component calls the exports that use no hook. The client component calls the hook.
expect(await Bun.file(path.join(appDir, "dist", "index.html")).text()).toContain(
"<ul><li>hoistedLabel</li><li>looseLabel</li><li>isoLabel</li><li>cjsLabel</li><li>nestedLabel</li><li><p>count=0</p></li></ul>",
);
});

test("useState that a package calls in a server component fails the build when the page renders", async () => {
const dir = await tempDirWithBakeDeps("bake-production-package-useState-called", {
"node_modules/hoisted-lib/package.json": libPackageJson("hoisted-lib"),
"node_modules/hoisted-lib/index.js": libWithHook("hoistedLabel"),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"apps/web/src/index.tsx": `export default { app: { framework: "react" } };`,
"apps/web/pages/index.tsx": `import { useCounter } from "hoisted-lib";

export default function IndexPage() {
const [count] = useCounter();
return <p>{"count=" + count}</p>;
}`,
"apps/web/package.json": JSON.stringify({ name: "web", version: "1.0.0" }),
});

const { exitCode, stderr } = await Bun.$`${bunExe()} build --app ./src/index.tsx`
.cwd(path.join(dir, "apps", "web"))
.throws(false);

expect({ useStateErrors: filesWithUseStateError(stderr.toString(), dir), exitCode }).toEqual({
useStateErrors: [],
exitCode: 1,
});
// The stack frame of the call that failed.
expect(normalizePath(stderr.toString())).toContain("node_modules/hoisted-lib/index.js:4:10)");
});

test("importing useState from client component", async () => {
const dir = await tempDirWithBakeDeps("bake-production-client-useState", {
"src/index.tsx": `
Expand Down
Loading