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,879 @@
|
|
|
1
|
+
// Generated by scripts/build.mjs from crates/workflow/src/js/orchestrator.ts; do not edit.
|
|
2
|
+
// --------------------------------------------------------------- errors ---
|
|
3
|
+
export class StepError extends Error {
|
|
4
|
+
constructor(label, cause) {
|
|
5
|
+
super(`step '${label}' failed: ${messageOf(cause)}`);
|
|
6
|
+
this.name = "StepError";
|
|
7
|
+
this.label = label;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export class CanceledError extends Error {
|
|
11
|
+
constructor(message = "the run was canceled") {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "CanceledError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export class AwaitingApprovalError extends Error {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "AwaitingApprovalError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
// ---------------------------------------------------------------- tasks ---
|
|
23
|
+
const TASK = Symbol.for("codemod.workflow.task");
|
|
24
|
+
/**
|
|
25
|
+
* The task builders (`forEachFile`, `shell`, `jssg`, ...). They only describe
|
|
26
|
+
* work, so they need no run. `options.callbackId(fn)` lets callbacks be given
|
|
27
|
+
* as functions, for hosts that run them in place.
|
|
28
|
+
*/
|
|
29
|
+
export function createTasks(options = {}) {
|
|
30
|
+
/** Inserted by the build in place of an extracted callback. */
|
|
31
|
+
function __callback(id, captures) {
|
|
32
|
+
return { __flowCallback: id, captures };
|
|
33
|
+
}
|
|
34
|
+
/** A callback the build extracted, or one given as a function on hosts that run them in place. */
|
|
35
|
+
function callbackOf(value) {
|
|
36
|
+
if (isRecord(value) && typeof value.__flowCallback === "string") {
|
|
37
|
+
return { id: value.__flowCallback, captures: value.captures };
|
|
38
|
+
}
|
|
39
|
+
if (typeof value === "function" && typeof options.callbackId === "function") {
|
|
40
|
+
const fn = value;
|
|
41
|
+
return { id: options.callbackId(fn), fn };
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Run a callback, or a `jssg(...)` or `astGrep(...)` transform, on every
|
|
47
|
+
* selected file.
|
|
48
|
+
*/
|
|
49
|
+
function forEachFile(selector, callback) {
|
|
50
|
+
if (callback === undefined && (callbackOf(selector) || isTask(selector))) {
|
|
51
|
+
callback = selector;
|
|
52
|
+
selector = undefined;
|
|
53
|
+
}
|
|
54
|
+
if (isTask(callback))
|
|
55
|
+
return transformFiles(selector, callback);
|
|
56
|
+
const extracted = callbackOf(callback);
|
|
57
|
+
if (!extracted) {
|
|
58
|
+
throw new TypeError(typeof callback === "function"
|
|
59
|
+
? "forEachFile: the callback was not extracted by the build; run the workflow through the codemod-workflow build"
|
|
60
|
+
: "forEachFile takes a callback written inline as a function, jssg(...) or astGrep(...)");
|
|
61
|
+
}
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
[TASK]: "forEachFile",
|
|
64
|
+
selector: normalizeSelector(selector),
|
|
65
|
+
callback: extracted,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* `forEachFile(selector, jssg(...))`: the transform's task, on the files
|
|
70
|
+
* the selector picks. The selector's fields become the transform's.
|
|
71
|
+
*/
|
|
72
|
+
function transformFiles(selector, transform) {
|
|
73
|
+
const kind = transform[TASK] === "host" ? transform.content.kind : "";
|
|
74
|
+
if (transform[TASK] !== "host" || (kind !== "jssg" && kind !== "astGrep")) {
|
|
75
|
+
throw new TypeError("forEachFile takes a callback written inline as a function, jssg(...) or astGrep(...)");
|
|
76
|
+
}
|
|
77
|
+
const { include, exclude, language, containing, concurrency } = normalizeSelector(selector);
|
|
78
|
+
if (containing !== undefined || concurrency !== undefined) {
|
|
79
|
+
const field = containing !== undefined ? "containing" : "concurrency";
|
|
80
|
+
throw new TypeError(`forEachFile: selector.${field} is for callbacks, not for ${kind}(...)`);
|
|
81
|
+
}
|
|
82
|
+
if (language !== undefined && kind === "astGrep") {
|
|
83
|
+
throw new TypeError("forEachFile: the rules of astGrep(...) name their languages; select files with globs");
|
|
84
|
+
}
|
|
85
|
+
const selected = {};
|
|
86
|
+
if (include.length)
|
|
87
|
+
selected.include = include;
|
|
88
|
+
if (exclude.length)
|
|
89
|
+
selected.exclude = exclude;
|
|
90
|
+
if (language !== undefined)
|
|
91
|
+
selected.language = language;
|
|
92
|
+
for (const field of Object.keys(selected)) {
|
|
93
|
+
if (field in transform.content) {
|
|
94
|
+
throw new TypeError(`forEachFile: '${field}' is given twice, in the selector and in ${kind}(...)`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const content = { ...transform.content, ...selected };
|
|
98
|
+
// Without a language, the package's (codemod.yaml), as for callbacks.
|
|
99
|
+
if (kind === "jssg" && content.language === undefined)
|
|
100
|
+
content.packageLanguage = true;
|
|
101
|
+
return Object.freeze({ [TASK]: "host", content });
|
|
102
|
+
}
|
|
103
|
+
function hostTask(kind, options) {
|
|
104
|
+
const content = withoutUndefined(options);
|
|
105
|
+
checkJson(content, kind);
|
|
106
|
+
return Object.freeze({
|
|
107
|
+
[TASK]: "host",
|
|
108
|
+
content: { ...content, kind },
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Run a shell command: `shell(command, options?)`, or as a tagged
|
|
113
|
+
* template, ``shell`grep -r ${pattern} src` ``, where each value is quoted
|
|
114
|
+
* for the shell. ``shell(options)`...` `` gives the template options.
|
|
115
|
+
*/
|
|
116
|
+
function shell(command, ...rest) {
|
|
117
|
+
if (isTemplateStrings(command))
|
|
118
|
+
return shellTemplate({}, command, rest);
|
|
119
|
+
if (typeof command === "string") {
|
|
120
|
+
return hostTask("shell", { ...rest[0], command });
|
|
121
|
+
}
|
|
122
|
+
if (isRecord(command) && rest.length === 0) {
|
|
123
|
+
const options = command;
|
|
124
|
+
return (strings, ...values) => {
|
|
125
|
+
if (!isTemplateStrings(strings)) {
|
|
126
|
+
throw new TypeError("shell(options) is used as a tag: shell(options)`command`");
|
|
127
|
+
}
|
|
128
|
+
return shellTemplate(options, strings, values);
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
throw new TypeError("shell: expected a command, shell`command`, or shell(options)`command`");
|
|
132
|
+
}
|
|
133
|
+
function shellTemplate(options, strings, values) {
|
|
134
|
+
// The text as written, backslashes included: it is shell, not JavaScript.
|
|
135
|
+
let command = strings.raw[0] ?? "";
|
|
136
|
+
values.forEach((value, index) => {
|
|
137
|
+
command += shellQuote(value, index) + (strings.raw[index + 1] ?? "");
|
|
138
|
+
});
|
|
139
|
+
return hostTask("shell", { ...options, command });
|
|
140
|
+
}
|
|
141
|
+
/** Run a JSSG transform file over the target. */
|
|
142
|
+
function jssg(path, options = {}) {
|
|
143
|
+
return hostTask("jssg", { ...options, path });
|
|
144
|
+
}
|
|
145
|
+
/** Apply an ast-grep YAML rule file. */
|
|
146
|
+
function astGrep(path, options = {}) {
|
|
147
|
+
return hostTask("astGrep", { ...options, path });
|
|
148
|
+
}
|
|
149
|
+
/** Split files into shards. */
|
|
150
|
+
function shard(options) {
|
|
151
|
+
return hostTask("shard", options);
|
|
152
|
+
}
|
|
153
|
+
/** Run another codemod package (registry name or local path). */
|
|
154
|
+
function codemod(source, options = {}) {
|
|
155
|
+
return hostTask("codemod", { ...options, source });
|
|
156
|
+
}
|
|
157
|
+
/** Hand a prompt to a coding agent. */
|
|
158
|
+
function agent(prompt, options = {}) {
|
|
159
|
+
return hostTask("agent", { ...options, prompt });
|
|
160
|
+
}
|
|
161
|
+
/** Install an agent skill package. */
|
|
162
|
+
function installSkill(options) {
|
|
163
|
+
return hostTask("installSkill", options);
|
|
164
|
+
}
|
|
165
|
+
/** Wait for a person to approve before continuing. */
|
|
166
|
+
function approval(message) {
|
|
167
|
+
return hostTask("approval", { message });
|
|
168
|
+
}
|
|
169
|
+
/** Wait for a time: milliseconds, or a string such as "30s" or "10m". */
|
|
170
|
+
function sleep(duration) {
|
|
171
|
+
return hostTask("sleep", { duration: milliseconds(duration, "sleep") });
|
|
172
|
+
}
|
|
173
|
+
/** Wait for an event sent to the run (`codemod workflow send`). */
|
|
174
|
+
function waitForEvent(name, options = {}) {
|
|
175
|
+
if (typeof name !== "string" || !/^[A-Za-z0-9._-]{1,100}$/.test(name)) {
|
|
176
|
+
throw new TypeError("waitForEvent: the event name must be 1 to 100 letters, digits, '.', '_' or '-'");
|
|
177
|
+
}
|
|
178
|
+
onlyKeys(options, ["timeout"], "waitForEvent");
|
|
179
|
+
return hostTask("waitForEvent", {
|
|
180
|
+
name,
|
|
181
|
+
timeout: options.timeout === undefined
|
|
182
|
+
? undefined
|
|
183
|
+
: milliseconds(options.timeout, "waitForEvent: timeout"),
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** Check out a branch for the following changes (managed git only). */
|
|
187
|
+
function branch(name) {
|
|
188
|
+
return hostTask("branch", { name });
|
|
189
|
+
}
|
|
190
|
+
/** Commit changes (managed git only). */
|
|
191
|
+
function commit(message, options = {}) {
|
|
192
|
+
return hostTask("commit", { ...options, message });
|
|
193
|
+
}
|
|
194
|
+
/** Push the branch and open a pull request (managed git only). */
|
|
195
|
+
function pullRequest(options) {
|
|
196
|
+
return hostTask("pullRequest", options);
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
callbackOf,
|
|
200
|
+
__callback,
|
|
201
|
+
forEachFile,
|
|
202
|
+
shell,
|
|
203
|
+
jssg,
|
|
204
|
+
astGrep,
|
|
205
|
+
shard,
|
|
206
|
+
codemod,
|
|
207
|
+
agent,
|
|
208
|
+
installSkill,
|
|
209
|
+
approval,
|
|
210
|
+
sleep,
|
|
211
|
+
waitForEvent,
|
|
212
|
+
branch,
|
|
213
|
+
commit,
|
|
214
|
+
pullRequest,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/** Tasks that wait: their step records when the wait began. */
|
|
218
|
+
const WAITS = new Set(["sleep", "waitForEvent"]);
|
|
219
|
+
function isRecord(value) {
|
|
220
|
+
return value !== null && typeof value === "object";
|
|
221
|
+
}
|
|
222
|
+
function onlyKeys(options, known, what) {
|
|
223
|
+
if (!isRecord(options) || Array.isArray(options)) {
|
|
224
|
+
throw new TypeError(`${what}: options must be an object`);
|
|
225
|
+
}
|
|
226
|
+
for (const key of Object.keys(options)) {
|
|
227
|
+
if (!known.includes(key)) {
|
|
228
|
+
throw new TypeError(`${what}: unknown option '${key}'; expected ${known.join(", ")}`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const UNITS = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
233
|
+
/** A duration in milliseconds, from a number of them or a string such as "30s". */
|
|
234
|
+
export function milliseconds(value, what) {
|
|
235
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
|
|
236
|
+
return Math.round(value);
|
|
237
|
+
const match = typeof value === "string" ? /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim()) : null;
|
|
238
|
+
if (!match) {
|
|
239
|
+
throw new TypeError(`${what}: expected milliseconds or a duration such as "500ms", "30s", "10m", "1h" or "2d"`);
|
|
240
|
+
}
|
|
241
|
+
return Math.round(Number(match[1]) * UNITS[match[2]]);
|
|
242
|
+
}
|
|
243
|
+
/** A duration in its largest whole unit, as the engine words it. */
|
|
244
|
+
export function describeDuration(ms) {
|
|
245
|
+
for (const unit of ["h", "m", "s"]) {
|
|
246
|
+
if (ms >= UNITS[unit] && ms % UNITS[unit] === 0)
|
|
247
|
+
return `${ms / UNITS[unit]}${unit}`;
|
|
248
|
+
}
|
|
249
|
+
return `${ms}ms`;
|
|
250
|
+
}
|
|
251
|
+
/** What `step(..., options)` asks for. */
|
|
252
|
+
function policyOf(options, what) {
|
|
253
|
+
if (options === undefined)
|
|
254
|
+
return { attempts: 1, retryDelay: 0, timeout: undefined };
|
|
255
|
+
onlyKeys(options, ["retries", "retryDelay", "timeout"], what);
|
|
256
|
+
const { retries = 0, retryDelay = "1s", timeout } = options;
|
|
257
|
+
if (!Number.isInteger(retries) || retries < 0) {
|
|
258
|
+
throw new TypeError(`${what}: retries must be a whole number, 0 or more`);
|
|
259
|
+
}
|
|
260
|
+
const limit = timeout === undefined ? undefined : milliseconds(timeout, `${what}: timeout`);
|
|
261
|
+
if (limit === 0)
|
|
262
|
+
throw new TypeError(`${what}: timeout must be more than 0`);
|
|
263
|
+
return {
|
|
264
|
+
attempts: retries + 1,
|
|
265
|
+
retryDelay: milliseconds(retryDelay, `${what}: retryDelay`),
|
|
266
|
+
timeout: limit,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function isTemplateStrings(value) {
|
|
270
|
+
return Array.isArray(value) && Array.isArray(value.raw);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* A value in a `shell` template, quoted for the shell: one word whatever it
|
|
274
|
+
* holds. An array is one word per item.
|
|
275
|
+
*/
|
|
276
|
+
function shellQuote(value, index) {
|
|
277
|
+
if (Array.isArray(value))
|
|
278
|
+
return value.map((item) => shellQuote(item, index)).join(" ");
|
|
279
|
+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
|
|
280
|
+
throw new TypeError(`shell: value ${index + 1} in the command is ${value === null ? "null" : typeof value}; give a string, a number, a boolean, or an array of them`);
|
|
281
|
+
}
|
|
282
|
+
const text = String(value);
|
|
283
|
+
if (/^[\w@%+=:,./-]+$/.test(text))
|
|
284
|
+
return text;
|
|
285
|
+
return `'${text.replaceAll("'", `'\\''`)}'`;
|
|
286
|
+
}
|
|
287
|
+
export function createRuntime(host) {
|
|
288
|
+
const tasks = createTasks(host);
|
|
289
|
+
const { callbackOf } = tasks;
|
|
290
|
+
// What earlier executions of the run recorded. A step is the one recorded
|
|
291
|
+
// when it has the same label and content (its key), wherever and whenever
|
|
292
|
+
// the body issues it: the order steps are issued in depends on how fast
|
|
293
|
+
// other steps finish, so it cannot say which step is which. Steps that are
|
|
294
|
+
// the same in both are interchangeable and take the records in turn.
|
|
295
|
+
const recorded = new Map();
|
|
296
|
+
// Recorded steps that did not finish, for a changed step to take over.
|
|
297
|
+
const unfinished = new Set();
|
|
298
|
+
// A step keeps its position for the whole run; new steps go after.
|
|
299
|
+
let nextPosition = 0;
|
|
300
|
+
// Steps are numbered in the order they finish, across executions of the run.
|
|
301
|
+
let nextSeq = 0;
|
|
302
|
+
for (const entry of [...host.history()].sort((a, b) => a.position - b.position)) {
|
|
303
|
+
const same = recorded.get(entry.key) ?? [];
|
|
304
|
+
same.push(entry);
|
|
305
|
+
recorded.set(entry.key, same);
|
|
306
|
+
if (!finished(entry))
|
|
307
|
+
unfinished.add(entry);
|
|
308
|
+
nextPosition = Math.max(nextPosition, entry.position + 1);
|
|
309
|
+
if (typeof entry.seq === "number")
|
|
310
|
+
nextSeq = Math.max(nextSeq, entry.seq + 1);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* The recorded step this one is, or the position of an unfinished step it
|
|
314
|
+
* replaces: a step with a recorded name but new content is the failed step,
|
|
315
|
+
* fixed. A finished step is never replaced; its record stays for a step
|
|
316
|
+
* with its content.
|
|
317
|
+
*/
|
|
318
|
+
function claim(label, key, content) {
|
|
319
|
+
const entry = recorded.get(key)?.shift();
|
|
320
|
+
if (entry) {
|
|
321
|
+
unfinished.delete(entry);
|
|
322
|
+
return { position: entry.position, entry };
|
|
323
|
+
}
|
|
324
|
+
for (const entry of unfinished) {
|
|
325
|
+
if (entry.label !== (label ?? defaultLabel(entry.position, content)))
|
|
326
|
+
continue;
|
|
327
|
+
unfinished.delete(entry);
|
|
328
|
+
const others = recorded.get(entry.key);
|
|
329
|
+
others?.splice(others.indexOf(entry), 1);
|
|
330
|
+
return { position: entry.position };
|
|
331
|
+
}
|
|
332
|
+
return { position: nextPosition++ };
|
|
333
|
+
}
|
|
334
|
+
const state = new Map();
|
|
335
|
+
// A test run can stop after one step (`until`) and skip steps with a given
|
|
336
|
+
// result (`given`), both matched by label.
|
|
337
|
+
const plan = host.testPlan() ?? {};
|
|
338
|
+
const given = new Map(Object.entries(plan.given ?? {}));
|
|
339
|
+
// Once closed, no step starts: steps issued from then on never settle. A
|
|
340
|
+
// run closes when a test's `until` step starts, when a step is canceled or
|
|
341
|
+
// waits for an approval, and when the host ends the run.
|
|
342
|
+
let closed = false;
|
|
343
|
+
// Recorded steps the body has issued again, waiting to settle. They settle
|
|
344
|
+
// one at a time in the order they finished when they ran, so the body sees
|
|
345
|
+
// state, the clock and promise races as it did then.
|
|
346
|
+
const replaying = [];
|
|
347
|
+
/**
|
|
348
|
+
* Settle the next replayed step. The host calls it whenever the workflow
|
|
349
|
+
* has nothing left to run, until it returns false.
|
|
350
|
+
*/
|
|
351
|
+
function replayNext() {
|
|
352
|
+
if (closed)
|
|
353
|
+
return false;
|
|
354
|
+
let next;
|
|
355
|
+
for (const replay of replaying) {
|
|
356
|
+
if (!next || replay.order < next.order)
|
|
357
|
+
next = replay;
|
|
358
|
+
}
|
|
359
|
+
if (!next)
|
|
360
|
+
return false;
|
|
361
|
+
replaying.splice(replaying.indexOf(next), 1);
|
|
362
|
+
next.settle();
|
|
363
|
+
return true;
|
|
364
|
+
}
|
|
365
|
+
/** The run is ending: no step starts from here on. */
|
|
366
|
+
function close() {
|
|
367
|
+
closed = true;
|
|
368
|
+
}
|
|
369
|
+
/** Whether steps issued now would never start. */
|
|
370
|
+
function isClosed() {
|
|
371
|
+
return closed;
|
|
372
|
+
}
|
|
373
|
+
// The body's clock only moves when a step finishes, to the time recorded
|
|
374
|
+
// for it, so Date.now() in the body gives the same answer on every replay.
|
|
375
|
+
function settleClock(entry) {
|
|
376
|
+
if (typeof entry.finishedAt === "number")
|
|
377
|
+
host.advanceClock(entry.finishedAt);
|
|
378
|
+
}
|
|
379
|
+
// ---------------------------------------------------------------- state ---
|
|
380
|
+
/** Read one state key, or the whole state as an object when called without one. Values are frozen. */
|
|
381
|
+
function getState(key) {
|
|
382
|
+
if (key === undefined)
|
|
383
|
+
return Object.freeze(Object.fromEntries(state));
|
|
384
|
+
return state.get(key);
|
|
385
|
+
}
|
|
386
|
+
/** Set workflow state. `undefined` removes the key. */
|
|
387
|
+
function setState(key, value) {
|
|
388
|
+
if (value === undefined) {
|
|
389
|
+
state.delete(key);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
checkJson(value, `state.${key}`);
|
|
393
|
+
state.set(key, freeze(JSON.parse(JSON.stringify(value))));
|
|
394
|
+
}
|
|
395
|
+
function unsetState(key) {
|
|
396
|
+
state.delete(key);
|
|
397
|
+
}
|
|
398
|
+
function applyState(changes) {
|
|
399
|
+
if (!changes)
|
|
400
|
+
return;
|
|
401
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
402
|
+
if (value === null)
|
|
403
|
+
state.delete(key);
|
|
404
|
+
else
|
|
405
|
+
state.set(key, freeze(value));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
function stateSnapshot() {
|
|
409
|
+
return Object.fromEntries(state);
|
|
410
|
+
}
|
|
411
|
+
// The body runs alone, so a lock there has nothing to wait for; steps and
|
|
412
|
+
// callbacks get the real one from their own runtime.
|
|
413
|
+
function acquireLock(_name) {
|
|
414
|
+
return () => { };
|
|
415
|
+
}
|
|
416
|
+
// Step outputs are kept for the transforms that still set them; nothing in
|
|
417
|
+
// a workflow reads them back but these functions.
|
|
418
|
+
const stepOutputs = new Map();
|
|
419
|
+
const outputKey = (stepId, name) => JSON.stringify([stepId, name]);
|
|
420
|
+
function setStepOutput(name, value) {
|
|
421
|
+
stepOutputs.set(outputKey("", name), String(value));
|
|
422
|
+
}
|
|
423
|
+
function getStepOutput(stepId, name) {
|
|
424
|
+
return stepOutputs.get(outputKey(stepId, name)) ?? null;
|
|
425
|
+
}
|
|
426
|
+
function getOrSetStepOutput(stepId, name, value) {
|
|
427
|
+
const key = outputKey(stepId, name);
|
|
428
|
+
const existing = stepOutputs.get(key);
|
|
429
|
+
if (existing !== undefined)
|
|
430
|
+
return existing;
|
|
431
|
+
const text = String(value);
|
|
432
|
+
stepOutputs.set(key, text);
|
|
433
|
+
return text;
|
|
434
|
+
}
|
|
435
|
+
/** Evaluate a workflow.yaml `${{ }}` expression; used by translated workflows. */
|
|
436
|
+
function __evaluate(kind, expression, scope) {
|
|
437
|
+
return host.evaluate(kind, expression, scope);
|
|
438
|
+
}
|
|
439
|
+
// ----------------------------------------------------------------- step ---
|
|
440
|
+
/**
|
|
441
|
+
* Run a task as a durable step: `step(label?, task, options?)`. Starts
|
|
442
|
+
* immediately; the returned promise resolves to the step's frozen result.
|
|
443
|
+
* `options` may give `retries`, `retryDelay` and `timeout`; they say how to
|
|
444
|
+
* run the step, not what it is, so changing them does not make it another
|
|
445
|
+
* step.
|
|
446
|
+
*/
|
|
447
|
+
function step(...args) {
|
|
448
|
+
const label = typeof args[0] === "string" ? args.shift() : undefined;
|
|
449
|
+
return runStep(label, args[0], args[1]).then(freeze);
|
|
450
|
+
}
|
|
451
|
+
/** Wait for a time, as a step: a resumed run waits for what is left. */
|
|
452
|
+
function sleep(duration) {
|
|
453
|
+
return step(tasks.sleep(duration));
|
|
454
|
+
}
|
|
455
|
+
/** Wait for an event sent to the run, as a step; resolves to the event's data. */
|
|
456
|
+
function waitForEvent(name, options) {
|
|
457
|
+
return step(tasks.waitForEvent(name, options));
|
|
458
|
+
}
|
|
459
|
+
async function runStep(label, task, options) {
|
|
460
|
+
const described = label === undefined ? "step" : `step '${label}'`;
|
|
461
|
+
const policy = policyOf(options, described);
|
|
462
|
+
// Everything up to the first await runs synchronously inside step(), so
|
|
463
|
+
// captures and state are a snapshot taken when the step is called.
|
|
464
|
+
let content;
|
|
465
|
+
let fn;
|
|
466
|
+
const callback = callbackOf(task);
|
|
467
|
+
if (callback) {
|
|
468
|
+
content = { kind: "function", callback: callback.id, captures: capturesOf(callback) };
|
|
469
|
+
fn = callback.fn;
|
|
470
|
+
}
|
|
471
|
+
else if (typeof task === "function") {
|
|
472
|
+
throw new TypeError(`${described}: write the function inline, as step(() => ...), so the build can run it in its own isolate`);
|
|
473
|
+
}
|
|
474
|
+
else if (isTask(task) && task[TASK] === "forEachFile") {
|
|
475
|
+
content = {
|
|
476
|
+
kind: "forEachFile",
|
|
477
|
+
selector: task.selector,
|
|
478
|
+
callback: task.callback.id,
|
|
479
|
+
captures: capturesOf(task.callback),
|
|
480
|
+
};
|
|
481
|
+
fn = task.callback.fn;
|
|
482
|
+
}
|
|
483
|
+
else if (isTask(task) && task[TASK] === "host") {
|
|
484
|
+
content = task.content;
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
throw new TypeError(`${described}: expected a task such as forEachFile(...) or a function`);
|
|
488
|
+
}
|
|
489
|
+
const key = canonical([label ?? null, content]);
|
|
490
|
+
if (closed)
|
|
491
|
+
return new Promise(() => { });
|
|
492
|
+
const { position, entry: prior } = claim(label, key, content);
|
|
493
|
+
const name = label ?? defaultLabel(position, content);
|
|
494
|
+
if (plan.until !== undefined && name === plan.until) {
|
|
495
|
+
closed = true;
|
|
496
|
+
host.stop();
|
|
497
|
+
}
|
|
498
|
+
if (given.has(name)) {
|
|
499
|
+
const result = given.get(name) ?? null;
|
|
500
|
+
host.event({ type: "stepReplayed", position, label: name });
|
|
501
|
+
host.record({ position, label: name, key, status: "succeeded", result, given: true, seq: nextSeq++ }, 0);
|
|
502
|
+
return JSON.parse(JSON.stringify(result));
|
|
503
|
+
}
|
|
504
|
+
if (prior && finished(prior)) {
|
|
505
|
+
return new Promise((resolve) => {
|
|
506
|
+
replaying.push({
|
|
507
|
+
// Steps recorded before finishing order was kept replay in the
|
|
508
|
+
// order they were issued.
|
|
509
|
+
order: prior.seq ?? prior.position,
|
|
510
|
+
settle() {
|
|
511
|
+
applyState(prior.state);
|
|
512
|
+
settleClock(prior);
|
|
513
|
+
host.event({ type: "stepReplayed", position, label: name });
|
|
514
|
+
resolve(prior.result ?? null);
|
|
515
|
+
},
|
|
516
|
+
});
|
|
517
|
+
host.wake?.();
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
if (host.canceled()) {
|
|
521
|
+
closed = true;
|
|
522
|
+
throw new CanceledError();
|
|
523
|
+
}
|
|
524
|
+
host.event({ type: "stepStarted", position, label: name });
|
|
525
|
+
const started = host.now();
|
|
526
|
+
// A wait counts from when it first began, also when it was interrupted
|
|
527
|
+
// and goes on now, so that is recorded before it starts. One that failed
|
|
528
|
+
// ran out of time, and starts over.
|
|
529
|
+
const since = !WAITS.has(content.kind)
|
|
530
|
+
? undefined
|
|
531
|
+
: prior && prior.status !== "failed" && typeof prior.since === "number"
|
|
532
|
+
? prior.since
|
|
533
|
+
: started;
|
|
534
|
+
if (since !== undefined) {
|
|
535
|
+
host.record({ position, label: name, key, status: "waiting", since }, 0);
|
|
536
|
+
}
|
|
537
|
+
let attempt = 1;
|
|
538
|
+
const record = (entry) => host.record({
|
|
539
|
+
position,
|
|
540
|
+
label: name,
|
|
541
|
+
key,
|
|
542
|
+
seq: nextSeq++,
|
|
543
|
+
...(since !== undefined && { since }),
|
|
544
|
+
...(attempt > 1 && { attempts: attempt }),
|
|
545
|
+
...entry,
|
|
546
|
+
}, host.now() - started);
|
|
547
|
+
const request = {
|
|
548
|
+
position,
|
|
549
|
+
label: name,
|
|
550
|
+
task: content,
|
|
551
|
+
state: stateSnapshot(),
|
|
552
|
+
fn,
|
|
553
|
+
...(policy.timeout !== undefined && { timeoutMs: policy.timeout }),
|
|
554
|
+
...(since !== undefined && { since }),
|
|
555
|
+
};
|
|
556
|
+
let outcome;
|
|
557
|
+
for (;;) {
|
|
558
|
+
let error;
|
|
559
|
+
try {
|
|
560
|
+
outcome = await host.start(request);
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
catch (cause) {
|
|
564
|
+
error = asError(cause);
|
|
565
|
+
}
|
|
566
|
+
// A failed step runs again while it has attempts left and the run is
|
|
567
|
+
// still going.
|
|
568
|
+
if (!interruptionOf(error) && attempt < policy.attempts && !closed) {
|
|
569
|
+
host.event({
|
|
570
|
+
type: "stepRetrying",
|
|
571
|
+
position,
|
|
572
|
+
label: name,
|
|
573
|
+
attempt,
|
|
574
|
+
attempts: policy.attempts,
|
|
575
|
+
error: messageOf(error),
|
|
576
|
+
});
|
|
577
|
+
try {
|
|
578
|
+
if (policy.retryDelay > 0) {
|
|
579
|
+
await host.start({
|
|
580
|
+
position,
|
|
581
|
+
label: name,
|
|
582
|
+
task: { kind: "sleep", duration: policy.retryDelay },
|
|
583
|
+
state: {},
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
attempt++;
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
catch (cause) {
|
|
590
|
+
// Canceled between attempts.
|
|
591
|
+
error = asError(cause);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
// A step that was canceled or waits for an approval runs again when
|
|
595
|
+
// the run is resumed; nothing else starts in this execution.
|
|
596
|
+
const interrupted = interruptionOf(error);
|
|
597
|
+
if (interrupted) {
|
|
598
|
+
closed = true;
|
|
599
|
+
record({ status: interrupted, error: messageOf(error) });
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
record({ status: "failed", error: messageOf(error) });
|
|
603
|
+
throw new StepError(name, error);
|
|
604
|
+
}
|
|
605
|
+
const result = outcome.result ?? null;
|
|
606
|
+
const changes = outcome.state ?? null;
|
|
607
|
+
applyState(changes);
|
|
608
|
+
const finishedAt = host.now();
|
|
609
|
+
// Some files failed: the step finished, and the rest of the run goes on.
|
|
610
|
+
if (outcome.partial !== undefined) {
|
|
611
|
+
record({ status: "partial", result, state: changes, finishedAt, error: outcome.partial });
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
record({ status: "succeeded", result, state: changes, finishedAt });
|
|
615
|
+
}
|
|
616
|
+
settleClock({ finishedAt });
|
|
617
|
+
return result;
|
|
618
|
+
}
|
|
619
|
+
/** Whether a recorded step finished, so a resume reuses its result. */
|
|
620
|
+
function finished(entry) {
|
|
621
|
+
return entry.status === "succeeded" || entry.status === "partial";
|
|
622
|
+
}
|
|
623
|
+
function interruptionOf(error) {
|
|
624
|
+
if (error instanceof CanceledError)
|
|
625
|
+
return "canceled";
|
|
626
|
+
if (error instanceof AwaitingApprovalError)
|
|
627
|
+
return "awaiting-approval";
|
|
628
|
+
return null;
|
|
629
|
+
}
|
|
630
|
+
/** Captured values of an extracted callback; none for callbacks run in place. */
|
|
631
|
+
function capturesOf(callback) {
|
|
632
|
+
if (typeof callback.captures !== "function")
|
|
633
|
+
return undefined;
|
|
634
|
+
const captures = callback.captures();
|
|
635
|
+
checkJson(captures, "captures");
|
|
636
|
+
return captures;
|
|
637
|
+
}
|
|
638
|
+
/** Turn a host rejection (`{ name, message }`) back into the runtime's errors. */
|
|
639
|
+
function asError(cause) {
|
|
640
|
+
if (cause instanceof Error) {
|
|
641
|
+
if (cause.name === "CanceledError" && !(cause instanceof CanceledError)) {
|
|
642
|
+
return new CanceledError(cause.message);
|
|
643
|
+
}
|
|
644
|
+
if (cause.name === "AwaitingApprovalError" && !(cause instanceof AwaitingApprovalError)) {
|
|
645
|
+
return new AwaitingApprovalError(cause.message);
|
|
646
|
+
}
|
|
647
|
+
return cause;
|
|
648
|
+
}
|
|
649
|
+
if (isRecord(cause) && typeof cause.message === "string") {
|
|
650
|
+
if (cause.name === "CanceledError")
|
|
651
|
+
return new CanceledError(cause.message);
|
|
652
|
+
if (cause.name === "AwaitingApprovalError")
|
|
653
|
+
return new AwaitingApprovalError(cause.message);
|
|
654
|
+
return new Error(cause.message);
|
|
655
|
+
}
|
|
656
|
+
return new Error(String(cause));
|
|
657
|
+
}
|
|
658
|
+
const { callbackOf: _, ...builders } = tasks;
|
|
659
|
+
return {
|
|
660
|
+
...builders,
|
|
661
|
+
getState,
|
|
662
|
+
setState,
|
|
663
|
+
unsetState,
|
|
664
|
+
acquireLock,
|
|
665
|
+
setStepOutput,
|
|
666
|
+
getStepOutput,
|
|
667
|
+
getOrSetStepOutput,
|
|
668
|
+
__evaluate,
|
|
669
|
+
step,
|
|
670
|
+
sleep,
|
|
671
|
+
waitForEvent,
|
|
672
|
+
replayNext,
|
|
673
|
+
close,
|
|
674
|
+
isClosed,
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
function isTask(value) {
|
|
678
|
+
return isRecord(value) && TASK in value;
|
|
679
|
+
}
|
|
680
|
+
function withoutUndefined(value) {
|
|
681
|
+
if (Array.isArray(value))
|
|
682
|
+
return value.map(withoutUndefined);
|
|
683
|
+
if (isRecord(value) && Object.getPrototypeOf(value) === Object.prototype) {
|
|
684
|
+
const result = {};
|
|
685
|
+
for (const [key, item] of Object.entries(value)) {
|
|
686
|
+
if (item !== undefined)
|
|
687
|
+
result[key] = withoutUndefined(item);
|
|
688
|
+
}
|
|
689
|
+
return result;
|
|
690
|
+
}
|
|
691
|
+
return value;
|
|
692
|
+
}
|
|
693
|
+
function normalizeSelector(selector) {
|
|
694
|
+
if (selector === undefined)
|
|
695
|
+
selector = {};
|
|
696
|
+
if (typeof selector === "string" || Array.isArray(selector))
|
|
697
|
+
selector = { include: selector };
|
|
698
|
+
if (!isRecord(selector)) {
|
|
699
|
+
throw new TypeError("forEachFile: the selector must be a glob, an array of globs, or an object");
|
|
700
|
+
}
|
|
701
|
+
const known = new Set(["include", "exclude", "language", "containing", "concurrency"]);
|
|
702
|
+
for (const key of Object.keys(selector)) {
|
|
703
|
+
if (!known.has(key))
|
|
704
|
+
throw new TypeError(`forEachFile: unknown selector field '${key}'`);
|
|
705
|
+
}
|
|
706
|
+
const normalized = {
|
|
707
|
+
include: globs(selector.include, "include"),
|
|
708
|
+
exclude: globs(selector.exclude, "exclude"),
|
|
709
|
+
};
|
|
710
|
+
for (const field of ["language", "containing"]) {
|
|
711
|
+
const value = selector[field];
|
|
712
|
+
if (value === undefined)
|
|
713
|
+
continue;
|
|
714
|
+
if (typeof value !== "string") {
|
|
715
|
+
throw new TypeError(`forEachFile: selector.${field} must be a string`);
|
|
716
|
+
}
|
|
717
|
+
normalized[field] = value;
|
|
718
|
+
}
|
|
719
|
+
const { concurrency } = selector;
|
|
720
|
+
if (concurrency !== undefined) {
|
|
721
|
+
if (typeof concurrency !== "number" || !Number.isInteger(concurrency) || concurrency < 1) {
|
|
722
|
+
throw new TypeError("forEachFile: concurrency must be a whole number of at least 1");
|
|
723
|
+
}
|
|
724
|
+
normalized.concurrency = concurrency;
|
|
725
|
+
}
|
|
726
|
+
// Neither include nor language: the package's languages from codemod.yaml.
|
|
727
|
+
return normalized;
|
|
728
|
+
}
|
|
729
|
+
function globs(value, field) {
|
|
730
|
+
if (value === undefined)
|
|
731
|
+
return [];
|
|
732
|
+
if (typeof value === "string")
|
|
733
|
+
return [value];
|
|
734
|
+
if (Array.isArray(value) && value.every((item) => typeof item === "string"))
|
|
735
|
+
return [...value];
|
|
736
|
+
throw new TypeError(`forEachFile: selector.${field} must be a glob or an array of globs`);
|
|
737
|
+
}
|
|
738
|
+
function defaultLabel(position, content) {
|
|
739
|
+
switch (content.kind) {
|
|
740
|
+
case "forEachFile": {
|
|
741
|
+
const { include, language } = content.selector;
|
|
742
|
+
return `forEachFile ${include.length ? include.join(", ") : (language ?? "")}`.trimEnd();
|
|
743
|
+
}
|
|
744
|
+
case "function":
|
|
745
|
+
return `step #${position}`;
|
|
746
|
+
case "shell":
|
|
747
|
+
return `shell ${truncate(content.command)}`;
|
|
748
|
+
case "jssg":
|
|
749
|
+
case "astGrep":
|
|
750
|
+
return `${content.kind} ${String(content.path)}`;
|
|
751
|
+
case "approval":
|
|
752
|
+
return `approval: ${truncate(content.message)}`;
|
|
753
|
+
case "sleep":
|
|
754
|
+
return `sleep ${describeDuration(Number(content.duration))}`;
|
|
755
|
+
case "waitForEvent":
|
|
756
|
+
return `wait for ${String(content.name)}`;
|
|
757
|
+
case "codemod":
|
|
758
|
+
return `codemod ${String(content.source)}`;
|
|
759
|
+
case "agent":
|
|
760
|
+
return `agent: ${truncate(content.prompt)}`;
|
|
761
|
+
default:
|
|
762
|
+
return content.kind;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
function truncate(text, length = 60) {
|
|
766
|
+
const line = String(text ?? "").split("\n")[0] ?? "";
|
|
767
|
+
return line.length > length ? `${line.slice(0, length - 1)}…` : line;
|
|
768
|
+
}
|
|
769
|
+
function canonical(value) {
|
|
770
|
+
return JSON.stringify(sortKeys(value));
|
|
771
|
+
}
|
|
772
|
+
function sortKeys(value) {
|
|
773
|
+
if (Array.isArray(value))
|
|
774
|
+
return value.map(sortKeys);
|
|
775
|
+
if (isRecord(value)) {
|
|
776
|
+
const sorted = {};
|
|
777
|
+
for (const key of Object.keys(value).sort())
|
|
778
|
+
sorted[key] = sortKeys(value[key]);
|
|
779
|
+
return sorted;
|
|
780
|
+
}
|
|
781
|
+
return value;
|
|
782
|
+
}
|
|
783
|
+
/** Freeze a JSON value, all the way down. */
|
|
784
|
+
export function freeze(value) {
|
|
785
|
+
if (isRecord(value) && !Object.isFrozen(value)) {
|
|
786
|
+
Object.freeze(value);
|
|
787
|
+
for (const key of Object.keys(value))
|
|
788
|
+
freeze(value[key]);
|
|
789
|
+
}
|
|
790
|
+
return value;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* An error as a step's failure says it. Changing a captured value or a step
|
|
794
|
+
* result fails as a TypeError that does not say why; the hint does.
|
|
795
|
+
*/
|
|
796
|
+
export function describeError(error) {
|
|
797
|
+
if (!isRecord(error))
|
|
798
|
+
return String(error);
|
|
799
|
+
let message = `${String(error.name || "Error")}: ${String(error.message)}`;
|
|
800
|
+
if (error instanceof TypeError &&
|
|
801
|
+
/extensible|read-only|read only|frozen|non-writable/i.test(error.message)) {
|
|
802
|
+
message += " (captured values and step results are frozen; copy one before changing it)";
|
|
803
|
+
}
|
|
804
|
+
return message;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* The `file` a `forEachFile` callback gets, and the effects it records on it.
|
|
808
|
+
* After `close()`, when the callback has finished, the file takes no more.
|
|
809
|
+
*/
|
|
810
|
+
export function fileHandle(path, text, language) {
|
|
811
|
+
const effects = [];
|
|
812
|
+
let open = true;
|
|
813
|
+
const guard = (name) => {
|
|
814
|
+
if (!open)
|
|
815
|
+
throw new Error(`file.${name}() was called after the callback finished`);
|
|
816
|
+
};
|
|
817
|
+
const file = Object.freeze({
|
|
818
|
+
path,
|
|
819
|
+
text,
|
|
820
|
+
language,
|
|
821
|
+
write(next) {
|
|
822
|
+
guard("write");
|
|
823
|
+
if (typeof next !== "string")
|
|
824
|
+
throw new TypeError("file.write(text) expects a string");
|
|
825
|
+
effects.push({ op: "write", text: next });
|
|
826
|
+
},
|
|
827
|
+
rename(to) {
|
|
828
|
+
guard("rename");
|
|
829
|
+
if (typeof to !== "string" || to === "") {
|
|
830
|
+
throw new TypeError("file.rename(path) expects a non-empty path");
|
|
831
|
+
}
|
|
832
|
+
effects.push({ op: "rename", to });
|
|
833
|
+
},
|
|
834
|
+
delete() {
|
|
835
|
+
guard("delete");
|
|
836
|
+
effects.push({ op: "delete" });
|
|
837
|
+
},
|
|
838
|
+
});
|
|
839
|
+
return {
|
|
840
|
+
file,
|
|
841
|
+
effects,
|
|
842
|
+
close() {
|
|
843
|
+
open = false;
|
|
844
|
+
},
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
function messageOf(error) {
|
|
848
|
+
return isRecord(error) && "message" in error ? String(error.message) : String(error);
|
|
849
|
+
}
|
|
850
|
+
/** Throw a TypeError naming the first part of `value` that is not JSON. */
|
|
851
|
+
export function checkJson(value, path, seen = new Set()) {
|
|
852
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
853
|
+
return;
|
|
854
|
+
if (typeof value === "number") {
|
|
855
|
+
if (!Number.isFinite(value))
|
|
856
|
+
throw new TypeError(`${path} is ${value}, which is not JSON`);
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
if (typeof value !== "object") {
|
|
860
|
+
const what = value === undefined ? "undefined" : `a ${typeof value}`;
|
|
861
|
+
throw new TypeError(`${path} is ${what}, which is not JSON`);
|
|
862
|
+
}
|
|
863
|
+
if (seen.has(value))
|
|
864
|
+
throw new TypeError(`${path} is a circular reference`);
|
|
865
|
+
seen.add(value);
|
|
866
|
+
if (Array.isArray(value)) {
|
|
867
|
+
value.forEach((item, index) => checkJson(item, `${path}[${index}]`, seen));
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
const proto = Object.getPrototypeOf(value);
|
|
871
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
872
|
+
const name = value.constructor?.name || "non-plain object";
|
|
873
|
+
throw new TypeError(`${path} is a ${name}, which is not JSON`);
|
|
874
|
+
}
|
|
875
|
+
for (const [key, item] of Object.entries(value))
|
|
876
|
+
checkJson(item, `${path}.${key}`, seen);
|
|
877
|
+
}
|
|
878
|
+
seen.delete(value);
|
|
879
|
+
}
|