omkit 0.0.8 → 0.0.10

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 (72) hide show
  1. package/dist/actions/chrome-page.d.ts +1 -1
  2. package/dist/actions/chrome-page.js +1 -1
  3. package/dist/actions/command.d.ts +1 -1
  4. package/dist/actions/command.js +5 -6
  5. package/dist/actions/healthcheck.d.ts +1 -1
  6. package/dist/actions/healthcheck.js +1 -1
  7. package/dist/actions/prompt.d.ts +1 -1
  8. package/dist/actions/prompt.js +1 -1
  9. package/dist/actions/tail-log.d.ts +1 -1
  10. package/dist/actions/tail-log.js +1 -1
  11. package/dist/actions/until-log.d.ts +2 -2
  12. package/dist/actions/until-log.js +1 -1
  13. package/dist/actions/watch-dir.d.ts +1 -1
  14. package/dist/actions/watch-dir.js +1 -1
  15. package/dist/actions/watch.d.ts +1 -1
  16. package/dist/actions/watch.js +1 -1
  17. package/dist/index.d.ts +13 -17
  18. package/dist/index.js +15 -17
  19. package/dist/orchestration/action/action.d.ts +23 -0
  20. package/dist/orchestration/action/action.js +254 -0
  21. package/dist/{core/action.d.ts → orchestration/action/types.d.ts} +37 -26
  22. package/dist/orchestration/action/types.js +1 -0
  23. package/dist/{core → orchestration/events}/events.d.ts +9 -1
  24. package/dist/{core → orchestration/events}/events.js +14 -22
  25. package/dist/orchestration/spin/SpinHost.d.ts +105 -0
  26. package/dist/orchestration/spin/SpinHost.js +303 -0
  27. package/dist/orchestration/spin/spin.d.ts +24 -0
  28. package/dist/orchestration/spin/spin.js +56 -0
  29. package/dist/orchestration/spin/types.d.ts +56 -0
  30. package/dist/orchestration/spin/types.js +1 -0
  31. package/dist/output/Output.d.ts +24 -0
  32. package/dist/output/Output.js +27 -0
  33. package/dist/output/folder/RunFolder.d.ts +29 -0
  34. package/dist/output/folder/RunFolder.js +56 -0
  35. package/dist/output/index.d.ts +11 -0
  36. package/dist/output/index.js +11 -0
  37. package/dist/output/log/LogRenderer.d.ts +73 -0
  38. package/dist/output/log/LogRenderer.js +131 -0
  39. package/dist/{core/log-collector → output/log}/LogsCollector.d.ts +21 -5
  40. package/dist/{core/log-collector → output/log}/LogsCollector.js +41 -10
  41. package/dist/output/log/RunLog.d.ts +44 -0
  42. package/dist/output/log/RunLog.js +119 -0
  43. package/dist/output/snapshot/SnapshotStore.d.ts +49 -0
  44. package/dist/output/snapshot/SnapshotStore.js +61 -0
  45. package/dist/system/fs/FolderCache.d.ts +47 -0
  46. package/dist/system/fs/FolderCache.js +117 -0
  47. package/dist/system/fs/streams.d.ts +11 -0
  48. package/dist/system/fs/streams.js +14 -0
  49. package/dist/{core → system/process}/process.d.ts +9 -8
  50. package/dist/{core → system/process}/process.js +8 -9
  51. package/dist/utils/format.d.ts +9 -0
  52. package/dist/utils/format.js +9 -0
  53. package/dist/utils/serialize.d.ts +2 -0
  54. package/dist/utils/serialize.js +12 -0
  55. package/package.json +1 -1
  56. package/dist/core/action.js +0 -188
  57. package/dist/core/folder-cache.d.ts +0 -39
  58. package/dist/core/folder-cache.js +0 -109
  59. package/dist/core/log-collector/global.d.ts +0 -7
  60. package/dist/core/log-collector/global.js +0 -7
  61. package/dist/core/log-collector/render.d.ts +0 -57
  62. package/dist/core/log-collector/render.js +0 -111
  63. package/dist/core/markers.d.ts +0 -9
  64. package/dist/core/markers.js +0 -13
  65. package/dist/core/output.d.ts +0 -64
  66. package/dist/core/output.js +0 -190
  67. package/dist/core/run.d.ts +0 -88
  68. package/dist/core/run.js +0 -240
  69. package/dist/core/spin.d.ts +0 -72
  70. package/dist/core/spin.js +0 -36
  71. /package/dist/{core/helpers → utils}/AsyncQueue.d.ts +0 -0
  72. /package/dist/{core/helpers → utils}/AsyncQueue.js +0 -0
package/dist/core/run.js DELETED
@@ -1,240 +0,0 @@
1
- import { relative } from "node:path";
2
- import { log as logs } from "./log-collector/global.js";
3
- import { createRenderer } from "./log-collector/render.js";
4
- import { streamLog, writeLog } from "./output.js";
5
- import { marker } from "./markers.js";
6
- /** One spin per process — a single world over the one global log. See {@link run}. */
7
- let started = false;
8
- /** Narrate a run-lifecycle milestone into the global log (renders as a `[run]` line). */
9
- const narrate = (message) => logs.append({ source: "run", level: "run", message });
10
- /** The entry script, relative to where node was invoked (so the log says what produced it). */
11
- const scriptPath = () => {
12
- const entry = process.argv[1];
13
- return entry ? relative(process.cwd(), entry) : "(unknown)";
14
- };
15
- /** A constructed instance is an object carrying a `start` function. */
16
- const isActionInstance = (value) => typeof value === "object" &&
17
- value !== null &&
18
- typeof value.start === "function";
19
- /** An *uncalled* action: the callable `action(name).run(…)` returns before it's invoked. */
20
- const isUncalledAction = (value) => typeof value === "function" && typeof value.actionName === "string";
21
- /**
22
- * Guard each launch argument: an action *instance* is required, not the action
23
- * itself. Forgetting the trailing `()` is an easy slip (the callable has no
24
- * `.start`), and silently treating it as something else would report a false
25
- * green — so fail loudly with the fix.
26
- */
27
- function assertInstance(value) {
28
- if (isActionInstance(value))
29
- return;
30
- const hint = isUncalledAction(value)
31
- ? ` — that looks like an action that wasn't invoked; construct an instance by calling it: action("…").run(…)()`
32
- : "";
33
- throw new Error(`run() expects action instances; received ${typeof value}${hint}`);
34
- }
35
- /**
36
- * Starts the spin: launches the given actions in parallel under one abort
37
- * controller, against the process-wide global log. Returns a {@link Spin} — add
38
- * more actions on demand with `.run(…)`, observe `.done` for the verdict, stop
39
- * with `.cancel()`.
40
- *
41
- * **Callable once per process.** A spin *is* the world being modelled, and there's
42
- * one global log per world; a second call would silently share that log, so it
43
- * throws instead. Attach further actions — including event-driven ones — to the
44
- * returned {@link Spin} via its `.run(…)` method, not by calling this again.
45
- *
46
- * Each action runs against its own child logger (which headers and indents its
47
- * lines into the global log) and the spin's shared abort signal — both injected
48
- * into its context, where the framework also binds a `proc` to them so child
49
- * processes stream into the right log and die on teardown. A **failing action
50
- * never tears the spin down** — its `{ ok: false }` outcome is recorded in the
51
- * verdict (and sets exit code 1) and the spin keeps running. Teardown to `closed`
52
- * happens only on Ctrl-C, `.cancel()`, natural completion, or an uncaught fatal.
53
- */
54
- export function run(...actions) {
55
- if (started) {
56
- throw new Error("run() may only be called once per process — attach more actions to the existing run with its .run(…) method.");
57
- }
58
- // Validate eagerly, before the one-run latch flips, so a bad argument throws
59
- // cleanly and leaves the process's single run slot still usable.
60
- for (const instance of actions)
61
- assertInstance(instance);
62
- started = true;
63
- const controller = new AbortController();
64
- // The log closes when the run tears down, so every `logs.subscribe(…)` ends on
65
- // its own — no subscriber has to watch the signal.
66
- logs.endOn(controller.signal);
67
- // ── Lifecycle state ──────────────────────────────────────────────────────
68
- // The single source of truth for "where in its life is this run". Only
69
- // `beginClosing` and the finalize step below mutate it, and only forward.
70
- let state = "open";
71
- // Genuine failures (not teardown cascade). Frozen into the verdict at close.
72
- const failures = [];
73
- // Every launched action's promise lives here until it settles; the drain loop
74
- // empties this set. Daemons keep it non-empty until the controller aborts.
75
- const inFlight = new Set();
76
- /**
77
- * Move `open → closing`: abort the signal (unwinding procs, waits, and
78
- * daemons), narrate the cause once, and stop accepting new actions. Idempotent
79
- * — only the first caller transitions; later triggers (a second failure, a
80
- * `cancel()` during teardown) are no-ops. This is the *only* path to abort, so
81
- * every teardown reason flows through one place.
82
- */
83
- const beginClosing = (reason) => {
84
- if (state !== "open")
85
- return;
86
- state = "closing";
87
- narrate(`tearing down · ${reason}`);
88
- controller.abort();
89
- };
90
- /**
91
- * Record a genuine fault in the verdict. It does **not** tear the spin down — a
92
- * failing action is data, and the spin keeps running (only Ctrl-C / cancel /
93
- * completion / an uncaught fatal close it).
94
- */
95
- const recordFailure = (action, error) => {
96
- failures.push({ action, error });
97
- };
98
- // Ctrl-C tears the spin down gracefully through the lifecycle, like cancel().
99
- const onSigint = () => beginClosing("interrupted (SIGINT)");
100
- process.once("SIGINT", onSigint);
101
- // A throw or rejection that escaped every action's own handling. Without a
102
- // handler Node prints it and exits *immediately* — before the run can flush its
103
- // log, which leaves a silent, empty log directory and no verdict. So catch it,
104
- // log it, fold it into the verdict, and drive teardown so the log still flushes
105
- // and the exit code reflects the fault — degrading a stray throw to a recorded
106
- // failure instead of a hard crash. Removed at finalize, so it only governs
107
- // while this run owns the process.
108
- const onFatal = (kind) => (error) => {
109
- logs.append({
110
- source: kind,
111
- level: "error",
112
- message: error instanceof Error ? (error.stack ?? error.message) : String(error),
113
- });
114
- // Genuine fault vs. teardown fallout: only one that surfaces *before* the
115
- // signal aborts is the spin's own (mirrors `launch`'s cascade rule); a throw
116
- // during unwind is logged but doesn't pollute the verdict. Either way tear
117
- // down — unlike an action's own failure, an *uncaught* fatal leaves the
118
- // process state undefined, so we always finish and flush.
119
- if (!controller.signal.aborted)
120
- failures.push({ action: kind, error });
121
- beginClosing(kind);
122
- };
123
- const onUncaught = onFatal("uncaughtException");
124
- const onUnhandled = onFatal("unhandledRejection");
125
- process.on("uncaughtException", onUncaught);
126
- process.on("unhandledRejection", onUnhandled);
127
- narrate(`run started · ${scriptPath()}`);
128
- // Start streaming log entries to disk immediately — incremental writes survive
129
- // hard kills where the final writeLog never runs. Kept so finalize can await it
130
- // *before* writeLog rewrites the same files: otherwise a late flush from this
131
- // stream lands past writeLog's truncation and the OS zero-fills the gap (a
132
- // multi-MB NUL run in run.log).
133
- const streaming = streamLog(logs).catch(() => { });
134
- const launch = (instance) => {
135
- narrate(`launch ${instance.name}`);
136
- // The action logs into the one shared store (entries carry their `source`;
137
- // grouping is applied at render time) and gets the spin's signal directly; the
138
- // framework injects a `proc` bound to both, so there's no ambient context.
139
- // `start()` resolves with the action's Outcome — it never rejects for the
140
- // action's own failure — so a failure is handled here as data, not a throw.
141
- const record = (error) => {
142
- // Always record the fault in the action's own log, under its name.
143
- logs.append({
144
- source: instance.name,
145
- level: "error",
146
- message: error instanceof Error ? (error.stack ?? error.message) : String(error),
147
- });
148
- // Genuine failure vs. teardown fallout: if the signal was already aborted
149
- // when this surfaced, the failure is almost certainly the abort killing the
150
- // action (a cascade), not its own fault — so it must not pollute the verdict.
151
- if (!controller.signal.aborted)
152
- recordFailure(instance.name, error);
153
- };
154
- const promise = instance
155
- .start({ logs, signal: controller.signal })
156
- .then((outcome) => {
157
- if (!outcome.ok)
158
- record(outcome.error);
159
- })
160
- // Defensive: `start()` shouldn't reject, but if the framework itself throws,
161
- // treat it as a fault rather than losing it to an unhandled rejection.
162
- .catch(record);
163
- inFlight.add(promise);
164
- void promise.finally(() => inFlight.delete(promise));
165
- };
166
- for (const instance of actions)
167
- launch(instance);
168
- // Drives the run to `closed`. The loop re-checks `inFlight` because actions can
169
- // be added (or daemons can settle on abort) while we await. A synchronous
170
- // `.run(…)` from a settling action's lifecycle event lands before that action's
171
- // `finally` removes it, so `inFlight` never spuriously hits 0 mid-handoff.
172
- const done = (async () => {
173
- for (;;) {
174
- if (inFlight.size === 0) {
175
- // Nothing left to run. If still open, every action finished on its own —
176
- // natural completion; tear down so daemons/listeners unwind uniformly.
177
- // If already closing, teardown is simply complete.
178
- if (state === "open")
179
- beginClosing("completed");
180
- break;
181
- }
182
- await Promise.allSettled([...inFlight]);
183
- }
184
- // ── Finalize (reached exactly once) ──────────────────────────────────────
185
- state = "closed";
186
- process.off("SIGINT", onSigint);
187
- process.off("uncaughtException", onUncaught);
188
- process.off("unhandledRejection", onUnhandled);
189
- narrate("finished");
190
- // Wait for the incremental streamer to fully close its files, so its last
191
- // flush can't land after writeLog truncates+rewrites them (which would leave
192
- // a NUL gap). The log is already closed, so this resolves promptly.
193
- await streaming;
194
- const file = await writeLog(logs);
195
- // Direct to the terminal — the file's already written, so this line isn't in it.
196
- console.log(marker("run", `log → ${file}`));
197
- const result = { ok: failures.length === 0, failures };
198
- // One process = one run = one verdict; reflect pass/fail in the exit code so
199
- // shells and CI see it without parsing the log. Only set it on failure, so a
200
- // code a failing action's own handler may have set isn't clobbered to 0.
201
- if (!result.ok)
202
- process.exitCode = 1;
203
- return result;
204
- })();
205
- // `done` resolves with the verdict and never rejects; guard anyway so a stray
206
- // finalize error can't surface as an unhandled rejection.
207
- done.catch(() => { });
208
- const drain = (write = (message) => console.log(message)) => {
209
- void (async () => {
210
- // A renderer applies grouping/indentation as entries stream by; its state
211
- // spans the replayed history and live entries as one continuous stream. The
212
- // subscription ends itself when the run tears down (the collector closes it),
213
- // so this loop simply runs to completion.
214
- const render = createRenderer();
215
- for await (const entry of logs.subscribe({ replay: true }))
216
- write(render(entry));
217
- })().catch(() => { });
218
- return self;
219
- };
220
- const self = {
221
- logs,
222
- get state() {
223
- return state;
224
- },
225
- done,
226
- signal: controller.signal,
227
- run(...more) {
228
- if (state !== "open") {
229
- throw new Error(`spin.run(…) rejected: the spin is "${state}", not "open". Launch actions before ` +
230
- `teardown, or from a lifecycle event of an action that is still running.`);
231
- }
232
- for (const instance of more)
233
- launch(instance);
234
- return self;
235
- },
236
- cancel: () => beginClosing("cancelled"),
237
- drain,
238
- };
239
- return self;
240
- }
@@ -1,72 +0,0 @@
1
- import { type AnyActionInstance } from "./action.ts";
2
- import { type Spin } from "./run.ts";
3
- /**
4
- * Launch an action into the spin and get the same instance back, so you can
5
- * `await` its `.done` (its {@link import("./action.ts").Outcome} — resolves with
6
- * `{ ok, value } | { ok, error }`, **never throws**), its `.ref` (the attached
7
- * handle; rejects on failure, so it's for data deps consumed inside other
8
- * actions), or subscribe with `.on` / `.once`. A nod is how the body waves an
9
- * action in.
10
- */
11
- export type Nod = <I extends AnyActionInstance>(instance: I) => I;
12
- /** Tunes a {@link spin} — currently just how it drains. */
13
- export interface SpinOptions {
14
- /**
15
- * Stream the log to the console automatically from the start. Default `true`.
16
- * Set `false` when you need to drain later via {@link SpinContext.drain} —
17
- * e.g. after an interactive `prompt`, so the stream doesn't write over it.
18
- */
19
- drain?: boolean;
20
- }
21
- /** What a {@link spin} body receives. */
22
- export interface SpinContext {
23
- /** Launch an action into the spin; returns the instance for awaiting/chaining. */
24
- readonly nod: Nod;
25
- /**
26
- * Start streaming the spin's log to the console now. Only needed when the spin
27
- * was created with `drain: false`; idempotent, so it's safe to call regardless.
28
- */
29
- readonly drain: Spin["drain"];
30
- /**
31
- * Tear the spin down (abort the signal, stopping daemons). Use it to end a spin
32
- * whose work is finished but which is held open by a daemon — e.g. once a
33
- * one-shot build completes while a watcher is still running.
34
- */
35
- readonly cancel: Spin["cancel"];
36
- /** The spin's abort signal — honor it to stop early. */
37
- readonly signal: AbortSignal;
38
- /**
39
- * Absolute path to this spin's output folder (`logs/<name>/<date>/<time>/`),
40
- * created up front. Hand it to actions (or use `ctx.artifactsFolder` inside
41
- * one) to write artifacts beside `run.log`.
42
- */
43
- readonly artifactsFolder: string;
44
- }
45
- /** The body of a {@link spin}: any (async) function — it isn't named or wrapped by you. */
46
- export type SpinBody = (ctx: SpinContext) => void | Promise<void>;
47
- /**
48
- * Runs a linear orchestration. You pass a plain (async) function; omkit hosts it
49
- * in a single in-flight action and hands it a {@link Nod}. Because that host
50
- * stays in-flight while your body `await`s, the spin never idles shut between
51
- * steps — so you write `await` / `if` control flow instead of nested callbacks.
52
- * When the body returns, the daemons it nodded in keep the spin alive until
53
- * teardown.
54
- *
55
- * A failing action **never throws into the body** — `await nod(x).done` yields an
56
- * {@link import("./action.ts").Outcome} you inspect, and the spin keeps going
57
- * (the failure is recorded in the verdict and sets exit code 1):
58
- *
59
- * spin({ drain: false }, async ({ nod }) => {
60
- * const ans = await nod(prompt({ … })).done; // Outcome — never throws
61
- * if (ans.ok && ans.value === "yes") await nod(test).done;
62
- * nod(devServer); // fire-and-forget daemon
63
- * const chrome = nod(chromedriver({ … }));
64
- * nod(chromePage(chrome.ref)); // data deps via .ref
65
- * });
66
- *
67
- * Auto-drains by default; pass `drain: false` and call `ctx.drain()` yourself to
68
- * stream the log only from a chosen point (e.g. after a `prompt`). Returns the
69
- * {@link Spin} — `await` its `.done` for the verdict.
70
- */
71
- export declare function spin(body: SpinBody): Spin;
72
- export declare function spin(options: SpinOptions, body: SpinBody): Spin;
package/dist/core/spin.js DELETED
@@ -1,36 +0,0 @@
1
- import { action } from "./action.js";
2
- import { run } from "./run.js";
3
- import { artifactsFolder } from "./output.js";
4
- export function spin(a, b) {
5
- const [options, body] = typeof a === "function" ? [{}, a] : [a, b];
6
- const { drain: autoDrain = true } = options;
7
- // `run(...)` below assigns `host` synchronously, before the action's async body
8
- // ever runs — so the closures here capture the spin safely.
9
- let host;
10
- // One-shot drain: auto-drain and a manual ctx.drain() can't double-subscribe.
11
- let drained = false;
12
- const startDrain = (write) => {
13
- if (!drained) {
14
- drained = true;
15
- host.drain(write);
16
- }
17
- return host;
18
- };
19
- const hosted = action("Spin").run(async ({ signal }) => {
20
- const nod = (instance) => {
21
- host.run(instance);
22
- return instance;
23
- };
24
- await body({
25
- nod,
26
- drain: startDrain,
27
- cancel: () => host.cancel(),
28
- signal,
29
- artifactsFolder: artifactsFolder(),
30
- });
31
- });
32
- host = run(hosted());
33
- if (autoDrain)
34
- startDrain();
35
- return host;
36
- }
File without changes
File without changes