Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 35 additions & 26 deletions packages/alchemy/bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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 tsx's loader 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);
}
Expand Down Expand Up @@ -211,7 +222,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"),
);
32 changes: 13 additions & 19 deletions packages/alchemy/bin/register-dev-mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand All @@ -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();
27 changes: 27 additions & 0 deletions packages/alchemy/bin/register-oxc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 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
// 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),
});
16 changes: 14 additions & 2 deletions packages/alchemy/src/Alchemist/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ export type StackModule = ReturnType<ReturnType<typeof Stack.make>> & {
readonly state: Layer.Layer<never> | undefined;
};

export interface StackModuleLoader {
readonly import: (url: string) => Promise<{ readonly default?: unknown }>;
}

export const StackModuleLoader = Context.Reference<StackModuleLoader>(
"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;
Expand All @@ -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) ||
Expand Down
7 changes: 7 additions & 0 deletions packages/alchemy/src/Cli/DevOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
92 changes: 49 additions & 43 deletions packages/alchemy/src/Cli/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@ 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 { DevOptions } from "../DevOptions.ts";
import { nodeLoaderArgs } from "../../Util/Node.ts";
import { DEV_RELOAD_EXIT_CODE, DevOptions } from "../DevOptions.ts";
import {
configPath,
envFile,
Expand Down Expand Up @@ -62,43 +59,44 @@ 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.
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()
? [
// Source checkout under node: run the .ts exec entry with
// the dev-mode hooks (tsx 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.
process.execPath,
...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), {
// 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.
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",
Expand All @@ -114,8 +112,16 @@ export const devCommand = Command.make(
// 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.
yield* Effect.repeat(runChild, {
until: (code) => code !== DEV_RELOAD_EXIT_CODE,
});
yield* child.exitCode;
},
(effect, args) =>
Effect.provide(
Expand Down
4 changes: 1 addition & 3 deletions packages/alchemy/src/Cli/commands/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@ export const handleCancellation = <A, E, R>(self: Effect.Effect<A, E, R>) =>
interruptMessagesSuppressed
? Effect.void
: Console.log(
colorsEnabled()
? `\n${ANSI_DIM}Interrupted.${ANSI_RESET}`
: "\nInterrupted.",
colorsEnabled() ? `\n${ANSI_DIM}Exited.${ANSI_RESET}` : "\nExited.",
),
),
);
Expand Down
Loading
Loading