From 151c65aa696a160707990aa88cae7a3baa29f756 Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 04:06:09 +0530 Subject: [PATCH 1/9] feat(cli): reload Node dev stacks in process Replace the Node tsx watch process with an Oxc-backed import loader and dependency-aware chokidar watcher. Reload changed config module graphs in process on Node while retaining Bun's existing child-process behavior. --- packages/alchemy/bin/cli.js | 6 +- packages/alchemy/bin/register-dev-mode.js | 32 ++-- packages/alchemy/src/Alchemist/Session.ts | 16 +- packages/alchemy/src/Cli/commands/dev.ts | 17 +- packages/alchemy/src/Cli/exec.ts | 59 ++++++- packages/alchemy/src/Cli/main.ts | 2 +- .../alchemy/test/Cli/devKeepAlive.test.ts | 11 +- .../alchemy/test/Cli/registerDevMode.test.ts | 8 +- packages/node-utils/package.json | 21 ++- packages/node-utils/src/import-loader.ts | 53 ++++++ packages/node-utils/src/register-oxc.ts | 155 +++++++++++++++++ packages/node-utils/src/transform-source.ts | 130 +++++++++++++++ packages/node-utils/src/watch-import.ts | 157 ++++++++++++++++++ packages/node-utils/test/watch-import.test.ts | 127 ++++++++++++++ pnpm-lock.yaml | 7 + 15 files changed, 750 insertions(+), 51 deletions(-) create mode 100644 packages/node-utils/src/import-loader.ts create mode 100644 packages/node-utils/src/register-oxc.ts create mode 100644 packages/node-utils/src/transform-source.ts create mode 100644 packages/node-utils/src/watch-import.ts create mode 100644 packages/node-utils/test/watch-import.test.ts diff --git a/packages/alchemy/bin/cli.js b/packages/alchemy/bin/cli.js index b8a5f33792b..7612d265bfa 100755 --- a/packages/alchemy/bin/cli.js +++ b/packages/alchemy/bin/cli.js @@ -20,8 +20,8 @@ // exports point at .ts source), but consumers install into `node_modules/`, // so the path check sends them to the bundled `alchemy.js` regardless. // -// Own the spawn so bun's hard-coded watcher warning can be filtered while -// signals, IPC messages, and the child's exit status are forwarded. +// Own the spawn so runtime diagnostics can be filtered while signals, IPC +// messages, and the child's exit status are forwarded. import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; import { constants } from "node:os"; @@ -163,7 +163,7 @@ if (runtime === "bun" && isDev) { if (runtime === "node" && isDev && nodeRunsTypeScript) { // Run the checkout's source directly, no build required: the - // register-dev-mode hooks load .ts/.tsx through tsx's loader AND resolve + // register-dev-mode hooks load .ts/.tsx through Oxc AND resolve // the monorepo's own packages (`alchemy/*`, `@alchemy.run/*`, // `@distilled.cloud/*`) through their `bun` export condition onto src/ — // so the CLI, the user's stack, and every workspace dependency load one diff --git a/packages/alchemy/bin/register-dev-mode.js b/packages/alchemy/bin/register-dev-mode.js index 83f426eb199..3d3ecc78e46 100644 --- a/packages/alchemy/bin/register-dev-mode.js +++ b/packages/alchemy/bin/register-dev-mode.js @@ -11,19 +11,15 @@ // Packages without a `bun` condition (e.g. the published sigil) are // untouched — an enabled condition their exports never mention simply // doesn't match. -// 2. tsx's loader handles the actual `.ts`/`.tsx` loading — esbuild -// transforms with tsx's own on-disk cache and source maps. Node's -// built-in `--experimental-transform-types` covers plain `.ts` but not -// JSX, and its wasm stripper re-runs uncached on every `node --watch` -// restart (~7s for a full stack graph vs ~1s pre-built). +// 2. node-utils handles the actual `.ts`/`.tsx` loading with Rolldown's Oxc +// transformer and source maps. Node's built-in TypeScript support does not +// cover TSX and cannot apply each package's nearest tsconfig. // // Dev-only: the launcher (`bin/cli.js`) and the dev supervisor pass this // via `--import` when spawning node in a checkout. Published installs run -// bundled `.js` and never load it (it is excluded from the tarball, and -// tsx is a devDependency). +// bundled `.js` and never load it; this file is excluded from the tarball. +// In a checkout, the source loader resolves from the workspace package. import { registerHooks } from "node:module"; -import { fileURLToPath } from "node:url"; -import { register } from "tsx/esm/api"; /** @param {string} specifier */ const isMonorepoPackage = (specifier) => @@ -42,13 +38,11 @@ registerHooks({ }, }); -register({ - // Pin tsx to alchemy's tsconfig, not whatever happens to be in the - // invoking project's cwd (tsx resolves its tsconfig from the working - // directory). Running `alchemy dev` from an example would otherwise - // transpile alchemy's own .tsx with that project's JSX settings — e.g. - // classic-runtime `React.createElement` with no React import, or - // `jsxImportSource: "solid-js"` — breaking the React files inside the - // CLI. Same trade the bun launcher makes with `--tsconfig-override`. - tsconfig: fileURLToPath(new URL("../tsconfig.json", import.meta.url)), -}); +// This import must happen after the condition hook is installed so a clean +// checkout resolves node-utils to source without requiring a prior build. +const { registerOxc } = await import("@alchemy.run/node-utils/register-oxc"); + +// Oxc discovers the nearest tsconfig for each transformed file. Alchemy's +// TSX therefore uses Alchemy's React settings while the user's config and its +// dependencies retain their own compiler settings. +registerOxc(); diff --git a/packages/alchemy/src/Alchemist/Session.ts b/packages/alchemy/src/Alchemist/Session.ts index 8c6c28c29ff..f7bccf07641 100644 --- a/packages/alchemy/src/Alchemist/Session.ts +++ b/packages/alchemy/src/Alchemist/Session.ts @@ -55,6 +55,17 @@ export type StackModule = ReturnType> & { readonly state: Layer.Layer | undefined; }; +export interface StackModuleLoader { + readonly import: (url: string) => Promise<{ readonly default?: unknown }>; +} + +export const StackModuleLoader = Context.Reference( + "Alchemy/Alchemist/StackModuleLoader", + { + defaultValue: () => ({ import: (url) => import(url) }), + }, +); + export const importStack = Effect.fn(function* (main: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -66,8 +77,9 @@ export const importStack = Effect.fn(function* (main: string) { }), ); } - const module: { readonly default?: unknown } = yield* Effect.promise( - () => import(pathToFileURL(absolutePath).href), + const loader = yield* StackModuleLoader; + const module = yield* Effect.promise(() => + loader.import(pathToFileURL(absolutePath).href), ); if ( !Effect.isEffect(module.default) || diff --git a/packages/alchemy/src/Cli/commands/dev.ts b/packages/alchemy/src/Cli/commands/dev.ts index c52edaf71f3..01b4179804f 100644 --- a/packages/alchemy/src/Cli/commands/dev.ts +++ b/packages/alchemy/src/Cli/commands/dev.ts @@ -8,10 +8,7 @@ import * as ChildProcess from "effect/unstable/process/ChildProcess"; import { fileURLToPath } from "node:url"; import { SPAWNER_URL_ENV_KEY } from "../../Local/RpcProviderProxy.ts"; import * as RpcSpawner from "../../Local/RpcSpawner.ts"; -import { - isRegisterHooksSupported, - transformTypesFlags, -} from "../../Util/Node.ts"; +import { isRegisterHooksSupported } from "../../Util/Node.ts"; import { DevOptions } from "../DevOptions.ts"; import { configPath, @@ -62,7 +59,10 @@ export const devCommand = Command.make( process.env.NODE_EXTRA_CA_CERTS ??= Floci.FLOCI_CA_PATH; } const spawner = yield* RpcSpawner.RpcSpawner; - // We no longer force Bun in development because this prevents us from testing in Node. + // Bun keeps its native process watcher: each change replaces the exec + // process and therefore gets a fresh module cache. Node deliberately + // does not use `node --watch`; exec.ts keeps one process alive and + // reloads only the user's stack graph so Ctrl+C remains deterministic. const command = typeof globalThis.Bun !== "undefined" ? [ @@ -76,7 +76,7 @@ export const devCommand = Command.make( : import.meta.url.endsWith(".ts") && isRegisterHooksSupported() ? [ // Source checkout under node: run the .ts exec entry with - // the dev-mode hooks (tsx loader + src-condition + // the dev-mode hooks (Oxc loader + src-condition // resolution), so dev works without a build (mirrors // bin/cli.js's launcher path). `process.execPath`, not // "node": the hooks are gated on THIS node's version. A @@ -86,16 +86,11 @@ export const devCommand = Command.make( ...process.execArgv, "--import", import.meta.resolve("../../../bin/register-dev-mode.js"), - "--watch", - "--watch-preserve-output", fileURLToPath(import.meta.resolve("alchemy/bin/exec.ts")), ] : [ process.execPath, ...process.execArgv, - ...transformTypesFlags(), - "--watch", - "--watch-preserve-output", fileURLToPath(import.meta.resolve("alchemy/bin/exec.js")), ]; const child = yield* ChildProcess.make(command[0], command.slice(1), { diff --git a/packages/alchemy/src/Cli/exec.ts b/packages/alchemy/src/Cli/exec.ts index 2e9e94e9bcc..4c254704ba3 100644 --- a/packages/alchemy/src/Cli/exec.ts +++ b/packages/alchemy/src/Cli/exec.ts @@ -7,8 +7,12 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"; +import { watchImport } from "@alchemy.run/node-utils/watch-import"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; import { AlchemyContextLive } from "../AlchemyContext.ts"; +import { StackModuleLoader } from "../Alchemist/Session.ts"; import { ArtifactStore, createArtifactStore } from "../Artifacts.ts"; import { CredentialsStoreLive } from "../Auth/Credentials.ts"; import { ProfileStoreLive } from "../Auth/Profile.ts"; @@ -39,9 +43,9 @@ const services = Layer.mergeAll( Layer.succeed(ArtifactStore, createArtifactStore()), // Dev runs live in this exec child, not the `alchemy` CLI process, so // without this layer they'd export no telemetry at all. No root - // `cli.dev` span though: dev parks in Effect.never until the watcher - // kills the process, so a wrapping span would never end (and never - // export) — plan/apply spans are the trace roots instead. + // `cli.dev` span though: dev remains alive across reloads, so a wrapping + // span would not end (and export) until shutdown — plan/apply spans are the + // trace roots instead. TelemetryLive, ).pipe( Layer.provideMerge( @@ -101,6 +105,48 @@ const runDev = Effect.fn(function* (options: DevOptions) { return once ? undefined : yield* Effect.never; }); +const runNodeDevWatcher = (options: DevOptions) => { + const entrypoint = path.resolve(options.main); + const root = path.dirname(entrypoint); + const nodeModules = `${path.sep}node_modules${path.sep}`; + return Effect.acquireRelease( + Effect.sync(() => + watchImport<{ readonly default?: unknown }>(entrypoint, { + parentURL: import.meta.url, + shouldInvalidate: (url) => { + if (!url.startsWith("file:")) return false; + const file = fileURLToPath(url); + const relative = path.relative(root, file); + return ( + !file.includes(nodeModules) && + (relative === "" || + (!relative.startsWith("..") && !path.isAbsolute(relative))) + ); + }, + }), + ), + (watcher) => Effect.promise(() => watcher.close()), + ).pipe( + Effect.flatMap((watcher) => { + const changed = Effect.callback((resume) => { + const unsubscribe = watcher.subscribe(() => resume(Effect.void)); + return Effect.sync(unsubscribe); + }); + return Effect.forever( + Effect.raceFirst( + devKeepAlive(runDev(options)).pipe( + Effect.provideService(StackModuleLoader, { + import: () => watcher.import().then(({ value }) => value), + }), + Effect.scoped, + ), + changed, + ), + ); + }), + ); +}; + // A mid-edit import or planning failure must keep the watch process alive so // the next save can restart it. Interruptions still propagate for Ctrl+C. export const devKeepAlive = ( @@ -132,7 +178,12 @@ const makeExec = () => { yield* forwardSidecarLogs((entry) => devLog.writeLine(`[${entry.channel}] ${entry.line}`), ); - return yield* devKeepAlive(runDev(options)); + // Bun's outer `--watch` process owns reloads and starts this module with a + // fresh cache each time. Node stays in this process and refreshes only the + // stack module graph through the Oxc/chokidar watcher above. + return yield* (yield* devOnce) || process.versions.bun !== undefined + ? devKeepAlive(runDev(options)) + : runNodeDevWatcher(options); }).pipe(Effect.provide(services), Effect.scoped, handleCliErrors); }; diff --git a/packages/alchemy/src/Cli/main.ts b/packages/alchemy/src/Cli/main.ts index e6dfd5b83fc..ef296632537 100644 --- a/packages/alchemy/src/Cli/main.ts +++ b/packages/alchemy/src/Cli/main.ts @@ -143,7 +143,7 @@ const root = Command.make("alchemy", {}, () => * How this CLI process is running, appended to `--version` in a checkout * for debugging the launcher's implicit mode selection (`bin/cli.js`): the * runtime, and whether we're executing `.ts` source (bun, or node with type - * stripping + the register-tsx hook) or built output — `node , lib` is + * stripping + the Oxc register hook) or built output — `node , lib` is * the tell for the old-node fallback that still needs a build. Published * installs print the plain version string. */ diff --git a/packages/alchemy/test/Cli/devKeepAlive.test.ts b/packages/alchemy/test/Cli/devKeepAlive.test.ts index 1cdcf48ba35..71265071640 100644 --- a/packages/alchemy/test/Cli/devKeepAlive.test.ts +++ b/packages/alchemy/test/Cli/devKeepAlive.test.ts @@ -8,10 +8,9 @@ import { importStack } from "@/Alchemist/Session.ts"; import { devKeepAlive } from "../../src/Cli/exec"; import { PlatformServices } from "../../src/Util/PlatformServices"; -// `alchemy dev` runs under `--watch`: exiting the process on error cancels -// the watch session, so a run wrapped in `devKeepAlive` must park (stay -// alive for the watcher to restart) on ANY failure — typed error or defect — -// while success and interruption pass through untouched. +// Node's import-aware dev loop interrupts a parked run when a dependency +// changes; Bun's process watcher restarts it. In both cases a failed generation +// must park instead of exiting the watch session, while interruption propagates. /** Resolves `true` when the effect is still running (parked) after the timeout. */ const parks = (effect: Effect.Effect) => @@ -62,8 +61,8 @@ describe("devKeepAlive", () => { // The real-world crash: a mid-edit save makes the stack entrypoint throw at // module evaluation, so `importStack`'s dynamic import rejects (a defect). - // Before the guard this crashed the exec process and killed the watch - // session; wrapped in `devKeepAlive` it must park until the next save. + // Wrapped in `devKeepAlive`, it must park until the import watcher observes + // the next save and interrupts this generation. test("a stack module that throws at evaluation parks instead of crashing", () => expect( parks( diff --git a/packages/alchemy/test/Cli/registerDevMode.test.ts b/packages/alchemy/test/Cli/registerDevMode.test.ts index 5c5b69dc9e7..f6f379524d1 100644 --- a/packages/alchemy/test/Cli/registerDevMode.test.ts +++ b/packages/alchemy/test/Cli/registerDevMode.test.ts @@ -13,10 +13,10 @@ import { nodePath, nodeSupportsDevMode } from "../nodeProbe.ts"; // process across two copies of the package — while leaving packages // without a `bun` condition (published sigil) on their built output, and // (2) transpile `.tsx` with ALCHEMY'S tsconfig (react-jsx) regardless of -// the invoking project: the child's cwd is an example on purpose — tsx -// resolves its tsconfig from the working directory, and an unpinned -// lookup transpiled the CLI's React files with the example's JSX settings -// ("ReferenceError: React is not defined" from classic-runtime output). +// the invoking project: the child's cwd is an example on purpose. Oxc resolves +// the nearest tsconfig per source file, so the CLI's React files cannot inherit +// the example's JSX settings (which previously produced classic-runtime output +// and "ReferenceError: React is not defined"). it.live.skipIf(!nodeSupportsDevMode)( "dev-mode hooks resolve monorepo packages to src and transpile tsx", () => diff --git a/packages/node-utils/package.json b/packages/node-utils/package.json index 9e6d4bcc968..abdc7a9e766 100644 --- a/packages/node-utils/package.json +++ b/packages/node-utils/package.json @@ -1,7 +1,7 @@ { "name": "@alchemy.run/node-utils", "version": "2.0.0-beta.76", - "description": "Gitignore-compatible path matching for Alchemy packages.", + "description": "Runtime utilities for Alchemy packages.", "homepage": "https://alchemy.run", "author": "Sam Goodwin ", "keywords": [ @@ -37,8 +37,27 @@ "types": "./lib/ignore.d.ts", "bun": "./src/ignore.ts", "import": "./lib/ignore.js" + }, + "./import-loader": { + "types": "./lib/import-loader.d.ts", + "bun": "./src/import-loader.ts", + "import": "./lib/import-loader.js" + }, + "./register-oxc": { + "types": "./lib/register-oxc.d.ts", + "bun": "./src/register-oxc.ts", + "import": "./lib/register-oxc.js" + }, + "./watch-import": { + "types": "./lib/watch-import.d.ts", + "bun": "./src/watch-import.ts", + "import": "./lib/watch-import.js" } }, + "dependencies": { + "chokidar": "^5.0.0", + "rolldown": "catalog:build" + }, "publishConfig": { "access": "public" }, diff --git a/packages/node-utils/src/import-loader.ts b/packages/node-utils/src/import-loader.ts new file mode 100644 index 00000000000..7453b43e779 --- /dev/null +++ b/packages/node-utils/src/import-loader.ts @@ -0,0 +1,53 @@ +import type { TransformOptions } from "rolldown/utils"; + +export interface TransformContext { + readonly url: string; + readonly path: string; + readonly format: "module" | "commonjs"; +} + +export interface SourceTransformResult { + readonly code: string; + readonly map?: string | object | undefined; +} + +export type SourceTransform = ( + code: string, + context: TransformContext, +) => string | SourceTransformResult | undefined; + +export interface ImportLoaderOptions { + /** Oxc transform configuration. */ + readonly transform?: TransformOptions | undefined; + /** Additional synchronous source transforms, applied after Oxc. */ + readonly transforms?: ReadonlyArray | undefined; + /** Controls which file URLs belong to the fresh import graph. */ + readonly shouldInvalidate?: + | ((url: string, parentURL: string | undefined) => boolean) + | undefined; +} + +export interface ImportLoaderRegistrationOptions extends ImportLoaderOptions { + /** Isolates one import graph in the runtime's module cache. */ + readonly namespace?: string | undefined; + /** Called once the runtime loads a file in this registration's graph. */ + readonly onImport?: ((url: string) => void) | undefined; +} + +export interface ImportLoader { + import(specifier: string, parentURL: string): Promise; + unregister(): void | Promise; +} + +/** Creates a Node import loader using synchronous module hooks backed by Oxc. */ +export const createImportLoader = async ( + options: ImportLoaderRegistrationOptions = {}, +): Promise => { + if (process.versions.bun !== undefined) { + throw new Error( + "The import-aware loader is only available in Node; use Bun's process-level watcher instead.", + ); + } + const { registerOxc } = await import("./register-oxc.ts"); + return registerOxc(options); +}; diff --git a/packages/node-utils/src/register-oxc.ts b/packages/node-utils/src/register-oxc.ts new file mode 100644 index 00000000000..19b2a8204d1 --- /dev/null +++ b/packages/node-utils/src/register-oxc.ts @@ -0,0 +1,155 @@ +import { + registerHooks, + type LoadFnOutput, + type ResolveFnOutput, + type ResolveHookContext, +} from "node:module"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import type { + ImportLoader, + ImportLoaderRegistrationOptions, +} from "./import-loader.ts"; +import { SourceTransformer, typeScriptSpecifier } from "./transform-source.ts"; + +export type { + ImportLoader as RegisteredOxcImporter, + ImportLoaderRegistrationOptions as RegisterOxcOptions, + SourceTransform, + SourceTransformResult, + TransformContext, +} from "./import-loader.ts"; + +const protocol = "alchemy-import:"; +const namespaceParameter = "alchemy-import-namespace"; + +interface ImportRequest { + readonly namespace?: string | undefined; + readonly parentURL: string; + readonly specifier: string; +} + +const namespaceOf = (url: string | undefined) => { + if (url === undefined || !url.startsWith("file:")) return undefined; + return new URL(url).searchParams.get(namespaceParameter) ?? undefined; +}; + +const withoutNamespace = (url: string) => { + if (!url.startsWith("file:")) return url; + const parsed = new URL(url); + parsed.searchParams.delete(namespaceParameter); + return parsed.href; +}; + +const withNamespace = (url: string, namespace: string) => { + const parsed = new URL(url); + parsed.searchParams.set(namespaceParameter, namespace); + return parsed.href; +}; + +const parseRequest = (specifier: string): ImportRequest | undefined => { + if (!specifier.startsWith(protocol)) return undefined; + return JSON.parse(decodeURIComponent(specifier.slice(protocol.length))); +}; + +const resolve = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, +): ResolveFnOutput => { + try { + return nextResolve(specifier, context); + } catch (error) { + const alternative = typeScriptSpecifier(specifier); + if (alternative === undefined) throw error; + try { + return nextResolve(alternative, context); + } catch { + throw error; + } + } +}; + +/** + * Registers synchronous Node module hooks that transpile TypeScript with + * Rolldown's Oxc transformer. A namespaced registration also provides a + * scoped import whose namespace propagates through the complete ESM graph. + */ +export const registerOxc = ( + options: ImportLoaderRegistrationOptions = {}, +): ImportLoader => { + const transformer = new SourceTransformer(options); + const shouldInvalidate = options.shouldInvalidate ?? (() => true); + const hooks = registerHooks({ + resolve(specifier, context, nextResolve) { + const request = parseRequest(specifier); + const inheritedNamespace = namespaceOf(context.parentURL); + const namespace = + options.namespace === undefined + ? undefined + : (request?.namespace ?? inheritedNamespace); + + if (options.namespace !== undefined && namespace !== options.namespace) { + return nextResolve(specifier, context); + } + + const resolved = request + ? resolve( + request.specifier, + { ...context, parentURL: request.parentURL }, + nextResolve, + ) + : resolve(specifier, context, nextResolve); + if ( + namespace !== undefined && + resolved.url.startsWith("file:") && + shouldInvalidate( + withoutNamespace(resolved.url), + context.parentURL === undefined + ? undefined + : withoutNamespace(context.parentURL), + ) + ) { + return { ...resolved, url: withNamespace(resolved.url, namespace) }; + } + return resolved; + }, + load(url, context, nextLoad): LoadFnOutput { + const namespace = namespaceOf(url); + if (options.namespace !== undefined && namespace !== options.namespace) { + return nextLoad(url, context); + } + + const cleanUrl = withoutNamespace(url); + if (!cleanUrl.startsWith("file:")) return nextLoad(cleanUrl, context); + options.onImport?.(cleanUrl); + + const transformed = transformer.transform( + fileURLToPath(cleanUrl), + cleanUrl, + ); + if (transformed === undefined) return nextLoad(cleanUrl, context); + return { ...transformed, shortCircuit: true }; + }, + }); + + return { + import(specifier: string, parentURL: string) { + const request: ImportRequest = { + namespace: options.namespace, + parentURL: parentURL.startsWith("file:") + ? parentURL + : pathToFileURL(parentURL).href, + specifier, + }; + return import( + `${protocol}${encodeURIComponent(JSON.stringify(request))}` + ) as Promise; + }, + unregister() { + hooks.deregister(); + }, + }; +}; diff --git a/packages/node-utils/src/transform-source.ts b/packages/node-utils/src/transform-source.ts new file mode 100644 index 00000000000..e167192969d --- /dev/null +++ b/packages/node-utils/src/transform-source.ts @@ -0,0 +1,130 @@ +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { + transformSync, + TsconfigCache, + type TransformOptions, +} from "rolldown/utils"; +import type { ImportLoaderOptions, TransformContext } from "./import-loader.ts"; + +export const transformExtensions = new Set([".ts", ".tsx", ".mts", ".cts"]); + +export const typeScriptSpecifier = (specifier: string): string | undefined => { + const metadataIndex = specifier.search(/[?#]/); + const path = + metadataIndex === -1 ? specifier : specifier.slice(0, metadataIndex); + const metadata = metadataIndex === -1 ? "" : specifier.slice(metadataIndex); + if (path.endsWith(".js")) return `${path.slice(0, -3)}.ts${metadata}`; + if (path.endsWith(".jsx")) return `${path.slice(0, -4)}.tsx${metadata}`; + if (path.endsWith(".mjs")) return `${path.slice(0, -4)}.mts${metadata}`; + if (path.endsWith(".cjs")) return `${path.slice(0, -4)}.cts${metadata}`; + return undefined; +}; + +const moduleFormat = (filePath: string): "module" | "commonjs" => { + const extension = path.extname(filePath); + if ( + extension === ".ts" || + extension === ".tsx" || + extension === ".mts" || + extension === ".mjs" + ) { + return "module"; + } + if (extension === ".cts" || extension === ".cjs") return "commonjs"; + let directory = path.dirname(filePath); + while (true) { + const packageJson = path.join(directory, "package.json"); + if (existsSync(packageJson)) { + try { + return JSON.parse(readFileSync(packageJson, "utf8")).type === "module" + ? "module" + : "commonjs"; + } catch { + return "commonjs"; + } + } + const parent = path.dirname(directory); + if (parent === directory) return "commonjs"; + directory = parent; + } +}; + +const language = (filePath: string): TransformOptions["lang"] => { + switch (path.extname(filePath)) { + case ".tsx": + return "tsx"; + case ".ts": + case ".mts": + case ".cts": + return "ts"; + case ".jsx": + return "jsx"; + default: + return "js"; + } +}; + +const sourceMapComment = (map: string | object) => { + const json = typeof map === "string" ? map : JSON.stringify(map); + return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(json).toString("base64")}`; +}; + +export class SourceTransformer { + readonly #options: ImportLoaderOptions; + readonly #tsconfigCache = new TsconfigCache(); + + constructor(options: ImportLoaderOptions) { + this.#options = options; + } + + transform( + filePath: string, + url: string, + ): + | { readonly format: "module" | "commonjs"; readonly source: string } + | undefined { + const extension = path.extname(filePath); + if ( + !transformExtensions.has(extension) && + this.#options.transforms === undefined + ) { + return undefined; + } + + const format = moduleFormat(filePath); + let source = readFileSync(filePath, "utf8"); + let map: string | object | undefined; + if (transformExtensions.has(extension)) { + const transformed = transformSync( + filePath, + source, + { + tsconfig: true, + sourcemap: true, + ...this.#options.transform, + lang: this.#options.transform?.lang ?? language(filePath), + sourceType: this.#options.transform?.sourceType ?? format, + }, + this.#tsconfigCache, + ); + if (transformed.errors.length > 0) throw transformed.errors[0]; + source = transformed.code; + map = transformed.map; + } + + const context: TransformContext = { url, path: filePath, format }; + for (const transform of this.#options.transforms ?? []) { + const result = transform(source, context); + if (typeof result === "string") { + source = result; + map = undefined; + } else if (result !== undefined) { + source = result.code; + map = result.map; + } + } + if (map !== undefined) source += sourceMapComment(map); + return { format, source }; + } +} diff --git a/packages/node-utils/src/watch-import.ts b/packages/node-utils/src/watch-import.ts new file mode 100644 index 00000000000..863b21e6829 --- /dev/null +++ b/packages/node-utils/src/watch-import.ts @@ -0,0 +1,157 @@ +import { randomUUID } from "node:crypto"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { watch, type ChokidarOptions, type FSWatcher } from "chokidar"; +import { + createImportLoader, + type ImportLoader, + type ImportLoaderOptions, +} from "./import-loader.ts"; + +export interface ImportGeneration { + readonly value: T; + readonly namespace: string; + readonly dependencies: ReadonlySet; +} + +export interface ImportChange { + readonly paths: ReadonlySet; +} + +export interface ImportWatcherOptions extends ImportLoaderOptions { + readonly parentURL: string; + /** Chokidar options passed to the dependency watcher. */ + readonly watch?: ChokidarOptions | undefined; + readonly debounceMs?: number | undefined; +} + +export type ImportChangeListener = (change: ImportChange) => void; + +/** + * Imports fresh Node module generations and watches the exact files loaded by + * the current generation. Chokidar follows editor atomic-save replacements + * without polling by default. Bun callers should use Bun's process watcher, + * which naturally starts each generation with a fresh module cache. + */ +export class ImportWatcher { + readonly #specifier: string; + readonly #options: ImportWatcherOptions; + readonly #listeners = new Set(); + readonly #watcher: FSWatcher; + #registration: ImportLoader | undefined; + #dependencies = new Set(); + #pending = new Set(); + #timer: NodeJS.Timeout | undefined; + #closed = false; + + constructor(specifier: string, options: ImportWatcherOptions) { + this.#specifier = specifier; + this.#options = options; + this.#watcher = watch([], { + ...options.watch, + ignoreInitial: true, + }); + this.#watcher.on("all", (_event, changed) => { + const absolute = path.resolve( + options.watch?.cwd ?? process.cwd(), + changed, + ); + if (this.#dependencies.has(absolute)) this.#queue(absolute); + }); + } + + get dependencies(): ReadonlySet { + return this.#dependencies; + } + + subscribe(listener: ImportChangeListener): () => void { + this.#listeners.add(listener); + return () => this.#listeners.delete(listener); + } + + async import(): Promise> { + if (this.#closed) throw new Error("ImportWatcher is closed"); + const namespace = randomUUID(); + const dependencies = new Set(); + const { + debounceMs: _, + parentURL, + watch: _watch, + ...registerOptions + } = this.#options; + const registration = await createImportLoader({ + ...registerOptions, + namespace, + onImport: (url) => { + if (!url.startsWith("file:")) return; + dependencies.add(fileURLToPath(url)); + if (this.#dependencies === dependencies) this.#syncWatchers(); + }, + }); + try { + const value = await registration.import(this.#specifier, parentURL); + await this.#registration?.unregister(); + this.#registration = registration; + this.#dependencies = dependencies; + this.#syncWatchers(); + return { value, namespace, dependencies }; + } catch (error) { + await registration.unregister(); + this.#dependencies = new Set([...this.#dependencies, ...dependencies]); + this.#syncWatchers(); + throw error; + } + } + + async close(): Promise { + if (this.#closed) return; + this.#closed = true; + if (this.#timer !== undefined) clearTimeout(this.#timer); + await this.#registration?.unregister(); + await this.#watcher.close(); + this.#listeners.clear(); + } + + async [Symbol.asyncDispose](): Promise { + await this.close(); + } + + #syncWatchers(): void { + const previous = this.#watcher.getWatched(); + const watched = new Set( + Object.entries(previous).flatMap(([directory, files]) => + files.map((file) => + path.resolve( + this.#options.watch?.cwd ?? process.cwd(), + directory, + file, + ), + ), + ), + ); + const removed = [...watched].filter( + (dependency) => !this.#dependencies.has(dependency), + ); + const added = [...this.#dependencies].filter( + (dependency) => !watched.has(dependency), + ); + if (removed.length > 0) void this.#watcher.unwatch(removed); + if (added.length > 0) this.#watcher.add(added); + } + + #queue(changed: string): void { + this.#pending.add(changed); + if (this.#timer !== undefined) clearTimeout(this.#timer); + this.#timer = setTimeout(() => { + this.#timer = undefined; + const paths = this.#pending; + this.#pending = new Set(); + for (const listener of this.#listeners) listener({ paths }); + }, this.#options.debounceMs ?? 50); + } +} + +export const watchImport = ( + specifier: string, + options: ImportWatcherOptions, +) => new ImportWatcher(specifier, options); diff --git a/packages/node-utils/test/watch-import.test.ts b/packages/node-utils/test/watch-import.test.ts new file mode 100644 index 00000000000..559f9bd87f2 --- /dev/null +++ b/packages/node-utils/test/watch-import.test.ts @@ -0,0 +1,127 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const temporaryDirectories: string[] = []; + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { force: true, recursive: true }); + } +}); + +describe("watchImport", () => { + it("transforms TypeScript, tracks dependencies, and reloads the whole graph", () => { + const temporaryDirectory = realpathSync( + mkdtempSync(path.join(os.tmpdir(), "alchemy-import-")), + ); + temporaryDirectories.push(temporaryDirectory); + const directory = path.join(temporaryDirectory, "project"); + mkdirSync(directory); + writeFileSync( + path.join(directory, "entry.ts"), + [ + 'import { count, text } from "./dependency.js";', + 'import { externalCount } from "../external.js";', + "interface Result { count: number; externalCount: number; text: string }", + "export const result: Result = { count, externalCount, text };", + ].join("\n"), + ); + writeFileSync( + path.join(directory, "dependency.ts"), + [ + "const state = globalThis as typeof globalThis & { calls?: number };", + "export const count = state.calls = (state.calls ?? 0) + 1;", + 'export const text: string = "__VALUE__";', + ].join("\n"), + ); + const external = path.join(temporaryDirectory, "external.ts"); + writeFileSync( + external, + [ + "const state = globalThis as typeof globalThis & { externalCalls?: number };", + "export const externalCount = state.externalCalls = (state.externalCalls ?? 0) + 1;", + ].join("\n"), + ); + + const moduleUrl = pathToFileURL( + path.resolve(import.meta.dir, "../src/watch-import.ts"), + ).href; + const registerUrl = pathToFileURL( + path.resolve(import.meta.dir, "../src/register-oxc.ts"), + ).href; + const script = ` + import { writeFile } from "node:fs/promises"; + import { fileURLToPath, pathToFileURL } from "node:url"; + import { watchImport } from ${JSON.stringify(moduleUrl)}; + const { registerOxc } = await import(${JSON.stringify(registerUrl)}); + registerOxc(); + + const directory = process.argv[1]; + const dependency = directory + "/dependency.ts"; + const external = fileURLToPath(new URL("../external.ts", pathToFileURL(directory + "/"))); + const watcher = watchImport("./entry.ts", { + parentURL: pathToFileURL(directory + "/runner.mjs").href, + debounceMs: 10, + shouldInvalidate: url => + url.startsWith("file:") && fileURLToPath(url).startsWith(directory + "/"), + transforms: [source => source.replaceAll("__VALUE__", "transformed")], + }); + const first = await watcher.import(); + if (first.value.result.count !== 1) throw new Error("first graph was not evaluated"); + if (first.value.result.externalCount !== 1) throw new Error("external module was not evaluated"); + if (first.value.result.text !== "transformed") throw new Error("custom transform was not applied"); + if (!first.dependencies.has(directory + "/entry.ts")) throw new Error("entry was not tracked"); + if (!first.dependencies.has(dependency)) throw new Error("dependency was not tracked"); + if (first.dependencies.has(external)) throw new Error("external module was tracked"); + + const changed = new Promise(resolve => watcher.subscribe(resolve)); + await new Promise(resolve => setTimeout(resolve, 100)); + await writeFile(dependency, [ + "const state = globalThis as typeof globalThis & { calls?: number };", + "export const count = state.calls = (state.calls ?? 0) + 1;", + 'export const text: string = "changed";', + ].join("\\n")); + let timeout; + const event = await Promise.race([ + changed, + new Promise((_, reject) => { + timeout = setTimeout(() => reject(new Error("watch timed out")), 3000); + }), + ]); + clearTimeout(timeout); + if (!event.paths.has(dependency)) throw new Error("change path was not reported"); + + const second = await watcher.import(); + if (second.value.result.count !== 2) throw new Error("dependency graph was not cache busted"); + if (second.value.result.externalCount !== 1) throw new Error("external module was cache busted"); + if (second.value.result.text !== "changed") throw new Error("changed module was not loaded"); + if (first.namespace === second.namespace) throw new Error("generation namespace was reused"); + await watcher.close(); + `; + + const result = spawnSync( + "node", + [ + "--experimental-transform-types", + "--no-warnings=ExperimentalWarning", + "--input-type=module", + "-e", + script, + directory, + ], + { encoding: "utf8", timeout: 10_000 }, + ); + + expect(result.status, result.stderr || result.stdout).toBe(0); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4f91fdffb9e..855adf66b71 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5939,6 +5939,13 @@ importers: version: 1.0.0-beta.7(@types/node@26.2.0)(esbuild@0.28.2)(jiti@2.7.0)(react-dom@19.2.8(react@19.2.8))(react-server-dom-webpack@19.2.8(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(webpack@5.109.2(cssnano@8.0.5(postcss@8.5.26))(csso@5.0.5)(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.26)))(react@19.2.8)(terser@5.50.0)(tsx@4.23.12)(yaml@2.9.0) packages/node-utils: + dependencies: + chokidar: + specifier: ^5.0.0 + version: 5.0.0 + rolldown: + specifier: 1.2.5 + version: 1.2.5 devDependencies: '@types/bun': specifier: catalog:tooling From ceef2e4b458d0120ca4f34fe6ddd77e560f7c384 Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 16:02:03 +0530 Subject: [PATCH 2/9] feat(cli): supervise Bun dev reloads and log what triggered them Both runtimes now reload from the exec child's own view of the stack graph instead of a native `--watch`, which hard-restarted the child with no teardown (stale widget left in scrollback) and never said why. - Log `Reloading stack: changed ` before every generation restart. - Node: the change listener detaches itself on delivery; `Effect.callback` only runs its cleanup on interruption, so each generation was leaving a listener behind. - Bun: `trackBunImports` records the project-local modules the stack loads through a runtime `Bun.plugin` load hook and watches them. Bun cannot evict evaluated modules, so a change tears the generation down and exits with `DEV_RELOAD_EXIT_CODE`; the `alchemy dev` supervisor respawns the child on that code while the sidecar spawner survives. - node-utils: the chokidar/debounce core moves into `DependencyWatcher`, shared by `ImportWatcher` and the new `watch-import-bun` entry. --- packages/alchemy/bin/cli.js | 4 +- packages/alchemy/src/Cli/DevOptions.ts | 7 ++ packages/alchemy/src/Cli/commands/dev.ts | 56 ++++++----- packages/alchemy/src/Cli/exec.ts | 99 +++++++++++++++---- .../alchemy/test/Cli/devKeepAlive.test.ts | 6 +- packages/node-utils/package.json | 5 + packages/node-utils/src/dependency-watcher.ts | 97 ++++++++++++++++++ packages/node-utils/src/watch-import-bun.ts | 91 +++++++++++++++++ packages/node-utils/src/watch-import.ts | 93 +++++------------ .../node-utils/test/watch-import-bun.test.ts | 75 ++++++++++++++ 10 files changed, 417 insertions(+), 116 deletions(-) create mode 100644 packages/node-utils/src/dependency-watcher.ts create mode 100644 packages/node-utils/src/watch-import-bun.ts create mode 100644 packages/node-utils/test/watch-import-bun.test.ts diff --git a/packages/alchemy/bin/cli.js b/packages/alchemy/bin/cli.js index 7612d265bfa..3be36e20f51 100755 --- a/packages/alchemy/bin/cli.js +++ b/packages/alchemy/bin/cli.js @@ -211,7 +211,5 @@ const program = foregroundChild( program, args, - (line) => - !line.includes("is not in the project directory and will not be watched") && - !line.includes("directory mismatch for directory"), + (line) => !line.includes("directory mismatch for directory"), ); diff --git a/packages/alchemy/src/Cli/DevOptions.ts b/packages/alchemy/src/Cli/DevOptions.ts index 04e08c5980b..a5a196648cf 100644 --- a/packages/alchemy/src/Cli/DevOptions.ts +++ b/packages/alchemy/src/Cli/DevOptions.ts @@ -10,3 +10,10 @@ export const DevOptions = Schema.Struct({ }); export type DevOptions = typeof DevOptions.Type; + +/** + * Exit status the exec child uses to ask the supervisor for a fresh process. + * Bun cannot evict evaluated modules, so a stack-graph change under Bun tears + * the generation down and exits with this code instead of reloading in place. + */ +export const DEV_RELOAD_EXIT_CODE = 75; diff --git a/packages/alchemy/src/Cli/commands/dev.ts b/packages/alchemy/src/Cli/commands/dev.ts index 01b4179804f..9efb8959854 100644 --- a/packages/alchemy/src/Cli/commands/dev.ts +++ b/packages/alchemy/src/Cli/commands/dev.ts @@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url"; import { SPAWNER_URL_ENV_KEY } from "../../Local/RpcProviderProxy.ts"; import * as RpcSpawner from "../../Local/RpcSpawner.ts"; import { isRegisterHooksSupported } from "../../Util/Node.ts"; -import { DevOptions } from "../DevOptions.ts"; +import { DEV_RELOAD_EXIT_CODE, DevOptions } from "../DevOptions.ts"; import { configPath, envFile, @@ -59,18 +59,18 @@ export const devCommand = Command.make( process.env.NODE_EXTRA_CA_CERTS ??= Floci.FLOCI_CA_PATH; } const spawner = yield* RpcSpawner.RpcSpawner; - // Bun keeps its native process watcher: each change replaces the exec - // process and therefore gets a fresh module cache. Node deliberately - // does not use `node --watch`; exec.ts keeps one process alive and - // reloads only the user's stack graph so Ctrl+C remains deterministic. + // Neither runtime uses its native `--watch`: those hard-restart the exec + // child with no teardown, leaving the previous generation's widget in + // scrollback and never saying what changed. exec.ts watches the user's + // stack graph itself. Under Node it reloads the graph in-process; under + // Bun (which cannot evict evaluated modules) it tears down and exits + // with DEV_RELOAD_EXIT_CODE, and this supervisor starts a fresh child. const command = typeof globalThis.Bun !== "undefined" ? [ "bun", "run", ...process.execArgv, - "--watch", - "--no-clear-screen", fileURLToPath(import.meta.resolve("alchemy/bin/exec.ts")), ] : import.meta.url.endsWith(".ts") && isRegisterHooksSupported() @@ -93,24 +93,32 @@ export const devCommand = Command.make( ...process.execArgv, fileURLToPath(import.meta.resolve("alchemy/bin/exec.js")), ]; - const child = yield* ChildProcess.make(command[0], command.slice(1), { - stdin: "inherit", - stdout: "inherit", - stderr: "inherit", - env: { - ALCHEMY_EXEC_OPTIONS: JSON.stringify(options), - ALCHEMY_DEV: "true", - ...(process.env.NODE_EXTRA_CA_CERTS - ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS } - : {}), - [SPAWNER_URL_ENV_KEY]: spawner.url, - }, - extendEnv: true, - // Same process group as this supervisor: the exec child owns the - // terminal (TUI stdin), so the tty's Ctrl+C must reach it directly. - detached: false, + const runChild = Effect.gen(function* () { + const child = yield* ChildProcess.make(command[0], command.slice(1), { + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + env: { + ALCHEMY_EXEC_OPTIONS: JSON.stringify(options), + ALCHEMY_DEV: "true", + ...(process.env.NODE_EXTRA_CA_CERTS + ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS } + : {}), + [SPAWNER_URL_ENV_KEY]: spawner.url, + }, + extendEnv: true, + // Same process group as this supervisor: the exec child owns the + // terminal (TUI stdin), so the tty's Ctrl+C must reach it directly. + detached: false, + }); + return yield* child.exitCode; + }).pipe(Effect.scoped); + // Each child gets its own scope so a reload exit releases the old + // handle before the replacement starts; the sidecar spawner lives in + // the command scope and survives every restart. + yield* Effect.repeat(runChild, { + until: (code) => code !== DEV_RELOAD_EXIT_CODE, }); - yield* child.exitCode; }, (effect, args) => Effect.provide( diff --git a/packages/alchemy/src/Cli/exec.ts b/packages/alchemy/src/Cli/exec.ts index 4c254704ba3..7be0cc283f8 100644 --- a/packages/alchemy/src/Cli/exec.ts +++ b/packages/alchemy/src/Cli/exec.ts @@ -8,6 +8,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"; import { watchImport } from "@alchemy.run/node-utils/watch-import"; +import { trackBunImports } from "@alchemy.run/node-utils/watch-import-bun"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -20,9 +21,10 @@ import { makeDevLogOpener } from "../Local/DevLog.ts"; import * as RpcProviderProxy from "../Local/RpcProviderProxy.ts"; import { forwardSidecarLogs } from "../Local/RpcSpawner.ts"; import { TelemetryLive } from "../Telemetry/Layer.ts"; +import { initialCwd } from "../Util/Node.ts"; import { PlatformServices } from "../Util/PlatformServices.ts"; import * as Stacks from "../Alchemist/routes/stack.ts"; -import { DevOptions } from "./DevOptions.ts"; +import { DEV_RELOAD_EXIT_CODE, DevOptions } from "./DevOptions.ts"; import { ConsoleLogLive } from "./GlobalLog.ts"; import { handleCliErrors, installShutdownFeedback } from "./commands/errors.ts"; import { renderApply, renderPlanning } from "./commands/render.ts"; @@ -105,6 +107,38 @@ const runDev = Effect.fn(function* (options: DevOptions) { return once ? undefined : yield* Effect.never; }); +/** + * Resolves with the files behind the next debounced change batch. The + * listener detaches itself on delivery — `Effect.callback` only runs its + * cleanup on interruption, so a listener left behind would fire once per + * past generation on every later change. + */ +const nextChange = (watcher: { + subscribe: ( + listener: (change: { paths: ReadonlySet }) => void, + ) => () => void; +}) => + Effect.callback>((resume) => { + const unsubscribe = watcher.subscribe(({ paths }) => { + unsubscribe(); + resume(Effect.succeed(paths)); + }); + return Effect.sync(unsubscribe); + }); + +const logReload = (paths: ReadonlySet) => + Effect.logInfo( + `Reloading stack: changed ${[...paths] + .map((file) => path.relative(initialCwd, file)) + .join(", ")}`, + ); + +/** + * Node: one process, many generations. The Oxc loader imports the stack graph + * under a fresh namespace each time; a change to any file it loaded + * interrupts the parked run (whose scope tears down the dev widget) and the + * loop imports the next generation. + */ const runNodeDevWatcher = (options: DevOptions) => { const entrypoint = path.resolve(options.main); const root = path.dirname(entrypoint); @@ -128,25 +162,55 @@ const runNodeDevWatcher = (options: DevOptions) => { (watcher) => Effect.promise(() => watcher.close()), ).pipe( Effect.flatMap((watcher) => { - const changed = Effect.callback((resume) => { - const unsubscribe = watcher.subscribe(() => resume(Effect.void)); - return Effect.sync(unsubscribe); - }); + const generation = devKeepAlive(runDev(options)).pipe( + Effect.provideService(StackModuleLoader, { + import: () => watcher.import().then(({ value }) => value), + }), + Effect.scoped, + ); return Effect.forever( - Effect.raceFirst( - devKeepAlive(runDev(options)).pipe( - Effect.provideService(StackModuleLoader, { - import: () => watcher.import().then(({ value }) => value), - }), - Effect.scoped, + Effect.raceFirst(generation, nextChange(watcher)).pipe( + Effect.flatMap((paths) => + paths === undefined ? Effect.void : logReload(paths), ), - changed, ), ); }), ); }; +/** + * Bun: one process per generation. Bun cannot evict evaluated modules, so the + * tracker only records which project files the stack graph loads; the first + * change to one of them logs, lets the generation scope tear down the dev + * widget, and exits with DEV_RELOAD_EXIT_CODE for the supervisor to respawn. + */ +const runBunDevWatcher = (options: DevOptions) => + Effect.acquireRelease( + Effect.sync(() => + trackBunImports({ root: path.dirname(path.resolve(options.main)) }), + ), + (tracker) => Effect.promise(() => tracker.close()), + ).pipe( + Effect.flatMap((tracker) => + Effect.raceFirst( + devKeepAlive(runDev(options)).pipe(Effect.scoped), + nextChange(tracker), + ), + ), + Effect.flatMap((paths) => + paths === undefined + ? Effect.void + : logReload(paths).pipe( + Effect.andThen( + Effect.sync(() => { + process.exitCode = DEV_RELOAD_EXIT_CODE; + }), + ), + ), + ), + ); + // A mid-edit import or planning failure must keep the watch process alive so // the next save can restart it. Interruptions still propagate for Ctrl+C. export const devKeepAlive = ( @@ -178,12 +242,13 @@ const makeExec = () => { yield* forwardSidecarLogs((entry) => devLog.writeLine(`[${entry.channel}] ${entry.line}`), ); - // Bun's outer `--watch` process owns reloads and starts this module with a - // fresh cache each time. Node stays in this process and refreshes only the - // stack module graph through the Oxc/chokidar watcher above. - return yield* (yield* devOnce) || process.versions.bun !== undefined + // Single-pass runs park nothing. Otherwise Node reloads the stack graph in + // this process; Bun exits for the supervisor to respawn (see above). + return yield* (yield* devOnce) ? devKeepAlive(runDev(options)) - : runNodeDevWatcher(options); + : process.versions.bun !== undefined + ? runBunDevWatcher(options) + : runNodeDevWatcher(options); }).pipe(Effect.provide(services), Effect.scoped, handleCliErrors); }; diff --git a/packages/alchemy/test/Cli/devKeepAlive.test.ts b/packages/alchemy/test/Cli/devKeepAlive.test.ts index 71265071640..b407de1a9ea 100644 --- a/packages/alchemy/test/Cli/devKeepAlive.test.ts +++ b/packages/alchemy/test/Cli/devKeepAlive.test.ts @@ -8,9 +8,9 @@ import { importStack } from "@/Alchemist/Session.ts"; import { devKeepAlive } from "../../src/Cli/exec"; import { PlatformServices } from "../../src/Util/PlatformServices"; -// Node's import-aware dev loop interrupts a parked run when a dependency -// changes; Bun's process watcher restarts it. In both cases a failed generation -// must park instead of exiting the watch session, while interruption propagates. +// The dev loop interrupts a parked run when a stack dependency changes (Node +// reloads in-process; Bun exits for the supervisor to respawn). In both cases a +// failed generation must park instead of exiting, while interruption propagates. /** Resolves `true` when the effect is still running (parked) after the timeout. */ const parks = (effect: Effect.Effect) => diff --git a/packages/node-utils/package.json b/packages/node-utils/package.json index abdc7a9e766..d7893a6eabf 100644 --- a/packages/node-utils/package.json +++ b/packages/node-utils/package.json @@ -52,6 +52,11 @@ "types": "./lib/watch-import.d.ts", "bun": "./src/watch-import.ts", "import": "./lib/watch-import.js" + }, + "./watch-import-bun": { + "types": "./lib/watch-import-bun.d.ts", + "bun": "./src/watch-import-bun.ts", + "import": "./lib/watch-import-bun.js" } }, "dependencies": { diff --git a/packages/node-utils/src/dependency-watcher.ts b/packages/node-utils/src/dependency-watcher.ts new file mode 100644 index 00000000000..543f9201b8f --- /dev/null +++ b/packages/node-utils/src/dependency-watcher.ts @@ -0,0 +1,97 @@ +import path from "node:path"; +import { watch, type ChokidarOptions, type FSWatcher } from "chokidar"; + +export interface DependencyChange { + readonly paths: ReadonlySet; +} + +export type DependencyChangeListener = (change: DependencyChange) => void; + +export interface DependencyWatcherOptions { + /** Chokidar options passed to the file watcher. */ + readonly watch?: ChokidarOptions | undefined; + readonly debounceMs?: number | undefined; +} + +/** + * Watches an explicit set of absolute file paths and delivers debounced + * change batches. Chokidar follows editor atomic-save replacements without + * polling by default. The set is replaced wholesale with {@link set}, so the + * watcher always mirrors exactly the files the caller currently depends on. + */ +export class DependencyWatcher { + readonly #options: DependencyWatcherOptions; + readonly #listeners = new Set(); + readonly #watcher: FSWatcher; + #dependencies: ReadonlySet = new Set(); + #pending = new Set(); + #timer: NodeJS.Timeout | undefined; + #closed = false; + + constructor(options: DependencyWatcherOptions = {}) { + this.#options = options; + this.#watcher = watch([], { + ...options.watch, + ignoreInitial: true, + }); + this.#watcher.on("all", (_event, changed) => { + const absolute = path.resolve(this.#cwd(), changed); + if (this.#dependencies.has(absolute)) this.#queue(absolute); + }); + } + + get dependencies(): ReadonlySet { + return this.#dependencies; + } + + subscribe(listener: DependencyChangeListener): () => void { + this.#listeners.add(listener); + return () => this.#listeners.delete(listener); + } + + /** Replace the watched set with `dependencies` (absolute paths). */ + set(dependencies: ReadonlySet): void { + if (this.#closed) return; + this.#dependencies = dependencies; + const watched = new Set( + Object.entries(this.#watcher.getWatched()).flatMap(([directory, files]) => + files.map((file) => path.resolve(this.#cwd(), directory, file)), + ), + ); + const removed = [...watched].filter( + (dependency) => !dependencies.has(dependency), + ); + const added = [...dependencies].filter( + (dependency) => !watched.has(dependency), + ); + if (removed.length > 0) void this.#watcher.unwatch(removed); + if (added.length > 0) this.#watcher.add(added); + } + + async close(): Promise { + if (this.#closed) return; + this.#closed = true; + if (this.#timer !== undefined) clearTimeout(this.#timer); + await this.#watcher.close(); + this.#listeners.clear(); + } + + async [Symbol.asyncDispose](): Promise { + await this.close(); + } + + #cwd(): string { + return this.#options.watch?.cwd ?? process.cwd(); + } + + #queue(changed: string): void { + this.#pending.add(changed); + if (this.#timer !== undefined) clearTimeout(this.#timer); + this.#timer = setTimeout(() => { + this.#timer = undefined; + const paths = this.#pending; + this.#pending = new Set(); + for (const listener of this.#listeners) listener({ paths }); + }, this.#options.debounceMs ?? 50); + } +} diff --git a/packages/node-utils/src/watch-import-bun.ts b/packages/node-utils/src/watch-import-bun.ts new file mode 100644 index 00000000000..5ef6a65eb6c --- /dev/null +++ b/packages/node-utils/src/watch-import-bun.ts @@ -0,0 +1,91 @@ +import path from "node:path"; +import { + DependencyWatcher, + type DependencyChangeListener, + type DependencyWatcherOptions, +} from "./dependency-watcher.ts"; + +export interface BunImportTrackerOptions extends DependencyWatcherOptions { + /** + * Directory whose modules belong to the tracked graph. Files outside it and + * anything under a `node_modules` directory load untouched. + */ + readonly root: string; +} + +const loaders: Record = { + ".js": "js", + ".mjs": "js", + ".cjs": "js", + ".jsx": "jsx", + ".ts": "ts", + ".mts": "ts", + ".cts": "ts", + ".tsx": "tsx", +}; + +const escapeRegExp = (value: string) => + value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +/** + * Records every project-local module Bun loads after registration and watches + * those files for changes. + * + * Bun has no loader hooks that can evict or re-namespace an evaluated module, + * so unlike Node's {@link ImportWatcher} this cannot import a fresh + * generation in-process. A runtime `Bun.plugin` `onLoad` hook is used purely + * as a dependency probe: it hands the source back unchanged with the loader + * Bun would have picked itself. Callers react to a change by exiting so a + * supervisor can start a fresh process. + */ +export class BunImportTracker { + readonly #watcher: DependencyWatcher; + readonly #dependencies = new Set(); + + constructor(options: BunImportTrackerOptions) { + if (process.versions.bun === undefined) { + throw new Error( + "BunImportTracker requires Bun; Node callers should use watchImport.", + ); + } + this.#watcher = new DependencyWatcher(options); + const root = path.resolve(options.root) + path.sep; + const nodeModules = `${path.sep}node_modules${path.sep}`; + const filter = new RegExp( + `^${escapeRegExp(root)}(?!.*${escapeRegExp(nodeModules)}).*\\.[cm]?[jt]sx?$`, + ); + Bun.plugin({ + name: "@alchemy.run/node-utils/watch-import-bun", + setup: (build) => { + build.onLoad({ filter }, async (args) => { + this.#dependencies.add(args.path); + this.#watcher.set(new Set(this.#dependencies)); + return { + contents: await Bun.file(args.path).text(), + loader: loaders[path.extname(args.path)] ?? "js", + }; + }); + }, + }); + } + + get dependencies(): ReadonlySet { + return this.#watcher.dependencies; + } + + subscribe(listener: DependencyChangeListener): () => void { + return this.#watcher.subscribe(listener); + } + + /** Stops watching. The load hook stays registered but only echoes sources. */ + close(): Promise { + return this.#watcher.close(); + } + + async [Symbol.asyncDispose](): Promise { + await this.close(); + } +} + +export const trackBunImports = (options: BunImportTrackerOptions) => + new BunImportTracker(options); diff --git a/packages/node-utils/src/watch-import.ts b/packages/node-utils/src/watch-import.ts index 863b21e6829..613a8ac8a52 100644 --- a/packages/node-utils/src/watch-import.ts +++ b/packages/node-utils/src/watch-import.ts @@ -1,7 +1,11 @@ import { randomUUID } from "node:crypto"; -import path from "node:path"; import { fileURLToPath } from "node:url"; -import { watch, type ChokidarOptions, type FSWatcher } from "chokidar"; +import { + DependencyWatcher, + type DependencyChange, + type DependencyChangeListener, + type DependencyWatcherOptions, +} from "./dependency-watcher.ts"; import { createImportLoader, type ImportLoader, @@ -14,50 +18,33 @@ export interface ImportGeneration { readonly dependencies: ReadonlySet; } -export interface ImportChange { - readonly paths: ReadonlySet; -} +export type ImportChange = DependencyChange; -export interface ImportWatcherOptions extends ImportLoaderOptions { +export interface ImportWatcherOptions + extends ImportLoaderOptions, DependencyWatcherOptions { readonly parentURL: string; - /** Chokidar options passed to the dependency watcher. */ - readonly watch?: ChokidarOptions | undefined; - readonly debounceMs?: number | undefined; } -export type ImportChangeListener = (change: ImportChange) => void; +export type ImportChangeListener = DependencyChangeListener; /** * Imports fresh Node module generations and watches the exact files loaded by - * the current generation. Chokidar follows editor atomic-save replacements - * without polling by default. Bun callers should use Bun's process watcher, - * which naturally starts each generation with a fresh module cache. + * the current generation. Bun callers should use `BunImportTracker` from + * `./watch-import-bun.ts`: Bun cannot evict evaluated modules, so a change + * there restarts the process instead of importing a new generation. */ export class ImportWatcher { readonly #specifier: string; readonly #options: ImportWatcherOptions; - readonly #listeners = new Set(); - readonly #watcher: FSWatcher; + readonly #watcher: DependencyWatcher; #registration: ImportLoader | undefined; #dependencies = new Set(); - #pending = new Set(); - #timer: NodeJS.Timeout | undefined; #closed = false; constructor(specifier: string, options: ImportWatcherOptions) { this.#specifier = specifier; this.#options = options; - this.#watcher = watch([], { - ...options.watch, - ignoreInitial: true, - }); - this.#watcher.on("all", (_event, changed) => { - const absolute = path.resolve( - options.watch?.cwd ?? process.cwd(), - changed, - ); - if (this.#dependencies.has(absolute)) this.#queue(absolute); - }); + this.#watcher = new DependencyWatcher(options); } get dependencies(): ReadonlySet { @@ -65,8 +52,7 @@ export class ImportWatcher { } subscribe(listener: ImportChangeListener): () => void { - this.#listeners.add(listener); - return () => this.#listeners.delete(listener); + return this.#watcher.subscribe(listener); } async import(): Promise> { @@ -85,7 +71,10 @@ export class ImportWatcher { onImport: (url) => { if (!url.startsWith("file:")) return; dependencies.add(fileURLToPath(url)); - if (this.#dependencies === dependencies) this.#syncWatchers(); + // A lazy import evaluated after this generation became current + // extends the watched set immediately. + if (this.#dependencies === dependencies) + this.#watcher.set(dependencies); }, }); try { @@ -93,12 +82,14 @@ export class ImportWatcher { await this.#registration?.unregister(); this.#registration = registration; this.#dependencies = dependencies; - this.#syncWatchers(); + this.#watcher.set(dependencies); return { value, namespace, dependencies }; } catch (error) { await registration.unregister(); + // Keep watching everything the failed import touched so the next save + // of any of those files retries. this.#dependencies = new Set([...this.#dependencies, ...dependencies]); - this.#syncWatchers(); + this.#watcher.set(this.#dependencies); throw error; } } @@ -106,49 +97,13 @@ export class ImportWatcher { async close(): Promise { if (this.#closed) return; this.#closed = true; - if (this.#timer !== undefined) clearTimeout(this.#timer); await this.#registration?.unregister(); await this.#watcher.close(); - this.#listeners.clear(); } async [Symbol.asyncDispose](): Promise { await this.close(); } - - #syncWatchers(): void { - const previous = this.#watcher.getWatched(); - const watched = new Set( - Object.entries(previous).flatMap(([directory, files]) => - files.map((file) => - path.resolve( - this.#options.watch?.cwd ?? process.cwd(), - directory, - file, - ), - ), - ), - ); - const removed = [...watched].filter( - (dependency) => !this.#dependencies.has(dependency), - ); - const added = [...this.#dependencies].filter( - (dependency) => !watched.has(dependency), - ); - if (removed.length > 0) void this.#watcher.unwatch(removed); - if (added.length > 0) this.#watcher.add(added); - } - - #queue(changed: string): void { - this.#pending.add(changed); - if (this.#timer !== undefined) clearTimeout(this.#timer); - this.#timer = setTimeout(() => { - this.#timer = undefined; - const paths = this.#pending; - this.#pending = new Set(); - for (const listener of this.#listeners) listener({ paths }); - }, this.#options.debounceMs ?? 50); - } } export const watchImport = ( diff --git a/packages/node-utils/test/watch-import-bun.test.ts b/packages/node-utils/test/watch-import-bun.test.ts new file mode 100644 index 00000000000..38f927f2484 --- /dev/null +++ b/packages/node-utils/test/watch-import-bun.test.ts @@ -0,0 +1,75 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { trackBunImports } from "../src/watch-import-bun.ts"; + +const temporaryDirectories: string[] = []; + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { force: true, recursive: true }); + } +}); + +describe("trackBunImports", () => { + it("records project-local modules and reports changes to them", async () => { + const temporaryDirectory = realpathSync( + mkdtempSync(path.join(os.tmpdir(), "alchemy-import-bun-")), + ); + temporaryDirectories.push(temporaryDirectory); + const directory = path.join(temporaryDirectory, "project"); + mkdirSync(directory); + const entry = path.join(directory, "entry.ts"); + const dependency = path.join(directory, "dependency.ts"); + const external = path.join(temporaryDirectory, "external.ts"); + writeFileSync( + entry, + [ + 'import { text } from "./dependency.ts";', + 'import { externalText } from "../external.ts";', + "interface Result { text: string; externalText: string }", + "export const result: Result = { text, externalText };", + ].join("\n"), + ); + writeFileSync(dependency, 'export const text: string = "original";\n'); + writeFileSync( + external, + 'export const externalText: string = "external";\n', + ); + + const tracker = trackBunImports({ root: directory, debounceMs: 10 }); + try { + const module = (await import(entry)) as { + result: { text: string; externalText: string }; + }; + expect(module.result).toEqual({ + text: "original", + externalText: "external", + }); + expect(tracker.dependencies).toEqual(new Set([entry, dependency])); + + const changed = new Promise>((resolve) => + tracker.subscribe(({ paths }) => resolve(paths)), + ); + // Give chokidar a moment to arm the file watchers before writing. + await new Promise((resolve) => setTimeout(resolve, 200)); + writeFileSync(dependency, 'export const text: string = "changed";\n'); + const paths = await Promise.race([ + changed, + new Promise((_, reject) => + setTimeout(() => reject(new Error("watch timed out")), 3000), + ), + ]); + expect(paths).toEqual(new Set([dependency])); + } finally { + await tracker.close(); + } + }); +}); From cc11470afb1b1677d0e38623c4b53cc8fe018eea Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 16:53:20 +0530 Subject: [PATCH 3/9] fix(cli): load every .ts through the Oxc loader under Node Node's built-in TypeScript support is strip-only (no parameter properties, enums, or TSX) and Node 26 removed the `--experimental-transform-types` flag that `transformTypesFlags()` leaned on. In a checkout under Node 26 the local-provider sidecar was spawned with no flags at all, died on the first parameter property in alchemy's own source, and `alchemy dev` surfaced only "Interrupted." during "Computing plan". Every alchemy Node process now starts with alchemy's Oxc loader hooks instead, and never relies on Node's TypeScript support: - `bin/cli.js` gates Node on `module.registerHooks` (22.15+/23.5+/24+) and passes `--import` of `register-dev-mode.js` (checkout: Oxc plus src-condition resolution) or the new `register-oxc.js` (published). - `register-oxc.js` transpiles only the user's own TypeScript: alchemy and its dependencies run their built JavaScript, and anything under `node_modules` is left to Node, matching Node's own rule. - `nodeLoaderArgs(entry)` replaces `transformTypesFlags()` for the sidecar, the Vite dev/build runners, and the dev exec child. The sidecar also launches on `process.execPath` rather than PATH's `node`, so supervisor and sidecar never run different Node versions. - `registerOxc()` is idempotent for the global registration, so a process started with `--import` can call it again safely. --- .gitignore | 1 + packages/alchemy/bin/cli.js | 53 +++++++++++-------- packages/alchemy/bin/register-oxc.js | 23 ++++++++ packages/alchemy/src/Cli/commands/dev.ts | 39 +++++++------- .../src/Cloudflare/Workers/ViteChild.ts | 11 ++-- packages/alchemy/src/Local/RpcSpawner.ts | 20 ++++--- packages/alchemy/src/Util/Node.ts | 40 +++++++------- packages/alchemy/test/Interaction.test.ts | 19 ++++--- packages/alchemy/test/Util/Node.test.ts | 28 +++++++--- packages/alchemy/test/nodeProbe.ts | 2 +- packages/node-utils/src/import-loader.ts | 7 +++ packages/node-utils/src/register-oxc.ts | 33 ++++++++++-- 12 files changed, 180 insertions(+), 96 deletions(-) create mode 100644 packages/alchemy/bin/register-oxc.js diff --git a/.gitignore b/.gitignore index e4fc7422165..2a24f7792c0 100644 --- a/.gitignore +++ b/.gitignore @@ -68,6 +68,7 @@ examples/cloudflare-worker/src/scratch.ts !/packages/alchemy/bin/cli.js !/packages/alchemy/bin/register-dev-mode.js +!/packages/alchemy/bin/register-oxc.js .vendor/* .tmp # the lockfile-pinning test fixture is a checked-in lockfile, not a generated one diff --git a/packages/alchemy/bin/cli.js b/packages/alchemy/bin/cli.js index 3be36e20f51..1c196d4b5e4 100755 --- a/packages/alchemy/bin/cli.js +++ b/packages/alchemy/bin/cli.js @@ -130,13 +130,15 @@ const [nodeMajor = 0, nodeMinor = 0] = process.versions.node .map(Number); /** - * Whether this node has `module.registerHooks` (v22.15 / v23.5 / v24+) — - * the capability gate for running the CLI from source: every hooks-capable - * node also loads `.ts` (via the transform flag below v26, natively from - * v26). Mirrors `src/Util/Node.ts#isRegisterHooksSupported` — duplicated - * because this launcher must run under plain node before any .ts can load. + * Whether this node has `module.registerHooks` (v22.15 / v23.5 / v24+). + * Alchemy loads every `.ts`/`.tsx` — its own source in a checkout, the + * user's stack everywhere — through the Oxc loader those hooks install, and + * never through Node's built-in TypeScript support (strip-only, and its + * transform flag was removed in Node 26). So this is THE gate for running + * under node at all. Mirrors `src/Util/Node.ts#isRegisterHooksSupported` — + * duplicated because this launcher must run under plain node first. */ -const nodeRunsTypeScript = +const nodeSupportsHooks = (nodeMajor === 22 && nodeMinor >= 15) || (nodeMajor === 23 && nodeMinor >= 5) || nodeMajor >= 24; @@ -149,6 +151,15 @@ const isDev = !( // We no longer force bun in dev when node is the invoker because this prevents us from testing in node. const runtime = invokedByBun ? "bun" : "node"; +if (runtime === "node" && !nodeSupportsHooks) { + process.stderr.write( + `alchemy: node ${process.versions.node} is not supported ` + + "(module.registerHooks needs node 22.15+, 23.5+, or 24+).\n" + + "Use a newer node, or run alchemy with bun.\n", + ); + process.exit(1); +} + const args = []; if (runtime === "bun" && isDev) { @@ -161,25 +172,25 @@ if (runtime === "bun" && isDev) { args.push(`--tsconfig-override=${path.join(binDir, "..", "tsconfig.json")}`); } -if (runtime === "node" && isDev && nodeRunsTypeScript) { - // Run the checkout's source directly, no build required: the - // register-dev-mode hooks load .ts/.tsx through Oxc AND resolve - // the monorepo's own packages (`alchemy/*`, `@alchemy.run/*`, - // `@distilled.cloud/*`) through their `bun` export condition onto src/ — +if (runtime === "node") { + // Checkout: run the source directly, no build required — the + // register-dev-mode hooks load .ts/.tsx through Oxc AND resolve the + // monorepo's own packages (`alchemy/*`, `@alchemy.run/*`, + // `@distilled.cloud/*`) through their `bun` export condition onto src/, // so the CLI, the user's stack, and every workspace dependency load one // source universe instead of whatever built lib/ happens to be around. - args.push("--import", new URL("register-dev-mode.js", import.meta.url).href); + // Published: only the Oxc loader, for the user's own .ts/.tsx. + args.push( + "--import", + new URL(isDev ? "register-dev-mode.js" : "register-oxc.js", import.meta.url) + .href, + ); } -const entry = - runtime === "bun" || (isDev && nodeRunsTypeScript) ? tsEntry : jsEntry; -if (entry === jsEntry && isDev && !existsSync(jsEntry)) { - // The version gate declined source mode and there is no built output to - // fall back to — fail with a diagnosis instead of a raw MODULE_NOT_FOUND. +const entry = runtime === "bun" || isDev ? tsEntry : jsEntry; +if (entry === jsEntry && !existsSync(jsEntry)) { process.stderr.write( - `alchemy: node ${process.versions.node} cannot run the TypeScript source ` + - "(module.registerHooks needs node 22.15+, 23.5+, or 24+) and " + - `${jsEntry} has not been built.\n` + - "Use bun or a newer node, or run `pnpm build` in packages/alchemy.\n", + `alchemy: ${jsEntry} has not been built.\n` + + "Run `pnpm build` in packages/alchemy.\n", ); process.exit(1); } diff --git a/packages/alchemy/bin/register-oxc.js b/packages/alchemy/bin/register-oxc.js new file mode 100644 index 00000000000..bc9b19ac381 --- /dev/null +++ b/packages/alchemy/bin/register-oxc.js @@ -0,0 +1,23 @@ +// Loader hook for published installs under Node. +// +// Every alchemy Node process — the `alchemy` CLI, the dev exec child, the +// local-provider sidecar, dev-server runners — is started with `--import` +// of this file. Alchemy itself and all of its dependencies run their built +// JavaScript; the hook exists so the USER's `.ts`/`.tsx` (the stack +// entrypoint and everything it imports from the project) transpiles through +// Oxc. Alchemy never relies on Node's built-in TypeScript support: it is +// strip-only (no parameter properties, enums, or TSX), and the transform +// flag that covered some of that was removed in Node 26. +// +// Anything under `node_modules` is left to Node, matching Node's own refusal +// to type-strip installed packages: a dependency is expected to ship +// JavaScript. +// +// Checkout runs use `register-dev-mode.js` instead, which installs the same +// loader without the filter (alchemy's own source is TypeScript there) and +// additionally resolves workspace packages onto their `src/`. +import { registerOxc } from "@alchemy.run/node-utils/register-oxc"; + +registerOxc({ + filter: (path) => !/[\\/]node_modules[\\/]/.test(path), +}); diff --git a/packages/alchemy/src/Cli/commands/dev.ts b/packages/alchemy/src/Cli/commands/dev.ts index 9efb8959854..5f408bd0863 100644 --- a/packages/alchemy/src/Cli/commands/dev.ts +++ b/packages/alchemy/src/Cli/commands/dev.ts @@ -8,7 +8,7 @@ import * as ChildProcess from "effect/unstable/process/ChildProcess"; import { fileURLToPath } from "node:url"; import { SPAWNER_URL_ENV_KEY } from "../../Local/RpcProviderProxy.ts"; import * as RpcSpawner from "../../Local/RpcSpawner.ts"; -import { isRegisterHooksSupported } from "../../Util/Node.ts"; +import { nodeLoaderArgs } from "../../Util/Node.ts"; import { DEV_RELOAD_EXIT_CODE, DevOptions } from "../DevOptions.ts"; import { configPath, @@ -73,26 +73,29 @@ export const devCommand = Command.make( ...process.execArgv, fileURLToPath(import.meta.resolve("alchemy/bin/exec.ts")), ] - : import.meta.url.endsWith(".ts") && isRegisterHooksSupported() - ? [ - // Source checkout under node: run the .ts exec entry with - // the dev-mode hooks (Oxc loader + src-condition - // resolution), so dev works without a build (mirrors - // bin/cli.js's launcher path). `process.execPath`, not - // "node": the hooks are gated on THIS node's version. A - // duplicate --import inherited via execArgv is harmless — - // the second import of the same URL hits the module cache. + : (() => { + // Node: the exec entry runs with alchemy's Oxc loader hooks, + // exactly as bin/cli.js started this process (checkout: the + // .ts entry plus src-condition resolution; published: the .js + // bundle plus the loader for the user's stack). Node's own + // TypeScript support is never relied on. `process.execPath`, + // not "node": the hooks are gated on THIS node's version. A + // duplicate --import inherited via execArgv is harmless — the + // second import of the same URL hits the module cache. + const entry = fileURLToPath( + import.meta.resolve( + import.meta.url.endsWith(".ts") + ? "alchemy/bin/exec.ts" + : "alchemy/bin/exec.js", + ), + ); + return [ process.execPath, ...process.execArgv, - "--import", - import.meta.resolve("../../../bin/register-dev-mode.js"), - fileURLToPath(import.meta.resolve("alchemy/bin/exec.ts")), - ] - : [ - process.execPath, - ...process.execArgv, - fileURLToPath(import.meta.resolve("alchemy/bin/exec.js")), + ...nodeLoaderArgs(entry), + entry, ]; + })(); const runChild = Effect.gen(function* () { const child = yield* ChildProcess.make(command[0], command.slice(1), { stdin: "inherit", diff --git a/packages/alchemy/src/Cloudflare/Workers/ViteChild.ts b/packages/alchemy/src/Cloudflare/Workers/ViteChild.ts index ae8ef3c2374..152321581ea 100644 --- a/packages/alchemy/src/Cloudflare/Workers/ViteChild.ts +++ b/packages/alchemy/src/Cloudflare/Workers/ViteChild.ts @@ -19,7 +19,7 @@ import { } from "../../Local/RpcServerEnvironment.ts"; import { Stack } from "../../Stack.ts"; import { unwrapRedacted } from "../../Util/index.ts"; -import { transformTypesFlags } from "../../Util/Node.ts"; +import { nodeLoaderArgs } from "../../Util/Node.ts"; import { type ViteBuildChildConfig, type ViteBuildChildResult, @@ -111,7 +111,7 @@ export const startViteChild = ( nodeExecPath ?? process.execPath, isBun && nodeExecPath === undefined ? ["run", runner] - : [...(runner.endsWith(".ts") ? transformTypesFlags() : []), runner], + : [...nodeLoaderArgs(runner), runner], { cwd: config.rootDir, stdin: Stream.succeed(serializedConfig), @@ -199,12 +199,7 @@ export const runViteBuildChild = ( const child = yield* spawner.spawn( ChildProcess.make( process.execPath, - isBun - ? ["run", runner] - : [ - ...(runner.endsWith(".ts") ? transformTypesFlags() : []), - runner, - ], + isBun ? ["run", runner] : [...nodeLoaderArgs(runner), runner], { cwd: config.rootDir, stdin: Stream.succeed(serializedConfig), diff --git a/packages/alchemy/src/Local/RpcSpawner.ts b/packages/alchemy/src/Local/RpcSpawner.ts index 241dbfd92a1..b6bd442c66f 100644 --- a/packages/alchemy/src/Local/RpcSpawner.ts +++ b/packages/alchemy/src/Local/RpcSpawner.ts @@ -22,7 +22,7 @@ import * as ChildProcess from "effect/unstable/process/ChildProcess"; import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; import { fileURLToPath } from "node:url"; import { pipedColorEnv } from "../Util/Terminal.ts"; -import { transformTypesFlags } from "../Util/Node.ts"; +import { nodeLoaderArgs } from "../Util/Node.ts"; import { httpServer } from "../Util/PlatformServices.ts"; import { SPAWNER_URL_ENV_KEY } from "./RpcProviderProxy.ts"; import { @@ -111,6 +111,11 @@ export const make = Effect.fn(function* ({ const spawn = Effect.fn(function* (serverEntryUrl: string) { const bin = typeof globalThis.Bun !== "undefined" ? "bun" : "node"; const main = fileURLToPath(serverEntryUrl); + // The sidecar runs on THIS process's runtime binary, not whatever PATH + // resolves: a `.ts` entry (checkout) needs the dev-mode loader hooks, + // which are gated on this node's version, and a published `.js` entry + // must not silently switch Node versions between supervisor and sidecar. + const program = bin === "bun" ? "bun" : process.execPath; // Stack-specific context is deliberately absent: sessions carry their // own SessionEnvironment, so one child serves every stack. const environment: RpcServerEnvironment = { @@ -124,15 +129,14 @@ export const make = Effect.fn(function* ({ // already decided (NO_COLOR / FORCE_COLOR). `extendEnv` propagates it // from the sidecar to its own children (dev servers, workerd). const command = ChildProcess.make( - bin, + program, { bun: ["run", main], - // Under Node, transparently strip TypeScript types so that `.ts` - // entry points work the same way they do under Bun. Mirrors what - // `dev.ts` already does for the outer process, so the dev experience - // is symmetric on both runtimes whether the entry came from `src/` - // (dev/tests) or `lib/` (published packages). - node: main.endsWith(".ts") ? [...transformTypesFlags(), main] : [main], + // Under Node the sidecar starts with alchemy's Oxc loader hooks, the + // same way `dev.ts` starts the exec child: a `.ts` entry (src/ in a + // checkout) also gets src-condition resolution, a `.js` entry (lib/ + // in a published install) gets the loader alone. + node: [...nodeLoaderArgs(main), main], }[bin], { stdout: "pipe", diff --git a/packages/alchemy/src/Util/Node.ts b/packages/alchemy/src/Util/Node.ts index 75c37411fac..f7883da06ea 100644 --- a/packages/alchemy/src/Util/Node.ts +++ b/packages/alchemy/src/Util/Node.ts @@ -46,31 +46,33 @@ export const disableCrossSpawnChdir = (): void => { (process.chdir as { disabled?: boolean }).disabled = true; }; -export const isTransformTypesSupported = ( - version = process.versions.node, -): boolean => { - const [major, minor] = version.split(".").map(Number); - return (major === 22 && minor >= 7) || (major >= 23 && major < 26); -}; - /** - * Node CLI flags that transparently transform TypeScript types so `.ts` - * entry points work the same way they do under Bun. Empty when the running - * Node doesn't support (or no longer needs) the experimental flag. + * Node arguments that install alchemy's Oxc loader in a child process, the + * same way `bin/cli.js` installs it for the CLI itself. Every `.ts`/`.tsx` + * a Node process loads — alchemy's own source in a checkout, the user's + * stack everywhere — goes through it; nothing relies on Node's built-in + * TypeScript support (strip-only, and Node 26 removed the transform flag). + * + * A `.ts` entry means a checkout: `bin/register-dev-mode.js` adds the + * src-condition resolution for workspace packages on top of the loader. + * A `.js` entry means a published install: `bin/register-oxc.js` is the + * loader alone. */ -export const transformTypesFlags = ( - version = process.versions.node, -): string[] => - isTransformTypesSupported(version) - ? ["--experimental-transform-types", "--no-warnings=ExperimentalWarning"] - : []; +export const nodeLoaderArgs = (entry: string): string[] => [ + "--import", + import.meta.resolve( + /\.[cm]?tsx?$/.test(entry) + ? "../../bin/register-dev-mode.js" + : "../../bin/register-oxc.js", + ), +]; /** * Whether this Node supports the synchronous in-thread loader hooks * (`module.registerHooks`, v22.15 / v23.5) that `bin/register-dev-mode.js` - * needs. Since every registerHooks-capable Node also loads `.ts` (via - * {@link transformTypesFlags} below v26, natively from v26), this is THE - * capability gate for running the CLI from source under node. + * needs. This is THE capability gate for running the CLI from source under + * node: with the hooks installed, the Oxc loader handles every `.ts`/`.tsx` + * file regardless of Node's own TypeScript support. * * `bin/cli.js` mirrors this predicate inline — it must run under plain node * before any `.ts` can load. Keep the two in sync. diff --git a/packages/alchemy/test/Interaction.test.ts b/packages/alchemy/test/Interaction.test.ts index 89b9c87bb84..fa27fb85308 100644 --- a/packages/alchemy/test/Interaction.test.ts +++ b/packages/alchemy/test/Interaction.test.ts @@ -1,5 +1,5 @@ import { Interaction, layerNonInteractive, accessors } from "@/Interaction.ts"; -import { transformTypesFlags } from "@/Util/Node.ts"; +import { nodeLoaderArgs } from "@/Util/Node.ts"; import { PlatformServices } from "@/Util/PlatformServices.ts"; import { expect, it } from "alchemy-test"; import * as Effect from "effect/Effect"; @@ -7,7 +7,7 @@ import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/unstable/process/ChildProcess"; import { PassThrough } from "node:stream"; import { fileURLToPath } from "node:url"; -import { nodePath, nodeSupportsDevMode, nodeVersion } from "./nodeProbe.ts"; +import { nodePath, nodeSupportsDevMode } from "./nodeProbe.ts"; class CaptureStream extends PassThrough { readonly columns = 80; @@ -65,14 +65,13 @@ it("task prints a start line and settles with a status line", () => { }).pipe(Effect.provide(nonInteractive(stdout))); }); -// The regression this pins: spawned dev children run under plain Node type -// stripping (which cannot load TSX) and carry NO interaction services at -// all. The vite child runner's entire module graph must therefore load -// under node and proceed to config resolution — the original bug was an -// eager CliKit/TSX import killing every `runtime: "node"` dev child at -// startup. +// The regression this pins: spawned dev children carry NO interaction +// services at all, so the vite child runner's entire module graph must load +// under node (the same dev-mode loader `ViteChild.ts` spawns it with) and +// proceed to config resolution — the original bug was an eager CliKit import +// killing every `runtime: "node"` dev child at startup. it.live.skipIf(!nodeSupportsDevMode)( - "the vite child runner's module graph loads under plain node", + "the vite child runner's module graph loads under node", () => Effect.gen(function* () { const runner = fileURLToPath( @@ -83,7 +82,7 @@ it.live.skipIf(!nodeSupportsDevMode)( ); const handle = yield* ChildProcess.make( nodePath!, - [...transformTypesFlags(nodeVersion ?? undefined), runner], + [...nodeLoaderArgs(runner), runner], { cwd: fileURLToPath(new URL("..", import.meta.url)), env: { NO_COLOR: "1" }, diff --git a/packages/alchemy/test/Util/Node.test.ts b/packages/alchemy/test/Util/Node.test.ts index d783b4a94d9..7c235882116 100644 --- a/packages/alchemy/test/Util/Node.test.ts +++ b/packages/alchemy/test/Util/Node.test.ts @@ -1,14 +1,30 @@ -import { findAvailablePort, isTransformTypesSupported } from "@/Util/Node"; +import { findAvailablePort, nodeLoaderArgs } from "@/Util/Node"; import { describe, expect, test } from "alchemy-test"; import * as Effect from "effect/Effect"; import * as NodeNet from "node:net"; describe("Node utilities", () => { - test("detects versions that support --experimental-transform-types", () => { - expect(isTransformTypesSupported("22.6.0")).toBe(false); - expect(isTransformTypesSupported("22.7.0")).toBe(true); - expect(isTransformTypesSupported("25.9.0")).toBe(true); - expect(isTransformTypesSupported("26.0.0")).toBe(false); + test("checkout .ts entries get the dev-mode hooks", () => { + for (const entry of [ + "/repo/packages/alchemy/src/Cloudflare/Local.ts", + "/repo/src/Runner.tsx", + "/repo/src/Runner.mts", + ]) { + const args = nodeLoaderArgs(entry); + expect(args[0]).toBe("--import"); + expect(args[1]).toMatch(/\/bin\/register-dev-mode\.js$/); + } + }); + + test("published .js entries get the Oxc loader alone", () => { + for (const entry of [ + "/app/node_modules/alchemy/lib/Cloudflare/Local.js", + "/app/lib/Runner.mjs", + ]) { + const args = nodeLoaderArgs(entry); + expect(args[0]).toBe("--import"); + expect(args[1]).toMatch(/\/bin\/register-oxc\.js$/); + } }); test("finds and releases an available port", async () => { diff --git a/packages/alchemy/test/nodeProbe.ts b/packages/alchemy/test/nodeProbe.ts index a2147b1b1f8..ecf6fe2be19 100644 --- a/packages/alchemy/test/nodeProbe.ts +++ b/packages/alchemy/test/nodeProbe.ts @@ -2,7 +2,7 @@ import { isRegisterHooksSupported } from "@/Util/Node.ts"; /** * The real node binary tests spawn, and ITS version — not bun's emulated - * `process.versions.node`, which is what `transformTypesFlags()` would + * `process.versions.node`, which is what the version gates would * consult by default. Gating on the wrong runtime made the node-launcher * tests run (and fail with zero diagnostics) on machines whose PATH node * is older than the version bun reports. diff --git a/packages/node-utils/src/import-loader.ts b/packages/node-utils/src/import-loader.ts index 7453b43e779..f1a7b3a0b54 100644 --- a/packages/node-utils/src/import-loader.ts +++ b/packages/node-utils/src/import-loader.ts @@ -25,6 +25,13 @@ export interface ImportLoaderOptions { readonly shouldInvalidate?: | ((url: string, parentURL: string | undefined) => boolean) | undefined; + /** + * Limits transformation to matching absolute file paths; everything else + * loads through Node untouched. Lets a published install transpile only + * the user's own TypeScript while alchemy and its dependencies run their + * built JavaScript. + */ + readonly filter?: ((path: string) => boolean) | undefined; } export interface ImportLoaderRegistrationOptions extends ImportLoaderOptions { diff --git a/packages/node-utils/src/register-oxc.ts b/packages/node-utils/src/register-oxc.ts index 19b2a8204d1..d5d06c4b61a 100644 --- a/packages/node-utils/src/register-oxc.ts +++ b/packages/node-utils/src/register-oxc.ts @@ -21,6 +21,9 @@ export type { const protocol = "alchemy-import:"; const namespaceParameter = "alchemy-import-namespace"; +const globalRegistrationKey = Symbol.for( + "@alchemy.run/node-utils/register-oxc", +); interface ImportRequest { readonly namespace?: string | undefined; @@ -80,6 +83,18 @@ const resolve = ( export const registerOxc = ( options: ImportLoaderRegistrationOptions = {}, ): ImportLoader => { + // One global (un-namespaced) registration per process. Alchemy starts every + // Node process with `--import` of a file that calls this, and in-process + // callers (the dev exec child, tests) may call it again; a second copy of + // the hooks would only re-run the resolve chain. The marker lives on + // globalThis because a checkout can load this module twice (src/ and lib/). + const globalRegistration = globalThis as typeof globalThis & { + [globalRegistrationKey]?: ImportLoader; + }; + if (options.namespace === undefined) { + const existing = globalRegistration[globalRegistrationKey]; + if (existing !== undefined) return existing; + } const transformer = new SourceTransformer(options); const shouldInvalidate = options.shouldInvalidate ?? (() => true); const hooks = registerHooks({ @@ -126,16 +141,17 @@ export const registerOxc = ( if (!cleanUrl.startsWith("file:")) return nextLoad(cleanUrl, context); options.onImport?.(cleanUrl); - const transformed = transformer.transform( - fileURLToPath(cleanUrl), - cleanUrl, - ); + const filePath = fileURLToPath(cleanUrl); + if (options.filter !== undefined && !options.filter(filePath)) { + return nextLoad(cleanUrl, context); + } + const transformed = transformer.transform(filePath, cleanUrl); if (transformed === undefined) return nextLoad(cleanUrl, context); return { ...transformed, shortCircuit: true }; }, }); - return { + const loader: ImportLoader = { import(specifier: string, parentURL: string) { const request: ImportRequest = { namespace: options.namespace, @@ -150,6 +166,13 @@ export const registerOxc = ( }, unregister() { hooks.deregister(); + if (globalRegistration[globalRegistrationKey] === loader) { + delete globalRegistration[globalRegistrationKey]; + } }, }; + if (options.namespace === undefined) { + globalRegistration[globalRegistrationKey] = loader; + } + return loader; }; From 8d12d94940d5f71450e1da1e218ee4473f42fa25 Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 17:42:41 +0530 Subject: [PATCH 4/9] feat(node-utils): make the Oxc register a drop-in tsx replacement Resolution now matches what tsx layers over Node for a TypeScript codebase, for ESM and `require()` alike (Node's sync hooks serve both): - tsconfig `paths`/`baseUrl` aliases, discovered per importing file - `./x.js` meaning `x.ts` (source wins over an emitted sibling), plus the `.mjs`/`.cjs`/`.jsx` substitutions - extensionless specifiers and directory indexes, TypeScript first - package `exports` naming unbuilt JavaScript (checkout workspace packages) - JSON imports without an import attribute Candidates come from rolldown's `ResolverFactory` (tsconfig `auto`, `extensionAlias`, `mainFiles`); Node's resolver stays the authority and receives every candidate, so it decides formats, validates exports, and reports the canonical errors. Bare specifiers are probed without following symlinks so a linked workspace package still reads as a package and keeps going through the checkout's src-condition hook. The load hook honours Node's `module-typescript`/`commonjs-typescript` formats; a `.ts` in a CommonJS package that uses `import` runs as ESM, as Node's own syntax detection would. `.jsx` transpiles too. Source maps are switched on for the process so the inline maps reach stack traces. The register API gains `tsconfig: false`, and `tsImport()` mirrors tsx's one-shot namespaced import. The Bun tracker and the Node watcher scope the graph by real path, so symlinked roots (`/tmp` on macOS, linked checkouts) match what the runtimes report. The existing watch test no longer passes a flag Node 26 removed. --- packages/alchemy/bin/register-oxc.js | 4 + packages/alchemy/src/Cli/exec.ts | 5 +- packages/node-utils/src/import-loader.ts | 11 +- packages/node-utils/src/register-oxc.ts | 196 ++++++++++++++++-- packages/node-utils/src/resolve-specifier.ts | 179 ++++++++++++++++ packages/node-utils/src/transform-source.ts | 114 ++++++---- packages/node-utils/src/watch-import-bun.ts | 5 +- packages/node-utils/test/register-oxc.test.ts | 195 +++++++++++++++++ packages/node-utils/test/watch-import.test.ts | 9 +- 9 files changed, 648 insertions(+), 70 deletions(-) create mode 100644 packages/node-utils/src/resolve-specifier.ts create mode 100644 packages/node-utils/test/register-oxc.test.ts diff --git a/packages/alchemy/bin/register-oxc.js b/packages/alchemy/bin/register-oxc.js index bc9b19ac381..6a85ee126d8 100644 --- a/packages/alchemy/bin/register-oxc.js +++ b/packages/alchemy/bin/register-oxc.js @@ -1,5 +1,9 @@ // Loader hook for published installs under Node. // +// Beyond transpiling, the hook resolves the way tsx does: tsconfig `paths`, +// `.js` imports that mean `.ts` source, extensionless and directory imports, +// JSON without import attributes, and `require()` of TypeScript from `.cts`. +// // Every alchemy Node process — the `alchemy` CLI, the dev exec child, the // local-provider sidecar, dev-server runners — is started with `--import` // of this file. Alchemy itself and all of its dependencies run their built diff --git a/packages/alchemy/src/Cli/exec.ts b/packages/alchemy/src/Cli/exec.ts index 7be0cc283f8..b494d07a4e6 100644 --- a/packages/alchemy/src/Cli/exec.ts +++ b/packages/alchemy/src/Cli/exec.ts @@ -9,6 +9,7 @@ import * as Schema from "effect/Schema"; import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"; import { watchImport } from "@alchemy.run/node-utils/watch-import"; import { trackBunImports } from "@alchemy.run/node-utils/watch-import-bun"; +import { realpathSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -140,7 +141,9 @@ const logReload = (paths: ReadonlySet) => * loop imports the next generation. */ const runNodeDevWatcher = (options: DevOptions) => { - const entrypoint = path.resolve(options.main); + // Node reports real paths for loaded files (symlinked checkouts, macOS + // `/tmp`), so the root the graph is scoped to must be a real path too. + const entrypoint = realpathSync.native(path.resolve(options.main)); const root = path.dirname(entrypoint); const nodeModules = `${path.sep}node_modules${path.sep}`; return Effect.acquireRelease( diff --git a/packages/node-utils/src/import-loader.ts b/packages/node-utils/src/import-loader.ts index f1a7b3a0b54..bb3cd02a07e 100644 --- a/packages/node-utils/src/import-loader.ts +++ b/packages/node-utils/src/import-loader.ts @@ -17,10 +17,19 @@ export type SourceTransform = ( ) => string | SourceTransformResult | undefined; export interface ImportLoaderOptions { - /** Oxc transform configuration. */ + /** + * Oxc transform configuration, layered over the nearest `tsconfig.json` + * of each transformed file (`jsx`, decorators, …). + */ readonly transform?: TransformOptions | undefined; /** Additional synchronous source transforms, applied after Oxc. */ readonly transforms?: ReadonlyArray | undefined; + /** + * Honour `tsconfig.json` discovered upward from each file: compiler + * options for the transform, `paths`/`baseUrl` aliases for resolution. + * @default true + */ + readonly tsconfig?: boolean | undefined; /** Controls which file URLs belong to the fresh import graph. */ readonly shouldInvalidate?: | ((url: string, parentURL: string | undefined) => boolean) diff --git a/packages/node-utils/src/register-oxc.ts b/packages/node-utils/src/register-oxc.ts index d5d06c4b61a..9f0533bf063 100644 --- a/packages/node-utils/src/register-oxc.ts +++ b/packages/node-utils/src/register-oxc.ts @@ -1,15 +1,24 @@ +import { randomUUID } from "node:crypto"; import { registerHooks, type LoadFnOutput, + type LoadHookContext, type ResolveFnOutput, type ResolveHookContext, } from "node:module"; -import { fileURLToPath, pathToFileURL } from "node:url"; +import { pathToFileURL } from "node:url"; import type { ImportLoader, ImportLoaderRegistrationOptions, } from "./import-loader.ts"; -import { SourceTransformer, typeScriptSpecifier } from "./transform-source.ts"; +import { + filePathOfUrl, + isFileLikeSpecifier, + isProjectPath, + SpecifierResolver, + splitSpecifierMetadata, +} from "./resolve-specifier.ts"; +import { SourceTransformer } from "./transform-source.ts"; export type { ImportLoader as RegisteredOxcImporter, @@ -31,6 +40,11 @@ interface ImportRequest { readonly specifier: string; } +type NextResolve = ( + specifier: string, + context?: Partial, +) => ResolveFnOutput; + const namespaceOf = (url: string | undefined) => { if (url === undefined || !url.startsWith("file:")) return undefined; return new URL(url).searchParams.get(namespaceParameter) ?? undefined; @@ -54,31 +68,137 @@ const parseRequest = (specifier: string): ImportRequest | undefined => { return JSON.parse(decodeURIComponent(specifier.slice(protocol.length))); }; -const resolve = ( +/** Specifiers Node owns outright: builtins, data URLs, remote schemes. */ +const isForeignSpecifier = (specifier: string) => + /^(?:node:|data:|[a-z][a-z\d+.-]*:\/\/)/i.test(specifier) && + !specifier.startsWith("file:"); + +const notFoundCodes = new Set([ + "ERR_MODULE_NOT_FOUND", + "MODULE_NOT_FOUND", + "ERR_UNSUPPORTED_DIR_IMPORT", + "ERR_PACKAGE_PATH_NOT_EXPORTED", +]); + +const isNotFound = (error: unknown): error is Error & { url?: string } => + error instanceof Error && + notFoundCodes.has((error as { code?: string }).code ?? ""); + +/** + * The file Node could not find, from the error it raised. Node names the + * resolved target (`url` on ESM errors, the message on CommonJS ones) — + * for a package `exports` entry pointing at emitted JavaScript that was + * never built, that is the `.js` path whose `.ts` source we can substitute. + */ +const missingPathOf = (error: Error & { url?: string }) => { + if (error.url !== undefined) return filePathOfUrl(error.url); + const match = error.message.match(/^Cannot find module '([^']+)'/); + if (match === null) return undefined; + const [, target] = match; + if (target === undefined) return undefined; + if (target.startsWith("file:")) return filePathOfUrl(target); + return target.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(target) + ? target + : undefined; +}; + +/** A `require()` reaching the hooks: Node's CommonJS resolver wants paths, not URLs. */ +const isRequireContext = (context: ResolveHookContext) => + context.conditions?.includes("require") === true && + !context.conditions.includes("import"); + +const resolveWithCandidate = ( + candidate: string, + metadata: string, + context: ResolveHookContext, + nextResolve: NextResolve, +): ResolveFnOutput | undefined => { + const specifier = isRequireContext(context) + ? candidate + metadata + : pathToFileURL(candidate).href + metadata; + try { + return nextResolve(specifier, context); + } catch { + return undefined; + } +}; + +/** + * tsx-compatible resolution. Node's resolver decides in the end; Oxc's + * resolver supplies the TypeScript-aware candidate (tsconfig `paths`, + * `.js` → `.ts` substitution, extensionless and directory imports) that + * Node would not find on its own. + */ +const resolveSpecifier = ( + resolver: SpecifierResolver, specifier: string, context: ResolveHookContext, - nextResolve: ( - specifier: string, - context?: Partial, - ) => ResolveFnOutput, + nextResolve: NextResolve, ): ResolveFnOutput => { + if (isForeignSpecifier(specifier)) return nextResolve(specifier, context); + + const parentPath = filePathOfUrl(context.parentURL); + const { specifier: clean, metadata } = splitSpecifierMetadata(specifier); + const conditions = context.conditions ?? []; + + // TypeScript's rules apply to project code. Dependencies keep Node's plain + // resolution so published packages behave exactly as they would without us. + if (parentPath !== undefined && isProjectPath(parentPath)) { + const candidate = resolver.resolve(parentPath, clean, conditions); + if (candidate !== undefined) { + const resolved = resolveWithCandidate( + candidate, + metadata, + context, + nextResolve, + ); + if (resolved !== undefined) return resolved; + } + } + try { return nextResolve(specifier, context); } catch (error) { - const alternative = typeScriptSpecifier(specifier); - if (alternative === undefined) throw error; - try { - return nextResolve(alternative, context); - } catch { - throw error; + if (!isNotFound(error)) throw error; + // A package `exports`/`main` target naming emitted JavaScript that only + // exists as TypeScript source (workspace packages in a checkout). + const missing = missingPathOf(error); + if (missing !== undefined && isFileLikeSpecifier(missing)) { + const candidate = resolver.resolveMissing(missing, conditions); + if (candidate !== undefined && candidate !== missing) { + const resolved = resolveWithCandidate( + candidate, + metadata, + context, + nextResolve, + ); + if (resolved !== undefined) return resolved; + } } + throw error; } }; +/** + * `import data from "./x.json"` without an import attribute is how + * TypeScript projects import JSON (`resolveJsonModule`); Node insists on + * `with { type: "json" }` for ESM. Supply it, as tsx does. + */ +const withJsonAttribute = (url: string, context: LoadHookContext) => { + if (!/\.json(?:[?#]|$)/.test(url) || context.importAttributes?.type) { + return context; + } + return { + ...context, + importAttributes: { ...context.importAttributes, type: "json" }, + }; +}; + /** * Registers synchronous Node module hooks that transpile TypeScript with - * Rolldown's Oxc transformer. A namespaced registration also provides a - * scoped import whose namespace propagates through the complete ESM graph. + * Rolldown's Oxc transformer and resolve it the way TypeScript (and tsx) + * does. A namespaced registration also provides a scoped import whose + * namespace propagates through the complete ESM graph. */ export const registerOxc = ( options: ImportLoaderRegistrationOptions = {}, @@ -96,7 +216,16 @@ export const registerOxc = ( if (existing !== undefined) return existing; } const transformer = new SourceTransformer(options); + const resolver = new SpecifierResolver({ + tsconfig: options.tsconfig ?? true, + }); const shouldInvalidate = options.shouldInvalidate ?? (() => true); + + // Transformed sources carry inline source maps; Node only applies them to + // stack traces once source-map support is on. + const sourceMapsWereEnabled = process.sourceMapsEnabled; + process.setSourceMapsEnabled(true); + const hooks = registerHooks({ resolve(specifier, context, nextResolve) { const request = parseRequest(specifier); @@ -111,12 +240,13 @@ export const registerOxc = ( } const resolved = request - ? resolve( + ? resolveSpecifier( + resolver, request.specifier, { ...context, parentURL: request.parentURL }, nextResolve, ) - : resolve(specifier, context, nextResolve); + : resolveSpecifier(resolver, specifier, context, nextResolve); if ( namespace !== undefined && resolved.url.startsWith("file:") && @@ -138,15 +268,21 @@ export const registerOxc = ( } const cleanUrl = withoutNamespace(url); - if (!cleanUrl.startsWith("file:")) return nextLoad(cleanUrl, context); + const filePath = filePathOfUrl(cleanUrl); + if (filePath === undefined) return nextLoad(cleanUrl, context); options.onImport?.(cleanUrl); - const filePath = fileURLToPath(cleanUrl); if (options.filter !== undefined && !options.filter(filePath)) { - return nextLoad(cleanUrl, context); + return nextLoad(cleanUrl, withJsonAttribute(cleanUrl, context)); + } + const transformed = transformer.transform( + filePath, + cleanUrl, + context.format, + ); + if (transformed === undefined) { + return nextLoad(cleanUrl, withJsonAttribute(cleanUrl, context)); } - const transformed = transformer.transform(filePath, cleanUrl); - if (transformed === undefined) return nextLoad(cleanUrl, context); return { ...transformed, shortCircuit: true }; }, }); @@ -169,6 +305,7 @@ export const registerOxc = ( if (globalRegistration[globalRegistrationKey] === loader) { delete globalRegistration[globalRegistrationKey]; } + if (sourceMapsWereEnabled === false) process.setSourceMapsEnabled(false); }, }; if (options.namespace === undefined) { @@ -176,3 +313,18 @@ export const registerOxc = ( } return loader; }; + +/** + * One-shot TypeScript import that leaves the rest of the runtime untouched: + * a private namespace is registered for the call, so nothing is shared with + * other imports of the same files. Mirrors tsx's `tsImport`. + */ +export const tsImport = ( + specifier: string, + parentURL: string, + options: Omit = {}, +): Promise => + registerOxc({ ...options, namespace: randomUUID() }).import( + specifier, + parentURL, + ); diff --git a/packages/node-utils/src/resolve-specifier.ts b/packages/node-utils/src/resolve-specifier.ts new file mode 100644 index 00000000000..f0e4634fbdb --- /dev/null +++ b/packages/node-utils/src/resolve-specifier.ts @@ -0,0 +1,179 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { ResolverFactory, type ResolveOptions } from "rolldown/experimental"; + +/** + * TypeScript-aware specifier resolution on top of Oxc's resolver, mirroring + * what tsx layers over Node's resolver: + * + * - `tsconfig.json` `paths` / `baseUrl` aliases, discovered per importing file + * - emitted-extension substitution (`./x.js` → `x.ts`/`x.tsx`, `.mjs` → `.mts`, + * `.cjs` → `.cts`, `.jsx` → `.tsx`), TypeScript source winning over an + * emitted sibling + * - extensionless specifiers and directory indexes, TypeScript first + * + * Node's own resolver stays the authority: every candidate this class + * produces is handed back to Node (`nextResolve`) so it decides the format, + * validates package exports, and reports the canonical error. + */ +export interface SpecifierResolverOptions { + /** Discover `tsconfig.json` upward from each importing file. */ + readonly tsconfig: boolean; +} + +export const nodeModulesSegment = `${path.sep}node_modules${path.sep}`; + +/** Local project code: a file path outside every `node_modules` directory. */ +export const isProjectPath = (filePath: string) => + !filePath.includes(nodeModulesSegment); + +const typeScriptExtensions = /\.(?:[cm]?ts|[tj]sx)$/; + +/** Whether TypeScript's extension substitution applies to this importer. */ +export const isTypeScriptPath = (filePath: string) => + typeScriptExtensions.test(filePath); + +export const isFileLikeSpecifier = (specifier: string) => + specifier.startsWith("./") || + specifier.startsWith("../") || + specifier === "." || + specifier === ".." || + specifier.startsWith("file:") || + path.isAbsolute(specifier); + +/** + * Splits `?query#fragment` metadata off a specifier. Bare specifiers never + * carry fragments in Node, so only `?` is honoured there. + */ +export const splitSpecifierMetadata = (specifier: string) => { + const index = isFileLikeSpecifier(specifier) + ? specifier.search(/[?#]/) + : specifier.indexOf("?"); + return index === -1 + ? { specifier, metadata: "" } + : { + specifier: specifier.slice(0, index), + metadata: specifier.slice(index), + }; +}; + +export const filePathOfUrl = (url: string | undefined) => { + if (url === undefined || !url.startsWith("file:")) return undefined; + try { + return fileURLToPath(new URL(url)); + } catch { + return undefined; + } +}; + +export class SpecifierResolver { + readonly #options: ResolveOptions; + readonly #base: ResolverFactory; + readonly #byConditions = new Map(); + + constructor(options: SpecifierResolverOptions) { + this.#options = { + tsconfig: options.tsconfig ? "auto" : undefined, + // TypeScript source first, then Node's implicit extensions. + extensions: [ + ".ts", + ".tsx", + ".mts", + ".cts", + ".jsx", + ".js", + ".mjs", + ".cjs", + ".json", + ".node", + ], + // TypeScript's emitted-extension substitution: `./x.js` may point at + // `x.ts` (source) or `x.js` (emitted); source wins when both exist. + extensionAlias: { + ".js": [".ts", ".tsx", ".js"], + ".jsx": [".tsx", ".jsx"], + ".mjs": [".mts", ".mjs"], + ".cjs": [".cts", ".cjs"], + }, + mainFiles: ["index"], + builtinModules: true, + moduleType: true, + }; + this.#base = new ResolverFactory(this.#options); + } + + /** + * Bare specifiers are probed without following symlinks: a workspace + * package linked into `node_modules` must still read as a package (and be + * left to Node), not as the project file its real path points at. + */ + #resolver(conditions: ReadonlyArray, symlinks: boolean) { + const key = `${symlinks} ${conditions.join(" ")}`; + let resolver = this.#byConditions.get(key); + if (resolver === undefined) { + // `cloneWithOptions` replaces the option set (sharing only the cache), + // so each conditions variant restates the base options. + resolver = this.#base.cloneWithOptions({ + ...this.#options, + symlinks, + conditionNames: [...conditions], + }); + this.#byConditions.set(key, resolver); + } + return resolver; + } + + /** + * Resolves `specifier` as imported from `parentPath` to an absolute file + * path, or `undefined` when Oxc cannot resolve it (Node then reports the + * error), when it is a builtin, or when a bare specifier lands inside + * `node_modules` — packages are Node's business, only `paths` aliases + * that map onto project files are ours. + */ + resolve( + parentPath: string, + specifier: string, + conditions: ReadonlyArray, + ): string | undefined { + const request = specifier.startsWith("file:") + ? filePathOfUrl(specifier) + : specifier; + if (request === undefined) return undefined; + let result; + try { + result = this.#resolver( + conditions, + isFileLikeSpecifier(request), + ).resolveFileSync(parentPath, request); + } catch { + return undefined; + } + if (result.path === undefined) return undefined; + if (!isFileLikeSpecifier(request) && !isProjectPath(result.path)) { + return undefined; + } + return result.path; + } + + /** + * Given a file path Node failed to find (typically an `exports`/`main` + * target that names emitted JavaScript that was never built), finds the + * TypeScript source it was emitted from via extension substitution. + */ + resolveMissing( + missingPath: string, + conditions: ReadonlyArray, + ): string | undefined { + const directory = path.dirname(missingPath); + const base = path.basename(missingPath); + try { + const result = this.#resolver(conditions, true).sync( + directory, + `./${base}`, + ); + return result.path; + } catch { + return undefined; + } + } +} diff --git a/packages/node-utils/src/transform-source.ts b/packages/node-utils/src/transform-source.ts index e167192969d..bc331e1f882 100644 --- a/packages/node-utils/src/transform-source.ts +++ b/packages/node-utils/src/transform-source.ts @@ -1,36 +1,48 @@ import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import { + parseSync, transformSync, TsconfigCache, type TransformOptions, } from "rolldown/utils"; import type { ImportLoaderOptions, TransformContext } from "./import-loader.ts"; -export const transformExtensions = new Set([".ts", ".tsx", ".mts", ".cts"]); +/** Extensions Oxc transpiles; everything else is JavaScript Node can run. */ +export const transformExtensions = new Set([ + ".ts", + ".tsx", + ".mts", + ".cts", + ".jsx", +]); -export const typeScriptSpecifier = (specifier: string): string | undefined => { - const metadataIndex = specifier.search(/[?#]/); - const path = - metadataIndex === -1 ? specifier : specifier.slice(0, metadataIndex); - const metadata = metadataIndex === -1 ? "" : specifier.slice(metadataIndex); - if (path.endsWith(".js")) return `${path.slice(0, -3)}.ts${metadata}`; - if (path.endsWith(".jsx")) return `${path.slice(0, -4)}.tsx${metadata}`; - if (path.endsWith(".mjs")) return `${path.slice(0, -4)}.mts${metadata}`; - if (path.endsWith(".cjs")) return `${path.slice(0, -4)}.cts${metadata}`; - return undefined; +export type ModuleFormat = "module" | "commonjs"; + +/** + * Module format from Node's `load` hook context. Node derives these from the + * extension and the nearest `package.json#type`; `*-typescript` variants are + * its TypeScript-aware spellings and mean the same thing. + */ +const nodeFormat = ( + format: string | null | undefined, +): ModuleFormat | undefined => { + switch (format) { + case "module": + case "module-typescript": + return "module"; + case "commonjs": + case "commonjs-typescript": + return "commonjs"; + default: + return undefined; + } }; -const moduleFormat = (filePath: string): "module" | "commonjs" => { +/** Fallback for older Nodes that pass no format: extension, then package type. */ +const inferFormat = (filePath: string): ModuleFormat => { const extension = path.extname(filePath); - if ( - extension === ".ts" || - extension === ".tsx" || - extension === ".mts" || - extension === ".mjs" - ) { - return "module"; - } + if (extension === ".mts" || extension === ".mjs") return "module"; if (extension === ".cts" || extension === ".cjs") return "commonjs"; let directory = path.dirname(filePath); while (true) { @@ -70,6 +82,11 @@ const sourceMapComment = (map: string | object) => { return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(json).toString("base64")}`; }; +export interface TransformedSource { + readonly format: ModuleFormat; + readonly source: string; +} + export class SourceTransformer { readonly #options: ImportLoaderOptions; readonly #tsconfigCache = new TsconfigCache(); @@ -78,42 +95,65 @@ export class SourceTransformer { this.#options = options; } + /** + * Transpiles `filePath` for Node, or returns `undefined` when the file is + * JavaScript that needs no work. `format` is what Node's `load` hook was + * told; it decides `sourceType` and the format handed back. + */ transform( filePath: string, url: string, - ): - | { readonly format: "module" | "commonjs"; readonly source: string } - | undefined { + format: string | null | undefined, + ): TransformedSource | undefined { const extension = path.extname(filePath); - if ( - !transformExtensions.has(extension) && - this.#options.transforms === undefined - ) { - return undefined; - } + const transpile = transformExtensions.has(extension); + if (!transpile && this.#options.transforms === undefined) return undefined; - const format = moduleFormat(filePath); + let moduleFormat = nodeFormat(format) ?? inferFormat(filePath); let source = readFileSync(filePath, "utf8"); let map: string | object | undefined; - if (transformExtensions.has(extension)) { + if (transpile) { + const lang = this.#options.transform?.lang ?? language(filePath); + // A `.ts` file in a CommonJS package that uses `import`/`export` runs + // as ESM — the same call Node's own module-syntax detection makes for + // `.js`. Explicit `.cts` stays CommonJS regardless. + if ( + moduleFormat === "commonjs" && + extension !== ".cts" && + parseSync(filePath, source, { lang, sourceType: "unambiguous" }).module + .hasModuleSyntax + ) { + moduleFormat = "module"; + } const transformed = transformSync( filePath, source, { - tsconfig: true, + tsconfig: this.#options.tsconfig ?? true, sourcemap: true, ...this.#options.transform, - lang: this.#options.transform?.lang ?? language(filePath), - sourceType: this.#options.transform?.sourceType ?? format, + lang, + sourceType: this.#options.transform?.sourceType ?? moduleFormat, }, this.#tsconfigCache, ); - if (transformed.errors.length > 0) throw transformed.errors[0]; + if (transformed.errors.length > 0) { + const [error] = transformed.errors; + throw error instanceof Error + ? error + : new SyntaxError( + `${filePath}: ${(error as { message?: string }).message ?? String(error)}`, + ); + } source = transformed.code; map = transformed.map; } - const context: TransformContext = { url, path: filePath, format }; + const context: TransformContext = { + url, + path: filePath, + format: moduleFormat, + }; for (const transform of this.#options.transforms ?? []) { const result = transform(source, context); if (typeof result === "string") { @@ -125,6 +165,6 @@ export class SourceTransformer { } } if (map !== undefined) source += sourceMapComment(map); - return { format, source }; + return { format: moduleFormat, source }; } } diff --git a/packages/node-utils/src/watch-import-bun.ts b/packages/node-utils/src/watch-import-bun.ts index 5ef6a65eb6c..285a2635bf6 100644 --- a/packages/node-utils/src/watch-import-bun.ts +++ b/packages/node-utils/src/watch-import-bun.ts @@ -1,3 +1,4 @@ +import { realpathSync } from "node:fs"; import path from "node:path"; import { DependencyWatcher, @@ -49,7 +50,9 @@ export class BunImportTracker { ); } this.#watcher = new DependencyWatcher(options); - const root = path.resolve(options.root) + path.sep; + // Bun reports real paths (`/private/tmp/...` for `/tmp/...` on macOS); + // match them against the root's real path too. + const root = realpathSync.native(path.resolve(options.root)) + path.sep; const nodeModules = `${path.sep}node_modules${path.sep}`; const filter = new RegExp( `^${escapeRegExp(root)}(?!.*${escapeRegExp(nodeModules)}).*\\.[cm]?[jt]sx?$`, diff --git a/packages/node-utils/test/register-oxc.test.ts b/packages/node-utils/test/register-oxc.test.ts new file mode 100644 index 00000000000..2f53bdd6e4b --- /dev/null +++ b/packages/node-utils/test/register-oxc.test.ts @@ -0,0 +1,195 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const temporaryDirectories: string[] = []; + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { force: true, recursive: true }); + } +}); + +const write = (file: string, content: string) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, content); +}; + +/** + * A project exercising everything tsx layers over Node that a TypeScript + * codebase relies on: tsconfig `paths`, emitted-extension imports, implicit + * extensions and directory indexes, JSON without attributes, TSX with a + * tsconfig-selected runtime, a workspace dependency whose `exports` name + * unbuilt JavaScript, and `require()` from a `.cts` into ESM TypeScript. + */ +const makeProject = () => { + const root = realpathSync( + mkdtempSync(path.join(os.tmpdir(), "alchemy-register-oxc-")), + ); + temporaryDirectories.push(root); + const at = (file: string) => path.join(root, file); + write(at("package.json"), '{"type":"module"}'); + write( + at("tsconfig.json"), + JSON.stringify({ + compilerOptions: { + jsx: "react-jsx", + jsxImportSource: "myjsx", + baseUrl: ".", + paths: { "@lib/*": ["src/lib/*"] }, + }, + }), + ); + write( + at("node_modules/myjsx/package.json"), + '{"name":"myjsx","type":"module","exports":{"./jsx-runtime":"./jsx-runtime.js","./jsx-dev-runtime":"./jsx-runtime.js"}}', + ); + write( + at("node_modules/myjsx/jsx-runtime.js"), + "export const jsx = (tag, props) => ({ tag, props });\nexport const jsxs = jsx;\nexport const jsxDEV = jsx;\nexport const Fragment = 'F';\n", + ); + write( + at("node_modules/wsdep/package.json"), + '{"name":"wsdep","type":"module","exports":{".":"./src/index.js"}}', + ); + write( + at("node_modules/wsdep/src/index.ts"), + 'export const fromWorkspaceDep: string = "ws";\n', + ); + write( + at("src/lib/helper.ts"), + 'export const helper = (): string => "helper";\n', + ); + write(at("src/lib/helper.js"), 'export const helper = () => "emitted";\n'); + write(at("src/dir/index.ts"), 'export const index = "dir-index";\n'); + write(at("src/sub.ts"), 'export const sub = "sub";\n'); + write(at("src/data.json"), '{ "answer": 42 }'); + write(at("src/View.tsx"), 'export const view =

hi

;\n'); + write(at("cjs/package.json"), '{"type":"commonjs"}'); + write( + at("cjs/esmish.ts"), + "export const value: number = 7;\nexport class A { constructor(readonly x: number) {} }\n", + ); + write( + at("cjs/consumer.cts"), + 'const { value, A } = require("./esmish.ts");\nconst sub = require("../src/sub");\nmodule.exports = { viaRequire: new A(value).x + 1, sub: sub.sub };\n', + ); + write( + at("src/entry.ts"), + [ + 'import { helper } from "@lib/helper";', + 'import { helper as helperJs } from "./lib/helper.js";', + 'import { sub } from "./sub";', + 'import { index } from "./dir";', + 'import { index as index2 } from "./dir/";', + 'import data from "./data.json";', + 'import { view } from "./View.tsx";', + 'import { fromWorkspaceDep } from "wsdep";', + 'import consumer from "../cjs/consumer.cts";', + "export const report = {", + " helper: helper(), helperJs: helperJs(), sub, index, index2,", + " data: data.answer, view: view.tag, fromWorkspaceDep,", + " viaRequire: consumer.viaRequire, requiredSub: consumer.sub,", + "};", + "export const boom = (): never => {", + ' throw new Error("boom");', + "};", + ].join("\n"), + ); + return root; +}; + +const registerUrl = pathToFileURL( + path.resolve(import.meta.dir, "../src/register-oxc.ts"), +).href; + +const runNode = (cwd: string, script: string) => + spawnSync("node", ["--no-warnings", "--input-type=module", "-e", script], { + cwd, + encoding: "utf8", + timeout: 20_000, + }); + +describe("registerOxc", () => { + it("resolves and transpiles TypeScript the way tsx does", () => { + const root = makeProject(); + const result = runNode( + root, + ` + const { registerOxc } = await import(${JSON.stringify(registerUrl)}); + registerOxc(); + const entry = await import("./src/entry.ts"); + console.log(JSON.stringify(entry.report)); + try { entry.boom(); } catch (error) { console.log(error.stack.split("\\n")[1].trim()); } + `, + ); + expect(result.status, result.stderr).toBe(0); + const [report, frame] = result.stdout.trim().split("\n"); + expect(JSON.parse(report!)).toEqual({ + // tsconfig paths alias + helper: "helper", + // `.js` import prefers the `.ts` source over the emitted sibling + helperJs: "helper", + // extensionless and directory imports + sub: "sub", + index: "dir-index", + index2: "dir-index", + // JSON without an import attribute + data: 42, + // TSX through the tsconfig's jsxImportSource + view: "p", + // dependency `exports` pointing at unbuilt JavaScript + fromWorkspaceDep: "ws", + // `.cts` requiring `.ts` (parameter property) and an extensionless path + viaRequire: 8, + requiredSub: "sub", + }); + // Inline source maps are applied to stack traces. + expect(frame).toMatch(/entry\.ts:16:/); + }); + + it("isolates namespaced imports and leaves node_modules to Node with a filter", () => { + const root = makeProject(); + const result = runNode( + root, + ` + const { registerOxc, tsImport } = await import(${JSON.stringify(registerUrl)}); + const state = globalThis; + state.count = 0; + const seen = []; + const api = registerOxc({ namespace: "one", onImport: (url) => seen.push(url.split("/").pop()) }); + const a = await api.import("./src/sub.ts", import.meta.url); + const b = await api.import("./src/sub.ts", import.meta.url); + const c = await tsImport("./src/sub.ts", import.meta.url); + console.log(JSON.stringify({ same: a === b, fresh: a !== c, seen })); + api.unregister(); + registerOxc({ filter: (file) => !file.includes("/node_modules/") }); + try { + await import("wsdep"); + console.log("wsdep: loaded"); + } catch (error) { + console.log("wsdep: " + error.code); + } + `, + ); + expect(result.status, result.stderr).toBe(0); + const [scoped, filtered] = result.stdout.trim().split("\n"); + expect(JSON.parse(scoped!)).toEqual({ + same: true, + fresh: true, + seen: ["sub.ts"], + }); + // With node_modules filtered out, the dependency's `.ts` is Node's to + // reject: the loader neither transpiles nor rewrites it. + expect(filtered).toBe("wsdep: ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING"); + }); +}); diff --git a/packages/node-utils/test/watch-import.test.ts b/packages/node-utils/test/watch-import.test.ts index 559f9bd87f2..7c920fe9cd8 100644 --- a/packages/node-utils/test/watch-import.test.ts +++ b/packages/node-utils/test/watch-import.test.ts @@ -111,14 +111,7 @@ describe("watchImport", () => { const result = spawnSync( "node", - [ - "--experimental-transform-types", - "--no-warnings=ExperimentalWarning", - "--input-type=module", - "-e", - script, - directory, - ], + ["--no-warnings", "--input-type=module", "-e", script, directory], { encoding: "utf8", timeout: 10_000 }, ); From 180f7a2613b67e1a57ec1f94eee0bfb0af44a0e7 Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 18:35:06 +0530 Subject: [PATCH 5/9] fix(cli): surface plan failures instead of a bare "Interrupted." MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plan whose resource references an undeployed stage reported its `InvalidReferenceError` only some of the time; otherwise dev printed a bare "Interrupted." and stopped. Same rate on main — `node --watch` just left the dead process around, so it was less visible. Two causes: - Resource diffs run concurrently and share memoized resolutions built with `Effect.cached`, which evaluates on the first caller's fiber. When that caller is cancelled, every waiter fails interrupt-only, and a fail-fast `Effect.all` lets that cancellation become the aggregate cause before the real failure arrives. - `devKeepAlive` treated an interrupt-only cause as Ctrl+C and exited. The plan now collects every diff's exit and reports real failures ahead of cancellations; the per-resource resolution memo runs in a detached fiber owned by the plan's own scope (`cachedInScope`), so a cancelled diff cannot poison it; and the keep-alive parks on internal interruptions too, printing the cause with a note that it is an engine/provider bug. Ctrl+C still tears the run down: it interrupts the fiber running the keep-alive rather than failing the effect it wraps. Verified on a stack with the failing shape against a remote state store: 5/5 runs report the error and park (2/5 died before, on main and here). --- packages/alchemy/src/Cli/exec.ts | 42 ++++++++--- packages/alchemy/src/Plan.ts | 42 +++++++++-- packages/alchemy/src/Util/Memoize.ts | 48 ++++++++++++ .../alchemy/test/Cli/devKeepAlive.test.ts | 32 ++++++-- packages/alchemy/test/Util/Memoize.test.ts | 73 +++++++++++++++++++ 5 files changed, 211 insertions(+), 26 deletions(-) create mode 100644 packages/alchemy/src/Util/Memoize.ts create mode 100644 packages/alchemy/test/Util/Memoize.test.ts diff --git a/packages/alchemy/src/Cli/exec.ts b/packages/alchemy/src/Cli/exec.ts index b494d07a4e6..14b48199495 100644 --- a/packages/alchemy/src/Cli/exec.ts +++ b/packages/alchemy/src/Cli/exec.ts @@ -94,11 +94,13 @@ const runDev = Effect.fn(function* (options: DevOptions) { ? applyPlan : applyPlan.pipe( Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Console.error( - `alchemy dev: apply failed; keeping dev alive so healthy resources keep serving.\n${Cause.pretty(cause)}`, - ).pipe(Effect.as(undefined)), + Console.error( + describeFailure( + "apply", + cause, + "keeping dev alive so healthy resources keep serving", + ), + ).pipe(Effect.as(undefined)), ), ); if (result !== undefined && once) { @@ -214,18 +216,36 @@ const runBunDevWatcher = (options: DevOptions) => ), ); +/** + * A run that ended by itself with nothing but interruptions in its cause was + * cancelled from the inside — a provider or engine race, never the user — + * so it must be reported like any other failure. Ctrl+C is different: it + * interrupts the fiber running this code, so `catchCause` never gets to + * park it (a parked `Effect.never` is interrupted straight away too). + */ +const describeFailure = ( + what: string, + cause: Cause.Cause, + next: string, +) => + Cause.hasInterruptsOnly(cause) + ? `alchemy dev: ${what} was interrupted internally (a bug in a provider or the engine — please report it with the trace below); ${next}.\n${Cause.pretty(cause)}` + : `alchemy dev: ${what} failed; ${next}.\n${Cause.pretty(cause)}`; + // A mid-edit import or planning failure must keep the watch process alive so -// the next save can restart it. Interruptions still propagate for Ctrl+C. +// the next save can restart it. Ctrl+C still tears the run down. export const devKeepAlive = ( effect: Effect.Effect, ): Effect.Effect => effect.pipe( Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Console.error( - `alchemy dev: run failed; waiting for the next file change to retry.\n${Cause.pretty(cause)}`, - ).pipe(Effect.andThen(Effect.never)), + Console.error( + describeFailure( + "run", + cause, + "waiting for the next file change to retry", + ), + ).pipe(Effect.andThen(Effect.never)), ), ); diff --git a/packages/alchemy/src/Plan.ts b/packages/alchemy/src/Plan.ts index 62c084c9c5d..357d81d5a3b 100644 --- a/packages/alchemy/src/Plan.ts +++ b/packages/alchemy/src/Plan.ts @@ -1,10 +1,13 @@ /** @effect-diagnostics anyUnknownInErrorContext:off */ /** @effect-diagnostics missingEffectError:off */ +import * as Cause from "effect/Cause"; import * as Config from "effect/Config"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import { cachedInScope } from "./Util/Memoize.ts"; import { asEffect } from ".//Util/types.ts"; import { isAction, type ActionLike } from "./Action.ts"; import { @@ -665,6 +668,10 @@ export const make = ( return { row, renamedFrom: undefined, renameMoved: false }; }); + // Shared resolutions run in fibers of the plan's own scope (see + // `cachedInScope`): a diff that fails or is cancelled must not take the + // resolution every other diff is waiting on down with it. + const memoScope = yield* Effect.scope; const resolvedResources: Record> = {}; const resolveResource = ( @@ -679,7 +686,7 @@ export const make = ( } // @ts-expect-error return yield* (resolvedResources[resourceExpr.src.FQN] ??= - yield* Effect.cached( + yield* cachedInScope(memoScope)( Effect.gen(function* () { const resource = resourceExpr.src; @@ -1679,13 +1686,32 @@ export const make = ( } }); + // Every diff runs to completion and every failure is reported. With + // fail-fast `Effect.all`, the first exit to arrive wins the aggregate + // cause — and when a diff is cancelled by a sibling's failure (or ends + // interrupt-only for any other reason) that can be a bare interruption, + // hiding the InvalidReferenceError or provider error that actually + // broke the plan. + const diffExits = yield* Effect.all( + resources.map((resource) => + Effect.exit(Effect.tap(diffResource(resource), resourcePlanned)), + ), + { concurrency: "unbounded" }, + ); + const diffFailures = diffExits.filter(Exit.isFailure); + if (diffFailures.length > 0) { + const reasons = diffFailures.flatMap((exit) => exit.cause.reasons); + const failures = reasons.filter( + (reason) => !Cause.isInterruptReason(reason), + ); + return yield* Effect.failCause( + Cause.fromReasons(failures.length > 0 ? failures : reasons), + ); + } const resourceGraph = Object.fromEntries( - (yield* Effect.all( - resources.map((resource) => - Effect.tap(diffResource(resource), resourcePlanned), - ), - { concurrency: "unbounded" }, - )).map((update) => [update.resource.FQN, update]), + diffExits + .filter(Exit.isSuccess) + .map((exit) => [exit.value.resource.FQN, exit.value]), ) as Plan["resources"]; // ── Action plan nodes ──────────────────────────────────────────────── @@ -2058,6 +2084,8 @@ export const make = ( defaultMode: runDefaultMode, } satisfies Plan as Plan; }).pipe( + // Owns the memoized resolutions' fibers for the plan's duration. + Effect.scoped, ensureArtifactStore, Effect.withSpan("plan.make", { attributes: { diff --git a/packages/alchemy/src/Util/Memoize.ts b/packages/alchemy/src/Util/Memoize.ts new file mode 100644 index 00000000000..c68c0b5f525 --- /dev/null +++ b/packages/alchemy/src/Util/Memoize.ts @@ -0,0 +1,48 @@ +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Scope from "effect/Scope"; + +/** + * A lazily evaluated, memoized effect whose computation runs in a fiber of + * its own, owned by `scope`. + * + * `Effect.cached` evaluates on the fiber of whichever caller gets there + * first. When that caller is interrupted while others are waiting — a + * concurrent plan cancelling sibling diffs — every waiter fails + * interrupt-only and the cache stays poisoned for the rest of the process. + * A computation that many fibers share must not have that failure mode: here + * it runs detached from every caller, so interrupting a waiter never touches + * it, and only closing `scope` cancels it (its waiters then see the + * interruption, as they should). + * + * Requirements are captured from the first caller, exactly as + * `Effect.cached` does. + */ +export const cachedInScope = + (scope: Scope.Scope) => + ( + effect: Effect.Effect, + ): Effect.Effect, never, R> => + Effect.gen(function* () { + const context = yield* Effect.context(); + const deferred = yield* Deferred.make(); + let started = false; + return Effect.suspend(() => { + if (started) return Deferred.await(deferred); + started = true; + return effect.pipe( + Effect.provideContext(context), + // `onExit` also runs on interruption, so the waiters always learn + // how the computation ended. + Effect.onExit((exit) => Deferred.done(deferred, exit)), + // Not a child of the caller: the caller's interruption must not + // reach it. The scope owns its lifetime instead. + Effect.forkDetach, + Effect.flatMap((fiber) => + Scope.addFinalizer(scope, Fiber.interrupt(fiber)), + ), + Effect.andThen(Deferred.await(deferred)), + ); + }); + }); diff --git a/packages/alchemy/test/Cli/devKeepAlive.test.ts b/packages/alchemy/test/Cli/devKeepAlive.test.ts index b407de1a9ea..aa8c9a8a436 100644 --- a/packages/alchemy/test/Cli/devKeepAlive.test.ts +++ b/packages/alchemy/test/Cli/devKeepAlive.test.ts @@ -36,14 +36,30 @@ describe("devKeepAlive", () => { ), ).resolves.toBe(true)); - test("an interrupt-only cause propagates instead of parking", async () => { - const exit = await Effect.runPromiseExit( - devKeepAlive(Effect.failCause(Cause.interrupt())), - ); - expect(exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)).toBe( - true, - ); - }); + // A run that ends by itself with nothing but interruptions in its cause was + // cancelled from the inside (a provider or engine race), not by the user. + // It must park like any other failure; letting it propagate exited dev + // with a bare "Interrupted." and no hint of what went wrong (#1461). + test("an internal interrupt-only cause parks instead of exiting", () => + expect( + parks(devKeepAlive(Effect.failCause(Cause.interrupt()))), + ).resolves.toBe(true)); + + test("interruption tears down a run that is still working (Ctrl-C in dev)", () => + expect( + Effect.runPromise( + Effect.gen(function* () { + const fiber = yield* Effect.forkChild( + devKeepAlive(Effect.sleep("1 second")), + ); + yield* Effect.sleep("20 millis"); + const exit = yield* Fiber.interrupt(fiber).pipe( + Effect.andThen(Fiber.await(fiber)), + ); + return exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause); + }), + ), + ).resolves.toBe(true)); test("interruption still tears down a parked run (Ctrl-C in dev)", () => expect( diff --git a/packages/alchemy/test/Util/Memoize.test.ts b/packages/alchemy/test/Util/Memoize.test.ts new file mode 100644 index 00000000000..23a0f2976fc --- /dev/null +++ b/packages/alchemy/test/Util/Memoize.test.ts @@ -0,0 +1,73 @@ +import { cachedInScope } from "@/Util/Memoize.ts"; +import { describe, expect, it } from "alchemy-test"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Scope from "effect/Scope"; + +// `Effect.cached` runs the computation on the first caller's fiber, so +// interrupting that caller while others wait fails every waiter with an +// interrupt-only cause and leaves the cache poisoned. These pin the +// behaviour `cachedInScope` exists for. +describe("cachedInScope", () => { + it.live("survives the first caller being interrupted", () => + Effect.gen(function* () { + const scope = yield* Scope.make(); + let runs = 0; + const memo = yield* cachedInScope(scope)( + Effect.sleep("100 millis").pipe( + Effect.map(() => { + runs++; + return 42; + }), + ), + ); + const owner = yield* Effect.forkChild(memo); + yield* Effect.sleep("10 millis"); + const waiter = yield* Effect.forkChild(memo); + yield* Effect.sleep("10 millis"); + yield* Fiber.interrupt(owner); + + expect(yield* Fiber.join(waiter)).toBe(42); + expect(yield* memo).toBe(42); + expect(runs).toBe(1); + yield* Scope.close(scope, Exit.void); + }), + ); + + it.live("runs once and shares failures with every waiter", () => + Effect.gen(function* () { + const scope = yield* Scope.make(); + let runs = 0; + const memo = yield* cachedInScope(scope)( + Effect.suspend(() => { + runs++; + return Effect.fail("boom"); + }), + ); + const [a, b] = yield* Effect.all( + [Effect.result(memo), Effect.result(memo)], + { concurrency: "unbounded" }, + ); + expect(a._tag).toBe("Failure"); + expect(b._tag).toBe("Failure"); + expect(runs).toBe(1); + yield* Scope.close(scope, Exit.void); + }), + ); + + it.live("closing the scope cancels the computation for its waiters", () => + Effect.gen(function* () { + const scope = yield* Scope.make(); + const memo = yield* cachedInScope(scope)(Effect.never); + const waiter = yield* Effect.forkChild(memo); + yield* Effect.sleep("10 millis"); + yield* Scope.close(scope, Exit.void); + const exit = yield* Fiber.await(waiter); + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe( + true, + ); + }), + ); +}); From 5e0366f660b73e3f693ffe89cec6cc8e334feccf Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 18:53:50 +0530 Subject: [PATCH 6/9] fix(cli): reload only changed project dependencies --- packages/alchemy/src/Cli/exec.ts | 14 +++-- packages/node-utils/src/dependency-watcher.ts | 59 +++++++++++++++---- packages/node-utils/src/register-oxc.ts | 15 +++-- packages/node-utils/test/register-oxc.test.ts | 23 ++++++++ .../node-utils/test/watch-import-bun.test.ts | 24 ++++++-- packages/node-utils/test/watch-import.test.ts | 28 +++++++-- 6 files changed, 131 insertions(+), 32 deletions(-) diff --git a/packages/alchemy/src/Cli/exec.ts b/packages/alchemy/src/Cli/exec.ts index 14b48199495..41269282089 100644 --- a/packages/alchemy/src/Cli/exec.ts +++ b/packages/alchemy/src/Cli/exec.ts @@ -144,9 +144,11 @@ const logReload = (paths: ReadonlySet) => */ const runNodeDevWatcher = (options: DevOptions) => { // Node reports real paths for loaded files (symlinked checkouts, macOS - // `/tmp`), so the root the graph is scoped to must be a real path too. + // `/tmp`), so the project root the graph is scoped to must be real too. + // Scope to the invocation directory, not the entrypoint's directory: a + // config under `infra/` commonly imports application code from `src/`. const entrypoint = realpathSync.native(path.resolve(options.main)); - const root = path.dirname(entrypoint); + const root = realpathSync.native(initialCwd); const nodeModules = `${path.sep}node_modules${path.sep}`; return Effect.acquireRelease( Effect.sync(() => @@ -159,7 +161,9 @@ const runNodeDevWatcher = (options: DevOptions) => { return ( !file.includes(nodeModules) && (relative === "" || - (!relative.startsWith("..") && !path.isAbsolute(relative))) + (relative !== ".." && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative))) ); }, }), @@ -193,7 +197,9 @@ const runNodeDevWatcher = (options: DevOptions) => { const runBunDevWatcher = (options: DevOptions) => Effect.acquireRelease( Effect.sync(() => - trackBunImports({ root: path.dirname(path.resolve(options.main)) }), + // Match Node's project-wide graph: the stack entrypoint may live in a + // subdirectory while importing sibling source trees. + trackBunImports({ root: initialCwd }), ), (tracker) => Effect.promise(() => tracker.close()), ).pipe( diff --git a/packages/node-utils/src/dependency-watcher.ts b/packages/node-utils/src/dependency-watcher.ts index 543f9201b8f..25905a51c27 100644 --- a/packages/node-utils/src/dependency-watcher.ts +++ b/packages/node-utils/src/dependency-watcher.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; import path from "node:path"; import { watch, type ChokidarOptions, type FSWatcher } from "chokidar"; @@ -15,15 +17,17 @@ export interface DependencyWatcherOptions { /** * Watches an explicit set of absolute file paths and delivers debounced - * change batches. Chokidar follows editor atomic-save replacements without - * polling by default. The set is replaced wholesale with {@link set}, so the - * watcher always mirrors exactly the files the caller currently depends on. + * batches only when their contents change. Chokidar follows editor atomic-save + * replacements without polling by default. The set is replaced wholesale + * with {@link set}, so the watcher always mirrors exactly the files the caller + * currently depends on. */ export class DependencyWatcher { readonly #options: DependencyWatcherOptions; readonly #listeners = new Set(); readonly #watcher: FSWatcher; #dependencies: ReadonlySet = new Set(); + #fingerprints = new Map(); #pending = new Set(); #timer: NodeJS.Timeout | undefined; #closed = false; @@ -52,20 +56,27 @@ export class DependencyWatcher { /** Replace the watched set with `dependencies` (absolute paths). */ set(dependencies: ReadonlySet): void { if (this.#closed) return; + const previous = this.#dependencies; this.#dependencies = dependencies; - const watched = new Set( - Object.entries(this.#watcher.getWatched()).flatMap(([directory, files]) => - files.map((file) => path.resolve(this.#cwd(), directory, file)), - ), - ); - const removed = [...watched].filter( + const removed = [...previous].filter( (dependency) => !dependencies.has(dependency), ); const added = [...dependencies].filter( - (dependency) => !watched.has(dependency), + (dependency) => !previous.has(dependency), ); - if (removed.length > 0) void this.#watcher.unwatch(removed); - if (added.length > 0) this.#watcher.add(added); + if (removed.length > 0) { + for (const dependency of removed) { + this.#fingerprints.delete(dependency); + this.#pending.delete(dependency); + } + void this.#watcher.unwatch(removed); + } + if (added.length > 0) { + for (const dependency of added) { + this.#fingerprints.set(dependency, this.#fingerprint(dependency)); + } + this.#watcher.add(added); + } } async close(): Promise { @@ -89,9 +100,31 @@ export class DependencyWatcher { if (this.#timer !== undefined) clearTimeout(this.#timer); this.#timer = setTimeout(() => { this.#timer = undefined; - const paths = this.#pending; + const pending = this.#pending; this.#pending = new Set(); + const paths = new Set(); + for (const dependency of pending) { + const previous = this.#fingerprints.get(dependency); + const current = this.#fingerprint(dependency); + if (current === previous) continue; + this.#fingerprints.set(dependency, current); + paths.add(dependency); + } + if (paths.size === 0) return; for (const listener of this.#listeners) listener({ paths }); }, this.#options.debounceMs ?? 50); } + + #fingerprint(file: string): string | undefined { + try { + return createHash("sha256") + .update(readFileSync(file)) + .digest("base64url"); + } catch { + // Missing and unreadable are both materially different from the last + // successfully read contents, while repeated missing-file events fold + // onto the same value. + return undefined; + } + } } diff --git a/packages/node-utils/src/register-oxc.ts b/packages/node-utils/src/register-oxc.ts index 9f0533bf063..187bfd98f34 100644 --- a/packages/node-utils/src/register-oxc.ts +++ b/packages/node-utils/src/register-oxc.ts @@ -319,12 +319,15 @@ export const registerOxc = ( * a private namespace is registered for the call, so nothing is shared with * other imports of the same files. Mirrors tsx's `tsImport`. */ -export const tsImport = ( +export const tsImport = async ( specifier: string, parentURL: string, options: Omit = {}, -): Promise => - registerOxc({ ...options, namespace: randomUUID() }).import( - specifier, - parentURL, - ); +): Promise => { + const loader = registerOxc({ ...options, namespace: randomUUID() }); + try { + return await loader.import(specifier, parentURL); + } finally { + await loader.unregister(); + } +}; diff --git a/packages/node-utils/test/register-oxc.test.ts b/packages/node-utils/test/register-oxc.test.ts index 2f53bdd6e4b..862260c0245 100644 --- a/packages/node-utils/test/register-oxc.test.ts +++ b/packages/node-utils/test/register-oxc.test.ts @@ -192,4 +192,27 @@ describe("registerOxc", () => { // reject: the loader neither transpiles nor rewrites it. expect(filtered).toBe("wsdep: ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING"); }); + + it("unregisters one-shot imports after success and failure", () => { + const root = makeProject(); + write(path.join(root, "src/broken.ts"), "export const = ;\n"); + const result = runNode( + root, + ` + const { tsImport } = await import(${JSON.stringify(registerUrl)}); + if (process.sourceMapsEnabled) throw new Error("source maps unexpectedly enabled before import"); + await tsImport("./src/sub.ts", import.meta.url); + const afterSuccess = process.sourceMapsEnabled; + try { + await tsImport("./src/broken.ts", import.meta.url); + } catch {} + console.log(JSON.stringify({ afterSuccess, afterFailure: process.sourceMapsEnabled })); + `, + ); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout.trim())).toEqual({ + afterSuccess: false, + afterFailure: false, + }); + }); }); diff --git a/packages/node-utils/test/watch-import-bun.test.ts b/packages/node-utils/test/watch-import-bun.test.ts index 38f927f2484..64f01f810ed 100644 --- a/packages/node-utils/test/watch-import-bun.test.ts +++ b/packages/node-utils/test/watch-import-bun.test.ts @@ -44,7 +44,12 @@ describe("trackBunImports", () => { 'export const externalText: string = "external";\n', ); - const tracker = trackBunImports({ root: directory, debounceMs: 10 }); + // The project root is wider than the entrypoint directory, as it is in a + // stack with `infra/alchemy.run.ts` importing from sibling `src/` trees. + const tracker = trackBunImports({ + root: temporaryDirectory, + debounceMs: 10, + }); try { const module = (await import(entry)) as { result: { text: string; externalText: string }; @@ -53,13 +58,24 @@ describe("trackBunImports", () => { text: "original", externalText: "external", }); - expect(tracker.dependencies).toEqual(new Set([entry, dependency])); + expect(tracker.dependencies).toEqual( + new Set([entry, dependency, external]), + ); - const changed = new Promise>((resolve) => - tracker.subscribe(({ paths }) => resolve(paths)), + const unchanged: ReadonlySet[] = []; + const unsubscribeUnchanged = tracker.subscribe(({ paths }) => + unchanged.push(paths), ); // Give chokidar a moment to arm the file watchers before writing. await new Promise((resolve) => setTimeout(resolve, 200)); + writeFileSync(dependency, 'export const text: string = "original";\n'); + await new Promise((resolve) => setTimeout(resolve, 100)); + unsubscribeUnchanged(); + expect(unchanged).toEqual([]); + + const changed = new Promise>((resolve) => + tracker.subscribe(({ paths }) => resolve(paths)), + ); writeFileSync(dependency, 'export const text: string = "changed";\n'); const paths = await Promise.race([ changed, diff --git a/packages/node-utils/test/watch-import.test.ts b/packages/node-utils/test/watch-import.test.ts index 7c920fe9cd8..0dbbe4a6b23 100644 --- a/packages/node-utils/test/watch-import.test.ts +++ b/packages/node-utils/test/watch-import.test.ts @@ -73,7 +73,7 @@ describe("watchImport", () => { parentURL: pathToFileURL(directory + "/runner.mjs").href, debounceMs: 10, shouldInvalidate: url => - url.startsWith("file:") && fileURLToPath(url).startsWith(directory + "/"), + url.startsWith("file:") && fileURLToPath(url).startsWith(process.argv[2] + "/"), transforms: [source => source.replaceAll("__VALUE__", "transformed")], }); const first = await watcher.import(); @@ -82,10 +82,21 @@ describe("watchImport", () => { if (first.value.result.text !== "transformed") throw new Error("custom transform was not applied"); if (!first.dependencies.has(directory + "/entry.ts")) throw new Error("entry was not tracked"); if (!first.dependencies.has(dependency)) throw new Error("dependency was not tracked"); - if (first.dependencies.has(external)) throw new Error("external module was tracked"); + if (!first.dependencies.has(external)) throw new Error("sibling project module was not tracked"); - const changed = new Promise(resolve => watcher.subscribe(resolve)); + let unchangedEvents = 0; + const unsubscribeUnchanged = watcher.subscribe(() => unchangedEvents++); + await new Promise(resolve => setTimeout(resolve, 100)); + await writeFile(dependency, [ + "const state = globalThis as typeof globalThis & { calls?: number };", + "export const count = state.calls = (state.calls ?? 0) + 1;", + 'export const text: string = "__VALUE__";', + ].join("\\n")); await new Promise(resolve => setTimeout(resolve, 100)); + unsubscribeUnchanged(); + if (unchangedEvents !== 0) throw new Error("unchanged contents triggered a reload"); + + const changed = new Promise(resolve => watcher.subscribe(resolve)); await writeFile(dependency, [ "const state = globalThis as typeof globalThis & { calls?: number };", "export const count = state.calls = (state.calls ?? 0) + 1;", @@ -103,7 +114,7 @@ describe("watchImport", () => { const second = await watcher.import(); if (second.value.result.count !== 2) throw new Error("dependency graph was not cache busted"); - if (second.value.result.externalCount !== 1) throw new Error("external module was cache busted"); + if (second.value.result.externalCount !== 2) throw new Error("sibling project module was not cache busted"); if (second.value.result.text !== "changed") throw new Error("changed module was not loaded"); if (first.namespace === second.namespace) throw new Error("generation namespace was reused"); await watcher.close(); @@ -111,7 +122,14 @@ describe("watchImport", () => { const result = spawnSync( "node", - ["--no-warnings", "--input-type=module", "-e", script, directory], + [ + "--no-warnings", + "--input-type=module", + "-e", + script, + directory, + temporaryDirectory, + ], { encoding: "utf8", timeout: 10_000 }, ); From 53bcd3d520b957ec7b05795eaee3122f7180fb10 Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 19:02:05 +0530 Subject: [PATCH 7/9] fix(cli): label interrupt shutdown as exited --- packages/alchemy/src/Cli/commands/errors.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/alchemy/src/Cli/commands/errors.ts b/packages/alchemy/src/Cli/commands/errors.ts index 1aa84dc4ece..13b78adfc90 100644 --- a/packages/alchemy/src/Cli/commands/errors.ts +++ b/packages/alchemy/src/Cli/commands/errors.ts @@ -96,9 +96,7 @@ export const handleCancellation = (self: Effect.Effect) => interruptMessagesSuppressed ? Effect.void : Console.log( - colorsEnabled() - ? `\n${ANSI_DIM}Interrupted.${ANSI_RESET}` - : "\nInterrupted.", + colorsEnabled() ? `\n${ANSI_DIM}Exited.${ANSI_RESET}` : "\nExited.", ), ), ); From 132141b1817f42f96dbe0ed2241a1c83461d46a9 Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 19:10:34 +0530 Subject: [PATCH 8/9] refactor(node-utils): trim watcher type aliases --- packages/node-utils/src/watch-import.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/node-utils/src/watch-import.ts b/packages/node-utils/src/watch-import.ts index 613a8ac8a52..e787dc3d082 100644 --- a/packages/node-utils/src/watch-import.ts +++ b/packages/node-utils/src/watch-import.ts @@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; import { DependencyWatcher, - type DependencyChange, type DependencyChangeListener, type DependencyWatcherOptions, } from "./dependency-watcher.ts"; @@ -18,15 +17,11 @@ export interface ImportGeneration { readonly dependencies: ReadonlySet; } -export type ImportChange = DependencyChange; - export interface ImportWatcherOptions extends ImportLoaderOptions, DependencyWatcherOptions { readonly parentURL: string; } -export type ImportChangeListener = DependencyChangeListener; - /** * Imports fresh Node module generations and watches the exact files loaded by * the current generation. Bun callers should use `BunImportTracker` from @@ -51,7 +46,7 @@ export class ImportWatcher { return this.#dependencies; } - subscribe(listener: ImportChangeListener): () => void { + subscribe(listener: DependencyChangeListener): () => void { return this.#watcher.subscribe(listener); } From 89aa3ccb9a40708d04ed725c2f9ba3849b7dae9e Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Thu, 3 Sep 2026 19:47:14 +0530 Subject: [PATCH 9/9] refactor(cli): simplify dev process setup --- packages/alchemy/src/Cli/commands/dev.ts | 102 +++++++++++------------ packages/alchemy/src/Cli/exec.ts | 22 +++-- 2 files changed, 64 insertions(+), 60 deletions(-) diff --git a/packages/alchemy/src/Cli/commands/dev.ts b/packages/alchemy/src/Cli/commands/dev.ts index 5f408bd0863..ce16354256c 100644 --- a/packages/alchemy/src/Cli/commands/dev.ts +++ b/packages/alchemy/src/Cli/commands/dev.ts @@ -65,57 +65,57 @@ export const devCommand = Command.make( // stack graph itself. Under Node it reloads the graph in-process; under // Bun (which cannot evict evaluated modules) it tears down and exits // with DEV_RELOAD_EXIT_CODE, and this supervisor starts a fresh child. - const command = - typeof globalThis.Bun !== "undefined" - ? [ - "bun", - "run", - ...process.execArgv, - fileURLToPath(import.meta.resolve("alchemy/bin/exec.ts")), - ] - : (() => { - // Node: the exec entry runs with alchemy's Oxc loader hooks, - // exactly as bin/cli.js started this process (checkout: the - // .ts entry plus src-condition resolution; published: the .js - // bundle plus the loader for the user's stack). Node's own - // TypeScript support is never relied on. `process.execPath`, - // not "node": the hooks are gated on THIS node's version. A - // duplicate --import inherited via execArgv is harmless — the - // second import of the same URL hits the module cache. - const entry = fileURLToPath( - import.meta.resolve( - import.meta.url.endsWith(".ts") - ? "alchemy/bin/exec.ts" - : "alchemy/bin/exec.js", - ), - ); - return [ - process.execPath, - ...process.execArgv, - ...nodeLoaderArgs(entry), - entry, - ]; - })(); - const runChild = Effect.gen(function* () { - const child = yield* ChildProcess.make(command[0], command.slice(1), { - stdin: "inherit", - stdout: "inherit", - stderr: "inherit", - env: { - ALCHEMY_EXEC_OPTIONS: JSON.stringify(options), - ALCHEMY_DEV: "true", - ...(process.env.NODE_EXTRA_CA_CERTS - ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS } - : {}), - [SPAWNER_URL_ENV_KEY]: spawner.url, - }, - extendEnv: true, - // Same process group as this supervisor: the exec child owns the - // terminal (TUI stdin), so the tty's Ctrl+C must reach it directly. - detached: false, - }); - return yield* child.exitCode; - }).pipe(Effect.scoped); + let command: [string, ...string[]]; + if (typeof globalThis.Bun !== "undefined") { + command = [ + "bun", + "run", + ...process.execArgv, + fileURLToPath(import.meta.resolve("alchemy/bin/exec.ts")), + ]; + } else { + // Node: the exec entry runs with alchemy's Oxc loader hooks, + // exactly as bin/cli.js started this process (checkout: the + // .ts entry plus src-condition resolution; published: the .js + // bundle plus the loader for the user's stack). Node's own + // TypeScript support is never relied on. `process.execPath`, + // not "node": the hooks are gated on THIS node's version. A + // duplicate --import inherited via execArgv is harmless — the + // second import of the same URL hits the module cache. + const entry = fileURLToPath( + import.meta.resolve( + import.meta.url.endsWith(".ts") + ? "alchemy/bin/exec.ts" + : "alchemy/bin/exec.js", + ), + ); + command = [ + process.execPath, + ...process.execArgv, + ...nodeLoaderArgs(entry), + entry, + ]; + } + const runChild = ChildProcess.make(command[0], command.slice(1), { + stdin: "inherit", + stdout: "inherit", + stderr: "inherit", + env: { + ALCHEMY_EXEC_OPTIONS: JSON.stringify(options), + ALCHEMY_DEV: "true", + ...(process.env.NODE_EXTRA_CA_CERTS + ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS } + : {}), + [SPAWNER_URL_ENV_KEY]: spawner.url, + }, + extendEnv: true, + // Same process group as this supervisor: the exec child owns the + // terminal (TUI stdin), so the tty's Ctrl+C must reach it directly. + detached: false, + }).pipe( + Effect.flatMap((child) => child.exitCode), + Effect.scoped, + ); // Each child gets its own scope so a reload exit releases the old // handle before the replacement starts; the sidecar spawner lives in // the command scope and survives every restart. diff --git a/packages/alchemy/src/Cli/exec.ts b/packages/alchemy/src/Cli/exec.ts index 41269282089..b3da6f69ecd 100644 --- a/packages/alchemy/src/Cli/exec.ts +++ b/packages/alchemy/src/Cli/exec.ts @@ -3,14 +3,14 @@ import * as Config from "effect/Config"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"; import { watchImport } from "@alchemy.run/node-utils/watch-import"; import { trackBunImports } from "@alchemy.run/node-utils/watch-import-bun"; -import { realpathSync } from "node:fs"; -import path from "node:path"; import { fileURLToPath } from "node:url"; import { AlchemyContextLive } from "../AlchemyContext.ts"; @@ -129,12 +129,14 @@ const nextChange = (watcher: { return Effect.sync(unsubscribe); }); -const logReload = (paths: ReadonlySet) => - Effect.logInfo( +const logReload = Effect.fn(function* (paths: ReadonlySet) { + const path = yield* Path.Path; + yield* Effect.logInfo( `Reloading stack: changed ${[...paths] .map((file) => path.relative(initialCwd, file)) .join(", ")}`, ); +}); /** * Node: one process, many generations. The Oxc loader imports the stack graph @@ -142,15 +144,17 @@ const logReload = (paths: ReadonlySet) => * interrupts the parked run (whose scope tears down the dev widget) and the * loop imports the next generation. */ -const runNodeDevWatcher = (options: DevOptions) => { +const runNodeDevWatcher = Effect.fn(function* (options: DevOptions) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; // Node reports real paths for loaded files (symlinked checkouts, macOS // `/tmp`), so the project root the graph is scoped to must be real too. // Scope to the invocation directory, not the entrypoint's directory: a // config under `infra/` commonly imports application code from `src/`. - const entrypoint = realpathSync.native(path.resolve(options.main)); - const root = realpathSync.native(initialCwd); + const entrypoint = yield* fs.realPath(path.resolve(options.main)); + const root = yield* fs.realPath(initialCwd); const nodeModules = `${path.sep}node_modules${path.sep}`; - return Effect.acquireRelease( + return yield* Effect.acquireRelease( Effect.sync(() => watchImport<{ readonly default?: unknown }>(entrypoint, { parentURL: import.meta.url, @@ -186,7 +190,7 @@ const runNodeDevWatcher = (options: DevOptions) => { ); }), ); -}; +}); /** * Bun: one process per generation. Bun cannot evict evaluated modules, so the