codemod 2.0.0-alpha.2 → 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/runtime/host.mjs CHANGED
@@ -8,383 +8,443 @@
8
8
  //
9
9
  // Code here has whatever Node.js gives it: capabilities are not enforced.
10
10
  // The codemod CLI runs workflows in its own sandboxed runtime instead.
11
-
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
+ */
12
39
  import "../register.mjs";
13
-
14
- import { readFileSync } from "node:fs";
15
40
  import { isAbsolute, resolve } from "node:path";
16
41
  import { fileURLToPath, pathToFileURL } from "node:url";
17
-
18
42
  import { addon } from "./addon.mjs";
19
43
  import { context, metricsOf, stateChanges, stepScope } from "./context.mjs";
20
- import {
21
- AwaitingApprovalError,
22
- CanceledError,
23
- checkJson,
24
- createRuntime,
25
- describeError,
26
- fileHandle,
27
- } from "./orchestrator.mjs";
44
+ import { ORCHESTRATOR_VERSION } from "./orchestrator-version.mjs";
45
+ import { AwaitingApprovalError, CanceledError, checkJson, createRuntime, describeDuration, describeError, fileHandle, } from "./orchestrator.mjs";
28
46
  import { callbackId } from "./workflow.mjs";
29
-
30
47
  /**
31
- * Run a workflow and resolve with its report, for every outcome.
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.
32
51
  *
33
- * `workflow` is a workflow file, a package directory, or the workflow module
34
- * itself (`await import("./workflow.ts")`), for test runners that should load
35
- * it through their own module system. A module needs `options.path` (or
52
+ * A module (`await import("./workflow.ts")`), for test runners that should
53
+ * load it through their own module system, needs `options.path` (or
36
54
  * `options.workflowDir`) so relative task paths resolve.
37
55
  */
38
56
  export async function runWorkflow(workflow, options = {}) {
39
- const native = addon();
40
- checkAddon(native);
41
- const { path, load } = locate(workflow, options);
42
- // A workflow that cannot be loaded is not a run: reject.
43
- const module = await load();
44
- const main = module?.default;
45
- if (typeof main !== "function") {
46
- throw new TypeError(`${path} must export a default function`);
47
- }
48
- if (options.captureConsole) captureConsole();
49
- const run = native.Run.open({
50
- workflow: path,
51
- target: resolve(options.target ?? "."),
52
- params: options.params ?? {},
53
- name: options.name,
54
- dryRun: options.dryRun ?? false,
55
- until: options.until,
56
- given: options.given,
57
- approve: options.approve ?? true,
58
- capabilities: options.capabilities ?? [],
59
- store: options.store,
60
- resume: options.resume,
61
- });
62
-
63
- const flight = inFlight();
64
- const runtime = createRuntime(host(run, flight, () => runtime));
65
- flight.closed = () => runtime.isClosed();
66
- const scope = { run, runtime, captureConsole: options.captureConsole ?? false };
67
- const abort = () => run.cancel();
68
- if (options.signal?.aborted) abort();
69
- options.signal?.addEventListener?.("abort", abort, { once: true });
70
-
71
- // How the body ended; `null` when it cannot end any more.
72
- let body;
73
- try {
74
- const input = { params: run.params, target: run.target, dryRun: run.dryRun };
75
- const ended = context
76
- .run(scope, () => main(input))
77
- .then((output) => ({ status: "succeeded", detail: toJson(output) }));
78
- body = await Promise.race([ended, flight.stalled]);
79
- } catch (error) {
80
- body = endingOf(error);
81
- }
82
- // Steps still running finish and are recorded before the run reports;
83
- // none starts from here on.
84
- runtime.close();
85
- await flight.idle();
86
- options.signal?.removeEventListener?.("abort", abort);
87
- const report = run.finish(JSON.stringify(body));
88
- return { ...report, events: run.takeEvents() };
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() };
89
107
  }
90
-
91
108
  let addonChecked = false;
92
-
93
109
  /**
94
110
  * The addon and this package share the orchestrator: one from another
95
111
  * version would record and replay steps differently.
96
112
  */
97
113
  function checkAddon(native) {
98
- if (addonChecked) return;
99
- const shipped = readFileSync(new URL("./orchestrator.mjs", import.meta.url), "utf8");
100
- if (!shipped.endsWith(native.orchestratorSource())) {
101
- throw new Error(
102
- "the codemod native addon is from another version than the codemod package; reinstall codemod so both match (in a checkout, rebuild with `cargo build -p codemod-node`)",
103
- );
104
- }
105
- addonChecked = true;
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;
106
122
  }
107
-
123
+ const CONSOLE_METHODS = ["log", "info", "debug", "warn", "error"];
108
124
  /**
109
125
  * Route `console` output of code that runs in a run started with
110
126
  * `captureConsole` to the run's logs, by step. Other code is untouched.
111
127
  */
112
128
  function captureConsole() {
113
- const key = Symbol.for("codemod.host.console");
114
- if (globalThis[key]) return;
115
- globalThis[key] = true;
116
- for (const method of ["log", "info", "debug", "warn", "error"]) {
117
- const original = console[method].bind(console);
118
- console[method] = (...items) => {
119
- const store = context.getStore();
120
- if (!store?.captureConsole) return original(...items);
121
- store.run.log(store.step?.position ?? null, items.map(formatLogItem).join(" "));
122
- };
123
- }
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
+ }
124
143
  }
125
-
126
144
  function formatLogItem(value) {
127
- if (typeof value === "string") return value;
128
- if (value instanceof Error) return value.stack || `${value.name}: ${value.message}`;
129
- try {
130
- return JSON.stringify(value) ?? String(value);
131
- } catch {
132
- return String(value);
133
- }
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
+ }
134
155
  }
135
-
136
156
  /** Where the workflow is, and how to load it. */
137
157
  function locate(workflow, options) {
138
- if (workflow && typeof workflow === "object" && !isUrl(workflow)) {
139
- if (!options.path && !options.workflowDir) {
140
- throw new TypeError(
141
- "runWorkflow(module, { path }): give the workflow file's path, so relative task paths resolve",
142
- );
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 };
143
167
  }
144
- // The file need not exist: only its directory matters here.
145
- const file = options.path
146
- ? resolve(String(options.path))
147
- : resolve(String(options.workflowDir), "workflow.ts");
148
- return { path: file, load: async () => workflow };
149
- }
150
- const source = isUrl(workflow) ? fileURLToPath(workflow.href) : String(workflow);
151
- const path = addon().resolveWorkflow(
152
- isAbsolute(source) ? source : resolve(source),
153
- options.workflowName ?? null,
154
- );
155
- if (!/\.m?ts$|\.m?js$/.test(path)) {
156
- throw new Error(
157
- `${path} is not a TypeScript workflow; run YAML workflows with the codemod CLI, or upgrade them with \`codemod workflow upgrade\``,
158
- );
159
- }
160
- return { path, load: () => import(pathToFileURL(path).href) };
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";
161
177
  }
162
-
178
+ // Not `instanceof URL`: test environments may have their own URL class.
163
179
  function isUrl(value) {
164
- return value !== null && typeof value === "object" && typeof value.href === "string";
180
+ return isRecord(value) && typeof value.href === "string";
165
181
  }
166
-
167
- /**
168
- * Tracks steps in flight. `stalled` resolves (with `null`) when the run is
169
- * closed and nothing is running: the body may be waiting on steps that will
170
- * never start, as after a test's `until` step. `idle()` resolves once nothing
171
- * is running.
172
- */
173
182
  function inFlight() {
174
- let count = 0;
175
- let stall;
176
- let waiters = [];
177
- const flight = {
178
- closed: () => false,
179
- stalled: new Promise((resolvePromise) => (stall = resolvePromise)),
180
- begin() {
181
- count++;
182
- },
183
- end() {
184
- count--;
185
- flight.check();
186
- },
187
- /** Look again once the body has reacted to whatever just happened. */
188
- check() {
189
- setImmediate(() => {
190
- if (count !== 0) return;
191
- if (flight.closed()) stall(null);
192
- for (const waiter of waiters.splice(0)) waiter();
193
- });
194
- },
195
- idle() {
196
- return new Promise((resolvePromise) => {
197
- waiters.push(resolvePromise);
198
- flight.check();
199
- });
200
- },
201
- };
202
- return flight;
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;
203
214
  }
204
-
205
215
  function host(run, flight, runtime) {
206
- // Replayed steps settle one per turn of the event loop, so the body reacts
207
- // to each before the next.
208
- let replaying = false;
209
- const replay = () => {
210
- replaying = runtime().replayNext();
211
- if (replaying) setImmediate(replay);
212
- };
213
- return {
214
- history: () => run.history(),
215
- record: (entry, ms) => run.record(JSON.stringify(entry), ms),
216
- event: (event) => run.event(JSON.stringify(event)),
217
- canceled: () => run.refusesSteps(),
218
- now: () => Date.now(),
219
- advanceClock() {},
220
- testPlan: () => run.testPlan(),
221
- stop() {
222
- run.stop();
223
- flight.check();
224
- },
225
- wake() {
226
- if (replaying) return;
227
- replaying = true;
228
- setImmediate(replay);
229
- },
230
- evaluate: (kind, expression, scope) => run.evaluate(kind, expression, JSON.stringify(scope)),
231
- callbackId,
232
- async start(request) {
233
- const { fn, ...task } = request;
234
- flight.begin();
235
- try {
236
- if (fn) return await runInPlace(run, task, fn);
237
- try {
238
- return await run.runTask(JSON.stringify(task));
239
- } catch (error) {
240
- throw payloadOf(error);
241
- }
242
- } finally {
243
- flight.end();
244
- }
245
- },
246
- };
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
+ };
247
262
  }
248
-
249
263
  /** A host task rejected with `{ name, message }` as JSON in the message. */
250
264
  function payloadOf(error) {
251
- try {
252
- const payload = JSON.parse(error.message);
253
- if (payload && typeof payload.message === "string") return payload;
254
- } catch {
255
- // a plain message
256
- }
257
- return { name: "Error", message: error?.message ?? String(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) };
258
276
  }
259
-
260
- // ----------------------------------------------------------- in place ---
261
-
262
- async function runInPlace(run, task, fn) {
263
- const outer = context.getStore();
264
- if (task.task.kind === "function") {
265
- const step = stepScope(task.position, task.label, task.state);
266
- let value;
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
+ });
267
293
  try {
268
- value = await context.run({ ...outer, step }, () => fn());
269
- } finally {
270
- // What the step measured counts even when it then fails.
271
- flushMetrics(run, step);
294
+ return await Promise.race([work(limit), late]);
295
+ }
296
+ finally {
297
+ clearTimeout(timer);
272
298
  }
273
- // A failure reported with failStep() stands even if the code caught it.
274
- if (step.failure !== undefined) throw new Error(step.failure);
275
- const result = value === undefined ? null : value;
276
- checkJson(result, "the step's result");
277
- return outcome(result, step);
278
- }
279
- if (task.task.kind === "forEachFile") return forEachFile(run, outer, task, fn);
280
- throw new Error(`cannot run a ${task.task.kind} task in place`);
281
299
  }
282
-
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
+ }
283
325
  function outcome(result, step) {
284
- const state = stateChanges(step);
285
- return Object.keys(state).length ? { result, state } : { result };
326
+ const state = stateChanges(step);
327
+ return Object.keys(state).length ? { result, state } : { result };
286
328
  }
287
-
288
329
  function flushMetrics(run, step) {
289
- const metrics = metricsOf(step);
290
- if (Object.keys(metrics).length) run.addMetrics(JSON.stringify(metrics));
291
- return metrics;
330
+ const metrics = metricsOf(step);
331
+ if (Object.keys(metrics).length)
332
+ run.addMetrics(JSON.stringify(metrics));
333
+ return metrics;
292
334
  }
293
-
294
- async function forEachFile(run, outer, task, fn) {
295
- const { selector } = task.task;
296
- const { language, files } = await run.selectFiles(JSON.stringify(selector));
297
- const step = stepScope(task.position, task.label, task.state, language ?? undefined);
298
- const total = files.length;
299
- const every = Math.max(1, Math.floor(total / 100));
300
- let processed = 0;
301
- const outputs = Array.from({ length: total });
302
- const failures = [];
303
- const effects = [];
304
- const concurrency = selector.concurrency ?? 1;
305
-
306
- const one = async (index) => {
307
- const [path, text] = files[index];
308
- const { file, effects: done, close } = fileHandle(path, text, step.language);
309
- try {
310
- step.failure = undefined;
311
- const output = await context.run({ ...outer, step }, () => fn(file));
312
- // A failure reported with failFile() stands even if the callback
313
- // caught it. With files in flight together it cannot be told whose it
314
- // was, as in the CLI.
315
- if (step.failure !== undefined && concurrency === 1) {
316
- failures.push({ path, error: step.failure });
317
- return;
318
- }
319
- if (output !== undefined) {
320
- checkJson(output, "return value");
321
- outputs[index] = { output };
322
- }
323
- if (done.length) effects.push({ path, original: text, effects: done });
324
- } catch (error) {
325
- failures.push({ path, error: describeError(error) });
326
- } finally {
327
- close();
328
- processed++;
329
- if (processed === total || processed % every === 0) {
330
- run.progress(task.position, processed, total);
331
- }
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}`);
332
411
  }
333
- };
334
-
335
- let next = 0;
336
- let sinceTurn = 0;
337
- const worker = async () => {
338
- while (next < total) {
339
- // Callbacks that never wait would keep the event loop to themselves:
340
- // give it a turn now and then, so a cancel can arrive.
341
- if (++sinceTurn >= 64) {
342
- sinceTurn = 0;
343
- await new Promise((turn) => setImmediate(turn));
344
- }
345
- if (run.refusesSteps()) throw new CanceledError();
346
- await one(next++);
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}`);
347
417
  }
348
- };
349
- await Promise.all(Array.from({ length: Math.min(concurrency, total) }, worker));
350
-
351
- // Before the commit: a commit that fails must not lose what was measured.
352
- const metrics = flushMetrics(run, step);
353
- effects.sort((a, b) => (a.path < b.path ? -1 : 1));
354
- const committed = await run.commitFiles(task.position, task.label, JSON.stringify(effects));
355
- const allFailures = [...failures, ...committed.failures].sort((a, b) =>
356
- a.path < b.path ? -1 : a.path > b.path ? 1 : 0,
357
- );
358
- return outcome(
359
- {
360
- outputs: outputs.filter(Boolean).map((entry) => entry.output),
361
- changes: committed.changes,
362
- failures: allFailures,
363
- metrics,
364
- },
365
- step,
366
- );
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
+ };
367
430
  }
368
-
369
431
  // -------------------------------------------------------------- ending ---
370
-
371
432
  /** How a body that threw ended. */
372
433
  function endingOf(error) {
373
- if (error instanceof CanceledError || error?.name === "CanceledError") {
374
- return { status: "canceled" };
375
- }
376
- if (error instanceof AwaitingApprovalError || error?.name === "AwaitingApprovalError") {
377
- return { status: "awaiting-approval", detail: error.message };
378
- }
379
- const message =
380
- error && typeof error === "object" && "message" in error
381
- ? `${error.name ?? "Error"}: ${error.message}`
382
- : String(error);
383
- return { status: "failed", detail: message };
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 };
384
445
  }
385
-
386
446
  /** A value as JSON keeps it; what JSON has no form for (a function) is null. */
387
447
  function toJson(value) {
388
- const text = JSON.stringify(value);
389
- return text === undefined ? null : JSON.parse(text);
448
+ const text = JSON.stringify(value);
449
+ return text === undefined ? null : JSON.parse(text);
390
450
  }