diff --git a/src/js_parser/visit/visit_expr.rs b/src/js_parser/visit/visit_expr.rs index 61e97b7a79a0..c3cb1ed23bbe 100644 --- a/src/js_parser/visit/visit_expr.rs +++ b/src/js_parser/visit/visit_expr.rs @@ -2455,8 +2455,12 @@ 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" + // A store that `node_modules` links to has no `node_modules` folder in `text`. + if original_name == b"useState" + && !strings::starts_with(p.source.path.pretty, b"node_modules") + && !bun_paths::strings::path_contains_node_modules_folder( + p.source.path.text, + ) { p.log() .add_error( diff --git a/test/bake/dev/bundle.test.ts b/test/bake/dev/bundle.test.ts index 6e7e8359aa46..9a9cc81bcadd 100644 --- a/test/bake/dev/bundle.test.ts +++ b/test/bake/dev/bundle.test.ts @@ -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"] }), diff --git a/test/bake/dev/production.test.ts b/test/bake/dev/production.test.ts index 6771c0f96261..93a5fb96db59 100644 --- a/test/bake/dev/production.test.ts +++ b/test/bake/dev/production.test.ts @@ -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"; @@ -612,6 +612,133 @@ 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(); + + // 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.concurrent("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"; +};`, + // A store that node_modules links to under another name. + "apps/web/node_modules.nosync/linked-lib/package.json": libPackageJson("linked-lib"), + "apps/web/node_modules.nosync/linked-lib/index.js": libWithHook("linkedLabel"), + "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 { linkedLabel } from "linked-lib"; +import { nestedLabel } from "../packages/x"; +import Counter from "../components/Counter"; + +export default function IndexPage() { + return ( +
{"count=" + count}
; +}`, + "apps/web/package.json": JSON.stringify({ name: "web", version: "1.0.0" }), + }); + const appDir = path.join(dir, "apps", "web"); + symlinkSync( + path.join(dir, "node_modules", ".bun", "iso-lib@1.0.0", "node_modules", "iso-lib"), + path.join(dir, "node_modules", "iso-lib"), + "junction", + ); + symlinkSync(path.join(appDir, "node_modules.nosync"), path.join(appDir, "node_modules"), "junction"); + + const { exitCode, stderr } = await Bun.$`${bunExe()} build --app ./src/index.tsx` + .cwd(appDir) + .env(bunEnv) + .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( + "count=0
{"count=" + count}
; +}`, + "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")) + .env(bunEnv) + .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": `