@mark1russell7/workflow-github 0.0.0-bootstrap.0 → 0.1.0

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/src/yaml.ts ADDED
@@ -0,0 +1,670 @@
1
+ import { isEnvelope, isRecord } from "@mark1russell7/coeval";
2
+ import { type Document, isAlias, isScalar, isSeq, parseDocument, stringify, visit } from "yaml";
3
+ import { parseExpression, printExpression, splitText } from "./expression.ts";
4
+
5
+ /** The name of the format of the layer of the add-on. */
6
+ export const GITHUB_LAYER = "github/1";
7
+
8
+ /** A problem of an import, at the path of its value in the YAML. */
9
+ export interface ImportIssue {
10
+ readonly level: "error" | "warning";
11
+ readonly at: readonly (string | number)[];
12
+ readonly message: string;
13
+ }
14
+
15
+ /** The result of `fromGitHub`: the workflow document, and the problems of the import. */
16
+ export interface ImportResult {
17
+ /** `false` when the text is not a workflow. Then the document is absent. */
18
+ readonly ok: boolean;
19
+ readonly doc?: { readonly type: "workflow"; readonly value: Record<string, unknown> };
20
+ readonly issues: readonly ImportIssue[];
21
+ }
22
+
23
+ /** The options of `fromGitHub`. */
24
+ export interface ImportOptions {
25
+ /** The name of the file. A workflow without a name gets it. */
26
+ readonly file?: string;
27
+ /** The id of the workspace of the workflow. The default is `default`. */
28
+ readonly workspace?: string;
29
+ }
30
+
31
+ type Rec = Record<string, unknown>;
32
+ type Path = readonly (string | number)[];
33
+
34
+ /** The kernel test of a record, with a type that the import can change. */
35
+ const isPlain = (value: unknown): value is Rec => isRecord(value);
36
+
37
+ const defined = (record: Rec): Rec => Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
38
+ const nonEmpty = (record: Rec): Rec | undefined => (Object.keys(record).length > 0 ? record : undefined);
39
+
40
+ /** This function tells if two JSON values are equal. The order of the keys of a record does not count. */
41
+ export function sameJson(a: unknown, b: unknown): boolean {
42
+ if (a === b) return true;
43
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((item, index) => sameJson(item, b[index]));
44
+ if (isPlain(a) && isPlain(b)) {
45
+ const keys = Object.keys(a);
46
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameJson(a[key], b[key]));
47
+ }
48
+ return Number.isNaN(a) && Number.isNaN(b);
49
+ }
50
+
51
+ // === Texts with expressions ===
52
+
53
+ /** The import state: the problems and the source texts of the expressions. */
54
+ interface In {
55
+ readonly issues: ImportIssue[];
56
+ /** The source text of each value with an expression, by the canonical JSON of its document, in the order of the file. */
57
+ readonly texts: Record<string, string[]>;
58
+ }
59
+
60
+ /** The value of a text of GitHub: a text, or the document of its expressions, and the problems of the read. */
61
+ export interface TextValue {
62
+ readonly value: unknown;
63
+ readonly problems: readonly string[];
64
+ }
65
+
66
+ /**
67
+ * This function reads a text value of GitHub. A text without `${{` stays a text, unless it is a condition. A text that
68
+ * is one expression gives its document. Another text with expressions gives a `template`. A text with a bad expression
69
+ * stays a text, with a problem.
70
+ *
71
+ * @param text - The text.
72
+ * @param condition - `true` for the text of `if`, which is an expression without `${{ }}`.
73
+ * @returns The value and the problems.
74
+ */
75
+ export function readText(text: string, condition = false): TextValue {
76
+ const problems: string[] = [];
77
+ const value = textValueOf(text, condition, problems);
78
+ return { value: value === undefined ? text : value, problems };
79
+ }
80
+
81
+ /** This function gives the document of a text, or `undefined` when the text stays a text. */
82
+ function textValueOf(text: string, condition: boolean, problems: string[]): unknown {
83
+ const parts = splitText(text);
84
+ if (parts === undefined) {
85
+ problems.push("An expression has no end }}. The value stays a text.");
86
+ return undefined;
87
+ }
88
+ const read = (source: string, offset: number): unknown => {
89
+ const result = parseExpression(source);
90
+ if (result.ok) return result.doc;
91
+ problems.push(`At ${offset + result.issue.offset}: ${result.issue.message} The value stays a text.`);
92
+ return undefined;
93
+ };
94
+ let doc: unknown;
95
+ const only = parts.length === 1 ? parts[0] : undefined;
96
+ if (only !== undefined && "source" in only) doc = read(only.source, only.offset);
97
+ else if (parts.every((part) => "text" in part)) {
98
+ if (!condition) return undefined;
99
+ doc = read(text, 0);
100
+ } else {
101
+ const value: unknown[] = [];
102
+ for (const part of parts) {
103
+ if ("text" in part) value.push(part.text);
104
+ else {
105
+ const expr = read(part.source, part.offset);
106
+ if (expr === undefined) return undefined;
107
+ value.push(expr);
108
+ }
109
+ }
110
+ doc = { type: "template", value };
111
+ }
112
+ return doc;
113
+ }
114
+
115
+ /** This function reads a YAML text value of a file, and keeps its source text for the export. */
116
+ function textDoc(state: In, text: string, condition: boolean, at: Path): unknown {
117
+ const problems: string[] = [];
118
+ const doc = textValueOf(text, condition, problems);
119
+ for (const message of problems) state.issues.push({ level: "warning", at, message });
120
+ if (doc === undefined) return text;
121
+ (state.texts[JSON.stringify(doc)] ??= []).push(text);
122
+ return doc;
123
+ }
124
+
125
+ const termOf = (state: In, value: unknown, at: Path, condition = false): unknown => (typeof value === "string" ? textDoc(state, value, condition, at) : value);
126
+ const termsOf = (state: In, record: Rec, at: Path): Rec => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, termOf(state, value, [...at, key])]));
127
+
128
+ /** The export state: the source texts, and the number of the texts that the export used for each document. */
129
+ interface Out {
130
+ readonly texts: Readonly<Record<string, readonly string[]>>;
131
+ readonly used: Record<string, number>;
132
+ }
133
+
134
+ /** This function writes a document as a YAML value: the source text when the document did not change, else new text. */
135
+ function plainOf(state: Out, value: unknown, condition = false): unknown {
136
+ if (!isEnvelope(value)) return value;
137
+ const key = JSON.stringify(value);
138
+ const texts = state.texts[key];
139
+ if (texts !== undefined && texts.length > 0) {
140
+ const index = state.used[key] ?? 0;
141
+ state.used[key] = index + 1;
142
+ return texts[Math.min(index, texts.length - 1)];
143
+ }
144
+ if (value.type === "template" && Array.isArray(value.value)) {
145
+ return value.value.map((part) => (typeof part === "string" ? part : `\${{ ${printExpression(part)} }}`)).join("");
146
+ }
147
+ const text = printExpression(value);
148
+ return condition && !text.startsWith("!") ? text : `\${{ ${text} }}`;
149
+ }
150
+
151
+ const plainsOf = (state: Out, record: unknown): Rec | undefined =>
152
+ isPlain(record) ? Object.fromEntries(Object.entries(record).map(([key, value]) => [key, plainOf(state, value)])) : undefined;
153
+
154
+ // === Minutes ===
155
+
156
+ /** This function gives the seconds of a count of minutes when the conversion back is exact. */
157
+ function secondsOf(minutes: unknown): number | undefined {
158
+ return typeof minutes === "number" && Number.isFinite(minutes) && (minutes * 60) / 60 === minutes ? minutes * 60 : undefined;
159
+ }
160
+
161
+ // === Import ===
162
+
163
+ function layerOf(record: Rec): Rec | undefined {
164
+ const github = nonEmpty(defined(record));
165
+ return github === undefined ? undefined : { github };
166
+ }
167
+
168
+ function stepOf(state: In, step: unknown, at: Path): unknown {
169
+ if (!isPlain(step)) {
170
+ state.issues.push({ level: "warning", at, message: "A step is not a map. The layer keeps it." });
171
+ return { type: "step", value: { do: { type: ["github", "run"], value: {} }, layers: { github: { raw: step } } } };
172
+ }
173
+ const { id, name, if: condition, uses, with: inputs, run, shell, "working-directory": cwd, env, "continue-on-error": goOn, "timeout-minutes": minutes, ...rest } = step;
174
+ const gh: Rec = {};
175
+ let call: unknown;
176
+ if (uses !== undefined) {
177
+ if (shell !== undefined) rest["shell"] = shell;
178
+ if (cwd !== undefined) rest["working-directory"] = cwd;
179
+ if (run !== undefined) rest["run"] = run;
180
+ if (typeof uses !== "string") gh["uses"] = uses;
181
+ if (inputs !== undefined && !isPlain(inputs)) gh["with"] = inputs;
182
+ call = {
183
+ type: ["github", "action"],
184
+ value: defined({ uses: typeof uses === "string" ? uses : undefined, with: isPlain(inputs) ? termsOf(state, inputs, [...at, "with"]) : undefined }),
185
+ };
186
+ } else {
187
+ if (inputs !== undefined) rest["with"] = inputs;
188
+ if (run === undefined) gh["noRun"] = true;
189
+ call = {
190
+ type: ["github", "run"],
191
+ value: defined({
192
+ script: run === undefined ? undefined : termOf(state, run, [...at, "run"]),
193
+ shell: shell === undefined ? undefined : termOf(state, shell, [...at, "shell"]),
194
+ cwd: cwd === undefined ? undefined : termOf(state, cwd, [...at, "working-directory"]),
195
+ }),
196
+ };
197
+ }
198
+ if (id !== undefined && typeof id !== "string") gh["id"] = id;
199
+ if (name !== undefined && typeof name !== "string") gh["name"] = name;
200
+ if (env !== undefined && !isPlain(env)) gh["env"] = env;
201
+ if (goOn !== undefined && typeof goOn !== "boolean") gh["continue"] = goOn;
202
+ const timeout = secondsOf(minutes);
203
+ if (minutes !== undefined && timeout === undefined) gh["timeout"] = minutes;
204
+ gh["keys"] = nonEmpty(rest);
205
+ return {
206
+ type: "step",
207
+ value: defined({
208
+ id: typeof id === "string" ? id : undefined,
209
+ name: typeof name === "string" ? name : undefined,
210
+ if: condition === undefined ? undefined : termOf(state, condition, [...at, "if"], true),
211
+ do: call,
212
+ env: isPlain(env) ? termsOf(state, env, [...at, "env"]) : undefined,
213
+ continue: typeof goOn === "boolean" ? goOn : undefined,
214
+ timeout,
215
+ layers: layerOf(gh),
216
+ }),
217
+ };
218
+ }
219
+
220
+ function matrixOf(state: In, matrix: unknown, parallel: unknown, at: Path): { doc: unknown; parallelUsed: boolean } {
221
+ if (!isPlain(matrix)) return { doc: termOf(state, matrix, at), parallelUsed: false };
222
+ const { include, exclude, ...axes } = matrix;
223
+ const whole = typeof parallel === "number" && Number.isInteger(parallel) && parallel >= 1;
224
+ return {
225
+ doc: {
226
+ type: "matrix",
227
+ value: defined({
228
+ axes: termsOf(state, axes, at),
229
+ include: include === undefined ? undefined : termOf(state, include, [...at, "include"]),
230
+ exclude: exclude === undefined ? undefined : termOf(state, exclude, [...at, "exclude"]),
231
+ parallel: whole ? parallel : undefined,
232
+ }),
233
+ },
234
+ parallelUsed: whole,
235
+ };
236
+ }
237
+
238
+ function jobOf(state: In, job: unknown, at: Path): unknown {
239
+ if (!isPlain(job)) {
240
+ state.issues.push({ level: "warning", at, message: "A job is not a map. The layer keeps it." });
241
+ return { type: "job", value: { steps: [], layers: { github: { raw: job } } } };
242
+ }
243
+ const { name, needs, if: condition, env, outputs, "timeout-minutes": minutes, strategy, steps, uses, with: inputs, secrets, ...rest } = job;
244
+ const gh: Rec = {};
245
+ let stepDocs: unknown[];
246
+ if (Array.isArray(steps)) {
247
+ if (uses !== undefined) rest["uses"] = uses;
248
+ if (inputs !== undefined) rest["with"] = inputs;
249
+ if (secrets !== undefined) rest["secrets"] = secrets;
250
+ stepDocs = steps.map((step, index) => stepOf(state, step, [...at, "steps", index]));
251
+ } else if (typeof uses === "string") {
252
+ gh["reusable"] = true;
253
+ if (steps !== undefined) gh["steps"] = steps;
254
+ if (inputs !== undefined && !isPlain(inputs)) gh["with"] = inputs;
255
+ if (secrets !== undefined && secrets !== "inherit" && !isPlain(secrets)) gh["secrets"] = secrets;
256
+ const call = {
257
+ type: ["github", "workflow"],
258
+ value: defined({
259
+ uses,
260
+ with: isPlain(inputs) ? termsOf(state, inputs, [...at, "with"]) : undefined,
261
+ secrets: isPlain(secrets) ? termsOf(state, secrets, [...at, "secrets"]) : undefined,
262
+ inherit: secrets === "inherit" ? true : undefined,
263
+ }),
264
+ };
265
+ stepDocs = [{ type: "step", value: { do: call } }];
266
+ } else {
267
+ if (uses !== undefined) rest["uses"] = uses;
268
+ if (inputs !== undefined) rest["with"] = inputs;
269
+ if (secrets !== undefined) rest["secrets"] = secrets;
270
+ if (steps !== undefined) gh["steps"] = steps;
271
+ gh["noSteps"] = true;
272
+ stepDocs = [];
273
+ }
274
+ let needList: string[] | undefined;
275
+ if (typeof needs === "string") {
276
+ needList = [needs];
277
+ gh["needsText"] = true;
278
+ } else if (Array.isArray(needs) && needs.every((need) => typeof need === "string")) needList = needs as string[];
279
+ else if (needs !== undefined) gh["needs"] = needs;
280
+ let matrix: unknown;
281
+ if (strategy !== undefined) {
282
+ if (isPlain(strategy)) {
283
+ const { matrix: m, "max-parallel": parallel, ...others } = strategy;
284
+ const strategyRest: Rec = { ...others };
285
+ if (m !== undefined) {
286
+ const read = matrixOf(state, m, parallel, [...at, "strategy", "matrix"]);
287
+ matrix = read.doc;
288
+ if (!read.parallelUsed && parallel !== undefined) strategyRest["max-parallel"] = parallel;
289
+ } else if (parallel !== undefined) strategyRest["max-parallel"] = parallel;
290
+ gh["strategy"] = strategyRest;
291
+ } else gh["strategyRaw"] = strategy;
292
+ }
293
+ if (name !== undefined && typeof name !== "string") gh["name"] = name;
294
+ if (env !== undefined && !isPlain(env)) gh["env"] = env;
295
+ if (outputs !== undefined && !isPlain(outputs)) gh["outputs"] = outputs;
296
+ const timeout = secondsOf(minutes);
297
+ if (minutes !== undefined && timeout === undefined) gh["timeout"] = minutes;
298
+ gh["keys"] = nonEmpty(rest);
299
+ return {
300
+ type: "job",
301
+ value: defined({
302
+ name: typeof name === "string" ? name : undefined,
303
+ needs: needList,
304
+ if: condition === undefined ? undefined : termOf(state, condition, [...at, "if"], true),
305
+ matrix,
306
+ env: isPlain(env) ? termsOf(state, env, [...at, "env"]) : undefined,
307
+ steps: stepDocs,
308
+ outputs: isPlain(outputs) ? termsOf(state, outputs, [...at, "outputs"]) : undefined,
309
+ timeout,
310
+ layers: layerOf(gh),
311
+ }),
312
+ };
313
+ }
314
+
315
+ const TRIGGER_KIND: Readonly<Record<string, string>> = { workflow_dispatch: "manual", workflow_call: "call", schedule: "schedule" };
316
+
317
+ interface Triggers {
318
+ readonly triggers: unknown[];
319
+ readonly inputs: Rec;
320
+ secrets?: Rec;
321
+ outputs?: Rec;
322
+ }
323
+
324
+ function addInputs(found: Triggers, kind: string, inputs: Rec, layer: Rec): void {
325
+ for (const [name, def] of Object.entries(inputs)) {
326
+ const known = found.inputs[name];
327
+ if (known === undefined) found.inputs[name] = { ...(isPlain(def) ? def : { value: def }), on: [kind] };
328
+ else if (isPlain(known) && isPlain(def) && sameJson({ ...known, on: undefined }, { ...def, on: undefined }) && Array.isArray(known["on"])) known["on"].push(kind);
329
+ else ((layer["inputs"] ??= {}) as Rec)[name] = def;
330
+ }
331
+ }
332
+
333
+ function triggersOf(state: In, on: unknown, gh: Rec): Triggers {
334
+ const found: Triggers = { triggers: [], inputs: {} };
335
+ let entries: [string, unknown][];
336
+ if (typeof on === "string") {
337
+ gh["on"] = "text";
338
+ entries = [[on, undefined]];
339
+ } else if (Array.isArray(on)) {
340
+ gh["on"] = "list";
341
+ entries = on.map((event) => [String(event), undefined]);
342
+ } else if (isPlain(on)) entries = Object.entries(on);
343
+ else {
344
+ gh["on"] = on === undefined ? "none" : "raw";
345
+ if (on !== undefined) gh["onRaw"] = on;
346
+ entries = [];
347
+ }
348
+ for (const [event, config] of entries) {
349
+ const at = ["on", event];
350
+ const layer: Rec = { event };
351
+ const kind = TRIGGER_KIND[event] ?? "event";
352
+ if (kind === "schedule" && Array.isArray(config) && config.every((item) => isPlain(item) && typeof item["cron"] === "string")) {
353
+ config.forEach((item, index) => {
354
+ const { cron, ...more } = item as Rec;
355
+ found.triggers.push({ type: ["trigger", "schedule"], value: defined({ cron, layers: layerOf({ event, index, keys: nonEmpty(more) }) }) });
356
+ });
357
+ if (config.length === 0) found.triggers.push({ type: ["trigger", "event"], value: { event, layers: { github: { event, config } } } });
358
+ continue;
359
+ }
360
+ const value: Rec = {};
361
+ if (config === null) layer["config"] = null;
362
+ else if (isPlain(config)) {
363
+ const rest: Rec = { ...config };
364
+ if ((kind === "manual" || kind === "call") && isPlain(rest["inputs"]) && Object.keys(rest["inputs"]).length > 0) {
365
+ addInputs(found, kind, rest["inputs"], layer);
366
+ delete rest["inputs"];
367
+ }
368
+ if (kind === "call" && isPlain(rest["secrets"])) {
369
+ found.secrets = rest["secrets"];
370
+ delete rest["secrets"];
371
+ }
372
+ if (kind === "call" && isPlain(rest["outputs"]) && Object.values(rest["outputs"]).every((def) => isPlain(def) && "value" in def)) {
373
+ const outputs: Rec = {};
374
+ const meta: Rec = {};
375
+ for (const [name, def] of Object.entries(rest["outputs"] as Record<string, Rec>)) {
376
+ const { value: expr, ...more } = def;
377
+ outputs[name] = termOf(state, expr, [...at, "outputs", name, "value"]);
378
+ meta[name] = more;
379
+ }
380
+ found.outputs = outputs;
381
+ layer["outputs"] = meta;
382
+ delete rest["outputs"];
383
+ }
384
+ if (kind === "event" && Array.isArray(rest["types"]) && rest["types"].every((type) => typeof type === "string")) {
385
+ value["types"] = rest["types"];
386
+ delete rest["types"];
387
+ }
388
+ layer["config"] = rest;
389
+ } else if (config !== undefined) layer["raw"] = config;
390
+ if (kind === "event") value["event"] = event;
391
+ found.triggers.push({ type: ["trigger", kind], value: { ...value, layers: { github: layer } } });
392
+ }
393
+ return found;
394
+ }
395
+
396
+ /**
397
+ * This function reads the YAML of a GitHub workflow into a workflow document. It does not throw.
398
+ *
399
+ * - The parser is the `yaml` package. A text with anchors or aliases is refused.
400
+ * - Each expression becomes a document, and the layer keeps its source text.
401
+ * - Each key that the core does not model stays in the layer `github` of its workflow, job, step or trigger.
402
+ * - The layer of the workflow keeps the source text, thus `toGitHub` changes only the edited values.
403
+ *
404
+ * @param text - The YAML text.
405
+ * @param options - The name of the file and the workspace.
406
+ * @returns The document and the problems.
407
+ */
408
+ export function fromGitHub(text: string, options: ImportOptions = {}): ImportResult {
409
+ const issues: ImportIssue[] = [];
410
+ const parsed = parseDocument(text, { prettyErrors: false });
411
+ for (const error of parsed.errors) issues.push({ level: "error", at: [], message: error.message });
412
+ if (parsed.errors.length > 0) return { ok: false, issues };
413
+ let shared = false;
414
+ visit(parsed, (_key, node) => {
415
+ if (isAlias(node) || (typeof node === "object" && node !== null && "anchor" in node && typeof node.anchor === "string" && node.anchor !== "")) {
416
+ shared = true;
417
+ return visit.BREAK;
418
+ }
419
+ return undefined;
420
+ });
421
+ if (shared) return { ok: false, issues: [{ level: "error", at: [], message: "The workflow has YAML anchors or aliases. Version 1 of the add-on does not read them." }] };
422
+ const source = parsed.toJS() as unknown;
423
+ if (!isPlain(source)) return { ok: false, issues: [{ level: "error", at: [], message: "A workflow is a map at the top." }] };
424
+ const state: In = { issues, texts: {} };
425
+ const { name, on, env, jobs, ...rest } = source;
426
+ const gh: Rec = { format: GITHUB_LAYER };
427
+ if (name === undefined) gh["unnamed"] = true;
428
+ else if (typeof name !== "string") gh["name"] = name;
429
+ const found = triggersOf(state, on, gh);
430
+ const jobDocs: Rec = {};
431
+ if (isPlain(jobs)) for (const [id, job] of Object.entries(jobs)) jobDocs[id] = jobOf(state, job, ["jobs", id]);
432
+ else if (jobs !== undefined) gh["jobs"] = jobs;
433
+ else gh["noJobs"] = true;
434
+ if (env !== undefined && !isPlain(env)) gh["env"] = env;
435
+ gh["keys"] = nonEmpty(rest);
436
+ gh["texts"] = state.texts;
437
+ gh["source"] = text;
438
+ const value = defined({
439
+ name: typeof name === "string" ? name : (options.file ?? "workflow"),
440
+ workspace: options.workspace ?? "default",
441
+ triggers: found.triggers,
442
+ inputs: nonEmpty(found.inputs),
443
+ secrets: found.secrets,
444
+ env: isPlain(env) ? termsOf(state, env, ["env"]) : undefined,
445
+ jobs: jobDocs,
446
+ outputs: found.outputs,
447
+ layers: { github: defined(gh) },
448
+ });
449
+ return { ok: true, doc: { type: "workflow", value }, issues };
450
+ }
451
+
452
+ // === Export ===
453
+
454
+ const githubOf = (value: unknown): Rec => {
455
+ const layers = isPlain(value) ? value["layers"] : undefined;
456
+ const github = isPlain(layers) ? layers["github"] : undefined;
457
+ return isPlain(github) ? github : {};
458
+ };
459
+ const valueOf = (doc: unknown): Rec => (isEnvelope(doc) && isPlain(doc.value) ? doc.value : {});
460
+
461
+ function stepOut(state: Out, step: unknown): unknown {
462
+ const value = valueOf(step);
463
+ const gh = githubOf(value);
464
+ if ("raw" in gh) return gh["raw"];
465
+ const call = valueOf(value["do"]);
466
+ const kind = isEnvelope(value["do"]) && Array.isArray(value["do"].type) ? value["do"].type[1] : undefined;
467
+ const out: Rec = {};
468
+ if (value["id"] !== undefined || gh["id"] !== undefined) out["id"] = value["id"] ?? gh["id"];
469
+ if (value["name"] !== undefined || gh["name"] !== undefined) out["name"] = value["name"] ?? gh["name"];
470
+ if (value["if"] !== undefined) out["if"] = plainOf(state, value["if"], true);
471
+ if (kind === "action") {
472
+ out["uses"] = call["uses"] ?? gh["uses"];
473
+ const inputs = plainsOf(state, call["with"]) ?? gh["with"];
474
+ if (inputs !== undefined) out["with"] = inputs;
475
+ } else {
476
+ if (call["script"] !== undefined) out["run"] = plainOf(state, call["script"]);
477
+ if (call["shell"] !== undefined) out["shell"] = plainOf(state, call["shell"]);
478
+ if (call["cwd"] !== undefined) out["working-directory"] = plainOf(state, call["cwd"]);
479
+ }
480
+ const env = plainsOf(state, value["env"]) ?? gh["env"];
481
+ if (env !== undefined) out["env"] = env;
482
+ if (value["continue"] !== undefined || gh["continue"] !== undefined) out["continue-on-error"] = value["continue"] ?? gh["continue"];
483
+ if (typeof value["timeout"] === "number") out["timeout-minutes"] = value["timeout"] / 60;
484
+ else if (gh["timeout"] !== undefined) out["timeout-minutes"] = gh["timeout"];
485
+ return { ...out, ...(isPlain(gh["keys"]) ? gh["keys"] : {}) };
486
+ }
487
+
488
+ function matrixOut(state: Out, matrix: unknown): { matrix: unknown; parallel?: unknown } {
489
+ if (!isEnvelope(matrix) || matrix.type !== "matrix") return { matrix: plainOf(state, matrix) };
490
+ const value = valueOf(matrix);
491
+ const out: Rec = { ...(plainsOf(state, value["axes"]) ?? {}) };
492
+ if (value["include"] !== undefined) out["include"] = plainOf(state, value["include"]);
493
+ if (value["exclude"] !== undefined) out["exclude"] = plainOf(state, value["exclude"]);
494
+ return value["parallel"] === undefined ? { matrix: out } : { matrix: out, parallel: value["parallel"] };
495
+ }
496
+
497
+ function jobOut(state: Out, job: unknown): unknown {
498
+ const value = valueOf(job);
499
+ const gh = githubOf(value);
500
+ if ("raw" in gh) return gh["raw"];
501
+ const out: Rec = {};
502
+ if (value["name"] !== undefined || gh["name"] !== undefined) out["name"] = value["name"] ?? gh["name"];
503
+ if (Array.isArray(value["needs"])) out["needs"] = gh["needsText"] === true && value["needs"].length === 1 ? value["needs"][0] : value["needs"];
504
+ else if (gh["needs"] !== undefined) out["needs"] = gh["needs"];
505
+ if (value["if"] !== undefined) out["if"] = plainOf(state, value["if"], true);
506
+ if (value["matrix"] !== undefined || isPlain(gh["strategy"])) {
507
+ const strategy: Rec = { ...(isPlain(gh["strategy"]) ? gh["strategy"] : {}) };
508
+ if (value["matrix"] !== undefined) {
509
+ const read = matrixOut(state, value["matrix"]);
510
+ strategy["matrix"] = read.matrix;
511
+ if (read.parallel !== undefined) strategy["max-parallel"] = read.parallel;
512
+ }
513
+ out["strategy"] = strategy;
514
+ } else if (gh["strategyRaw"] !== undefined) out["strategy"] = gh["strategyRaw"];
515
+ const env = plainsOf(state, value["env"]) ?? gh["env"];
516
+ if (env !== undefined) out["env"] = env;
517
+ const steps = Array.isArray(value["steps"]) ? value["steps"] : [];
518
+ if (gh["reusable"] === true && steps.length === 1) {
519
+ const call = valueOf(valueOf(steps[0])["do"]);
520
+ out["uses"] = call["uses"];
521
+ const inputs = plainsOf(state, call["with"]) ?? gh["with"];
522
+ if (inputs !== undefined) out["with"] = inputs;
523
+ if (call["inherit"] === true) out["secrets"] = "inherit";
524
+ else if (call["secrets"] !== undefined) out["secrets"] = plainsOf(state, call["secrets"]);
525
+ else if (gh["secrets"] !== undefined) out["secrets"] = gh["secrets"];
526
+ if (gh["steps"] !== undefined) out["steps"] = gh["steps"];
527
+ } else if (gh["noSteps"] === true && steps.length === 0) {
528
+ if (gh["steps"] !== undefined) out["steps"] = gh["steps"];
529
+ } else out["steps"] = steps.map((step) => stepOut(state, step));
530
+ const outputs = plainsOf(state, value["outputs"]) ?? gh["outputs"];
531
+ if (outputs !== undefined) out["outputs"] = outputs;
532
+ if (typeof value["timeout"] === "number") out["timeout-minutes"] = value["timeout"] / 60;
533
+ else if (gh["timeout"] !== undefined) out["timeout-minutes"] = gh["timeout"];
534
+ return { ...out, ...(isPlain(gh["keys"]) ? gh["keys"] : {}) };
535
+ }
536
+
537
+ const EVENT_OF: Readonly<Record<string, string>> = { manual: "workflow_dispatch", call: "workflow_call", schedule: "schedule" };
538
+
539
+ function onOut(state: Out, workflow: Rec, gh: Rec): unknown {
540
+ if (gh["on"] === "raw") return gh["onRaw"];
541
+ const triggers = Array.isArray(workflow["triggers"]) ? workflow["triggers"] : [];
542
+ const on: Rec = {};
543
+ const inputs = isPlain(workflow["inputs"]) ? workflow["inputs"] : {};
544
+ for (const trigger of triggers) {
545
+ if (!isEnvelope(trigger) || !Array.isArray(trigger.type)) continue;
546
+ const kind = String(trigger.type[1]);
547
+ const value = valueOf(trigger);
548
+ const layer = githubOf(value);
549
+ const event = typeof layer["event"] === "string" ? layer["event"] : kind === "event" ? String(value["event"]) : (EVENT_OF[kind] ?? kind);
550
+ if (kind === "schedule") {
551
+ const list = Array.isArray(on[event]) ? (on[event] as unknown[]) : [];
552
+ list.push({ cron: value["cron"], ...(isPlain(layer["keys"]) ? layer["keys"] : {}) });
553
+ on[event] = list;
554
+ continue;
555
+ }
556
+ if ("raw" in layer) {
557
+ on[event] = layer["raw"];
558
+ continue;
559
+ }
560
+ const config: Rec = isPlain(layer["config"]) ? { ...layer["config"] } : {};
561
+ if (Array.isArray(value["types"])) config["types"] = value["types"];
562
+ if (kind === "manual" || kind === "call") {
563
+ const own: Rec = {};
564
+ for (const [name, def] of Object.entries(inputs)) {
565
+ if (!isPlain(def)) continue;
566
+ const { on: takers, ...rest } = def;
567
+ if (takers === undefined || (Array.isArray(takers) && takers.includes(kind))) own[name] = "value" in rest && Object.keys(rest).length === 1 ? rest["value"] : rest;
568
+ }
569
+ Object.assign(own, isPlain(layer["inputs"]) ? layer["inputs"] : {});
570
+ if (Object.keys(own).length > 0) config["inputs"] = own;
571
+ }
572
+ if (kind === "call") {
573
+ if (workflow["secrets"] !== undefined) config["secrets"] = workflow["secrets"];
574
+ if (isPlain(workflow["outputs"])) {
575
+ const meta = isPlain(layer["outputs"]) ? layer["outputs"] : {};
576
+ config["outputs"] = Object.fromEntries(
577
+ Object.entries(workflow["outputs"]).map(([name, expr]) => [name, { ...(isPlain(meta[name]) ? meta[name] : {}), value: plainOf(state, expr) }]),
578
+ );
579
+ }
580
+ }
581
+ on[event] = layer["config"] === null && Object.keys(config).length === 0 ? null : layer["config"] === undefined && Object.keys(config).length === 0 ? null : config;
582
+ }
583
+ if (gh["on"] === "text" || gh["on"] === "list") {
584
+ const events = Object.keys(on);
585
+ if (events.every((event) => on[event] === null)) return gh["on"] === "text" && events.length === 1 ? events[0] : events;
586
+ }
587
+ return on;
588
+ }
589
+
590
+ /**
591
+ * This function writes a workflow document as the plain value of a GitHub workflow: the value that the YAML of the
592
+ * file gives. Each expression gives its source text when its document did not change.
593
+ *
594
+ * @param doc - The workflow document.
595
+ * @returns The value.
596
+ */
597
+ export function toGitHubObject(doc: unknown): Rec {
598
+ const workflow = valueOf(doc);
599
+ const gh = githubOf(workflow);
600
+ const state: Out = { texts: isPlain(gh["texts"]) ? (gh["texts"] as Record<string, string[]>) : {}, used: {} };
601
+ const out: Rec = {};
602
+ if (gh["unnamed"] !== true) out["name"] = gh["name"] ?? workflow["name"];
603
+ if (gh["on"] !== "none") out["on"] = onOut(state, workflow, gh);
604
+ Object.assign(out, isPlain(gh["keys"]) ? gh["keys"] : {});
605
+ const env = plainsOf(state, workflow["env"]) ?? gh["env"];
606
+ if (env !== undefined) out["env"] = env;
607
+ if (gh["noJobs"] !== true) {
608
+ out["jobs"] = isPlain(workflow["jobs"]) ? Object.fromEntries(Object.entries(workflow["jobs"]).map(([id, job]) => [id, jobOut(state, job)])) : gh["jobs"];
609
+ }
610
+ return out;
611
+ }
612
+
613
+ /** This function changes the YAML tree at a path from the value `before` to the value `after`, and keeps the rest. */
614
+ function patch(tree: Document, path: Path, before: unknown, after: unknown): void {
615
+ if (sameJson(before, after)) return;
616
+ if (isPlain(before) && isPlain(after)) {
617
+ for (const key of Object.keys(before)) if (!Object.hasOwn(after, key)) tree.deleteIn([...path, key]);
618
+ for (const [key, value] of Object.entries(after)) {
619
+ if (Object.hasOwn(before, key)) patch(tree, [...path, key], before[key], value);
620
+ else tree.setIn([...path, key], tree.createNode(value));
621
+ }
622
+ return;
623
+ }
624
+ const node = path.length === 0 ? tree.contents : tree.getIn(path, true);
625
+ if (Array.isArray(before) && Array.isArray(after) && isSeq(node)) {
626
+ let head = 0;
627
+ while (head < before.length && head < after.length && sameJson(before[head], after[head])) head++;
628
+ let tail = 0;
629
+ while (tail < before.length - head && tail < after.length - head && sameJson(before[before.length - 1 - tail], after[after.length - 1 - tail])) tail++;
630
+ const removed = before.length - head - tail;
631
+ const added = after.length - head - tail;
632
+ if (removed === added) {
633
+ for (let index = head; index < head + added; index++) patch(tree, [...path, index], before[index], after[index]);
634
+ return;
635
+ }
636
+ node.items.splice(head, removed, ...after.slice(head, head + added).map((item) => tree.createNode(item)));
637
+ return;
638
+ }
639
+ if (isScalar(node) && !isPlain(after) && !Array.isArray(after)) {
640
+ node.value = after;
641
+ return;
642
+ }
643
+ if (path.length === 0) tree.contents = tree.createNode(after);
644
+ else tree.setIn(path, tree.createNode(after));
645
+ }
646
+
647
+ /**
648
+ * This function writes a workflow document as the YAML of a GitHub workflow.
649
+ *
650
+ * - A document from `fromGitHub` keeps its source text in its layer. When the document did not change, the result is
651
+ * that text, byte for byte.
652
+ * - After an edit, the export changes only the edited values of the source tree. The comments and the forms of the
653
+ * other values stay.
654
+ * - A document with no source text gives new YAML.
655
+ *
656
+ * @param doc - The workflow document.
657
+ * @returns The YAML text.
658
+ */
659
+ export function toGitHub(doc: unknown): string {
660
+ const gh = githubOf(valueOf(doc));
661
+ const after = toGitHubObject(doc);
662
+ if (typeof gh["source"] === "string") {
663
+ const tree = parseDocument(gh["source"]);
664
+ const before = tree.toJS() as unknown;
665
+ if (sameJson(before, after)) return gh["source"];
666
+ patch(tree, [], before, after);
667
+ return tree.toString({ lineWidth: 0, nullStr: "" });
668
+ }
669
+ return stringify(after, { lineWidth: 0, nullStr: "" });
670
+ }