codemod 2.0.0-alpha.1 → 2.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -2
- package/codemod +17 -30
- package/package.json +80 -10
- package/register.d.mts +2 -0
- package/register.mjs +67 -0
- package/runtime/addon.d.mts +114 -0
- package/runtime/addon.mjs +55 -0
- package/runtime/ast-grep.d.mts +20 -0
- package/runtime/ast-grep.mjs +82 -0
- package/runtime/context.d.mts +49 -0
- package/runtime/context.mjs +59 -0
- package/runtime/hooks.d.mts +2 -0
- package/runtime/hooks.mjs +7 -0
- package/runtime/host.d.mts +121 -0
- package/runtime/host.mjs +450 -0
- package/runtime/llm.d.mts +2 -0
- package/runtime/llm.mjs +5 -0
- package/runtime/metrics.d.mts +9 -0
- package/runtime/metrics.mjs +42 -0
- package/runtime/modules.d.mts +3 -0
- package/runtime/modules.mjs +17 -0
- package/runtime/orchestrator-version.d.mts +2 -0
- package/runtime/orchestrator-version.mjs +3 -0
- package/runtime/orchestrator.d.mts +261 -0
- package/runtime/orchestrator.mjs +879 -0
- package/runtime/runtime.d.mts +15 -0
- package/runtime/runtime.mjs +40 -0
- package/runtime/workflow.d.mts +19 -0
- package/runtime/workflow.mjs +126 -0
- package/testing/index.d.mts +157 -0
- package/testing/index.mjs +648 -0
- package/types/index.d.ts +8 -0
- package/types/langs/angular.d.ts +5 -0
- package/types/langs/c.d.ts +5 -0
- package/types/langs/c_sharp.d.ts +5 -0
- package/types/langs/cpp.d.ts +5 -0
- package/types/langs/css.d.ts +5 -0
- package/types/langs/elixir.d.ts +5 -0
- package/types/langs/go.d.ts +5 -0
- package/types/langs/html.d.ts +5 -0
- package/types/langs/java.d.ts +5 -0
- package/types/langs/javascript.d.ts +5 -0
- package/types/langs/json.d.ts +5 -0
- package/types/langs/kotlin.d.ts +5 -0
- package/types/langs/package.json +3 -0
- package/types/langs/php.d.ts +5 -0
- package/types/langs/python.d.ts +5 -0
- package/types/langs/ruby.d.ts +5 -0
- package/types/langs/rust.d.ts +5 -0
- package/types/langs/scala.d.ts +5 -0
- package/types/langs/toml.d.ts +5 -0
- package/types/langs/tsx.d.ts +5 -0
- package/types/langs/typescript.d.ts +5 -0
- package/types/langs/xml.d.ts +5 -0
- package/types/langs/yaml.d.ts +5 -0
- package/types/llm.d.ts +6 -0
- package/types/llrt/abort.d.ts +69 -0
- package/types/llrt/assert.d.ts +39 -0
- package/types/llrt/async_hooks.d.ts +210 -0
- package/types/llrt/buffer.d.ts +1186 -0
- package/types/llrt/child_process.d.ts +447 -0
- package/types/llrt/console.d.ts +210 -0
- package/types/llrt/crypto.d.ts +854 -0
- package/types/llrt/dgram.d.ts +381 -0
- package/types/llrt/dns.d.ts +124 -0
- package/types/llrt/dom-events.d.ts +51 -0
- package/types/llrt/events.d.ts +245 -0
- package/types/llrt/exceptions.d.ts +26 -0
- package/types/llrt/fetch.d.ts +332 -0
- package/types/llrt/fs/promises.d.ts +554 -0
- package/types/llrt/fs.d.ts +360 -0
- package/types/llrt/globals.d.ts +23 -0
- package/types/llrt/https.d.ts +27 -0
- package/types/llrt/index.d.ts +33 -0
- package/types/llrt/module.d.ts +285 -0
- package/types/llrt/navigator.d.ts +9 -0
- package/types/llrt/net.d.ts +488 -0
- package/types/llrt/os.d.ts +293 -0
- package/types/llrt/path.d.ts +150 -0
- package/types/llrt/perf_hooks.d.ts +23 -0
- package/types/llrt/process.d.ts +502 -0
- package/types/llrt/stream/web.d.ts +526 -0
- package/types/llrt/stream.d.ts +366 -0
- package/types/llrt/string_decoder.d.ts +63 -0
- package/types/llrt/timers.d.ts +72 -0
- package/types/llrt/timezone.d.ts +101 -0
- package/types/llrt/tty.d.ts +11 -0
- package/types/llrt/url.d.ts +774 -0
- package/types/llrt/util.d.ts +240 -0
- package/types/llrt/zlib.d.ts +177 -0
- package/types/main.d.ts +5 -0
- package/types/metrics.d.ts +5 -0
- package/types/modules/ast-grep.d.ts +634 -0
- package/types/modules/langs.d.ts +87 -0
- package/types/modules/llm.d.ts +23 -0
- package/types/modules/metrics.d.ts +107 -0
- package/types/modules/runtime.d.ts +66 -0
- package/types/modules/workflow.d.ts +915 -0
- package/types/runtime.d.ts +6 -0
- package/types/workflow.d.ts +5 -0
- package/vite.d.mts +7 -0
- package/vite.mjs +32 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Which run, and which step of it, the code running now belongs to. The
|
|
2
|
+
// `codemod/*` modules are singletons, and runs may overlap (tests in
|
|
3
|
+
// parallel), so they look the run up here.
|
|
4
|
+
//
|
|
5
|
+
// The store is shared through a global symbol, so it stays one store when a
|
|
6
|
+
// test runner loads this package twice (once natively, once through its own
|
|
7
|
+
// module graph).
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
const KEY = Symbol.for("codemod.workflow.context");
|
|
10
|
+
const shared = globalThis;
|
|
11
|
+
export const context = (shared[KEY] ??= new AsyncLocalStorage());
|
|
12
|
+
/** The run the calling code belongs to; throws outside a run. */
|
|
13
|
+
export function current(what) {
|
|
14
|
+
const store = context.getStore();
|
|
15
|
+
if (!store) {
|
|
16
|
+
throw new Error(`${what} only works while a workflow runs; run the workflow with codemod (the CLI, or runWorkflow from codemod/testing)`);
|
|
17
|
+
}
|
|
18
|
+
return store;
|
|
19
|
+
}
|
|
20
|
+
/** A fresh step scope, starting from the workflow state the step began with. */
|
|
21
|
+
export function stepScope(position, label, state, language) {
|
|
22
|
+
const entries = Object.entries(state ?? {});
|
|
23
|
+
return {
|
|
24
|
+
position,
|
|
25
|
+
label,
|
|
26
|
+
state: new Map(entries.map(([key, value]) => [key, structuredClone(value)])),
|
|
27
|
+
initial: new Map(entries.map(([key, value]) => [key, JSON.stringify(value)])),
|
|
28
|
+
unpersisted: new Set(),
|
|
29
|
+
removed: new Set(),
|
|
30
|
+
outputs: new Map(),
|
|
31
|
+
metrics: new Map(),
|
|
32
|
+
failure: undefined,
|
|
33
|
+
language,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The state a step set or removed (`null`), compared with the state it
|
|
38
|
+
* started with: what the engine's isolates report for the same code.
|
|
39
|
+
*/
|
|
40
|
+
export function stateChanges(scope) {
|
|
41
|
+
const changes = {};
|
|
42
|
+
for (const [key, value] of scope.state) {
|
|
43
|
+
if (scope.unpersisted.has(key))
|
|
44
|
+
continue;
|
|
45
|
+
// What a step sets was made JSON when it was set (`stateValue`).
|
|
46
|
+
if (scope.initial.get(key) !== JSON.stringify(value))
|
|
47
|
+
changes[key] = value;
|
|
48
|
+
}
|
|
49
|
+
for (const key of scope.removed)
|
|
50
|
+
changes[key] = null;
|
|
51
|
+
return changes;
|
|
52
|
+
}
|
|
53
|
+
/** The metrics a step recorded, as the engine reports them. */
|
|
54
|
+
export function metricsOf(scope) {
|
|
55
|
+
const data = {};
|
|
56
|
+
for (const [name, entries] of scope.metrics)
|
|
57
|
+
data[name] = [...entries.values()];
|
|
58
|
+
return data;
|
|
59
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Resolve hooks for Node.js versions without `module.registerHooks`
|
|
2
|
+
// (loaded through `module.register`, on the loader thread).
|
|
3
|
+
import { resolveCodemodModule } from "./modules.mjs";
|
|
4
|
+
export const resolve = async (specifier, context, nextResolve) => {
|
|
5
|
+
const url = resolveCodemodModule(specifier);
|
|
6
|
+
return url ? { url, shortCircuit: true } : nextResolve(specifier, context);
|
|
7
|
+
};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run a workflow in this Node.js or Bun process.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { runWorkflow } from "codemod/host";
|
|
6
|
+
*
|
|
7
|
+
* const report = await runWorkflow("./my-codemod", { target: "./repo" });
|
|
8
|
+
* if (report.status !== "succeeded") throw new Error(report.error ?? report.status);
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* The workflow's body, function steps and `forEachFile` callbacks run here,
|
|
12
|
+
* so they can be debugged, covered and mocked. Host tasks (`jssg`, `shell`,
|
|
13
|
+
* `codemod`, ...) and the run store go through the native addon.
|
|
14
|
+
*
|
|
15
|
+
* Code here has whatever Node.js gives it: the capabilities codemod.yaml
|
|
16
|
+
* declares are not enforced. The codemod CLI runs workflows in its own
|
|
17
|
+
* sandboxed runtime instead; run packages from the registry with the CLI.
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
import "../register.mts";
|
|
22
|
+
import type { JsonValue } from "../testing/index.mts";
|
|
23
|
+
/** A `URL` (`new URL("./workflow.ts", import.meta.url)`); only `file:` URLs are paths. */
|
|
24
|
+
export interface UrlLike {
|
|
25
|
+
readonly href: string;
|
|
26
|
+
}
|
|
27
|
+
/** An `AbortSignal`, or what a test environment has in its place. */
|
|
28
|
+
export interface AbortSignalLike {
|
|
29
|
+
readonly aborted: boolean;
|
|
30
|
+
addEventListener?(type: "abort", listener: () => void, options?: {
|
|
31
|
+
once?: boolean;
|
|
32
|
+
}): void;
|
|
33
|
+
removeEventListener?(type: "abort", listener: () => void): void;
|
|
34
|
+
}
|
|
35
|
+
/** A workflow module: what `import("./workflow.ts")` gives. */
|
|
36
|
+
export interface WorkflowModule {
|
|
37
|
+
default: (context: {
|
|
38
|
+
params: Record<string, JsonValue>;
|
|
39
|
+
target: string;
|
|
40
|
+
dryRun: boolean;
|
|
41
|
+
}) => unknown;
|
|
42
|
+
}
|
|
43
|
+
export interface HostRunOptions {
|
|
44
|
+
/** The directory the workflow changes. Default: the current directory. */
|
|
45
|
+
target?: string;
|
|
46
|
+
/** The workflow's parameters. */
|
|
47
|
+
params?: Record<string, JsonValue>;
|
|
48
|
+
/** A name for the run, where runs are listed. */
|
|
49
|
+
name?: string;
|
|
50
|
+
/** Run every step but change no files. */
|
|
51
|
+
dryRun?: boolean;
|
|
52
|
+
/** Stop after the step with this label (a test run). */
|
|
53
|
+
until?: string;
|
|
54
|
+
/** Results for steps that should not run, by label (a test run). */
|
|
55
|
+
given?: Record<string, JsonValue>;
|
|
56
|
+
/** Give every approval the workflow asks for. Default `true`. */
|
|
57
|
+
approve?: boolean;
|
|
58
|
+
/** Capabilities for host tasks' transforms, on top of those codemod.yaml declares. */
|
|
59
|
+
capabilities?: ("fs" | "fetch" | "child_process")[];
|
|
60
|
+
/** Which workflow to run when codemod.yaml defines several. */
|
|
61
|
+
workflowName?: string;
|
|
62
|
+
/**
|
|
63
|
+
* `"memory"` (the default) keeps nothing; `"local"` records the run where
|
|
64
|
+
* `codemod workflow list` and `status` show it.
|
|
65
|
+
*/
|
|
66
|
+
store?: "memory" | "local";
|
|
67
|
+
/**
|
|
68
|
+
* Continue this run (with `store: "local"`). A run is resumed by the host
|
|
69
|
+
* that started it: one started here cannot be resumed with
|
|
70
|
+
* `codemod workflow resume`, nor one the CLI started here.
|
|
71
|
+
*/
|
|
72
|
+
resume?: string;
|
|
73
|
+
/** The workflow file, when `workflow` is the module itself. */
|
|
74
|
+
path?: string;
|
|
75
|
+
/** Instead of `path`: the directory relative task paths resolve against. */
|
|
76
|
+
workflowDir?: string;
|
|
77
|
+
/** Send `console` output of the workflow's code to the report's events. */
|
|
78
|
+
captureConsole?: boolean;
|
|
79
|
+
/** Stops the run. */
|
|
80
|
+
signal?: AbortSignalLike;
|
|
81
|
+
}
|
|
82
|
+
export interface HostStepReport {
|
|
83
|
+
readonly position: number;
|
|
84
|
+
readonly label: string;
|
|
85
|
+
/** `"partial"`: the step finished, but some of its files failed. */
|
|
86
|
+
readonly status: "succeeded" | "partial" | "failed";
|
|
87
|
+
readonly result: JsonValue | null;
|
|
88
|
+
readonly error: string | null;
|
|
89
|
+
readonly given: boolean;
|
|
90
|
+
}
|
|
91
|
+
export interface HostRunReport {
|
|
92
|
+
readonly runId: string;
|
|
93
|
+
readonly status: "succeeded" | "failed" | "canceled" | "awaiting-approval" | "stopped";
|
|
94
|
+
readonly output: JsonValue | null;
|
|
95
|
+
readonly error: string | null;
|
|
96
|
+
/** The approval the run waits for. */
|
|
97
|
+
readonly awaiting: string | null;
|
|
98
|
+
/** The `until` step the run stopped after. */
|
|
99
|
+
readonly stoppedAt: string | null;
|
|
100
|
+
readonly steps: readonly HostStepReport[];
|
|
101
|
+
readonly metrics: Record<string, unknown>;
|
|
102
|
+
readonly stats: {
|
|
103
|
+
readonly filesModified: number;
|
|
104
|
+
readonly filesUnmodified: number;
|
|
105
|
+
readonly filesWithErrors: number;
|
|
106
|
+
};
|
|
107
|
+
/** What the engine reported while the run progressed. */
|
|
108
|
+
readonly events: readonly ({
|
|
109
|
+
readonly event: string;
|
|
110
|
+
} & Record<string, unknown>)[];
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Run a workflow (a workflow file, a package directory, or the workflow
|
|
114
|
+
* module itself). Resolves for every outcome; rejects when the workflow
|
|
115
|
+
* cannot be loaded. YAML workflows run only with the CLI.
|
|
116
|
+
*
|
|
117
|
+
* A module (`await import("./workflow.ts")`), for test runners that should
|
|
118
|
+
* load it through their own module system, needs `options.path` (or
|
|
119
|
+
* `options.workflowDir`) so relative task paths resolve.
|
|
120
|
+
*/
|
|
121
|
+
export declare function runWorkflow(workflow: string | UrlLike | WorkflowModule, options?: HostRunOptions): Promise<HostRunReport>;
|
package/runtime/host.mjs
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
// `codemod/host`: run a workflow in this Node.js or Bun process.
|
|
2
|
+
//
|
|
3
|
+
// The workflow module is imported here (or given already imported), so its
|
|
4
|
+
// body, function steps and `forEachFile` callbacks run in this process: they
|
|
5
|
+
// can be debugged, covered and mocked like any other code. What the engine
|
|
6
|
+
// owns goes through the native addon: the run store, host tasks (`jssg`,
|
|
7
|
+
// `shell`, `codemod`, ...), and selecting and committing files.
|
|
8
|
+
//
|
|
9
|
+
// Code here has whatever Node.js gives it: capabilities are not enforced.
|
|
10
|
+
// The codemod CLI runs workflows in its own sandboxed runtime instead.
|
|
11
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
12
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
13
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
14
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return path;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Run a workflow in this Node.js or Bun process.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { runWorkflow } from "codemod/host";
|
|
24
|
+
*
|
|
25
|
+
* const report = await runWorkflow("./my-codemod", { target: "./repo" });
|
|
26
|
+
* if (report.status !== "succeeded") throw new Error(report.error ?? report.status);
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* The workflow's body, function steps and `forEachFile` callbacks run here,
|
|
30
|
+
* so they can be debugged, covered and mocked. Host tasks (`jssg`, `shell`,
|
|
31
|
+
* `codemod`, ...) and the run store go through the native addon.
|
|
32
|
+
*
|
|
33
|
+
* Code here has whatever Node.js gives it: the capabilities codemod.yaml
|
|
34
|
+
* declares are not enforced. The codemod CLI runs workflows in its own
|
|
35
|
+
* sandboxed runtime instead; run packages from the registry with the CLI.
|
|
36
|
+
*
|
|
37
|
+
* @module
|
|
38
|
+
*/
|
|
39
|
+
import "../register.mjs";
|
|
40
|
+
import { isAbsolute, resolve } from "node:path";
|
|
41
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
42
|
+
import { addon } from "./addon.mjs";
|
|
43
|
+
import { context, metricsOf, stateChanges, stepScope } from "./context.mjs";
|
|
44
|
+
import { ORCHESTRATOR_VERSION } from "./orchestrator-version.mjs";
|
|
45
|
+
import { AwaitingApprovalError, CanceledError, checkJson, createRuntime, describeDuration, describeError, fileHandle, } from "./orchestrator.mjs";
|
|
46
|
+
import { callbackId } from "./workflow.mjs";
|
|
47
|
+
/**
|
|
48
|
+
* Run a workflow (a workflow file, a package directory, or the workflow
|
|
49
|
+
* module itself). Resolves for every outcome; rejects when the workflow
|
|
50
|
+
* cannot be loaded. YAML workflows run only with the CLI.
|
|
51
|
+
*
|
|
52
|
+
* A module (`await import("./workflow.ts")`), for test runners that should
|
|
53
|
+
* load it through their own module system, needs `options.path` (or
|
|
54
|
+
* `options.workflowDir`) so relative task paths resolve.
|
|
55
|
+
*/
|
|
56
|
+
export async function runWorkflow(workflow, options = {}) {
|
|
57
|
+
const native = addon();
|
|
58
|
+
checkAddon(native);
|
|
59
|
+
const { path, load } = locate(workflow, options);
|
|
60
|
+
// A workflow that cannot be loaded is not a run: reject.
|
|
61
|
+
const module = await load();
|
|
62
|
+
const main = module?.default;
|
|
63
|
+
if (typeof main !== "function") {
|
|
64
|
+
throw new TypeError(`${path} must export a default function`);
|
|
65
|
+
}
|
|
66
|
+
if (options.captureConsole)
|
|
67
|
+
captureConsole();
|
|
68
|
+
const run = native.Run.open({
|
|
69
|
+
workflow: path,
|
|
70
|
+
target: resolve(options.target ?? "."),
|
|
71
|
+
params: options.params ?? {},
|
|
72
|
+
name: options.name,
|
|
73
|
+
dryRun: options.dryRun ?? false,
|
|
74
|
+
until: options.until,
|
|
75
|
+
given: options.given,
|
|
76
|
+
approve: options.approve ?? true,
|
|
77
|
+
capabilities: options.capabilities ?? [],
|
|
78
|
+
store: options.store,
|
|
79
|
+
resume: options.resume,
|
|
80
|
+
});
|
|
81
|
+
const flight = inFlight();
|
|
82
|
+
const runtime = createRuntime(host(run, flight, () => runtime));
|
|
83
|
+
flight.closed = () => runtime.isClosed();
|
|
84
|
+
const scope = { run, runtime, captureConsole: options.captureConsole ?? false };
|
|
85
|
+
const abort = () => run.cancel();
|
|
86
|
+
if (options.signal?.aborted)
|
|
87
|
+
abort();
|
|
88
|
+
options.signal?.addEventListener?.("abort", abort, { once: true });
|
|
89
|
+
let body;
|
|
90
|
+
try {
|
|
91
|
+
const input = { params: run.params, target: run.target, dryRun: run.dryRun };
|
|
92
|
+
const ended = context
|
|
93
|
+
.run(scope, async () => main(input))
|
|
94
|
+
.then((output) => ({ status: "succeeded", detail: toJson(output) }));
|
|
95
|
+
body = await Promise.race([ended, flight.stalled]);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
body = endingOf(error);
|
|
99
|
+
}
|
|
100
|
+
// Steps still running finish and are recorded before the run reports;
|
|
101
|
+
// none starts from here on.
|
|
102
|
+
runtime.close();
|
|
103
|
+
await flight.idle();
|
|
104
|
+
options.signal?.removeEventListener?.("abort", abort);
|
|
105
|
+
const report = run.finish(JSON.stringify(body));
|
|
106
|
+
return { ...report, events: run.takeEvents() };
|
|
107
|
+
}
|
|
108
|
+
let addonChecked = false;
|
|
109
|
+
/**
|
|
110
|
+
* The addon and this package share the orchestrator: one from another
|
|
111
|
+
* version would record and replay steps differently.
|
|
112
|
+
*/
|
|
113
|
+
function checkAddon(native) {
|
|
114
|
+
if (addonChecked)
|
|
115
|
+
return;
|
|
116
|
+
// An addon from before the check by version has no `orchestratorVersion`.
|
|
117
|
+
const built = typeof native.orchestratorVersion === "function" ? native.orchestratorVersion() : undefined;
|
|
118
|
+
if (built !== ORCHESTRATOR_VERSION) {
|
|
119
|
+
throw new Error("the codemod native addon is from another version than the codemod package; reinstall codemod so both match (in a checkout, rebuild both: `cargo build -p codemod-node` and `pnpm --filter codemod build`)");
|
|
120
|
+
}
|
|
121
|
+
addonChecked = true;
|
|
122
|
+
}
|
|
123
|
+
const CONSOLE_METHODS = ["log", "info", "debug", "warn", "error"];
|
|
124
|
+
/**
|
|
125
|
+
* Route `console` output of code that runs in a run started with
|
|
126
|
+
* `captureConsole` to the run's logs, by step. Other code is untouched.
|
|
127
|
+
*/
|
|
128
|
+
function captureConsole() {
|
|
129
|
+
const key = Symbol.for("codemod.host.console");
|
|
130
|
+
const shared = globalThis;
|
|
131
|
+
if (shared[key])
|
|
132
|
+
return;
|
|
133
|
+
shared[key] = true;
|
|
134
|
+
for (const method of CONSOLE_METHODS) {
|
|
135
|
+
const original = console[method].bind(console);
|
|
136
|
+
console[method] = (...items) => {
|
|
137
|
+
const store = context.getStore();
|
|
138
|
+
if (!store?.captureConsole)
|
|
139
|
+
return original(...items);
|
|
140
|
+
store.run.log(store.step?.position ?? null, items.map(formatLogItem).join(" "));
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function formatLogItem(value) {
|
|
145
|
+
if (typeof value === "string")
|
|
146
|
+
return value;
|
|
147
|
+
if (value instanceof Error)
|
|
148
|
+
return value.stack || `${value.name}: ${value.message}`;
|
|
149
|
+
try {
|
|
150
|
+
return JSON.stringify(value) ?? String(value);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return String(value);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** Where the workflow is, and how to load it. */
|
|
157
|
+
function locate(workflow, options) {
|
|
158
|
+
if (typeof workflow !== "string" && !isUrl(workflow)) {
|
|
159
|
+
if (!options.path && !options.workflowDir) {
|
|
160
|
+
throw new TypeError("runWorkflow(module, { path }): give the workflow file's path, so relative task paths resolve");
|
|
161
|
+
}
|
|
162
|
+
// The file need not exist: only its directory matters here.
|
|
163
|
+
const file = options.path
|
|
164
|
+
? resolve(String(options.path))
|
|
165
|
+
: resolve(String(options.workflowDir), "workflow.ts");
|
|
166
|
+
return { path: file, load: async () => workflow };
|
|
167
|
+
}
|
|
168
|
+
const source = isUrl(workflow) ? fileURLToPath(workflow.href) : String(workflow);
|
|
169
|
+
const path = addon().resolveWorkflow(isAbsolute(source) ? source : resolve(source), options.workflowName ?? null);
|
|
170
|
+
if (!/\.m?ts$|\.m?js$/.test(path)) {
|
|
171
|
+
throw new Error(`${path} is not a TypeScript workflow; run YAML workflows with the codemod CLI, or upgrade them with \`codemod workflow upgrade\``);
|
|
172
|
+
}
|
|
173
|
+
return { path, load: () => import(__rewriteRelativeImportExtension(pathToFileURL(path).href)) };
|
|
174
|
+
}
|
|
175
|
+
function isRecord(value) {
|
|
176
|
+
return value !== null && typeof value === "object";
|
|
177
|
+
}
|
|
178
|
+
// Not `instanceof URL`: test environments may have their own URL class.
|
|
179
|
+
function isUrl(value) {
|
|
180
|
+
return isRecord(value) && typeof value.href === "string";
|
|
181
|
+
}
|
|
182
|
+
function inFlight() {
|
|
183
|
+
let count = 0;
|
|
184
|
+
let stall = () => { };
|
|
185
|
+
const waiters = [];
|
|
186
|
+
const flight = {
|
|
187
|
+
closed: () => false,
|
|
188
|
+
stalled: new Promise((resolvePromise) => (stall = resolvePromise)),
|
|
189
|
+
begin() {
|
|
190
|
+
count++;
|
|
191
|
+
},
|
|
192
|
+
end() {
|
|
193
|
+
count--;
|
|
194
|
+
flight.check();
|
|
195
|
+
},
|
|
196
|
+
check() {
|
|
197
|
+
setImmediate(() => {
|
|
198
|
+
if (count !== 0)
|
|
199
|
+
return;
|
|
200
|
+
if (flight.closed())
|
|
201
|
+
stall(null);
|
|
202
|
+
for (const waiter of waiters.splice(0))
|
|
203
|
+
waiter();
|
|
204
|
+
});
|
|
205
|
+
},
|
|
206
|
+
idle() {
|
|
207
|
+
return new Promise((resolvePromise) => {
|
|
208
|
+
waiters.push(resolvePromise);
|
|
209
|
+
flight.check();
|
|
210
|
+
});
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
return flight;
|
|
214
|
+
}
|
|
215
|
+
function host(run, flight, runtime) {
|
|
216
|
+
// Replayed steps settle one per turn of the event loop, so the body reacts
|
|
217
|
+
// to each before the next.
|
|
218
|
+
let replaying = false;
|
|
219
|
+
const replay = () => {
|
|
220
|
+
replaying = runtime().replayNext();
|
|
221
|
+
if (replaying)
|
|
222
|
+
setImmediate(replay);
|
|
223
|
+
};
|
|
224
|
+
return {
|
|
225
|
+
history: () => run.history(),
|
|
226
|
+
record: (entry, ms) => run.record(JSON.stringify(entry), ms),
|
|
227
|
+
event: (event) => run.event(JSON.stringify(event)),
|
|
228
|
+
canceled: () => run.refusesSteps(),
|
|
229
|
+
now: () => Date.now(),
|
|
230
|
+
advanceClock() { },
|
|
231
|
+
testPlan: () => run.testPlan(),
|
|
232
|
+
stop() {
|
|
233
|
+
run.stop();
|
|
234
|
+
flight.check();
|
|
235
|
+
},
|
|
236
|
+
wake() {
|
|
237
|
+
if (replaying)
|
|
238
|
+
return;
|
|
239
|
+
replaying = true;
|
|
240
|
+
setImmediate(replay);
|
|
241
|
+
},
|
|
242
|
+
evaluate: (kind, expression, scope) => run.evaluate(kind, expression, JSON.stringify(scope)),
|
|
243
|
+
callbackId,
|
|
244
|
+
async start(request) {
|
|
245
|
+
const { fn, ...task } = request;
|
|
246
|
+
flight.begin();
|
|
247
|
+
try {
|
|
248
|
+
if (fn)
|
|
249
|
+
return await within(task.timeoutMs, (limit) => runInPlace(run, task, fn, limit));
|
|
250
|
+
try {
|
|
251
|
+
return await run.runTask(JSON.stringify(task));
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
throw payloadOf(error);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
flight.end();
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/** A host task rejected with `{ name, message }` as JSON in the message. */
|
|
264
|
+
function payloadOf(error) {
|
|
265
|
+
const message = isRecord(error) && typeof error.message === "string" ? error.message : undefined;
|
|
266
|
+
try {
|
|
267
|
+
const payload = JSON.parse(message ?? "");
|
|
268
|
+
if (isRecord(payload) && typeof payload.message === "string") {
|
|
269
|
+
return { name: String(payload.name ?? "Error"), message: payload.message };
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// a plain message
|
|
274
|
+
}
|
|
275
|
+
return { name: "Error", message: message ?? String(error) };
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Run `work` for at most `ms`. JavaScript that is running cannot be stopped
|
|
279
|
+
* from outside: when the time is up the step fails, `limit.expired` tells
|
|
280
|
+
* the work to stop where it can, and whatever it still does is discarded.
|
|
281
|
+
*/
|
|
282
|
+
async function within(ms, work) {
|
|
283
|
+
const limit = { expired: false };
|
|
284
|
+
if (ms === undefined)
|
|
285
|
+
return work(limit);
|
|
286
|
+
let timer;
|
|
287
|
+
const late = new Promise((_, reject) => {
|
|
288
|
+
timer = setTimeout(() => {
|
|
289
|
+
limit.expired = true;
|
|
290
|
+
reject({ name: "Error", message: `timed out after ${describeDuration(ms)}` });
|
|
291
|
+
}, ms);
|
|
292
|
+
});
|
|
293
|
+
try {
|
|
294
|
+
return await Promise.race([work(limit), late]);
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
clearTimeout(timer);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
async function runInPlace(run, task, fn, limit) {
|
|
301
|
+
const outer = context.getStore();
|
|
302
|
+
if (!outer)
|
|
303
|
+
throw new Error("a step started outside its run");
|
|
304
|
+
if (task.task.kind === "function") {
|
|
305
|
+
const step = stepScope(task.position, task.label, task.state);
|
|
306
|
+
let value;
|
|
307
|
+
try {
|
|
308
|
+
value = await context.run({ ...outer, step }, () => fn());
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
// What the step measured counts even when it then fails.
|
|
312
|
+
flushMetrics(run, step);
|
|
313
|
+
}
|
|
314
|
+
// A failure reported with failStep() stands even if the code caught it.
|
|
315
|
+
if (step.failure !== undefined)
|
|
316
|
+
throw new Error(step.failure);
|
|
317
|
+
const result = value === undefined ? null : value;
|
|
318
|
+
checkJson(result, "the step's result");
|
|
319
|
+
return outcome(result, step);
|
|
320
|
+
}
|
|
321
|
+
if (task.task.kind === "forEachFile")
|
|
322
|
+
return forEachFile(run, outer, task, fn, limit);
|
|
323
|
+
throw new Error(`cannot run a ${task.task.kind} task in place`);
|
|
324
|
+
}
|
|
325
|
+
function outcome(result, step) {
|
|
326
|
+
const state = stateChanges(step);
|
|
327
|
+
return Object.keys(state).length ? { result, state } : { result };
|
|
328
|
+
}
|
|
329
|
+
function flushMetrics(run, step) {
|
|
330
|
+
const metrics = metricsOf(step);
|
|
331
|
+
if (Object.keys(metrics).length)
|
|
332
|
+
run.addMetrics(JSON.stringify(metrics));
|
|
333
|
+
return metrics;
|
|
334
|
+
}
|
|
335
|
+
async function forEachFile(run, outer, task, fn, limit) {
|
|
336
|
+
const selector = task.task.selector;
|
|
337
|
+
const { language, files } = await run.selectFiles(JSON.stringify(selector));
|
|
338
|
+
const step = stepScope(task.position, task.label, task.state, language ?? undefined);
|
|
339
|
+
const total = files.length;
|
|
340
|
+
const every = Math.max(1, Math.floor(total / 100));
|
|
341
|
+
let processed = 0;
|
|
342
|
+
const outputs = Array.from({ length: total });
|
|
343
|
+
const failures = [];
|
|
344
|
+
const effects = [];
|
|
345
|
+
const concurrency = selector.concurrency ?? 1;
|
|
346
|
+
const one = async (index, [path, text]) => {
|
|
347
|
+
const { file, effects: done, close } = fileHandle(path, text, step.language);
|
|
348
|
+
try {
|
|
349
|
+
step.failure = undefined;
|
|
350
|
+
const output = await context.run({ ...outer, step }, () => fn(file));
|
|
351
|
+
// A failure reported with failFile() stands even if the callback
|
|
352
|
+
// caught it. With files in flight together it cannot be told whose it
|
|
353
|
+
// was, as in the CLI.
|
|
354
|
+
if (step.failure !== undefined && concurrency === 1) {
|
|
355
|
+
failures.push({ path, error: step.failure });
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (output !== undefined) {
|
|
359
|
+
checkJson(output, "return value");
|
|
360
|
+
outputs[index] = { output };
|
|
361
|
+
}
|
|
362
|
+
if (done.length)
|
|
363
|
+
effects.push({ path, original: text, effects: done });
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
failures.push({ path, error: describeError(error) });
|
|
367
|
+
}
|
|
368
|
+
finally {
|
|
369
|
+
close();
|
|
370
|
+
processed++;
|
|
371
|
+
if (processed === total || processed % every === 0) {
|
|
372
|
+
run.progress(task.position, processed, total);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
let next = 0;
|
|
377
|
+
let sinceTurn = 0;
|
|
378
|
+
const worker = async () => {
|
|
379
|
+
for (;;) {
|
|
380
|
+
const index = next++;
|
|
381
|
+
const file = files[index];
|
|
382
|
+
if (!file)
|
|
383
|
+
return;
|
|
384
|
+
// Callbacks that never wait would keep the event loop to themselves:
|
|
385
|
+
// give it a turn now and then, so a cancel can arrive.
|
|
386
|
+
if (++sinceTurn >= 64) {
|
|
387
|
+
sinceTurn = 0;
|
|
388
|
+
await new Promise((turn) => setImmediate(turn));
|
|
389
|
+
}
|
|
390
|
+
if (run.refusesSteps())
|
|
391
|
+
throw new CanceledError();
|
|
392
|
+
if (limit.expired)
|
|
393
|
+
return;
|
|
394
|
+
await one(index, file);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, total) }, worker));
|
|
398
|
+
// Out of time: the step has already failed, and nothing it did is written.
|
|
399
|
+
if (limit.expired)
|
|
400
|
+
throw new CanceledError("the step ran out of time");
|
|
401
|
+
// Before the commit: a commit that fails must not lose what was measured.
|
|
402
|
+
const metrics = flushMetrics(run, step);
|
|
403
|
+
effects.sort((a, b) => (a.path < b.path ? -1 : 1));
|
|
404
|
+
const committed = await run.commitFiles(task.position, task.label, JSON.stringify(effects));
|
|
405
|
+
const allFailures = [...failures, ...committed.failures].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
406
|
+
// As the CLI does: each file that failed, then its error.
|
|
407
|
+
for (const { path, error } of allFailures) {
|
|
408
|
+
run.log(task.position, path);
|
|
409
|
+
for (const line of error.split("\n"))
|
|
410
|
+
run.log(task.position, ` ${line}`);
|
|
411
|
+
}
|
|
412
|
+
// The step fails when the callback failed on every file, and is partial
|
|
413
|
+
// when it failed on some.
|
|
414
|
+
const [first] = allFailures;
|
|
415
|
+
if (first && allFailures.length === total) {
|
|
416
|
+
throw new Error(`the callback failed on every file; first error: ${first.path}: ${first.error}`);
|
|
417
|
+
}
|
|
418
|
+
const result = outcome({
|
|
419
|
+
outputs: outputs.flatMap((entry) => (entry ? [entry.output] : [])),
|
|
420
|
+
changes: committed.changes,
|
|
421
|
+
failures: allFailures,
|
|
422
|
+
metrics,
|
|
423
|
+
}, step);
|
|
424
|
+
if (!allFailures.length)
|
|
425
|
+
return result;
|
|
426
|
+
return {
|
|
427
|
+
...result,
|
|
428
|
+
partial: `${allFailures.length} of ${total} ${total === 1 ? "file" : "files"} failed`,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
// -------------------------------------------------------------- ending ---
|
|
432
|
+
/** How a body that threw ended. */
|
|
433
|
+
function endingOf(error) {
|
|
434
|
+
const name = isRecord(error) ? error.name : undefined;
|
|
435
|
+
if (error instanceof CanceledError || name === "CanceledError") {
|
|
436
|
+
return { status: "canceled" };
|
|
437
|
+
}
|
|
438
|
+
if (error instanceof AwaitingApprovalError || name === "AwaitingApprovalError") {
|
|
439
|
+
return { status: "awaiting-approval", detail: String(error.message) };
|
|
440
|
+
}
|
|
441
|
+
const message = isRecord(error) && "message" in error
|
|
442
|
+
? `${String(name ?? "Error")}: ${String(error.message)}`
|
|
443
|
+
: String(error);
|
|
444
|
+
return { status: "failed", detail: message };
|
|
445
|
+
}
|
|
446
|
+
/** A value as JSON keeps it; what JSON has no form for (a function) is null. */
|
|
447
|
+
function toJson(value) {
|
|
448
|
+
const text = JSON.stringify(value);
|
|
449
|
+
return text === undefined ? null : JSON.parse(text);
|
|
450
|
+
}
|
package/runtime/llm.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { MetricEntry } from "./context.mts";
|
|
2
|
+
declare class MetricAtom {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
constructor(name: string);
|
|
5
|
+
increment(cardinality?: Record<string, unknown> | null, amount?: unknown): void;
|
|
6
|
+
getEntries(): MetricEntry[];
|
|
7
|
+
}
|
|
8
|
+
export declare function useMetricAtom(name: string): MetricAtom;
|
|
9
|
+
export { MetricAtom };
|