The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { afterEach, describe, expect, it } from "bun:test"; |
| 2 | import { spawnSync } from "node:child_process"; |
| 3 | import { |
| 4 | existsSync, |
| 5 | mkdirSync, |
| 6 | mkdtempSync, |
| 7 | readdirSync, |
| 8 | readFileSync, |
| 9 | realpathSync, |
| 10 | rmSync, |
| 11 | writeFileSync, |
| 12 | } from "node:fs"; |
| 13 | import os from "node:os"; |
| 14 | import path from "node:path"; |
| 15 | import { pathToFileURL } from "node:url"; |
| 16 | |
| 17 | const temporaryDirectories: string[] = []; |
| 18 | |
| 19 | afterEach(() => { |
| 20 | for (const directory of temporaryDirectories.splice(0)) { |
| 21 | rmSync(directory, { force: true, recursive: true }); |
| 22 | } |
| 23 | }); |
| 24 | |
| 25 | const write = (file: string, content: string) => { |
| 26 | mkdirSync(path.dirname(file), { recursive: true }); |
| 27 | writeFileSync(file, content); |
| 28 | }; |
| 29 | |
| 30 | /** |
| 31 | * A project exercising everything tsx layers over Node that a TypeScript |
| 32 | * codebase relies on: tsconfig `paths`, emitted-extension imports, implicit |
| 33 | * extensions and directory indexes, JSON without attributes, TSX with a |
| 34 | * tsconfig-selected runtime, and `require()` from a `.cts` into ESM |
| 35 | * TypeScript. |
| 36 | */ |
| 37 | const makeProject = () => { |
| 38 | const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "alchemy-register-oxc-"))); |
| 39 | temporaryDirectories.push(root); |
| 40 | const at = (file: string) => path.join(root, file); |
| 41 | write(at("package.json"), '{"type":"module"}'); |
| 42 | write( |
| 43 | at("tsconfig.json"), |
| 44 | JSON.stringify({ |
| 45 | compilerOptions: { |
| 46 | jsx: "react-jsx", |
| 47 | jsxImportSource: "myjsx", |
| 48 | baseUrl: ".", |
| 49 | paths: { "@lib/*": ["src/lib/*"] }, |
| 50 | }, |
| 51 | }), |
| 52 | ); |
| 53 | write( |
| 54 | at("node_modules/myjsx/package.json"), |
| 55 | '{"name":"myjsx","type":"module","exports":{"./jsx-runtime":"./jsx-runtime.js","./jsx-dev-runtime":"./jsx-runtime.js"}}', |
| 56 | ); |
| 57 | write( |
| 58 | at("node_modules/myjsx/jsx-runtime.js"), |
| 59 | "export const jsx = (tag, props) => ({ tag, props });\nexport const jsxs = jsx;\nexport const jsxDEV = jsx;\nexport const Fragment = 'F';\n", |
| 60 | ); |
| 61 | write( |
| 62 | at("node_modules/wsdep/package.json"), |
| 63 | '{"name":"wsdep","type":"module","exports":{".":"./src/index.ts"}}', |
| 64 | ); |
| 65 | write(at("node_modules/wsdep/src/index.ts"), 'export const fromWorkspaceDep: string = "ws";\n'); |
| 66 | write( |
| 67 | at("node_modules/conditional/package.json"), |
| 68 | '{"name":"conditional","type":"module","exports":{".":{"bun":"./src/index.ts","import":"./lib/index.js"}}}', |
| 69 | ); |
| 70 | write(at("node_modules/conditional/src/index.ts"), 'export const selected: string = "src";\n'); |
| 71 | write(at("node_modules/conditional/lib/index.js"), 'export const selected = "lib";\n'); |
| 72 | write(at("src/lib/helper.ts"), 'export const helper = (): string => "helper";\n'); |
| 73 | write(at("src/lib/helper.js"), 'export const helper = () => "emitted";\n'); |
| 74 | write(at("src/dir/index.ts"), 'export const index = "dir-index";\n'); |
| 75 | write(at("src/sub.ts"), 'export const sub = "sub";\n'); |
| 76 | write(at("src/data.json"), '{ "answer": 42 }'); |
| 77 | write(at("src/View.tsx"), 'export const view = <p id="x">hi</p>;\n'); |
| 78 | write(at("cjs/package.json"), '{"type":"commonjs"}'); |
| 79 | write( |
| 80 | at("cjs/esmish.ts"), |
| 81 | "export const value: number = 7;\nexport class A { constructor(readonly x: number) {} }\n", |
| 82 | ); |
| 83 | write( |
| 84 | at("cjs/consumer.cts"), |
| 85 | 'const { value, A } = require("./esmish.ts");\nconst sub = require("../src/sub");\nmodule.exports = { viaRequire: new A(value).x + 1, sub: sub.sub };\n', |
| 86 | ); |
| 87 | write( |
| 88 | at("src/entry.ts"), |
| 89 | [ |
| 90 | 'import { helper } from "@lib/helper";', |
| 91 | 'import { helper as helperJs } from "./lib/helper.js";', |
| 92 | 'import { sub } from "./sub";', |
| 93 | 'import { index } from "./dir";', |
| 94 | 'import { index as index2 } from "./dir/";', |
| 95 | 'import data from "./data.json";', |
| 96 | 'import { view } from "./View.tsx";', |
| 97 | 'import consumer from "../cjs/consumer.cts";', |
| 98 | "export const report = {", |
| 99 | " helper: helper(), helperJs: helperJs(), sub, index, index2,", |
| 100 | " data: data.answer, view: view.tag,", |
| 101 | " viaRequire: consumer.viaRequire, requiredSub: consumer.sub,", |
| 102 | "};", |
| 103 | "export const boom = (): never => {", |
| 104 | ' throw new Error("boom");', |
| 105 | "};", |
| 106 | ].join("\n"), |
| 107 | ); |
| 108 | return root; |
| 109 | }; |
| 110 | |
| 111 | const srcUrl = (file: string) => pathToFileURL(path.resolve(import.meta.dir, "../src", file)).href; |
| 112 | const registerUrl = srcUrl("loader/register.ts"); |
| 113 | |
| 114 | const runNode = ( |
| 115 | cwd: string, |
| 116 | script: string, |
| 117 | env: Record<string, string> = {}, |
| 118 | nodeArgs: ReadonlyArray<string> = [], |
| 119 | ) => |
| 120 | spawnSync("node", [...nodeArgs, "--no-warnings", "--input-type=module", "-e", script], { |
| 121 | cwd, |
| 122 | encoding: "utf8", |
| 123 | env: { ...process.env, ...env }, |
| 124 | timeout: 20_000, |
| 125 | }); |
| 126 | |
| 127 | describe("registerOxc", () => { |
| 128 | it("resolves and transpiles TypeScript the way tsx does", () => { |
| 129 | const root = makeProject(); |
| 130 | const cache = path.join(root, "cache"); |
| 131 | const script = ` |
| 132 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 133 | registerOxc(); |
| 134 | const entry = await import("./src/entry.ts"); |
| 135 | console.log(JSON.stringify(entry.report)); |
| 136 | try { entry.boom(); } catch (error) { console.log(error.stack.split("\\n")[1].trim()); } |
| 137 | `; |
| 138 | const result = runNode(root, script, { ALCHEMY_TRANSFORM_CACHE: cache }); |
| 139 | expect(result.status, result.stderr).toBe(0); |
| 140 | const [report, frame] = result.stdout.trim().split("\n"); |
| 141 | expect(JSON.parse(report!)).toEqual({ |
| 142 | // tsconfig paths alias |
| 143 | helper: "helper", |
| 144 | // `.js` import prefers the `.ts` source over the emitted sibling |
| 145 | helperJs: "helper", |
| 146 | // extensionless and directory imports |
| 147 | sub: "sub", |
| 148 | index: "dir-index", |
| 149 | index2: "dir-index", |
| 150 | // JSON without an import attribute |
| 151 | data: 42, |
| 152 | // TSX through the tsconfig's jsxImportSource |
| 153 | view: "p", |
| 154 | // `.cts` requiring `.ts` (parameter property) and an extensionless path |
| 155 | viaRequire: 8, |
| 156 | requiredSub: "sub", |
| 157 | }); |
| 158 | // Source maps are applied to stack traces. They are not inlined: each |
| 159 | // sits next to its cache entry, without `sourcesContent`, and the module |
| 160 | // points at it by path. |
| 161 | expect(frame).toMatch(/entry\.ts:15:/); |
| 162 | const maps = readdirSync(cache).filter((name) => name.endsWith(".map")); |
| 163 | expect(maps.length).toBeGreaterThan(0); |
| 164 | for (const name of maps) { |
| 165 | const map = JSON.parse(readFileSync(path.join(cache, name), "utf8")); |
| 166 | expect(map.sourcesContent).toBeUndefined(); |
| 167 | // By URL: a bare path would resolve against the cache directory. |
| 168 | expect(map.sources[0]).toMatch(/^file:\/\/.*\.(ts|tsx|cts|js)$/); |
| 169 | } |
| 170 | // The cache-hit path references the same file. |
| 171 | const hit = runNode(root, script, { ALCHEMY_TRANSFORM_CACHE: cache }); |
| 172 | expect(hit.status, hit.stderr).toBe(0); |
| 173 | expect(hit.stdout.trim().split("\n")[1]).toMatch(/entry\.ts:15:/); |
| 174 | // With no cache there is nowhere to put the map, so it is inlined. |
| 175 | const inline = runNode(root, script, { ALCHEMY_TRANSFORM_CACHE: "0" }); |
| 176 | expect(inline.status, inline.stderr).toBe(0); |
| 177 | expect(inline.stdout.trim().split("\n")[1]).toMatch(/entry\.ts:15:/); |
| 178 | }); |
| 179 | |
| 180 | it("inlines source maps with their source while an inspector is attached", () => { |
| 181 | const root = makeProject(); |
| 182 | const cache = path.join(root, "cache"); |
| 183 | // What a debugger sees for each module: a map it can always read, not a |
| 184 | // reference into the shared cache directory. Run twice to cover a cold |
| 185 | // transform and a cache hit. |
| 186 | const script = ` |
| 187 | const { Session } = await import("node:inspector"); |
| 188 | const session = new Session(); |
| 189 | session.connect(); |
| 190 | const maps = {}; |
| 191 | session.on("Debugger.scriptParsed", ({ params }) => { |
| 192 | if (params.url.endsWith("/src/sub.ts")) maps.sub = params.sourceMapURL; |
| 193 | }); |
| 194 | session.post("Debugger.enable"); |
| 195 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 196 | registerOxc(); |
| 197 | await import("./src/sub.ts"); |
| 198 | console.log(maps.sub); |
| 199 | `; |
| 200 | for (const _ of [0, 1]) { |
| 201 | const result = runNode(root, script, { ALCHEMY_TRANSFORM_CACHE: cache }, ["--inspect=0"]); |
| 202 | expect(result.status, result.stderr).toBe(0); |
| 203 | const sourceMapUrl = result.stdout.trim(); |
| 204 | expect(sourceMapUrl).toStartWith("data:application/json;base64,"); |
| 205 | const map = JSON.parse(Buffer.from(sourceMapUrl.split(",")[1]!, "base64").toString("utf8")); |
| 206 | expect(map.sources).toEqual([pathToFileURL(path.join(root, "src/sub.ts")).href]); |
| 207 | expect(map.sourcesContent).toEqual([readFileSync(path.join(root, "src/sub.ts"), "utf8")]); |
| 208 | } |
| 209 | }); |
| 210 | |
| 211 | it("imports files as text with the type: text attribute", () => { |
| 212 | const root = makeProject(); |
| 213 | write(path.join(root, "src/notes.txt"), "\uFEFFhéllo\n`${not code}`\n"); |
| 214 | write(path.join(root, "node_modules/textdep/data.txt"), "from a dependency"); |
| 215 | write( |
| 216 | path.join(root, "src/texts.ts"), |
| 217 | [ |
| 218 | 'import notes from "./notes.txt" with { type: "text" };', |
| 219 | 'import source from "./sub.ts" with { type: "text" };', |
| 220 | 'import { sub } from "./sub.ts";', |
| 221 | 'import dependency from "textdep/data.txt" with { type: "text" };', |
| 222 | "export const texts = { notes, source, sub, dependency };", |
| 223 | ].join("\n"), |
| 224 | ); |
| 225 | const result = runNode( |
| 226 | root, |
| 227 | ` |
| 228 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 229 | registerOxc({ filter: (path) => !path.includes("/node_modules/") }); |
| 230 | const { texts } = await import("./src/texts.ts"); |
| 231 | console.log(JSON.stringify(texts)); |
| 232 | `, |
| 233 | ); |
| 234 | expect(result.status, result.stderr).toBe(0); |
| 235 | expect(JSON.parse(result.stdout.trim())).toEqual({ |
| 236 | // UTF-8 decoded like TextDecoder: BOM stripped, nothing evaluated |
| 237 | notes: "héllo\n`${not code}`\n", |
| 238 | // TypeScript imported as text is its untranspiled source, a module |
| 239 | // distinct from the same file imported as code |
| 240 | source: 'export const sub = "sub";\n', |
| 241 | sub: "sub", |
| 242 | // the node_modules filter only limits transpiling |
| 243 | dependency: "from a dependency", |
| 244 | }); |
| 245 | }); |
| 246 | |
| 247 | it("adds configured package export conditions to project resolution", () => { |
| 248 | const root = makeProject(); |
| 249 | write(path.join(root, "src/conditional.ts"), 'export { selected } from "conditional";\n'); |
| 250 | const result = runNode( |
| 251 | root, |
| 252 | ` |
| 253 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 254 | registerOxc({ conditions: ["bun"] }); |
| 255 | const conditional = await import("./src/conditional.ts"); |
| 256 | console.log(conditional.selected); |
| 257 | `, |
| 258 | ); |
| 259 | expect(result.status, result.stderr).toBe(0); |
| 260 | expect(result.stdout.trim()).toBe("src"); |
| 261 | }); |
| 262 | |
| 263 | it("isolates namespaced imports and leaves node_modules to Node with a filter", () => { |
| 264 | const root = makeProject(); |
| 265 | const result = runNode( |
| 266 | root, |
| 267 | ` |
| 268 | const { registerHooks } = await import("node:module"); |
| 269 | const { createHooks } = await import(${JSON.stringify(srcUrl("loader/hooks.ts"))}); |
| 270 | const { namespaced, importNamespaced } = await import(${JSON.stringify(srcUrl("loader/namespace.ts"))}); |
| 271 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 272 | const seen = []; |
| 273 | const one = registerHooks(namespaced(createHooks(), { namespace: "one", onImport: (url) => seen.push(url.split("/").pop()) })); |
| 274 | const a = await importNamespaced("./src/sub.ts", import.meta.url, "one"); |
| 275 | const b = await importNamespaced("./src/sub.ts", import.meta.url, "one"); |
| 276 | const two = registerHooks(namespaced(createHooks(), { namespace: "two" })); |
| 277 | const c = await importNamespaced("./src/sub.ts", import.meta.url, "two"); |
| 278 | console.log(JSON.stringify({ same: a === b, fresh: a !== c, seen })); |
| 279 | one.deregister(); |
| 280 | two.deregister(); |
| 281 | registerOxc({ filter: (file) => !file.includes("/node_modules/") }); |
| 282 | try { |
| 283 | await import("wsdep"); |
| 284 | console.log("wsdep: loaded"); |
| 285 | } catch (error) { |
| 286 | console.log("wsdep: " + error.code); |
| 287 | } |
| 288 | `, |
| 289 | ); |
| 290 | expect(result.status, result.stderr).toBe(0); |
| 291 | const [scoped, filtered] = result.stdout.trim().split("\n"); |
| 292 | expect(JSON.parse(scoped!)).toEqual({ |
| 293 | same: true, |
| 294 | fresh: true, |
| 295 | seen: ["sub.ts"], |
| 296 | }); |
| 297 | // With node_modules filtered out, the dependency's `.ts` is Node's to |
| 298 | // reject: the loader neither transpiles nor rewrites it. |
| 299 | expect(filtered).toBe("wsdep: ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING"); |
| 300 | }); |
| 301 | }); |
| 302 | |
| 303 | describe("transform cache", () => { |
| 304 | /** `options` is the literal passed to `registerOxc` in the child. */ |
| 305 | const importSub = (options: string) => ` |
| 306 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 307 | registerOxc(${options}); |
| 308 | const { sub } = await import("./src/sub.ts"); |
| 309 | console.log(sub); |
| 310 | `; |
| 311 | |
| 312 | it("reuses Oxc output across processes and keys on the tsconfig", () => { |
| 313 | const root = makeProject(); |
| 314 | const cache = path.join(root, "cache"); |
| 315 | const first = runNode(root, importSub(`{ cache: ${JSON.stringify(cache)} }`)); |
| 316 | expect(first.status, first.stderr).toBe(0); |
| 317 | expect(first.stdout.trim()).toBe("sub"); |
| 318 | const entries = readdirSync(cache) |
| 319 | .filter((name) => name.endsWith(".code")) |
| 320 | .map((name) => path.join(cache, name)); |
| 321 | expect(entries.length).toBeGreaterThan(0); |
| 322 | // The only proof a second process READ the entry rather than |
| 323 | // transforming again: make the cached code say something the source |
| 324 | // does not. |
| 325 | const entry = entries.find((file) => readFileSync(file, "utf8").includes('"sub"')); |
| 326 | expect(entry).toBeDefined(); |
| 327 | writeFileSync(entry!, readFileSync(entry!, "utf8").replace('"sub"', '"from-cache"')); |
| 328 | const second = runNode(root, importSub(`{ cache: ${JSON.stringify(cache)} }`)); |
| 329 | expect(second.status, second.stderr).toBe(0); |
| 330 | expect(second.stdout.trim()).toBe("from-cache"); |
| 331 | // The resolved tsconfig is part of the key: editing it is a miss. |
| 332 | const tsconfig = path.join(root, "tsconfig.json"); |
| 333 | const config = JSON.parse(readFileSync(tsconfig, "utf8")) as { |
| 334 | compilerOptions: Record<string, unknown>; |
| 335 | }; |
| 336 | config.compilerOptions.target = "ES2020"; |
| 337 | writeFileSync(tsconfig, JSON.stringify(config)); |
| 338 | const third = runNode(root, importSub(`{ cache: ${JSON.stringify(cache)} }`)); |
| 339 | expect(third.status, third.stderr).toBe(0); |
| 340 | expect(third.stdout.trim()).toBe("sub"); |
| 341 | }); |
| 342 | |
| 343 | it("takes its directory from the environment and can be switched off", () => { |
| 344 | const root = makeProject(); |
| 345 | const fromEnv = path.join(root, "cache-from-env"); |
| 346 | const viaEnv = runNode(root, importSub("{}"), { |
| 347 | ALCHEMY_TRANSFORM_CACHE: fromEnv, |
| 348 | }); |
| 349 | expect(viaEnv.status, viaEnv.stderr).toBe(0); |
| 350 | expect(readdirSync(fromEnv).length).toBeGreaterThan(0); |
| 351 | |
| 352 | const disabled = path.join(root, "cache-disabled"); |
| 353 | const off = runNode(root, importSub("{ cache: false }"), { |
| 354 | ALCHEMY_TRANSFORM_CACHE: disabled, |
| 355 | }); |
| 356 | expect(off.status, off.stderr).toBe(0); |
| 357 | expect(off.stdout.trim()).toBe("sub"); |
| 358 | expect(existsSync(disabled)).toBe(false); |
| 359 | }); |
| 360 | }); |
| 361 | |
| 362 | describe("compile cache", () => { |
| 363 | it("flushes lazily loaded modules to Node's compile cache", () => { |
| 364 | const root = makeProject(); |
| 365 | const directory = path.join(root, "compile-cache"); |
| 366 | const result = runNode( |
| 367 | root, |
| 368 | ` |
| 369 | import { enableCompileCache } from "node:module"; |
| 370 | import { readdirSync } from "node:fs"; |
| 371 | enableCompileCache(${JSON.stringify(directory)}); |
| 372 | const count = () => |
| 373 | readdirSync(${JSON.stringify(directory)}, { recursive: true }) |
| 374 | .filter((name) => name.includes("/")).length; |
| 375 | const { registerOxc } = await import(${JSON.stringify(registerUrl)}); |
| 376 | registerOxc(); |
| 377 | // Past Node's own post-entry persist. |
| 378 | await new Promise((resolve) => setTimeout(resolve, 300)); |
| 379 | const before = count(); |
| 380 | await import("./src/sub.ts"); |
| 381 | await new Promise((resolve) => setTimeout(resolve, 1500)); |
| 382 | console.log(JSON.stringify({ before, after: count() })); |
| 383 | // Not a clean exit: whatever is on disk got there through the flush. |
| 384 | process.kill(process.pid, "SIGKILL"); |
| 385 | `, |
| 386 | ); |
| 387 | expect(result.signal).toBe("SIGKILL"); |
| 388 | const { before, after } = JSON.parse(result.stdout.trim()) as { |
| 389 | before: number; |
| 390 | after: number; |
| 391 | }; |
| 392 | expect(after).toBeGreaterThan(before); |
| 393 | }); |
| 394 | }); |