The best way to control Claude Code, Codex and more from any computer or phone

main
ts 194 lines 8.33 KB
Raw
1 import { afterEach, describe, expect, it } from "bun:test";
2 import { spawnSync } from "node:child_process";
3 import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4 import os from "node:os";
5 import path from "node:path";
6 import { pathToFileURL } from "node:url";
7
8 const temporaryDirectories: string[] = [];
9
10 afterEach(() => {
11 for (const directory of temporaryDirectories.splice(0)) {
12 rmSync(directory, { force: true, recursive: true });
13 }
14 });
15
16 describe("watchImport", () => {
17 it("transforms TypeScript, tracks dependencies, and reloads the whole graph", () => {
18 const temporaryDirectory = realpathSync(mkdtempSync(path.join(os.tmpdir(), "alchemy-import-")));
19 temporaryDirectories.push(temporaryDirectory);
20 const directory = path.join(temporaryDirectory, "project");
21 mkdirSync(directory);
22 writeFileSync(
23 path.join(directory, "entry.ts"),
24 [
25 'import { count, text } from "./dependency.js";',
26 'import { externalCount } from "../external.js";',
27 "interface Result { count: number; externalCount: number; text: string }",
28 "export const result: Result = { count, externalCount, text };",
29 ].join("\n"),
30 );
31 writeFileSync(
32 path.join(directory, "dependency.ts"),
33 [
34 "const state = globalThis as typeof globalThis & { calls?: number };",
35 "export const count = state.calls = (state.calls ?? 0) + 1;",
36 'export const text: string = "__VALUE__";',
37 ].join("\n"),
38 );
39 const external = path.join(temporaryDirectory, "external.ts");
40 writeFileSync(
41 external,
42 [
43 "const state = globalThis as typeof globalThis & { externalCalls?: number };",
44 "export const externalCount = state.externalCalls = (state.externalCalls ?? 0) + 1;",
45 ].join("\n"),
46 );
47
48 const moduleUrl = pathToFileURL(
49 path.resolve(import.meta.dir, "../src/watch/import-watcher.ts"),
50 ).href;
51 const registerUrl = pathToFileURL(
52 path.resolve(import.meta.dir, "../src/loader/register.ts"),
53 ).href;
54 const script = `
55 import { writeFile } from "node:fs/promises";
56 import { fileURLToPath, pathToFileURL } from "node:url";
57 import { watchImport } from ${JSON.stringify(moduleUrl)};
58 const { registerOxc } = await import(${JSON.stringify(registerUrl)});
59 registerOxc();
60
61 const directory = process.argv[1];
62 const dependency = directory + "/dependency.ts";
63 const external = fileURLToPath(new URL("../external.ts", pathToFileURL(directory + "/")));
64 const watcher = watchImport("./entry.ts", {
65 parentURL: pathToFileURL(directory + "/runner.mjs").href,
66 debounceMs: 10,
67 shouldInvalidate: url =>
68 url.startsWith("file:") && fileURLToPath(url).startsWith(process.argv[2] + "/"),
69 });
70 const first = await watcher.import();
71 if (first.value.result.count !== 1) throw new Error("first graph was not evaluated");
72 if (first.value.result.externalCount !== 1) throw new Error("external module was not evaluated");
73 if (!first.dependencies.has(directory + "/entry.ts")) throw new Error("entry was not tracked");
74 if (!first.dependencies.has(dependency)) throw new Error("dependency was not tracked");
75 if (!first.dependencies.has(external)) throw new Error("sibling project module was not tracked");
76
77 let unchangedEvents = 0;
78 const unsubscribeUnchanged = watcher.subscribe(() => unchangedEvents++);
79 await new Promise(resolve => setTimeout(resolve, 100));
80 await writeFile(dependency, [
81 "const state = globalThis as typeof globalThis & { calls?: number };",
82 "export const count = state.calls = (state.calls ?? 0) + 1;",
83 'export const text: string = "__VALUE__";',
84 ].join("\\n"));
85 await new Promise(resolve => setTimeout(resolve, 100));
86 unsubscribeUnchanged();
87 if (unchangedEvents !== 0) throw new Error("unchanged contents triggered a reload");
88
89 const changed = new Promise(resolve => watcher.subscribe(resolve));
90 await writeFile(dependency, [
91 "const state = globalThis as typeof globalThis & { calls?: number };",
92 "export const count = state.calls = (state.calls ?? 0) + 1;",
93 'export const text: string = "changed";',
94 ].join("\\n"));
95 let timeout;
96 const event = await Promise.race([
97 changed,
98 new Promise((_, reject) => {
99 timeout = setTimeout(() => reject(new Error("watch timed out")), 3000);
100 }),
101 ]);
102 clearTimeout(timeout);
103 if (!event.paths.has(dependency)) throw new Error("change path was not reported");
104
105 const second = await watcher.import();
106 if (second.value.result.count !== 2) throw new Error("dependency graph was not cache busted");
107 if (second.value.result.externalCount !== 2) throw new Error("sibling project module was not cache busted");
108 if (second.value.result.text !== "changed") throw new Error("changed module was not loaded");
109 if (first.namespace === second.namespace) throw new Error("generation namespace was reused");
110 await watcher.close();
111 `;
112
113 const result = spawnSync(
114 "node",
115 ["--no-warnings", "--input-type=module", "-e", script, directory, temporaryDirectory],
116 { encoding: "utf8", timeout: 10_000 },
117 );
118
119 expect(result.status, result.stderr || result.stdout).toBe(0);
120 });
121
122 it("standalone: follows a member's require() calls, refreshes them and enables source maps", () => {
123 const temporaryDirectory = realpathSync(mkdtempSync(path.join(os.tmpdir(), "alchemy-import-")));
124 temporaryDirectories.push(temporaryDirectory);
125 const directory = path.join(temporaryDirectory, "project");
126 mkdirSync(directory);
127 writeFileSync(
128 path.join(directory, "entry.ts"),
129 ['import lib from "./lib.cjs";', "export const result: { n: number; h: number } = lib;"].join(
130 "\n",
131 ),
132 );
133 writeFileSync(
134 path.join(directory, "lib.cts"),
135 [
136 'const helper: { h: number } = require("./helper.cjs");',
137 "const state = globalThis as typeof globalThis & { libCalls?: number };",
138 "const n: number = (state.libCalls = (state.libCalls ?? 0) + 1);",
139 "module.exports = { n, h: helper.h };",
140 ].join("\n"),
141 );
142 writeFileSync(
143 path.join(directory, "helper.cts"),
144 [
145 "const state = globalThis as typeof globalThis & { helperCalls?: number };",
146 "const h: number = (state.helperCalls = (state.helperCalls ?? 0) + 1);",
147 "module.exports = { h };",
148 ].join("\n"),
149 );
150
151 const moduleUrl = pathToFileURL(
152 path.resolve(import.meta.dir, "../src/watch/import-watcher.ts"),
153 ).href;
154 // No `registerOxc()`: the watcher is the only loader in this process.
155 const script = `
156 import { getSourceMapsSupport } from "node:module";
157 import { pathToFileURL } from "node:url";
158 import { watchImport } from ${JSON.stringify(moduleUrl)};
159
160 const directory = process.argv[1];
161 const members = ["entry.ts", "lib.cts", "helper.cts"].map(file => directory + "/" + file);
162 if (getSourceMapsSupport().enabled) throw new Error("source maps were already on");
163 const watcher = watchImport("./entry.ts", {
164 parentURL: pathToFileURL(directory + "/runner.mjs").href,
165 debounceMs: 10,
166 });
167
168 const first = await watcher.import();
169 if (!getSourceMapsSupport().enabled) throw new Error("source maps were not enabled");
170 for (const file of members) {
171 if (!first.dependencies.has(file)) throw new Error(file + " was not tracked");
172 }
173 if (first.value.result.n !== 1 || first.value.result.h !== 1) throw new Error("first graph was not evaluated");
174
175 const second = await watcher.import();
176 for (const file of members) {
177 if (!second.dependencies.has(file)) throw new Error(file + " was not tracked again");
178 }
179 if (second.value.result.n !== 2) throw new Error("CommonJS member was not re-evaluated");
180 if (second.value.result.h !== 2) throw new Error("required CommonJS member was not re-evaluated");
181
182 await watcher.close();
183 if (getSourceMapsSupport().enabled) throw new Error("source maps were not restored");
184 `;
185
186 const result = spawnSync(
187 "node",
188 ["--no-warnings", "--input-type=module", "-e", script, directory],
189 { encoding: "utf8", timeout: 10_000 },
190 );
191
192 expect(result.status, result.stderr || result.stdout).toBe(0);
193 });
194 });