forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.ts
More file actions
438 lines (377 loc) · 11.3 KB
/
Copy pathrun.ts
File metadata and controls
438 lines (377 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import * as fs from "node:fs";
import * as path from "node:path";
import { execSync, spawn } from "node:child_process";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface ManifestEntry {
id: string;
file: string;
lang: string;
category: string;
source: string;
}
interface DoctestConfig {
python?: { deps: string[] };
typescript?: { deps: string[] };
node?: { deps: string[] };
}
interface Result {
id: string;
category: string;
status: "pass" | "fail";
error?: string;
}
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const OUTPUT_DIR = path.resolve(__dirname, "../../.doctest-output");
const MANIFEST_PATH = path.join(OUTPUT_DIR, "manifest.json");
const DEFAULT_ENV: Record<string, string> = {
OPENAI_API_KEY: "test-key",
OPENAI_BASE_URL: "http://localhost:4010",
};
const SERVER_TIMEOUT_MS = 30_000;
const SERVER_POLL_MS = 500;
const SCRIPT_TIMEOUT_MS = 30_000;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function validateDepName(dep: string): string {
if (!/^[@\w][\w./-]*(?:@[\w.^~>=<*-]+)?$/.test(dep)) {
throw new Error(`Invalid dependency name: ${dep}`);
}
return dep;
}
function loadDoctestConfig(snippetDir: string): DoctestConfig {
const configPath = path.join(snippetDir, "doctest.json");
if (fs.existsSync(configPath)) {
return JSON.parse(fs.readFileSync(configPath, "utf-8"));
}
return {};
}
function mergeEnv(extra?: Record<string, string>): Record<string, string> {
return { ...process.env, ...DEFAULT_ENV, ...extra } as Record<string, string>;
}
async function waitForPort(
port: number,
timeoutMs: number,
pollMs: number,
): Promise<boolean> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
const resp = await fetch(`http://localhost:${port}/`).catch(() => null);
if (resp) return true;
} catch {
// Server not ready yet
}
await new Promise((r) => setTimeout(r, pollMs));
}
return false;
}
function detectPort(code: string): number {
// Look for port=NNNN or PORT=NNNN or --port NNNN
const match = code.match(/\bport[=\s:]+(\d{4,5})/i);
return match ? parseInt(match[1], 10) : 8000;
}
// ---------------------------------------------------------------------------
// Runners
// ---------------------------------------------------------------------------
async function runPythonServer(
snippetDir: string,
entryFile: string,
config: DoctestConfig,
): Promise<Result> {
const id = path.basename(snippetDir);
const venvDir = path.join(snippetDir, ".venv");
try {
// Create virtualenv
execSync(`python3 -m venv ${venvDir}`, { cwd: snippetDir, stdio: "pipe" });
const pip = path.join(venvDir, "bin", "pip");
const python = path.join(venvDir, "bin", "python");
// Install deps
const deps = config.python?.deps || [];
if (deps.length > 0) {
const safeDeps = deps.map(validateDepName);
execSync(`${pip} install ${safeDeps.join(" ")}`, {
cwd: snippetDir,
stdio: "pipe",
timeout: 120_000,
});
}
const code = fs.readFileSync(path.join(snippetDir, entryFile), "utf-8");
const port = detectPort(code);
// Start server
const proc = spawn(python, [entryFile], {
cwd: snippetDir,
env: mergeEnv(),
stdio: "pipe",
});
try {
const ready = await waitForPort(port, SERVER_TIMEOUT_MS, SERVER_POLL_MS);
if (!ready) {
return {
id,
category: "server",
status: "fail",
error: `Server did not bind to port ${port} within ${SERVER_TIMEOUT_MS}ms`,
};
}
return { id, category: "server", status: "pass" };
} finally {
try {
proc.kill("SIGTERM");
} catch {}
}
} catch (e: any) {
return {
id,
category: "server",
status: "fail",
error: e.message || String(e),
};
}
}
async function runTypeScriptServer(
snippetDir: string,
entryFile: string,
config: DoctestConfig,
): Promise<Result> {
const id = path.basename(snippetDir);
try {
// Init and install deps
execSync("npm init -y", { cwd: snippetDir, stdio: "pipe" });
const deps = config.typescript?.deps || config.node?.deps || [];
if (deps.length > 0) {
const safeDeps = deps.map(validateDepName);
execSync(`npm install ${safeDeps.join(" ")}`, {
cwd: snippetDir,
stdio: "pipe",
timeout: 120_000,
});
}
const code = fs.readFileSync(path.join(snippetDir, entryFile), "utf-8");
const port = detectPort(code);
// Determine runner
const runner = entryFile.endsWith(".ts") ? "npx tsx" : "node";
const proc = spawn(
runner.split(" ")[0],
[...runner.split(" ").slice(1), entryFile],
{
cwd: snippetDir,
env: mergeEnv(),
stdio: "pipe",
},
);
try {
const ready = await waitForPort(port, SERVER_TIMEOUT_MS, SERVER_POLL_MS);
if (!ready) {
return {
id,
category: "server",
status: "fail",
error: `Server did not bind to port ${port} within ${SERVER_TIMEOUT_MS}ms`,
};
}
return { id, category: "server", status: "pass" };
} finally {
try {
proc.kill("SIGTERM");
} catch {}
}
} catch (e: any) {
return {
id,
category: "server",
status: "fail",
error: e.message || String(e),
};
}
}
async function runScript(
snippetDir: string,
entryFile: string,
lang: string,
config: DoctestConfig,
): Promise<Result> {
const id = path.basename(snippetDir);
try {
if (lang === "python") {
const venvDir = path.join(snippetDir, ".venv");
execSync(`python3 -m venv ${venvDir}`, {
cwd: snippetDir,
stdio: "pipe",
});
const pip = path.join(venvDir, "bin", "pip");
const python = path.join(venvDir, "bin", "python");
const deps = config.python?.deps || [];
if (deps.length > 0) {
const safeDeps = deps.map(validateDepName);
execSync(`${pip} install ${safeDeps.join(" ")}`, {
cwd: snippetDir,
stdio: "pipe",
timeout: 120_000,
});
}
execSync(`${python} ${entryFile}`, {
cwd: snippetDir,
env: mergeEnv(),
stdio: "pipe",
timeout: SCRIPT_TIMEOUT_MS,
});
} else {
execSync("npm init -y", { cwd: snippetDir, stdio: "pipe" });
const deps = config.typescript?.deps || config.node?.deps || [];
if (deps.length > 0) {
const safeDeps = deps.map(validateDepName);
execSync(`npm install ${safeDeps.join(" ")}`, {
cwd: snippetDir,
stdio: "pipe",
timeout: 120_000,
});
}
const runner = entryFile.endsWith(".ts") ? "npx tsx" : "node";
execSync(`${runner} ${entryFile}`, {
cwd: snippetDir,
env: mergeEnv(),
stdio: "pipe",
timeout: SCRIPT_TIMEOUT_MS,
});
}
return { id, category: "script", status: "pass" };
} catch (e: any) {
return {
id,
category: "script",
status: "fail",
error: e.message || String(e),
};
}
}
async function runComponent(
snippetDir: string,
entryFile: string,
config: DoctestConfig,
): Promise<Result> {
const id = path.basename(snippetDir);
try {
execSync("npm init -y", { cwd: snippetDir, stdio: "pipe" });
const deps = config.typescript?.deps || [];
const baseDeps = ["typescript", "@types/react", "@types/node"];
const allDeps = [...new Set([...baseDeps, ...deps])];
const safeAllDeps = allDeps.map(validateDepName);
execSync(`npm install ${safeAllDeps.join(" ")}`, {
cwd: snippetDir,
stdio: "pipe",
timeout: 120_000,
});
// Write minimal tsconfig if none exists
const tsconfigPath = path.join(snippetDir, "tsconfig.json");
if (!fs.existsSync(tsconfigPath)) {
fs.writeFileSync(
tsconfigPath,
JSON.stringify(
{
compilerOptions: {
target: "ES2020",
module: "ESNext",
moduleResolution: "bundler",
jsx: "react-jsx",
strict: true,
noEmit: true,
esModuleInterop: true,
skipLibCheck: true,
},
include: [entryFile],
},
null,
2,
),
"utf-8",
);
}
execSync("npx tsc --noEmit", {
cwd: snippetDir,
stdio: "pipe",
timeout: SCRIPT_TIMEOUT_MS,
});
return { id, category: "component", status: "pass" };
} catch (e: any) {
return {
id,
category: "component",
status: "fail",
error: e.message || String(e),
};
}
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main() {
if (!fs.existsSync(MANIFEST_PATH)) {
console.error(
`Manifest not found at ${MANIFEST_PATH}. Run extract.ts first.`,
);
process.exit(1);
}
const manifest: ManifestEntry[] = JSON.parse(
fs.readFileSync(MANIFEST_PATH, "utf-8"),
);
if (manifest.length === 0) {
console.log("No doctest snippets found in manifest.");
process.exit(0);
}
console.log(`Running ${manifest.length} doctest snippet(s)...\n`);
const results: Result[] = [];
for (const entry of manifest) {
const snippetDir = path.join(OUTPUT_DIR, path.dirname(entry.file));
const entryFile = path.basename(entry.file);
const config = loadDoctestConfig(snippetDir);
console.log(` Running: ${entry.id} [${entry.category}/${entry.lang}]`);
let result: Result;
if (entry.category === "server") {
if (entry.lang === "python") {
result = await runPythonServer(snippetDir, entryFile, config);
} else {
result = await runTypeScriptServer(snippetDir, entryFile, config);
}
} else if (entry.category === "script") {
result = await runScript(snippetDir, entryFile, entry.lang, config);
} else if (entry.category === "component") {
result = await runComponent(snippetDir, entryFile, config);
} else {
result = {
id: entry.id,
category: entry.category,
status: "fail",
error: `Unknown category: ${entry.category}`,
};
}
results.push(result);
const icon = result.status === "pass" ? "PASS" : "FAIL";
console.log(
` ${icon}: ${entry.id}${result.error ? ` — ${result.error}` : ""}\n`,
);
}
// Summary
const passed = results.filter((r) => r.status === "pass").length;
const failed = results.filter((r) => r.status === "fail").length;
console.log("─".repeat(60));
console.log(
`Results: ${passed} passed, ${failed} failed, ${results.length} total`,
);
console.log("─".repeat(60));
if (failed > 0) {
console.log("\nFailed snippets:");
for (const r of results.filter((r) => r.status === "fail")) {
console.log(` ${r.id}: ${r.error}`);
}
process.exit(1);
}
}
main().catch((e) => {
console.error("Unexpected error:", e);
process.exit(1);
});