@operad-io/engine 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/config.schema.json +188 -0
  3. package/keys.schema.json +12 -0
  4. package/package.json +22 -4
  5. package/src/config/config.ts +627 -0
  6. package/src/config/index.ts +1 -0
  7. package/src/flow/define-flow.ts +57 -0
  8. package/src/flow/index.ts +5 -0
  9. package/src/flow/load.ts +41 -0
  10. package/src/flow/types.ts +107 -0
  11. package/src/flow/validate.ts +296 -0
  12. package/src/http/address.ts +142 -0
  13. package/src/http/index.ts +25 -0
  14. package/src/http/link.ts +20 -0
  15. package/src/http/server.ts +920 -0
  16. package/src/http/token.ts +85 -0
  17. package/src/index.ts +16 -0
  18. package/src/kernel/decide.ts +689 -0
  19. package/src/kernel/index.ts +3 -0
  20. package/src/kernel/state.ts +275 -0
  21. package/src/kernel/types.ts +366 -0
  22. package/src/log/errors.ts +77 -0
  23. package/src/log/facts.ts +50 -0
  24. package/src/log/index.ts +6 -0
  25. package/src/log/json-value.ts +67 -0
  26. package/src/log/open-log.ts +17 -0
  27. package/src/log/schema.ts +5 -0
  28. package/src/log/secret.ts +30 -0
  29. package/src/log/sqlite.ts +1011 -0
  30. package/src/log/types.ts +230 -0
  31. package/src/loop/code-watch.ts +486 -0
  32. package/src/loop/index.ts +3 -0
  33. package/src/loop/older-code.ts +58 -0
  34. package/src/loop/serve.ts +483 -0
  35. package/src/markdown.ts +451 -0
  36. package/src/notify/index.ts +10 -0
  37. package/src/notify/notify.ts +256 -0
  38. package/src/platform/file-lock.ts +385 -0
  39. package/src/platform/index.ts +13 -0
  40. package/src/platform/load.ts +18 -0
  41. package/src/platform/process-group.ts +635 -0
  42. package/src/platform/process-watch.ts +152 -0
  43. package/src/platform/sqlite-open.ts +104 -0
  44. package/src/platform/step-reap.ts +668 -0
  45. package/src/platform/watch.ts +158 -0
  46. package/src/platform/worker-reports.ts +34 -0
  47. package/src/plugin/action-schema.ts +550 -0
  48. package/src/plugin/declared-flows.ts +74 -0
  49. package/src/plugin/define-plugin.ts +12 -0
  50. package/src/plugin/errors.ts +73 -0
  51. package/src/plugin/filters.ts +46 -0
  52. package/src/plugin/harness.ts +50 -0
  53. package/src/plugin/home.ts +13 -0
  54. package/src/plugin/index.ts +65 -0
  55. package/src/plugin/install.ts +268 -0
  56. package/src/plugin/keys.ts +63 -0
  57. package/src/plugin/load.ts +256 -0
  58. package/src/plugin/logger.ts +30 -0
  59. package/src/plugin/object-facts.ts +132 -0
  60. package/src/plugin/open-store.ts +32 -0
  61. package/src/plugin/paging.ts +133 -0
  62. package/src/plugin/registry.ts +1783 -0
  63. package/src/plugin/secrets.ts +141 -0
  64. package/src/plugin/semver.ts +110 -0
  65. package/src/plugin/settings.ts +64 -0
  66. package/src/plugin/sqlite-store.ts +756 -0
  67. package/src/plugin/store.ts +318 -0
  68. package/src/plugin/types.ts +1236 -0
  69. package/src/plugin/usage.ts +157 -0
  70. package/src/plugin/validate.ts +1028 -0
  71. package/src/runner/answer.ts +156 -0
  72. package/src/runner/ask.ts +483 -0
  73. package/src/runner/cancel.ts +51 -0
  74. package/src/runner/errors.ts +20 -0
  75. package/src/runner/grants.ts +92 -0
  76. package/src/runner/index.ts +33 -0
  77. package/src/runner/limits.ts +403 -0
  78. package/src/runner/lock.ts +140 -0
  79. package/src/runner/runner.ts +1175 -0
  80. package/src/runner/service.ts +184 -0
  81. package/src/runner/step-worker.ts +303 -0
  82. package/src/testing/clock.ts +67 -0
  83. package/src/testing/index.ts +90 -0
  84. package/src/testing/types.ts +116 -0
  85. package/src/testing/world.ts +369 -0
  86. package/src/trigger/cron.ts +193 -0
  87. package/src/trigger/index.ts +32 -0
  88. package/src/trigger/kernel.ts +1212 -0
  89. package/src/trigger/rules.ts +300 -0
  90. package/src/trigger/store.ts +233 -0
  91. package/src/trigger/types.ts +156 -0
  92. package/src/util.ts +50 -0
  93. package/src/views/history.ts +634 -0
  94. package/src/views/index.ts +7 -0
  95. package/src/views/pending.ts +209 -0
  96. package/src/views/presentation.ts +2551 -0
  97. package/src/views/running.ts +255 -0
  98. package/src/views/settings.ts +452 -0
  99. package/src/views/types.ts +72 -0
  100. package/src/views/uploads.ts +228 -0
  101. package/triggers.schema.json +48 -0
  102. package/README.md +0 -3
@@ -0,0 +1,451 @@
1
+ /**
2
+ * A small terminal renderer for the one content type the kernel has: Markdown
3
+ * with GFM tables and fenced code. With `colour` it styles headings, emphasis,
4
+ * links, code and tables for a terminal; without it the output is plain text.
5
+ * It draws no plugin colours, and it never decides layout: headings become
6
+ * bold, a diff gets red and green lines, every other fence stays code.
7
+ */
8
+
9
+ const ANSI = {
10
+ reset: "\x1b[0m",
11
+ bold: "\x1b[1m",
12
+ dim: "\x1b[2m",
13
+ italic: "\x1b[3m",
14
+ underline: "\x1b[4m",
15
+ red: "\x1b[31m",
16
+ green: "\x1b[32m",
17
+ cyan: "\x1b[36m",
18
+ weak: "\x1b[90m",
19
+ } as const;
20
+
21
+ export interface RenderOptions {
22
+ /** Add ANSI styling, for a terminal; off by default. */
23
+ readonly colour?: boolean | undefined;
24
+ /**
25
+ * Terminal columns available. With it a table is laid out to fit: one line
26
+ * per row, no pipes. Without it a table keeps its natural width.
27
+ */
28
+ readonly width?: number | undefined;
29
+ }
30
+
31
+ /** One rendered line. `code` marks a fenced code line, including its label. */
32
+ export interface MarkdownLine {
33
+ readonly text: string;
34
+ readonly code: boolean;
35
+ /** For a fenced code line: the fence's info string (empty when it has none). */
36
+ readonly language?: string;
37
+ /** True for the line that prints the fence's info string, not a code line. */
38
+ readonly label?: boolean;
39
+ }
40
+
41
+ function styled(text: string, code: string): string {
42
+ return `${code}${text}${ANSI.reset}`;
43
+ }
44
+
45
+ function stripInline(text: string): string {
46
+ return text
47
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
48
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1 ($2)")
49
+ .replace(CODE_SPAN, (_match, _fence: string, body: string) => unpadCode(body))
50
+ .replace(/\*\*([^*]+)\*\*/g, "$1")
51
+ .replace(/__([^_]+)__/g, "$1")
52
+ .replace(/(^|[^*])\*([^*]+)\*/g, "$1$2")
53
+ .replace(/(^|[^_])_([^_]+)_/g, "$1$2")
54
+ .replace(/~~([^~]+)~~/g, "$1");
55
+ }
56
+
57
+ /** A CommonMark code span: a run of backticks, a body, the same run again. */
58
+ const CODE_SPAN = /(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)/g;
59
+
60
+ /** CommonMark: a body with a space at both ends and something else inside loses one space each side. */
61
+ function unpadCode(body: string): string {
62
+ return body.length > 2 && body.startsWith(" ") && body.endsWith(" ") && body.trim().length > 0 ? body.slice(1, -1) : body;
63
+ }
64
+
65
+ /** Styles inline text without changing what a terminal shows. */
66
+ function styledInline(text: string): string {
67
+ let out = "";
68
+ let at = 0;
69
+ for (const match of text.matchAll(CODE_SPAN)) {
70
+ out += styledPlainInline(text.slice(at, match.index));
71
+ out += styled(unpadCode(match[2] ?? ""), ANSI.cyan);
72
+ at = match.index + match[0].length;
73
+ }
74
+ return out + styledPlainInline(text.slice(at));
75
+ }
76
+
77
+ function styledPlainInline(text: string): string {
78
+ return text
79
+ .replace(
80
+ /!\[([^\]]*)\]\([^)]*\)/g,
81
+ (_match, alt: string) => styled(alt, ANSI.dim),
82
+ )
83
+ .replace(
84
+ /\[([^\]]+)\]\(([^)]+)\)/g,
85
+ (_match, label: string, url: string) =>
86
+ `${styled(label, `${ANSI.underline}${ANSI.cyan}`)} ${styled(`(${url})`, ANSI.dim)}`,
87
+ )
88
+ .replace(
89
+ /\*\*([^*]+)\*\*/g,
90
+ (_match, body: string) => styled(body, ANSI.bold),
91
+ )
92
+ .replace(
93
+ /__([^_]+)__/g,
94
+ (_match, body: string) => styled(body, ANSI.bold),
95
+ )
96
+ .replace(
97
+ /(^|[^*])\*([^*]+)\*/g,
98
+ (_match, lead: string, body: string) => `${lead}${styled(body, ANSI.italic)}`,
99
+ )
100
+ .replace(
101
+ /(^|[^_])_([^_]+)_/g,
102
+ (_match, lead: string, body: string) => `${lead}${styled(body, ANSI.italic)}`,
103
+ )
104
+ .replace(
105
+ /~~([^~]+)~~/g,
106
+ (_match, body: string) => styled(body, `\x1b[9m`),
107
+ );
108
+ }
109
+
110
+ function renderInline(text: string, colour: boolean): string {
111
+ return colour ? styledInline(text) : stripInline(text);
112
+ }
113
+
114
+ function visibleLength(text: string): number {
115
+ return [...stripInline(text)].length;
116
+ }
117
+
118
+ /** An opening fence: its character, length and language (the info string's first word). */
119
+ interface Fence {
120
+ readonly char: string;
121
+ readonly length: number;
122
+ readonly language: string;
123
+ }
124
+
125
+ /** Reads an opening fence per CommonMark: 3+ backticks or tildes, indented at most 3 spaces. */
126
+ function openingFence(line: string): Fence | undefined {
127
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
128
+ if (match === null) return undefined;
129
+ const run = match[1] ?? "";
130
+ const info = (match[2] ?? "").trim();
131
+ // A backtick fence's info string may not contain a backtick.
132
+ if (run.startsWith("`") && info.includes("`")) return undefined;
133
+ return {
134
+ char: run.charAt(0),
135
+ length: run.length,
136
+ language: info.split(/\s+/)[0] ?? "",
137
+ };
138
+ }
139
+
140
+ /** A closing fence: the same character, at least as long, then only spaces. */
141
+ function closesFence(line: string, fence: Fence): boolean {
142
+ const match = /^ {0,3}(`{3,}|~{3,}) *$/.exec(line);
143
+ const run = match?.[1];
144
+ return run !== undefined && run.charAt(0) === fence.char && run.length >= fence.length;
145
+ }
146
+
147
+ function splitCells(line: string): string[] {
148
+ let text = line.trim();
149
+ if (text.startsWith("|")) text = text.slice(1);
150
+ if (text.endsWith("|")) text = text.slice(0, -1);
151
+ return text.split("|").map((cell) => cell.trim());
152
+ }
153
+
154
+ function isTableSeparator(line: string): boolean {
155
+ return /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line);
156
+ }
157
+
158
+ function renderTable(rows: readonly string[], colour: boolean): string[] {
159
+ const cells = rows.map(splitCells);
160
+ const width = Math.max(1, ...cells.map((row) => row.length));
161
+ const widths: number[] = [];
162
+ for (let index = 0; index < width; index += 1) {
163
+ widths.push(
164
+ Math.max(
165
+ 1,
166
+ ...cells.map((row) => visibleLength(row[index] ?? "")),
167
+ ),
168
+ );
169
+ }
170
+
171
+ const draw = (row: readonly string[], separator: string): string => {
172
+ const parts: string[] = [];
173
+ for (let index = 0; index < width; index += 1) {
174
+ const cell = row[index] ?? "";
175
+ const length = visibleLength(cell);
176
+ const text = renderInline(cell, colour);
177
+ parts.push(`${text}${" ".repeat(Math.max(0, (widths[index] ?? 1) - length))}`);
178
+ }
179
+ return `${separator} ${parts.join(` ${separator} `)} ${separator}`.replace(
180
+ /\s+$/,
181
+ "",
182
+ );
183
+ };
184
+
185
+ const lines: string[] = [];
186
+ const header = cells[0] ?? [];
187
+ lines.push(draw(header, "|"));
188
+ const rule = `|${widths.map((size) => "-".repeat(size + 2)).join("|")}|`;
189
+ lines.push(colour ? styled(rule, ANSI.dim) : rule);
190
+ for (const row of cells.slice(1)) {
191
+ if (isTableSeparator(row.join("|"))) continue;
192
+ lines.push(draw(row, "|"));
193
+ }
194
+ return lines;
195
+ }
196
+
197
+ const NUMERIC_CELL =
198
+ /^[-+~≈]?[$€£¥]?\s?\d[\d,]*(\.\d+)?\s?(%|ms|s|m|h|d|w|[kKMB])?(\s\d+(\.\d+)?\s?(ms|s|m|h|d))*$/;
199
+
200
+ /** True for a number, a duration or an amount of money. */
201
+ function isNumericCell(text: string): boolean {
202
+ return NUMERIC_CELL.test(stripInline(text).trim());
203
+ }
204
+
205
+ /** The widest columns shrink first, down to `floor`, until `excess` is gone. */
206
+ function shrinkWidest(
207
+ widths: number[],
208
+ eligible: readonly boolean[],
209
+ floor: number,
210
+ excess: number,
211
+ ): number {
212
+ let left = excess;
213
+ while (left > 0) {
214
+ let pick = -1;
215
+ for (let index = 0; index < widths.length; index += 1) {
216
+ const size = widths[index] ?? 0;
217
+ if (eligible[index] !== true || size <= floor) continue;
218
+ if (pick < 0 || size > (widths[pick] ?? 0)) pick = index;
219
+ }
220
+ if (pick < 0) break;
221
+ widths[pick] = (widths[pick] ?? 0) - 1;
222
+ left -= 1;
223
+ }
224
+ return left;
225
+ }
226
+
227
+ /** Terminal columns a text takes: CJK and emoji are two wide. */
228
+ function displayWidth(text: string): number {
229
+ return Bun.stringWidth(stripInline(text));
230
+ }
231
+
232
+ const SEGMENTER = new Intl.Segmenter();
233
+
234
+ function cut(text: string, size: number): string {
235
+ const plain = stripInline(text);
236
+ if (Bun.stringWidth(plain) <= size) return plain;
237
+ let kept = "";
238
+ let used = 0;
239
+ for (const { segment } of SEGMENTER.segment(plain)) {
240
+ const next = Bun.stringWidth(segment);
241
+ if (used + next > size - 1) break;
242
+ kept += segment;
243
+ used += next;
244
+ }
245
+ return `${kept}…`;
246
+ }
247
+
248
+ /** A table laid out for `available` columns: no pipes, one line per row. */
249
+ function renderFittedTable(
250
+ rows: readonly string[],
251
+ colour: boolean,
252
+ available: number,
253
+ ): string[] {
254
+ const cells = rows
255
+ .map(splitCells)
256
+ .filter((row, index) => index === 0 || !isTableSeparator(row.join("|")));
257
+ const count = Math.max(1, ...cells.map((row) => row.length));
258
+ const widths: number[] = [];
259
+ const numeric: boolean[] = [];
260
+ for (let index = 0; index < count; index += 1) {
261
+ widths.push(
262
+ Math.max(1, ...cells.map((row) => displayWidth(row[index] ?? ""))),
263
+ );
264
+ const body = cells
265
+ .slice(1)
266
+ .map((row) => row[index] ?? "")
267
+ .filter((cell) => cell.length > 0);
268
+ numeric.push(body.length > 0 && body.every(isNumericCell));
269
+ }
270
+ const gap = 2;
271
+ const total = (): number =>
272
+ widths.reduce((sum, size) => sum + size, 0) + gap * (count - 1);
273
+ const text = numeric.map((flag) => !flag);
274
+ const all = numeric.map(() => true);
275
+ // Long text columns first, keeping short ones whole; only then anything.
276
+ for (const [eligible, floor] of [
277
+ [text, 12],
278
+ [text, 4],
279
+ [all, 3],
280
+ [all, 1],
281
+ ] as const) {
282
+ const excess = total() - available;
283
+ if (excess <= 0) break;
284
+ shrinkWidest(widths, eligible, floor, excess);
285
+ }
286
+
287
+ const draw = (row: readonly string[], header: boolean): string => {
288
+ const parts: string[] = [];
289
+ for (let index = 0; index < count; index += 1) {
290
+ const cell = row[index] ?? "";
291
+ const size = widths[index] ?? 1;
292
+ const length = displayWidth(cell);
293
+ const fits = length <= size;
294
+ const shown = fits ? cell : cut(cell, size);
295
+ const body = header
296
+ ? stripInline(shown)
297
+ : fits
298
+ ? renderInline(shown, colour)
299
+ : shown;
300
+ const pad = " ".repeat(Math.max(0, size - (fits ? length : Bun.stringWidth(shown))));
301
+ const styledBody =
302
+ header && colour ? styled(body, `${ANSI.bold}${ANSI.weak}`) : body;
303
+ parts.push(numeric[index] === true ? `${pad}${styledBody}` : `${styledBody}${pad}`);
304
+ }
305
+ return parts.join(" ".repeat(gap)).replace(/\s+$/, "");
306
+ };
307
+
308
+ const lines = [draw(cells[0] ?? [], true)];
309
+ const rule = "─".repeat(Math.max(1, Math.min(total(), available)));
310
+ lines.push(colour ? styled(rule, ANSI.weak) : rule);
311
+ for (const row of cells.slice(1)) lines.push(draw(row, false));
312
+ return lines;
313
+ }
314
+
315
+ function renderCode(
316
+ language: string,
317
+ code: readonly string[],
318
+ colour: boolean,
319
+ ): MarkdownLine[] {
320
+ const lines: MarkdownLine[] = [];
321
+ if (language.length > 0) {
322
+ lines.push({
323
+ text: colour ? styled(` ${language}`, ANSI.dim) : ` ${language}`,
324
+ code: true,
325
+ language,
326
+ label: true,
327
+ });
328
+ }
329
+ const diff = language === "diff";
330
+ for (const codeLine of code) {
331
+ const body = ` ${codeLine}`;
332
+ if (!colour || codeLine.length === 0) {
333
+ lines.push({ text: body, code: true, language });
334
+ continue;
335
+ }
336
+ if (diff && codeLine.startsWith("+")) {
337
+ lines.push({ text: styled(body, ANSI.green), code: true, language });
338
+ } else if (diff && codeLine.startsWith("-")) {
339
+ lines.push({ text: styled(body, ANSI.red), code: true, language });
340
+ } else if (diff && codeLine.startsWith("@@")) {
341
+ lines.push({ text: styled(body, ANSI.cyan), code: true, language });
342
+ } else {
343
+ lines.push({ text: styled(body, ANSI.dim), code: true, language });
344
+ }
345
+ }
346
+ return lines;
347
+ }
348
+
349
+ /**
350
+ * Renders one Markdown document as lines; `code` tells a client which lines
351
+ * came from a fence, so it may draw them as monospace.
352
+ */
353
+ export function renderMarkdownLines(
354
+ markdown: string,
355
+ options: RenderOptions = {},
356
+ ): MarkdownLine[] {
357
+ const colour = options.colour === true;
358
+ const width =
359
+ options.width !== undefined && Number.isFinite(options.width) && options.width > 0
360
+ ? Math.floor(options.width)
361
+ : undefined;
362
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
363
+ const output: MarkdownLine[] = [];
364
+ const push = (text: string): void => {
365
+ output.push({ text, code: false });
366
+ };
367
+
368
+ for (let index = 0; index < lines.length; index += 1) {
369
+ const line = lines[index] ?? "";
370
+
371
+ const opening = openingFence(line);
372
+ if (opening !== undefined) {
373
+ const language = opening.language;
374
+ index += 1;
375
+ const code: string[] = [];
376
+ while (index < lines.length && !closesFence(lines[index] ?? "", opening)) {
377
+ code.push(lines[index] ?? "");
378
+ index += 1;
379
+ }
380
+ output.push(...renderCode(language, code, colour));
381
+ continue;
382
+ }
383
+
384
+ const next = lines[index + 1] ?? "";
385
+ if (line.includes("|") && isTableSeparator(next)) {
386
+ const table: string[] = [line, next];
387
+ index += 2;
388
+ while (index < lines.length && (lines[index] ?? "").includes("|")) {
389
+ table.push(lines[index] ?? "");
390
+ index += 1;
391
+ }
392
+ index -= 1;
393
+ (width === undefined
394
+ ? renderTable(table, colour)
395
+ : renderFittedTable(table, colour, width)
396
+ ).forEach(push);
397
+ continue;
398
+ }
399
+
400
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
401
+ if (heading !== null) {
402
+ const level = heading[1]?.length ?? 1;
403
+ const raw = heading[2] ?? "";
404
+ const title = renderInline(level === 1 ? raw.toUpperCase() : raw, colour);
405
+ push(colour ? styled(title, ANSI.bold) : title);
406
+ continue;
407
+ }
408
+
409
+ if (/^\s*([-*_])\s*\1\s*\1[\s\S]*$/.test(line)) {
410
+ const rule = "─".repeat(40);
411
+ push(colour ? styled(rule, ANSI.dim) : rule);
412
+ continue;
413
+ }
414
+
415
+ const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
416
+ if (bullet !== null) {
417
+ const marker = colour ? styled("•", ANSI.cyan) : "•";
418
+ push(`${bullet[1] ?? ""}${marker} ${renderInline(bullet[2] ?? "", colour)}`);
419
+ continue;
420
+ }
421
+
422
+ const numbered = /^(\s*)(\d+)[.)]\s+(.*)$/.exec(line);
423
+ if (numbered !== null) {
424
+ const marker = `${numbered[2] ?? "1"}.`;
425
+ push(
426
+ `${numbered[1] ?? ""}${colour ? styled(marker, ANSI.cyan) : marker} ${renderInline(numbered[3] ?? "", colour)}`,
427
+ );
428
+ continue;
429
+ }
430
+
431
+ const quote = /^\s*>\s?(.*)$/.exec(line);
432
+ if (quote !== null) {
433
+ const marker = colour ? styled("│", ANSI.dim) : "│";
434
+ push(` ${marker} ${renderInline(quote[1] ?? "", colour)}`);
435
+ continue;
436
+ }
437
+
438
+ push(renderInline(line, colour));
439
+ }
440
+
441
+ return output;
442
+ }
443
+
444
+ /** Renders one Markdown document as terminal text. */
445
+ export function renderMarkdown(
446
+ markdown: string,
447
+ options: RenderOptions = {},
448
+ ): string {
449
+ const output = renderMarkdownLines(markdown, options).map((line) => line.text);
450
+ return `${output.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd()}\n`;
451
+ }
@@ -0,0 +1,10 @@
1
+ export {
2
+ NOTIFIED_FACT,
3
+ NOTIFY_TIMEOUT_MS,
4
+ Notifier,
5
+ notificationKey,
6
+ shellHookRunner,
7
+ type HookOutcome,
8
+ type HookRunner,
9
+ type NotifierOptions,
10
+ } from "./notify.ts";