codemod 1.18.7 → 2.0.0-alpha.2

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.
Files changed (89) hide show
  1. package/README.md +57 -2
  2. package/codemod +17 -30
  3. package/package.json +78 -10
  4. package/register.d.mts +11 -0
  5. package/register.mjs +60 -0
  6. package/runtime/addon.mjs +59 -0
  7. package/runtime/ast-grep.mjs +93 -0
  8. package/runtime/context.mjs +77 -0
  9. package/runtime/hooks.mjs +9 -0
  10. package/runtime/host.d.mts +120 -0
  11. package/runtime/host.mjs +390 -0
  12. package/runtime/llm.mjs +11 -0
  13. package/runtime/metrics.mjs +45 -0
  14. package/runtime/modules.mjs +19 -0
  15. package/runtime/orchestrator.mjs +657 -0
  16. package/runtime/runtime.mjs +48 -0
  17. package/runtime/workflow.mjs +135 -0
  18. package/testing/index.d.mts +203 -0
  19. package/testing/index.mjs +638 -0
  20. package/types/index.d.ts +8 -0
  21. package/types/langs/angular.d.ts +5 -0
  22. package/types/langs/c.d.ts +5 -0
  23. package/types/langs/c_sharp.d.ts +5 -0
  24. package/types/langs/cpp.d.ts +5 -0
  25. package/types/langs/css.d.ts +5 -0
  26. package/types/langs/elixir.d.ts +5 -0
  27. package/types/langs/go.d.ts +5 -0
  28. package/types/langs/html.d.ts +5 -0
  29. package/types/langs/java.d.ts +5 -0
  30. package/types/langs/javascript.d.ts +5 -0
  31. package/types/langs/json.d.ts +5 -0
  32. package/types/langs/kotlin.d.ts +5 -0
  33. package/types/langs/php.d.ts +5 -0
  34. package/types/langs/python.d.ts +5 -0
  35. package/types/langs/ruby.d.ts +5 -0
  36. package/types/langs/rust.d.ts +5 -0
  37. package/types/langs/scala.d.ts +5 -0
  38. package/types/langs/toml.d.ts +5 -0
  39. package/types/langs/tsx.d.ts +5 -0
  40. package/types/langs/typescript.d.ts +5 -0
  41. package/types/langs/xml.d.ts +5 -0
  42. package/types/langs/yaml.d.ts +5 -0
  43. package/types/llm.d.ts +6 -0
  44. package/types/llrt/abort.d.ts +69 -0
  45. package/types/llrt/assert.d.ts +39 -0
  46. package/types/llrt/async_hooks.d.ts +210 -0
  47. package/types/llrt/buffer.d.ts +1186 -0
  48. package/types/llrt/child_process.d.ts +447 -0
  49. package/types/llrt/console.d.ts +210 -0
  50. package/types/llrt/crypto.d.ts +854 -0
  51. package/types/llrt/dgram.d.ts +381 -0
  52. package/types/llrt/dns.d.ts +124 -0
  53. package/types/llrt/dom-events.d.ts +51 -0
  54. package/types/llrt/events.d.ts +245 -0
  55. package/types/llrt/exceptions.d.ts +26 -0
  56. package/types/llrt/fetch.d.ts +332 -0
  57. package/types/llrt/fs/promises.d.ts +554 -0
  58. package/types/llrt/fs.d.ts +360 -0
  59. package/types/llrt/globals.d.ts +23 -0
  60. package/types/llrt/https.d.ts +27 -0
  61. package/types/llrt/index.d.ts +33 -0
  62. package/types/llrt/module.d.ts +285 -0
  63. package/types/llrt/navigator.d.ts +9 -0
  64. package/types/llrt/net.d.ts +488 -0
  65. package/types/llrt/os.d.ts +293 -0
  66. package/types/llrt/path.d.ts +150 -0
  67. package/types/llrt/perf_hooks.d.ts +23 -0
  68. package/types/llrt/process.d.ts +502 -0
  69. package/types/llrt/stream/web.d.ts +526 -0
  70. package/types/llrt/stream.d.ts +366 -0
  71. package/types/llrt/string_decoder.d.ts +63 -0
  72. package/types/llrt/timers.d.ts +72 -0
  73. package/types/llrt/timezone.d.ts +101 -0
  74. package/types/llrt/tty.d.ts +11 -0
  75. package/types/llrt/url.d.ts +774 -0
  76. package/types/llrt/util.d.ts +240 -0
  77. package/types/llrt/zlib.d.ts +177 -0
  78. package/types/main.d.ts +5 -0
  79. package/types/metrics.d.ts +5 -0
  80. package/types/modules/ast-grep.d.ts +634 -0
  81. package/types/modules/langs.d.ts +87 -0
  82. package/types/modules/llm.d.ts +23 -0
  83. package/types/modules/metrics.d.ts +107 -0
  84. package/types/modules/runtime.d.ts +66 -0
  85. package/types/modules/workflow.d.ts +750 -0
  86. package/types/runtime.d.ts +6 -0
  87. package/types/workflow.d.ts +5 -0
  88. package/vite.d.mts +24 -0
  89. package/vite.mjs +26 -0
@@ -0,0 +1,657 @@
1
+ // Generated from crates/workflow/src/js/orchestrator.js by `pnpm sync-orchestrator`; do not edit.
2
+
3
+ // The workflow orchestrator: step(), replay, test plans and the task
4
+ // builders that make up `codemod/workflow`. It holds no host globals, so the
5
+ // same code runs in the engine's QuickJS context and in Node.js or Bun.
6
+ //
7
+ // `createRuntime(host)` returns the module's exports for one run. The host:
8
+ // history(): StepRecord[] steps recorded by earlier runs
9
+ // record(entry, ms) persist one step's outcome
10
+ // event(event) report step started / replayed
11
+ // canceled(): boolean whether a step about to start must not,
12
+ // because the run was asked to stop
13
+ // start(request): Promise<outcome> run a task; rejects with { name, message }
14
+ // evaluate(kind, expression, scope) evaluate a workflow.yaml `${{ }}` expression
15
+ // now(): number the real time, for step records
16
+ // advanceClock(ms) move the body's clock forward
17
+ // testPlan(): { until?, given? } | null when the run is a test
18
+ // stop() the test's `until` step has started
19
+ // wake?() a replayed step waits for `replayNext()`
20
+ // callbackId?(fn): string identifies a callback given as a function;
21
+ // hosts without it need the build to extract callbacks
22
+ //
23
+ // The host drives two more things, on the object `createRuntime` returns:
24
+ // replayNext(): boolean settle the next replayed step; call it whenever the
25
+ // workflow has nothing left to run, until it is false
26
+ // close() the run is ending: no step starts from here on
27
+ // isClosed(): boolean whether steps issued now would never start
28
+
29
+ export class NondeterminismError extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = "NondeterminismError";
33
+ }
34
+ }
35
+
36
+ export class StepError extends Error {
37
+ constructor(label, cause) {
38
+ super(`step '${label}' failed: ${messageOf(cause)}`);
39
+ this.name = "StepError";
40
+ this.label = label;
41
+ }
42
+ }
43
+
44
+ export class CanceledError extends Error {
45
+ constructor(message = "the run was canceled") {
46
+ super(message);
47
+ this.name = "CanceledError";
48
+ }
49
+ }
50
+
51
+ export class AwaitingApprovalError extends Error {
52
+ constructor(message) {
53
+ super(message);
54
+ this.name = "AwaitingApprovalError";
55
+ }
56
+ }
57
+
58
+ const TASK = Symbol.for("codemod.workflow.task");
59
+
60
+ /**
61
+ * The task builders (`forEachFile`, `shell`, `jssg`, ...). They only describe
62
+ * work, so they need no run. `options.callbackId(fn)` lets callbacks be given
63
+ * as functions, for hosts that run them in place.
64
+ */
65
+ export function createTasks(options = {}) {
66
+ /** Inserted by the build in place of an extracted callback. */
67
+ function __callback(id, captures) {
68
+ return { __flowCallback: id, captures };
69
+ }
70
+
71
+ /** A callback the build extracted, or one given as a function on hosts that run them in place. */
72
+ function callbackOf(value) {
73
+ if (value && typeof value.__flowCallback === "string") {
74
+ return { id: value.__flowCallback, captures: value.captures };
75
+ }
76
+ if (typeof value === "function" && typeof options.callbackId === "function") {
77
+ return { id: options.callbackId(value), fn: value };
78
+ }
79
+ return null;
80
+ }
81
+
82
+ function forEachFile(selector, callback) {
83
+ if (callback === undefined && callbackOf(selector)) {
84
+ callback = selector;
85
+ selector = undefined;
86
+ }
87
+ const extracted = callbackOf(callback);
88
+ if (!extracted) {
89
+ throw new TypeError(
90
+ "forEachFile: the callback was not extracted by the build; run the workflow through the codemod-workflow build",
91
+ );
92
+ }
93
+ return Object.freeze({
94
+ [TASK]: "forEachFile",
95
+ selector: normalizeSelector(selector),
96
+ callback: extracted,
97
+ });
98
+ }
99
+
100
+ function hostTask(kind, options) {
101
+ const content = withoutUndefined(options);
102
+ checkJson(content, kind);
103
+ return Object.freeze({ [TASK]: "host", content: { ...content, kind } });
104
+ }
105
+
106
+ /** Run a shell command. */
107
+ function shell(command, options = {}) {
108
+ return hostTask("shell", { ...options, command });
109
+ }
110
+
111
+ /** Run a JSSG transform file over the target. */
112
+ function jssg(path, options = {}) {
113
+ return hostTask("jssg", { ...options, path });
114
+ }
115
+
116
+ /** Apply an ast-grep YAML rule file. */
117
+ function astGrep(path, options = {}) {
118
+ return hostTask("astGrep", { ...options, path });
119
+ }
120
+
121
+ /** Split files into shards. */
122
+ function shard(options) {
123
+ return hostTask("shard", options);
124
+ }
125
+
126
+ /** Run another codemod package (registry name or local path). */
127
+ function codemod(source, options = {}) {
128
+ return hostTask("codemod", { ...options, source });
129
+ }
130
+
131
+ /** Hand a prompt to a coding agent. */
132
+ function agent(prompt, options = {}) {
133
+ return hostTask("agent", { ...options, prompt });
134
+ }
135
+
136
+ /** Install an agent skill package. */
137
+ function installSkill(options) {
138
+ return hostTask("installSkill", options);
139
+ }
140
+
141
+ /** Wait for a person to approve before continuing. */
142
+ function approval(message) {
143
+ return hostTask("approval", { message });
144
+ }
145
+
146
+ /** Check out a branch for the following changes (managed git only). */
147
+ function branch(name) {
148
+ return hostTask("branch", { name });
149
+ }
150
+
151
+ /** Commit changes (managed git only). */
152
+ function commit(message, options = {}) {
153
+ return hostTask("commit", { ...options, message });
154
+ }
155
+
156
+ /** Push the branch and open a pull request (managed git only). */
157
+ function pullRequest(options) {
158
+ return hostTask("pullRequest", options);
159
+ }
160
+
161
+ return {
162
+ callbackOf,
163
+ __callback,
164
+ forEachFile,
165
+ shell,
166
+ jssg,
167
+ astGrep,
168
+ shard,
169
+ codemod,
170
+ agent,
171
+ installSkill,
172
+ approval,
173
+ branch,
174
+ commit,
175
+ pullRequest,
176
+ };
177
+ }
178
+
179
+ export function createRuntime(host) {
180
+ const tasks = createTasks(host);
181
+ const { callbackOf } = tasks;
182
+
183
+ const recorded = new Map();
184
+ // Steps are numbered in the order they finish, across executions of the run.
185
+ let nextSeq = 0;
186
+ for (const entry of host.history()) {
187
+ recorded.set(entry.position, entry);
188
+ if (typeof entry.seq === "number") nextSeq = Math.max(nextSeq, entry.seq + 1);
189
+ }
190
+
191
+ const state = new Map();
192
+ let nextPosition = 0;
193
+
194
+ // A test run can stop after one step (`until`) and skip steps with a given
195
+ // result (`given`), both matched by label.
196
+ const plan = host.testPlan() ?? {};
197
+ const given = new Map(Object.entries(plan.given ?? {}));
198
+
199
+ // Once closed, no step starts: steps issued from then on never settle. A
200
+ // run closes when a test's `until` step starts, when a step is canceled or
201
+ // waits for an approval, and when the host ends the run.
202
+ let closed = false;
203
+
204
+ // Recorded steps the body has issued again, waiting to settle. They settle
205
+ // one at a time in the order they finished when they ran, so the body sees
206
+ // state, the clock and promise races as it did then.
207
+ const replaying = [];
208
+
209
+ function replayNext() {
210
+ if (closed || replaying.length === 0) return false;
211
+ let next = 0;
212
+ for (let i = 1; i < replaying.length; i++) {
213
+ if (replaying[i].order < replaying[next].order) next = i;
214
+ }
215
+ replaying.splice(next, 1)[0].settle();
216
+ return true;
217
+ }
218
+
219
+ function close() {
220
+ closed = true;
221
+ }
222
+
223
+ function isClosed() {
224
+ return closed;
225
+ }
226
+
227
+ // The body's clock only moves when a step finishes, to the time recorded
228
+ // for it, so Date.now() in the body gives the same answer on every replay.
229
+ function settleClock(entry) {
230
+ if (entry && typeof entry.finishedAt === "number") host.advanceClock(entry.finishedAt);
231
+ }
232
+
233
+ // ---------------------------------------------------------------- state ---
234
+
235
+ /** Read one state key, or the whole state as an object when called without one. Values are frozen. */
236
+ function getState(key) {
237
+ if (key === undefined) return Object.freeze(Object.fromEntries(state));
238
+ return state.get(key);
239
+ }
240
+
241
+ /** Set workflow state. `undefined` removes the key. */
242
+ function setState(key, value) {
243
+ if (value === undefined) {
244
+ state.delete(key);
245
+ return;
246
+ }
247
+ checkJson(value, `state.${key}`);
248
+ state.set(key, freeze(JSON.parse(JSON.stringify(value))));
249
+ }
250
+
251
+ function unsetState(key) {
252
+ state.delete(key);
253
+ }
254
+
255
+ function applyState(changes) {
256
+ if (!changes) return;
257
+ for (const [key, value] of Object.entries(changes)) {
258
+ if (value === null) state.delete(key);
259
+ else state.set(key, freeze(value));
260
+ }
261
+ }
262
+
263
+ function stateSnapshot() {
264
+ return Object.fromEntries(state);
265
+ }
266
+
267
+ // The body runs alone, so a lock there has nothing to wait for; steps and
268
+ // callbacks get the real one from their own runtime.
269
+ function acquireLock(_name) {
270
+ return () => {};
271
+ }
272
+
273
+ // Step outputs are kept for the transforms that still set them; nothing in
274
+ // a workflow reads them back but these functions.
275
+ const stepOutputs = new Map();
276
+ const outputKey = (stepId, name) => JSON.stringify([stepId, name]);
277
+
278
+ function setStepOutput(name, value) {
279
+ stepOutputs.set(outputKey("", name), String(value));
280
+ }
281
+
282
+ function getStepOutput(stepId, name) {
283
+ return stepOutputs.get(outputKey(stepId, name)) ?? null;
284
+ }
285
+
286
+ function getOrSetStepOutput(stepId, name, value) {
287
+ const key = outputKey(stepId, name);
288
+ if (!stepOutputs.has(key)) stepOutputs.set(key, String(value));
289
+ return stepOutputs.get(key);
290
+ }
291
+
292
+ /** Evaluate a workflow.yaml `${{ }}` expression; used by translated workflows. */
293
+ function __evaluate(kind, expression, scope) {
294
+ return host.evaluate(kind, expression, scope);
295
+ }
296
+
297
+ // ----------------------------------------------------------------- step ---
298
+
299
+ /**
300
+ * Run a task as a durable step. Starts immediately; the returned promise
301
+ * resolves to the step's frozen result.
302
+ */
303
+ function step(labelOrTask, maybeTask) {
304
+ const position = nextPosition++;
305
+ const [label, task] =
306
+ typeof labelOrTask === "string" ? [labelOrTask, maybeTask] : [undefined, labelOrTask];
307
+ return runStep(position, label, task).then(freeze);
308
+ }
309
+
310
+ async function runStep(position, label, task) {
311
+ // Everything up to the first await runs synchronously inside step(), so
312
+ // captures and state are a snapshot taken when the step is called.
313
+ let content;
314
+ let fn;
315
+ const callback = callbackOf(task);
316
+ if (callback) {
317
+ content = { kind: "function", callback: callback.id, captures: capturesOf(callback) };
318
+ fn = callback.fn;
319
+ } else if (typeof task === "function") {
320
+ throw new TypeError(
321
+ `step #${position}: write the function inline, as step(() => ...), so the build can run it in its own isolate`,
322
+ );
323
+ } else if (task && task[TASK] === "forEachFile") {
324
+ content = {
325
+ kind: "forEachFile",
326
+ selector: task.selector,
327
+ callback: task.callback.id,
328
+ captures: capturesOf(task.callback),
329
+ };
330
+ fn = task.callback.fn;
331
+ } else if (task && task[TASK] === "host") {
332
+ content = task.content;
333
+ } else {
334
+ throw new TypeError(
335
+ `step #${position}: expected a task such as forEachFile(...) or a function`,
336
+ );
337
+ }
338
+
339
+ const name = label ?? defaultLabel(position, content);
340
+ const key = canonical(content);
341
+ if (closed) return new Promise(() => {});
342
+ if (plan.until !== undefined && name === plan.until) {
343
+ closed = true;
344
+ host.stop();
345
+ }
346
+ if (given.has(name)) {
347
+ const result = given.get(name);
348
+ host.event({ type: "stepReplayed", position, label: name });
349
+ host.record(
350
+ { position, label: name, key, status: "succeeded", result, given: true, seq: nextSeq++ },
351
+ 0,
352
+ );
353
+ return JSON.parse(JSON.stringify(result ?? null));
354
+ }
355
+ const prior = recorded.get(position);
356
+ if (prior && prior.status === "succeeded") {
357
+ if (prior.key !== key) {
358
+ throw new NondeterminismError(
359
+ `step #${position} ('${name}') differs from the recorded run; the workflow changed before this step, so its recorded result cannot be reused`,
360
+ );
361
+ }
362
+ return new Promise((resolve) => {
363
+ replaying.push({
364
+ // Steps recorded before finishing order was kept replay in the
365
+ // order they were issued.
366
+ order: prior.seq ?? prior.position,
367
+ settle() {
368
+ applyState(prior.state);
369
+ settleClock(prior);
370
+ host.event({ type: "stepReplayed", position, label: name });
371
+ resolve(prior.result);
372
+ },
373
+ });
374
+ host.wake?.();
375
+ });
376
+ }
377
+
378
+ if (host.canceled()) {
379
+ closed = true;
380
+ throw new CanceledError();
381
+ }
382
+ host.event({ type: "stepStarted", position, label: name });
383
+ const started = host.now();
384
+ const record = (entry) =>
385
+ host.record({ position, label: name, key, seq: nextSeq++, ...entry }, host.now() - started);
386
+ let result;
387
+ let changes = null;
388
+ try {
389
+ const outcome = await host.start({
390
+ position,
391
+ label: name,
392
+ task: content,
393
+ state: stateSnapshot(),
394
+ fn,
395
+ });
396
+ result = outcome.result ?? null;
397
+ changes = outcome.state ?? null;
398
+ } catch (cause) {
399
+ const error = asError(cause);
400
+ // A step that was canceled or waits for an approval runs again when
401
+ // the run is resumed; nothing else starts in this execution.
402
+ const interrupted =
403
+ error instanceof CanceledError
404
+ ? "canceled"
405
+ : error instanceof AwaitingApprovalError
406
+ ? "awaiting-approval"
407
+ : null;
408
+ if (interrupted) {
409
+ closed = true;
410
+ record({ status: interrupted, error: messageOf(error) });
411
+ throw error;
412
+ }
413
+ record({ status: "failed", error: messageOf(error) });
414
+ throw new StepError(name, error);
415
+ }
416
+ applyState(changes);
417
+ const finishedAt = host.now();
418
+ record({ status: "succeeded", result, state: changes, finishedAt });
419
+ settleClock({ finishedAt });
420
+ return result;
421
+ }
422
+
423
+ /** Captured values of an extracted callback; none for callbacks run in place. */
424
+ function capturesOf(callback) {
425
+ if (typeof callback.captures !== "function") return undefined;
426
+ const captures = callback.captures();
427
+ checkJson(captures, "captures");
428
+ return captures;
429
+ }
430
+
431
+ /** Turn a host rejection (`{ name, message }`) back into the runtime's errors. */
432
+ function asError(cause) {
433
+ if (cause instanceof Error) {
434
+ if (cause.name === "CanceledError" && !(cause instanceof CanceledError)) {
435
+ return new CanceledError(cause.message);
436
+ }
437
+ if (cause.name === "AwaitingApprovalError" && !(cause instanceof AwaitingApprovalError)) {
438
+ return new AwaitingApprovalError(cause.message);
439
+ }
440
+ return cause;
441
+ }
442
+ if (cause && typeof cause === "object" && typeof cause.message === "string") {
443
+ if (cause.name === "CanceledError") return new CanceledError(cause.message);
444
+ if (cause.name === "AwaitingApprovalError") return new AwaitingApprovalError(cause.message);
445
+ return new Error(cause.message);
446
+ }
447
+ return new Error(String(cause));
448
+ }
449
+
450
+ const { callbackOf: _, ...builders } = tasks;
451
+ return {
452
+ ...builders,
453
+ getState,
454
+ setState,
455
+ unsetState,
456
+ acquireLock,
457
+ setStepOutput,
458
+ getStepOutput,
459
+ getOrSetStepOutput,
460
+ __evaluate,
461
+ step,
462
+ replayNext,
463
+ close,
464
+ isClosed,
465
+ };
466
+ }
467
+
468
+ function withoutUndefined(value) {
469
+ if (Array.isArray(value)) return value.map(withoutUndefined);
470
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
471
+ const result = {};
472
+ for (const [key, item] of Object.entries(value)) {
473
+ if (item !== undefined) result[key] = withoutUndefined(item);
474
+ }
475
+ return result;
476
+ }
477
+ return value;
478
+ }
479
+
480
+ function normalizeSelector(selector) {
481
+ if (selector === undefined) selector = {};
482
+ if (typeof selector === "string" || Array.isArray(selector)) selector = { include: selector };
483
+ if (!selector || typeof selector !== "object") {
484
+ throw new TypeError(
485
+ "forEachFile: the selector must be a glob, an array of globs, or an object",
486
+ );
487
+ }
488
+ const known = new Set(["include", "exclude", "language", "containing", "concurrency"]);
489
+ for (const key of Object.keys(selector)) {
490
+ if (!known.has(key)) throw new TypeError(`forEachFile: unknown selector field '${key}'`);
491
+ }
492
+ const normalized = {
493
+ include: globs(selector.include, "include"),
494
+ exclude: globs(selector.exclude, "exclude"),
495
+ };
496
+ for (const field of ["language", "containing"]) {
497
+ if (selector[field] === undefined) continue;
498
+ if (typeof selector[field] !== "string") {
499
+ throw new TypeError(`forEachFile: selector.${field} must be a string`);
500
+ }
501
+ normalized[field] = selector[field];
502
+ }
503
+ if (selector.concurrency !== undefined) {
504
+ if (!Number.isInteger(selector.concurrency) || selector.concurrency < 1) {
505
+ throw new TypeError("forEachFile: concurrency must be a whole number of at least 1");
506
+ }
507
+ normalized.concurrency = selector.concurrency;
508
+ }
509
+ // Neither include nor language: the package's languages from codemod.yaml.
510
+ return normalized;
511
+ }
512
+
513
+ function globs(value, field) {
514
+ if (value === undefined) return [];
515
+ if (typeof value === "string") return [value];
516
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return [...value];
517
+ throw new TypeError(`forEachFile: selector.${field} must be a glob or an array of globs`);
518
+ }
519
+
520
+ function defaultLabel(position, content) {
521
+ switch (content.kind) {
522
+ case "forEachFile": {
523
+ const { include, language } = content.selector;
524
+ return `forEachFile ${include.length ? include.join(", ") : (language ?? "")}`.trimEnd();
525
+ }
526
+ case "function":
527
+ return `step #${position}`;
528
+ case "shell":
529
+ return `shell ${truncate(content.command)}`;
530
+ case "jssg":
531
+ case "astGrep":
532
+ return `${content.kind} ${content.path}`;
533
+ case "approval":
534
+ return `approval: ${truncate(content.message)}`;
535
+ case "codemod":
536
+ return `codemod ${content.source}`;
537
+ case "agent":
538
+ return `agent: ${truncate(content.prompt)}`;
539
+ default:
540
+ return content.kind;
541
+ }
542
+ }
543
+
544
+ function truncate(text, length = 60) {
545
+ const line = String(text ?? "").split("\n")[0];
546
+ return line.length > length ? `${line.slice(0, length - 1)}…` : line;
547
+ }
548
+
549
+ function canonical(value) {
550
+ return JSON.stringify(sortKeys(value));
551
+ }
552
+
553
+ function sortKeys(value) {
554
+ if (Array.isArray(value)) return value.map(sortKeys);
555
+ if (value && typeof value === "object") {
556
+ const sorted = {};
557
+ for (const key of Object.keys(value).sort()) sorted[key] = sortKeys(value[key]);
558
+ return sorted;
559
+ }
560
+ return value;
561
+ }
562
+
563
+ /** Freeze a JSON value, all the way down. */
564
+ export function freeze(value) {
565
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
566
+ Object.freeze(value);
567
+ for (const key of Object.keys(value)) freeze(value[key]);
568
+ }
569
+ return value;
570
+ }
571
+
572
+ /**
573
+ * An error as a step's failure says it. Changing a captured value or a step
574
+ * result fails as a TypeError that does not say why; the hint does.
575
+ */
576
+ export function describeError(error) {
577
+ if (!error || typeof error !== "object") return String(error);
578
+ let message = `${error.name || "Error"}: ${error.message}`;
579
+ if (
580
+ error instanceof TypeError &&
581
+ /extensible|read-only|read only|frozen|non-writable/i.test(error.message)
582
+ ) {
583
+ message += " (captured values and step results are frozen; copy one before changing it)";
584
+ }
585
+ return message;
586
+ }
587
+
588
+ /**
589
+ * The `file` a `forEachFile` callback gets, and the effects it records on it:
590
+ * `{ op: "write", text }`, `{ op: "rename", to }` and `{ op: "delete" }`.
591
+ * After `close()`, when the callback has finished, the file takes no more.
592
+ */
593
+ export function fileHandle(path, text, language) {
594
+ const effects = [];
595
+ let open = true;
596
+ const guard = (name) => {
597
+ if (!open) throw new Error(`file.${name}() was called after the callback finished`);
598
+ };
599
+ const file = Object.freeze({
600
+ path,
601
+ text,
602
+ language,
603
+ write(next) {
604
+ guard("write");
605
+ if (typeof next !== "string") throw new TypeError("file.write(text) expects a string");
606
+ effects.push({ op: "write", text: next });
607
+ },
608
+ rename(to) {
609
+ guard("rename");
610
+ if (typeof to !== "string" || to === "") {
611
+ throw new TypeError("file.rename(path) expects a non-empty path");
612
+ }
613
+ effects.push({ op: "rename", to });
614
+ },
615
+ delete() {
616
+ guard("delete");
617
+ effects.push({ op: "delete" });
618
+ },
619
+ });
620
+ return {
621
+ file,
622
+ effects,
623
+ close() {
624
+ open = false;
625
+ },
626
+ };
627
+ }
628
+
629
+ function messageOf(error) {
630
+ return error && typeof error === "object" && "message" in error ? error.message : String(error);
631
+ }
632
+
633
+ /** Throw a TypeError naming the first part of `value` that is not JSON. */
634
+ export function checkJson(value, path, seen = new Set()) {
635
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
636
+ if (typeof value === "number") {
637
+ if (!Number.isFinite(value)) throw new TypeError(`${path} is ${value}, which is not JSON`);
638
+ return;
639
+ }
640
+ if (typeof value !== "object") {
641
+ const what = value === undefined ? "undefined" : `a ${typeof value}`;
642
+ throw new TypeError(`${path} is ${what}, which is not JSON`);
643
+ }
644
+ if (seen.has(value)) throw new TypeError(`${path} is a circular reference`);
645
+ seen.add(value);
646
+ if (Array.isArray(value)) {
647
+ value.forEach((item, index) => checkJson(item, `${path}[${index}]`, seen));
648
+ } else {
649
+ const proto = Object.getPrototypeOf(value);
650
+ if (proto !== Object.prototype && proto !== null) {
651
+ const name = (value.constructor && value.constructor.name) || "non-plain object";
652
+ throw new TypeError(`${path} is a ${name}, which is not JSON`);
653
+ }
654
+ for (const key of Object.keys(value)) checkJson(value[key], `${path}.${key}`, seen);
655
+ }
656
+ seen.delete(value);
657
+ }
@@ -0,0 +1,48 @@
1
+ // `codemod/runtime` in Node.js and Bun. Progress and warnings become the
2
+ // step's log lines, written as the CLI writes them; failures throw, and stay
3
+ // reported even when the code catches the error.
4
+
5
+ import { context } from "./context.mjs";
6
+
7
+ function text(message, what) {
8
+ if (typeof message !== "string") throw new TypeError(`${what} expects a message string`);
9
+ return message;
10
+ }
11
+
12
+ function log(prefix, message, meta) {
13
+ const store = context.getStore();
14
+ if (!store) return;
15
+ const line = meta === undefined ? message : `${message} ${JSON.stringify(meta)}`;
16
+ store.run.log(store.step?.position ?? null, `${prefix} ${line}`);
17
+ }
18
+
19
+ export function progress(message, meta) {
20
+ log("[progress]", text(message, "progress()"), meta);
21
+ }
22
+
23
+ export function warn(message, meta) {
24
+ log("[warn]", text(message, "warn()"), meta);
25
+ }
26
+
27
+ export function setCurrentUnit(_unitId, _meta) {}
28
+
29
+ function fail(message, what) {
30
+ const step = context.getStore()?.step;
31
+ if (step) step.failure = text(message, what);
32
+ throw new Error(text(message, what));
33
+ }
34
+
35
+ export function failFile(message, _meta) {
36
+ fail(message, "failFile()");
37
+ }
38
+
39
+ export function failStep(message, _meta) {
40
+ fail(message, "failStep()");
41
+ }
42
+
43
+ export function isCanceled() {
44
+ return context.getStore()?.run.canceled() ?? false;
45
+ }
46
+
47
+ const runtime = { progress, warn, setCurrentUnit, failFile, failStep, isCanceled };
48
+ export default runtime;