@mark1russell7/workflow 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/edit.ts ADDED
@@ -0,0 +1,267 @@
1
+ import { isRecord } from "@mark1russell7/coeval";
2
+ import { scopeAt } from "./check.ts";
3
+
4
+ /**
5
+ * The edits of a workflow document. Each edit gives a new document and keeps the original. A builder uses them on
6
+ * each click, then it checks the new document. The edits name no host: a host gives its own step documents.
7
+ */
8
+
9
+ type Key = string | number;
10
+ type Rec = Record<string, unknown>;
11
+
12
+ /** The result of an edit that can refuse: the new document, or the reason of the refusal. */
13
+ export type EditResult = { readonly ok: true; readonly doc: unknown } | { readonly ok: false; readonly why: string };
14
+
15
+ const recordOr = (value: unknown): Rec => (isRecord(value) ? (value as Rec) : {});
16
+ const listOr = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : []);
17
+
18
+ /**
19
+ * This function reads the value at a JSON path. The path goes through records and lists, also through the `value` of
20
+ * an envelope, as the paths of the problems of `checkWorkflow` do.
21
+ *
22
+ * @param doc - The document.
23
+ * @param at - The JSON path.
24
+ * @returns The value, or `undefined`.
25
+ */
26
+ export function getIn(doc: unknown, at: readonly Key[]): unknown {
27
+ let here: unknown = doc;
28
+ for (const key of at) {
29
+ if (Array.isArray(here) && typeof key === "number") here = here[key];
30
+ else if (isRecord(here) && typeof key === "string") here = (here as Rec)[key];
31
+ else return undefined;
32
+ }
33
+ return here;
34
+ }
35
+
36
+ /**
37
+ * This function gives a copy of a document with a new value at a JSON path. The value `undefined` removes the key, or
38
+ * the item of a list. A missing record on the path becomes an empty record.
39
+ *
40
+ * @param doc - The document.
41
+ * @param at - The JSON path.
42
+ * @param value - The new value.
43
+ * @returns The new document.
44
+ */
45
+ export function setIn(doc: unknown, at: readonly Key[], value: unknown): unknown {
46
+ if (at.length === 0) return value;
47
+ const [key, ...rest] = at as [Key, ...Key[]];
48
+ if (Array.isArray(doc) && typeof key === "number") {
49
+ const copy = [...doc];
50
+ if (rest.length === 0 && value === undefined) copy.splice(key, 1);
51
+ else copy[key] = setIn(doc[key], rest, value);
52
+ return copy;
53
+ }
54
+ const record = recordOr(doc);
55
+ const copy: Rec = { ...record };
56
+ const next = setIn(record[String(key)], rest, value);
57
+ if (next === undefined) delete copy[String(key)];
58
+ else copy[String(key)] = next;
59
+ return copy;
60
+ }
61
+
62
+ const jobsOf = (doc: unknown): Rec => recordOr(getIn(doc, ["value", "jobs"]));
63
+ const needsOf = (job: unknown): string[] => listOr(getIn(job, ["value", "needs"])).filter((need): need is string => typeof need === "string");
64
+
65
+ /** This function gives a new id from a base that no key of a record has: `base`, `base-2`, `base-3` and on. */
66
+ export function freeId(taken: Iterable<string>, base: string): string {
67
+ const used = new Set(taken);
68
+ if (!used.has(base)) return base;
69
+ for (let n = 2; ; n++) if (!used.has(`${base}-${String(n)}`)) return `${base}-${String(n)}`;
70
+ }
71
+
72
+ /**
73
+ * This function adds a job with the given steps.
74
+ *
75
+ * @param doc - The workflow document.
76
+ * @param base - The base of the id of the job.
77
+ * @param steps - The step documents of the job.
78
+ * @returns The new document and the id of the job.
79
+ */
80
+ export function addJob(doc: unknown, base: string, steps: readonly unknown[]): { readonly doc: unknown; readonly id: string } {
81
+ const id = freeId(Object.keys(jobsOf(doc)), base);
82
+ return { doc: setIn(doc, ["value", "jobs", id], { type: "job", value: { steps: [...steps] } }), id };
83
+ }
84
+
85
+ /** This function changes each reference to a job in a document: `needs.<from>` and `jobs.<from>`. */
86
+ function renameRefs(value: unknown, from: string, to: string | undefined): unknown {
87
+ if (Array.isArray(value)) return value.map((item) => renameRefs(item, from, to));
88
+ if (!isRecord(value)) return value;
89
+ const record = value as Rec;
90
+ if (record["type"] === "ref" && Array.isArray(record["value"])) {
91
+ const path = record["value"];
92
+ if (path[0] === "names" && (path[1] === "needs" || path[1] === "jobs") && path[2] === from && to !== undefined) return { type: "ref", value: [path[0], path[1], to, ...path.slice(3)] };
93
+ return record;
94
+ }
95
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [key, renameRefs(item, from, to)]));
96
+ }
97
+
98
+ /**
99
+ * This function removes a job, and removes it from the needs of the other jobs. A reference to its outputs stays, and
100
+ * the check finds it.
101
+ *
102
+ * @param doc - The workflow document.
103
+ * @param id - The id of the job.
104
+ * @returns The new document.
105
+ */
106
+ export function removeJob(doc: unknown, id: string): unknown {
107
+ let out = setIn(doc, ["value", "jobs", id], undefined);
108
+ for (const [other, job] of Object.entries(jobsOf(out))) {
109
+ const needs = needsOf(job);
110
+ if (needs.includes(id)) out = setIn(out, ["value", "jobs", other, "value", "needs"], needs.length === 1 ? undefined : needs.filter((need) => need !== id));
111
+ }
112
+ return out;
113
+ }
114
+
115
+ /**
116
+ * This function gives a job a new id. The needs of the other jobs and each reference to the job change with it. The
117
+ * order of the jobs stays.
118
+ *
119
+ * @param doc - The workflow document.
120
+ * @param from - The id of the job.
121
+ * @param to - The new id.
122
+ * @returns The new document, or the reason of a refusal.
123
+ */
124
+ export function renameJob(doc: unknown, from: string, to: string): EditResult {
125
+ const jobs = jobsOf(doc);
126
+ if (!(from in jobs)) return { ok: false, why: `The workflow has no job ${from}.` };
127
+ if (from === to) return { ok: true, doc };
128
+ if (to in jobs) return { ok: false, why: `The workflow has a job ${to} already.` };
129
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(to)) return { ok: false, why: "A job id has letters, digits, _ and -, and it starts with a letter or _." };
130
+ const renamed: Rec = {};
131
+ for (const [id, job] of Object.entries(jobs)) {
132
+ const needs = needsOf(job);
133
+ const next = needs.includes(from) ? setIn(job, ["value", "needs"], needs.map((need) => (need === from ? to : need))) : job;
134
+ renamed[id === from ? to : id] = next;
135
+ }
136
+ return { ok: true, doc: renameRefs(setIn(doc, ["value", "jobs"], renamed), from, to) };
137
+ }
138
+
139
+ /** This function tells if a job reaches another job through the needs. */
140
+ function reaches(jobs: Rec, from: string, to: string): boolean {
141
+ const seen = new Set<string>();
142
+ const stack = [from];
143
+ while (stack.length > 0) {
144
+ const id = stack.pop() as string;
145
+ if (id === to) return true;
146
+ if (seen.has(id)) continue;
147
+ seen.add(id);
148
+ stack.push(...needsOf(jobs[id]));
149
+ }
150
+ return false;
151
+ }
152
+
153
+ /**
154
+ * This function adds a need to a job, or removes it. A need that makes a cycle is refused.
155
+ *
156
+ * @param doc - The workflow document.
157
+ * @param job - The id of the job.
158
+ * @param need - The id of the job that it needs.
159
+ * @param on - `true` to add the need, `false` to remove it.
160
+ * @returns The new document, or the reason of a refusal.
161
+ */
162
+ export function setNeed(doc: unknown, job: string, need: string, on: boolean): EditResult {
163
+ const jobs = jobsOf(doc);
164
+ if (!(job in jobs) || !(need in jobs)) return { ok: false, why: "The workflow has no such job." };
165
+ const needs = needsOf(jobs[job]);
166
+ if (!on) return { ok: true, doc: setIn(doc, ["value", "jobs", job, "value", "needs"], needs.length <= 1 && needs.includes(need) ? undefined : needs.filter((id) => id !== need)) };
167
+ if (needs.includes(need)) return { ok: true, doc };
168
+ if (need === job || reaches(jobs, need, job)) return { ok: false, why: `The job ${need} already runs after ${job}. This need makes a cycle.` };
169
+ return { ok: true, doc: setIn(doc, ["value", "jobs", job, "value", "needs"], [...needs, need]) };
170
+ }
171
+
172
+ /**
173
+ * This function adds a step to a job.
174
+ *
175
+ * @param doc - The workflow document.
176
+ * @param job - The id of the job.
177
+ * @param step - The step document.
178
+ * @param index - The place of the new step. The default is the end.
179
+ * @returns The new document.
180
+ */
181
+ export function addStep(doc: unknown, job: string, step: unknown, index?: number): unknown {
182
+ const steps = [...listOr(getIn(doc, ["value", "jobs", job, "value", "steps"]))];
183
+ steps.splice(index ?? steps.length, 0, step);
184
+ return setIn(doc, ["value", "jobs", job, "value", "steps"], steps);
185
+ }
186
+
187
+ /**
188
+ * This function moves a step of a job to another place in the job.
189
+ *
190
+ * @param doc - The workflow document.
191
+ * @param job - The id of the job.
192
+ * @param from - The place of the step.
193
+ * @param to - The new place.
194
+ * @returns The new document.
195
+ */
196
+ export function moveStep(doc: unknown, job: string, from: number, to: number): unknown {
197
+ const steps = [...listOr(getIn(doc, ["value", "jobs", job, "value", "steps"]))];
198
+ if (from < 0 || from >= steps.length || to < 0 || to >= steps.length) return doc;
199
+ const [step] = steps.splice(from, 1);
200
+ steps.splice(to, 0, step);
201
+ return setIn(doc, ["value", "jobs", job, "value", "steps"], steps);
202
+ }
203
+
204
+ /** A value that an expression can read at a position: the reference document and its text. */
205
+ export interface RefChoice {
206
+ /** The group of the value, for example `inputs` or `needs`. */
207
+ readonly group: string;
208
+ /** The text of the value, for example `needs.build.outputs.folder`. */
209
+ readonly label: string;
210
+ readonly doc: unknown;
211
+ }
212
+
213
+ const nameRef = (...path: string[]): unknown => ({ type: "ref", value: ["names", ...path] });
214
+ const choice = (group: string, ...path: string[]): RefChoice => ({ group, label: path.join("."), doc: nameRef(...path) });
215
+
216
+ /**
217
+ * This function gives the paths into the result of each step that the references of the document read, for example
218
+ * `folder` of `steps.source.folder`. The result of a step has no declared shape, thus the known reads are the offer.
219
+ */
220
+ function knownStepReads(doc: unknown, out: Map<string, Set<string>> = new Map()): Map<string, Set<string>> {
221
+ if (Array.isArray(doc)) for (const item of doc) knownStepReads(item, out);
222
+ else if (isRecord(doc)) {
223
+ const record = doc as Rec;
224
+ const path = record["value"];
225
+ if (record["type"] === "ref" && Array.isArray(path) && path[1] === "steps" && typeof path[2] === "string" && path.length > 3 && path.slice(3).every((key) => typeof key === "string")) {
226
+ const reads = out.get(path[2]) ?? new Set<string>();
227
+ reads.add(path.slice(3).join("."));
228
+ out.set(path[2], reads);
229
+ } else for (const item of Object.values(record)) knownStepReads(item, out);
230
+ }
231
+ return out;
232
+ }
233
+
234
+ /**
235
+ * This function gives the values that an expression at a JSON path can read. These are the inputs, the env
236
+ * values, the matrix axes, the outputs of the needed jobs and the known reads of the earlier steps. The list follows
237
+ * the scope of `scopeAt`, thus each choice passes the check.
238
+ *
239
+ * @param doc - The workflow document.
240
+ * @param at - The JSON path of the expression.
241
+ * @param host - More choices of the host, for example its contexts.
242
+ * @returns The choices, in groups.
243
+ */
244
+ export function refChoices(doc: unknown, at: readonly Key[], host: readonly RefChoice[] = []): RefChoice[] {
245
+ const scope = scopeAt(doc, at);
246
+ if (scope === undefined) return [...host];
247
+ const out: RefChoice[] = [];
248
+ const value = recordOr(getIn(doc, ["value"]));
249
+ const jobs = recordOr(value["jobs"]);
250
+ if (scope.names.has("inputs")) for (const name of Object.keys(recordOr(value["inputs"]))) out.push(choice("inputs", "inputs", name));
251
+ if (scope.names.has("env")) {
252
+ const job = at[1] === "jobs" && typeof at[2] === "string" ? jobs[at[2]] : undefined;
253
+ const names = new Set([...Object.keys(recordOr(value["env"])), ...Object.keys(recordOr(getIn(job, ["value", "env"])))]);
254
+ for (const name of names) out.push(choice("env", "env", name));
255
+ }
256
+ if (scope.names.has("matrix") && scope.matrix !== undefined && scope.matrix !== "any") for (const axis of scope.matrix) out.push(choice("matrix", "matrix", axis));
257
+ if (scope.names.has("steps") && scope.steps !== undefined) {
258
+ const known = knownStepReads(doc);
259
+ for (const id of scope.steps) for (const read of known.get(id) ?? []) out.push(choice("steps", "steps", id, ...read.split(".")));
260
+ }
261
+ if (scope.names.has("needs") && scope.needs !== undefined) {
262
+ for (const id of scope.needs) for (const name of Object.keys(recordOr(getIn(jobs[id], ["value", "outputs"])))) out.push(choice("needs", "needs", id, "outputs", name));
263
+ }
264
+ if (scope.names.has("jobs")) for (const [id, job] of Object.entries(jobs)) for (const name of Object.keys(recordOr(getIn(job, ["value", "outputs"])))) out.push(choice("jobs", "jobs", id, "outputs", name));
265
+ return [...out, ...host];
266
+ }
267
+
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ export { WORKFLOW_FORMAT, WORKFLOW_WORLD } from "./world.ts";
2
+ export { type SecretRef, WORKFLOW_LANGUAGE, WORKFLOW_OPS, WORKFLOW_VERSION, expandMatrix, isSecretRef, workflowMachine, workflowMachineWith } from "./language.ts";
3
+ export {
4
+ type Access,
5
+ type AccessAnswer,
6
+ type ProcedureInfo,
7
+ type WorkflowCheckOptions,
8
+ type WorkflowEdge,
9
+ type WorkflowGraph,
10
+ type WorkflowIssue,
11
+ type WorkflowNode,
12
+ type WorkflowScope,
13
+ callPath,
14
+ checkWorkflow,
15
+ isPresenceTest,
16
+ scopeAt,
17
+ workflowGraph,
18
+ } from "./check.ts";
19
+ export { SAMPLE_WORKFLOW } from "./sample.ts";
20
+ export { addJob, addStep, freeId, getIn, moveStep, refChoices, removeJob, renameJob, setIn, setNeed } from "./edit.ts";
21
+ export type { EditResult, RefChoice } from "./edit.ts";
@@ -0,0 +1,225 @@
1
+ import {
2
+ type Evaluator,
3
+ type FormulaProfile,
4
+ type Language,
5
+ type Machine,
6
+ type OpFn,
7
+ type Result,
8
+ type Runner,
9
+ type Signature,
10
+ STD_OPS,
11
+ compose,
12
+ defineLanguage,
13
+ fail,
14
+ formulaMachine,
15
+ isRecord,
16
+ } from "@mark1russell7/coeval";
17
+ import { WORKFLOW_WORLD } from "./world.ts";
18
+
19
+ /** The version of the workflow language. */
20
+ export const WORKFLOW_VERSION = "0.1.0";
21
+
22
+ /** A reference to a secret. It holds the name of the secret, not its value. */
23
+ export interface SecretRef {
24
+ readonly secret: string;
25
+ }
26
+
27
+ /** This function tells if a value is a reference to a secret. */
28
+ export function isSecretRef(value: unknown): value is SecretRef {
29
+ return isRecord(value) && typeof value["secret"] === "string" && Object.keys(value).length === 1 && Object.isFrozen(value);
30
+ }
31
+
32
+ const ok = (value: unknown): Result => ({ ok: true, value });
33
+
34
+ function scalarText(value: unknown): string | undefined {
35
+ if (typeof value === "string") return value;
36
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
37
+ if (value === null) return "";
38
+ return undefined;
39
+ }
40
+
41
+ function noSecret(op: string, args: readonly unknown[]): void {
42
+ if (args.some(isSecretRef)) throw new TypeError(`The operation ${op} cannot read a secret. Only a call can use a secret.`);
43
+ }
44
+
45
+ /**
46
+ * The operations of the workflow language, beside the operations of the formula kit. Each one is a general operation on
47
+ * texts and lists. No operation reads a secret.
48
+ */
49
+ const OPS: Readonly<Record<string, (...args: unknown[]) => unknown>> = {
50
+ contains: (...args) => {
51
+ noSecret("contains", args);
52
+ const [where, what] = args;
53
+ if (Array.isArray(where)) return where.some((item) => item === what);
54
+ const a = scalarText(where);
55
+ const b = scalarText(what);
56
+ if (a === undefined || b === undefined) throw new TypeError("contains takes a list or a text, and a value.");
57
+ return a.toLowerCase().includes(b.toLowerCase());
58
+ },
59
+ startsWith: (...args) => {
60
+ noSecret("startsWith", args);
61
+ const [a, b] = args.map(scalarText);
62
+ if (a === undefined || b === undefined) throw new TypeError("startsWith takes two texts.");
63
+ return a.toLowerCase().startsWith(b.toLowerCase());
64
+ },
65
+ endsWith: (...args) => {
66
+ noSecret("endsWith", args);
67
+ const [a, b] = args.map(scalarText);
68
+ if (a === undefined || b === undefined) throw new TypeError("endsWith takes two texts.");
69
+ return a.toLowerCase().endsWith(b.toLowerCase());
70
+ },
71
+ join: (...args) => {
72
+ noSecret("join", args);
73
+ const [list, separator = ","] = args;
74
+ const by = scalarText(separator) ?? ",";
75
+ if (!Array.isArray(list)) return scalarText(list) ?? "";
76
+ return list.map((item) => scalarText(item) ?? "").join(by);
77
+ },
78
+ toJSON: (...args) => {
79
+ noSecret("toJSON", args);
80
+ return JSON.stringify(args[0] ?? null, null, 2);
81
+ },
82
+ fromJSON: (...args) => {
83
+ const text = scalarText(args[0]);
84
+ if (text === undefined) throw new TypeError("fromJSON takes a text.");
85
+ return JSON.parse(text) as unknown;
86
+ },
87
+ format: (...args) => {
88
+ noSecret("format", args);
89
+ const [pattern, ...values] = args;
90
+ const text = scalarText(pattern);
91
+ if (text === undefined) throw new TypeError("format takes a text first.");
92
+ return text.replace(/\{\{|\}\}|\{(\d+)\}/g, (match, index: string | undefined) => {
93
+ if (match === "{{") return "{";
94
+ if (match === "}}") return "}";
95
+ const value = values[Number(index)];
96
+ return scalarText(value) ?? JSON.stringify(value);
97
+ });
98
+ },
99
+ };
100
+
101
+ const TEXT_2: Signature = { params: ["unknown", "unknown"], to: "bool" };
102
+ const SIGS: Readonly<Record<string, Signature | readonly Signature[]>> = {
103
+ contains: TEXT_2,
104
+ startsWith: TEXT_2,
105
+ endsWith: TEXT_2,
106
+ join: { params: ["unknown", "unknown"], to: "text" },
107
+ toJSON: { params: ["unknown"], to: "text" },
108
+ fromJSON: { params: ["text"], to: "unknown" },
109
+ format: { params: ["text", "unknown", "unknown", "unknown", "unknown"], to: "text" },
110
+ };
111
+
112
+ /** This function gives the combinations of the axes of a matrix, without the excluded ones, with the included ones. */
113
+ export function expandMatrix(axes: Readonly<Record<string, unknown>>, include: readonly unknown[] = [], exclude: readonly unknown[] = []): Record<string, unknown>[] {
114
+ const lists = Object.entries(axes);
115
+ let rows: Record<string, unknown>[] = lists.length === 0 ? [] : [{}];
116
+ for (const [key, values] of lists) {
117
+ if (!Array.isArray(values)) throw new TypeError(`The axis ${key} of a matrix must be a list.`);
118
+ rows = rows.flatMap((row) => values.map((value) => ({ ...row, [key]: value })));
119
+ }
120
+ const fits = (entry: unknown, row: Record<string, unknown>, keys: Iterable<string>): boolean =>
121
+ isRecord(entry) && [...keys].every((key) => !(key in entry) || JSON.stringify(entry[key]) === JSON.stringify(row[key]));
122
+ rows = rows.filter((row) => !exclude.some((entry) => isRecord(entry) && fits(entry, row, Object.keys(entry))));
123
+ const axisKeys = lists.map(([key]) => key);
124
+ for (const entry of include) {
125
+ if (!isRecord(entry)) continue;
126
+ const matches = rows.filter((row) => fits(entry, row, axisKeys.filter((key) => key in entry)) && axisKeys.some((key) => key in entry));
127
+ if (matches.length === 0) rows.push({ ...entry });
128
+ else for (const row of matches) Object.assign(row, entry);
129
+ }
130
+ return rows;
131
+ }
132
+
133
+ const EVALUATORS: Readonly<Record<string, Evaluator>> = {
134
+ "workflow.secret": ({ data }) =>
135
+ typeof data === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(data)
136
+ ? ok(Object.freeze({ secret: data }))
137
+ : fail("#VALUE!", "A secret holds the name of a secret: letters, digits and _, not first a digit."),
138
+ "workflow.template": ({ parts }) => {
139
+ let out = "";
140
+ for (const part of parts) {
141
+ const result = part.evaluate();
142
+ if (!result.ok) return result;
143
+ if (isSecretRef(result.value)) return fail("#VALUE!", "A secret cannot be part of a text. Give it to a call as an input.");
144
+ const text = scalarText(result.value);
145
+ out += text ?? JSON.stringify(result.value);
146
+ }
147
+ return ok(out);
148
+ },
149
+ "workflow.matrix": ({ parts }) => {
150
+ const axes: Record<string, unknown> = {};
151
+ let include: unknown[] = [];
152
+ let exclude: unknown[] = [];
153
+ for (const part of parts) {
154
+ const result = part.evaluate();
155
+ if (!result.ok) return result;
156
+ const [field, key] = part.path;
157
+ if (field === "axes" && typeof key === "string") axes[key] = result.value;
158
+ else if (field === "include") include = Array.isArray(result.value) ? result.value : [];
159
+ else if (field === "exclude") exclude = Array.isArray(result.value) ? result.value : [];
160
+ }
161
+ try {
162
+ return ok(expandMatrix(axes, include, exclude));
163
+ } catch (error) {
164
+ return fail("#VALUE!", error instanceof Error ? error.message : String(error));
165
+ }
166
+ },
167
+ "workflow.trigger": ({ kind, data }) => ok({ kind, ...(isRecord(data) ? data : {}) }),
168
+ "workflow.workflow": () => fail("#CALC!", "A workflow runs through a runner, not through an evaluation."),
169
+ "workflow.job": () => fail("#CALC!", "A job runs through a runner, not through an evaluation."),
170
+ "workflow.step": () => fail("#CALC!", "A step runs through a runner, not through an evaluation."),
171
+ "workflow.call": () => fail("#CALC!", "A call runs through a runner, not through an evaluation."),
172
+ };
173
+
174
+ /**
175
+ * The runner of a call. It evaluates each input, in the order of the value, and causes one effect. The kind of the
176
+ * effect is the path of the call, for example `procedure.git.clone`, and its payload is the record of the inputs. A
177
+ * reference to a secret stays a reference: the host of the procedure reads the secret, thus no log holds its value.
178
+ */
179
+ const RUNNERS: Readonly<Record<string, Runner>> = {
180
+ "workflow.call": function* ({ kind, parts, effect }) {
181
+ const inputs: Record<string, unknown> = {};
182
+ for (const part of parts) {
183
+ const result = yield* part.evaluate();
184
+ if (!result.ok) return result;
185
+ inputs[part.key] = result.value;
186
+ }
187
+ return yield* effect(kind, inputs);
188
+ },
189
+ };
190
+
191
+ /** The workflow language: the kinds of `WORKFLOW_WORLD` and their code, on the formula kit of the kernel. */
192
+ export const WORKFLOW_LANGUAGE: Language = defineLanguage({
193
+ name: "workflow",
194
+ version: WORKFLOW_VERSION,
195
+ world: WORKFLOW_WORLD,
196
+ code: { evaluators: EVALUATORS, runners: RUNNERS },
197
+ });
198
+
199
+ /** The formula profile of the expressions of a workflow: the operations of the kernel and the text operations. */
200
+ export const WORKFLOW_OPS: FormulaProfile = { ops: { ...STD_OPS.ops, ...(OPS as Readonly<Record<string, OpFn>>) }, lazy: STD_OPS.lazy, sigs: { ...STD_OPS.sigs, ...SIGS }, pure: [...STD_OPS.pure, ...Object.keys(OPS)] };
201
+
202
+ /**
203
+ * This function gives the machine of the workflow language: the formula kit with the operations of a workflow, and
204
+ * the kinds of the workflow world. An add-on composes its own language after it.
205
+ *
206
+ * @param more - The languages of add-ons, in order.
207
+ * @returns The machine.
208
+ */
209
+ export function workflowMachine(...more: readonly Language[]): Machine {
210
+ return workflowMachineWith(WORKFLOW_OPS, ...more);
211
+ }
212
+
213
+ /**
214
+ * This function gives the machine of the workflow language with another formula profile. An add-on gives the
215
+ * operations of its host here, for example `WORKFLOW_OPS` with more operations.
216
+ *
217
+ * @param profile - The formula profile of the expressions.
218
+ * @param more - The languages of add-ons, in order.
219
+ * @returns The machine.
220
+ */
221
+ export function workflowMachineWith(profile: FormulaProfile, ...more: readonly Language[]): Machine {
222
+ const { world, ...code } = formulaMachine(profile);
223
+ const kit = defineLanguage({ name: "formula", version: "1.0.0", world, code });
224
+ return compose(kit, WORKFLOW_LANGUAGE, ...more);
225
+ }
package/src/sample.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A sample workflow: a build on two versions of a runtime, then a release with a secret. The tests and the site use it.
3
+ */
4
+ export const SAMPLE_WORKFLOW = {
5
+ type: "workflow",
6
+ value: {
7
+ name: "Build and release",
8
+ summary: "It builds the package on two versions, and it releases it when a person asks.",
9
+ workspace: "technical",
10
+ triggers: [
11
+ { type: ["trigger", "event"], value: { event: "push" } },
12
+ { type: ["trigger", "manual"], value: { summary: "Release now" } },
13
+ ],
14
+ inputs: { channel: { type: "choice", options: ["latest", "next"], default: "latest", description: "The channel of the release." } },
15
+ secrets: { REGISTRY_TOKEN: { description: "The token of the registry.", required: true } },
16
+ jobs: {
17
+ build: {
18
+ type: "job",
19
+ value: {
20
+ name: "Build",
21
+ matrix: { type: "matrix", value: { axes: { version: { type: "list", value: [20, 22] } } } },
22
+ steps: [
23
+ { type: "step", value: { id: "source", name: "Get the source", do: { type: ["procedure", "git", "clone"], value: { branch: "main" } } } },
24
+ {
25
+ type: "step",
26
+ value: {
27
+ id: "test",
28
+ name: "Test",
29
+ do: { type: ["procedure", "pnpm", "test"], value: { cwd: { type: "ref", value: ["names", "steps", "source", "folder"] }, version: { type: "ref", value: ["names", "matrix", "version"] } } },
30
+ },
31
+ },
32
+ ],
33
+ outputs: { folder: { type: "ref", value: ["names", "steps", "source", "folder"] } },
34
+ },
35
+ },
36
+ release: {
37
+ type: "job",
38
+ value: {
39
+ name: "Release",
40
+ needs: ["build"],
41
+ if: { type: ["ops", "eq"], value: [{ type: "ref", value: ["event", "name"] }, "manual"] },
42
+ steps: [
43
+ {
44
+ type: "step",
45
+ value: {
46
+ id: "publish",
47
+ name: "Publish",
48
+ do: {
49
+ type: ["procedure", "npm", "publish"],
50
+ value: {
51
+ cwd: { type: "ref", value: ["names", "needs", "build", "outputs", "folder"] },
52
+ tag: { type: "ref", value: ["names", "inputs", "channel"] },
53
+ token: { type: "secret", value: "REGISTRY_TOKEN" },
54
+ note: { type: "template", value: ["Release on the channel ", { type: "ref", value: ["names", "inputs", "channel"] }] },
55
+ },
56
+ },
57
+ },
58
+ },
59
+ ],
60
+ },
61
+ },
62
+ },
63
+ },
64
+ } as const;