@operad-io/engine 0.0.0-stage → 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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,255 @@
1
+ /** The running view: active runs, their current step and how long they took. */
2
+
3
+ import type { RowMark } from "../plugin/types.ts";
4
+ import type { LogBackend } from "../log/types.ts";
5
+ import { evolve, initialState } from "../kernel/state.ts";
6
+ import type { KernelState } from "../kernel/types.ts";
7
+ import { queuedSteps } from "../runner/limits.ts";
8
+ import { parseObjectKey } from "../runner/service.ts";
9
+ import type { Views } from "./presentation.ts";
10
+
11
+ export interface RunningItem {
12
+ readonly runId: string;
13
+ readonly flow: string;
14
+ readonly step: string | null;
15
+ readonly startedAt: number;
16
+ /** The run's age. */
17
+ readonly elapsedMs: number;
18
+ /** The object the run belongs to, as rows and `operad show` name it; null for none. */
19
+ readonly object: string | null;
20
+ /** The object's row title; null when there is no object or the lookup failed. */
21
+ readonly title: string | null;
22
+ /** When the current step's current attempt started running, after any wait for a place; null before any step or while it is queued. */
23
+ readonly stepStartedAt: number | null;
24
+ /** How long that attempt has run; null when `stepStartedAt` is. */
25
+ readonly stepElapsedMs: number | null;
26
+ /** How long the step's current attempt spent queued for a place, so far or in all; 0 when it did not. */
27
+ readonly queuedMs?: number;
28
+ /** Set while the step waits for a place under a limit key. */
29
+ readonly queued: { readonly key: string; readonly ahead: number } | null;
30
+ /** The step in words: `queued (<key>, <n> ahead)` while it waits. */
31
+ readonly stepLabel: string | null;
32
+ /** The object's row note (a plugin's word on what it waits for); null for none. */
33
+ readonly note?: string | null;
34
+ /** The object's row mark; omitted when the row has none. */
35
+ readonly mark?: RowMark;
36
+ }
37
+
38
+ /** Reads a run's state and when its current step's current attempt started. */
39
+ async function readRun(
40
+ log: LogBackend,
41
+ runId: string,
42
+ ): Promise<{
43
+ state: KernelState;
44
+ stepStartedAt: number | null;
45
+ queuedMs: number;
46
+ queuedSince: number | null;
47
+ }> {
48
+ let state = initialState();
49
+ let stepStartedAt: number | null = null;
50
+ let queuedMs = 0;
51
+ // Open waits for a place by effect id, and when each began.
52
+ const queues = new Map<string, number>();
53
+ for await (const fact of log.read(runId)) {
54
+ state = evolve(state, fact);
55
+ // A new step, or a new request for the step (a retry or a recovery),
56
+ // starts the attempt over.
57
+ if (fact.kind === "step_entered" || fact.kind === "effect_requested") {
58
+ stepStartedAt = fact.time;
59
+ queuedMs = 0;
60
+ queues.clear();
61
+ }
62
+ const payload = fact.payload;
63
+ const effectId =
64
+ typeof payload === "object" && payload !== null && !Array.isArray(payload)
65
+ ? payload.effectId
66
+ : undefined;
67
+ if (typeof effectId !== "string") continue;
68
+ if (fact.kind === "step_queued") {
69
+ if (!queues.has(effectId)) queues.set(effectId, fact.time);
70
+ } else if (fact.kind === "step_slot" || fact.kind === "step_released") {
71
+ // The place was granted or the wait ended: the step runs from now.
72
+ const since = queues.get(effectId);
73
+ if (since === undefined) continue;
74
+ queues.delete(effectId);
75
+ queuedMs += Math.max(0, fact.time - since);
76
+ stepStartedAt = fact.time;
77
+ }
78
+ }
79
+ const queuedSince = queues.size === 0 ? null : Math.min(...queues.values());
80
+ return { state, stepStartedAt, queuedMs, queuedSince };
81
+ }
82
+
83
+ /** A run that waits for a person or has ended is not running. */
84
+ function isRunning(state: KernelState): boolean {
85
+ return state.status !== "waiting_person" && state.status !== "ended";
86
+ }
87
+
88
+ /** One stretch of a run: a step, or a wait for a person, with when it began and ended. */
89
+ export interface RunSegment {
90
+ readonly step: string;
91
+ /** True while the run waited for a person in this step. */
92
+ readonly person: boolean;
93
+ readonly from: number;
94
+ /** Null while the stretch is still open (the run is active). */
95
+ readonly to: number | null;
96
+ }
97
+
98
+ /** A run's own times, read from its facts and nothing else. */
99
+ export interface RunTimes {
100
+ readonly startedAt: number;
101
+ /** When the run ended (its end fact, else the log's end); null while it is active. */
102
+ readonly endedAt: number | null;
103
+ /** The stretches in order: each is a step, or a wait for a person in a step. */
104
+ readonly segments: readonly RunSegment[];
105
+ }
106
+
107
+ /**
108
+ * A run's start, its end and the stretches between: a step runs from its
109
+ * `step_entered` until it hands over or the run ends; a wait for a person is
110
+ * a stretch of its own. A stretch of no time is left out. Undefined for a run the log does not know.
111
+ */
112
+ export async function runTimes(
113
+ log: LogBackend,
114
+ runId: string,
115
+ /** The log's runs, when the caller already read them for another run. */
116
+ known?: Promise<Awaited<ReturnType<LogBackend["runs"]>>>,
117
+ ): Promise<RunTimes | undefined> {
118
+ const info = (await (known ?? log.runs())).find((run) => run.runId === runId);
119
+ if (info === undefined) return undefined;
120
+ let state = initialState();
121
+ let startedAt = info.startedAt;
122
+ let endedAt: number | null = null;
123
+ const segments: { step: string; person: boolean; from: number; to: number | null }[] = [];
124
+ for await (const fact of log.read(runId)) {
125
+ if (fact.kind === "run_started") startedAt = fact.time;
126
+ state = evolve(state, fact);
127
+ const wanted =
128
+ state.status === "ended" || state.step === null
129
+ ? undefined
130
+ : { step: state.step, person: state.status === "waiting_person" };
131
+ const open = segments[segments.length - 1];
132
+ const same =
133
+ wanted !== undefined &&
134
+ open?.to === null &&
135
+ open.step === wanted.step &&
136
+ open.person === wanted.person;
137
+ if (open?.to === null && !same) {
138
+ // A stretch that began and ended in the same instant carries no time.
139
+ if (open.from === fact.time) segments.pop();
140
+ else open.to = fact.time;
141
+ }
142
+ if (wanted !== undefined && !same) segments.push({ ...wanted, from: fact.time, to: null });
143
+ if (fact.kind === "run_ended") endedAt = fact.time;
144
+ }
145
+ if (endedAt === null && !info.active) endedAt = info.endedAt ?? startedAt;
146
+ if (endedAt !== null) {
147
+ for (const segment of segments) if (segment.to === null) segment.to = endedAt;
148
+ }
149
+ return { startedAt, endedAt, segments };
150
+ }
151
+
152
+ export async function listRunning(
153
+ log: LogBackend,
154
+ clock: () => number = () => Date.now(),
155
+ views?: Views,
156
+ ): Promise<readonly RunningItem[]> {
157
+ const now = clock();
158
+ const runs = (await log.runs({ active: true })).sort(
159
+ (left, right) => left.startedAt - right.startedAt,
160
+ );
161
+ const queued = await queuedSteps(log);
162
+ const live: {
163
+ run: (typeof runs)[number];
164
+ state: KernelState;
165
+ stepStartedAt: number | null;
166
+ queuedMs: number;
167
+ queuedSince: number | null;
168
+ }[] = [];
169
+
170
+ for (const run of runs) {
171
+ const read = await readRun(log, run.runId);
172
+ if (!isRunning(read.state)) continue;
173
+ live.push({ run, ...read });
174
+ }
175
+
176
+ const rows = await rowsFor(views, live.map((item) => item.run.object));
177
+ const items: RunningItem[] = [];
178
+ for (const { run, state, stepStartedAt, queuedMs, queuedSince } of live) {
179
+ const waiting = queued.get(run.runId) ?? null;
180
+ const named = rows.get(run.object);
181
+ items.push({
182
+ runId: run.runId,
183
+ flow: run.flow,
184
+ step: state.step,
185
+ queued: waiting,
186
+ stepLabel:
187
+ waiting === null
188
+ ? state.step
189
+ : `${state.step ?? "-"} queued (${waiting.key}, ${waiting.ahead} ahead)`,
190
+ startedAt: run.startedAt,
191
+ elapsedMs: Math.max(0, now - run.startedAt),
192
+ object: named === undefined ? null : named.object,
193
+ title: named === undefined ? null : named.title,
194
+ note: named?.note ?? null,
195
+ ...(named?.mark === undefined ? {} : { mark: named.mark }),
196
+ // While it waits for a place the step has not started running.
197
+ stepStartedAt: queuedSince === null ? stepStartedAt : null,
198
+ stepElapsedMs:
199
+ queuedSince !== null
200
+ ? 0
201
+ : stepStartedAt === null
202
+ ? null
203
+ : Math.max(0, now - stepStartedAt),
204
+ queuedMs: queuedMs + (queuedSince === null ? 0 : Math.max(0, now - queuedSince)),
205
+ });
206
+ }
207
+
208
+ return items;
209
+ }
210
+
211
+ interface Named {
212
+ readonly object: string;
213
+ readonly title: string | null;
214
+ readonly note?: string | null;
215
+ readonly mark?: RowMark;
216
+ }
217
+
218
+ /**
219
+ * The object name and row title of each run's object, from one `rowsOf` call
220
+ * (one store read per object, the plugin's `row` once per object). A failed
221
+ * lookup leaves the title null; it never fails the view.
222
+ */
223
+ async function rowsFor(
224
+ views: Views | undefined,
225
+ keys: readonly string[],
226
+ ): Promise<ReadonlyMap<string, Named>> {
227
+ const named = new Map<string, Named>();
228
+ const refs = new Map<string, { type: string; id: string }>();
229
+ for (const key of keys) {
230
+ const parsed = parseObjectKey(key);
231
+ if (parsed !== undefined) refs.set(key, parsed);
232
+ }
233
+ let rows: Awaited<ReturnType<Views["rowsOf"]>> | undefined;
234
+ if (views !== undefined && refs.size > 0) {
235
+ try {
236
+ rows = await views.rowsOf([...refs.values()]);
237
+ } catch {
238
+ rows = undefined;
239
+ }
240
+ }
241
+ for (const [key, ref] of refs) {
242
+ const row = rows?.get(key);
243
+ if (row === undefined) {
244
+ named.set(key, { object: ref.id, title: null });
245
+ continue;
246
+ }
247
+ named.set(key, {
248
+ object: row.scope === undefined ? row.id : `${row.scope}/${row.id}`,
249
+ title: row.error === undefined ? row.title : null,
250
+ note: row.error === undefined ? (row.note ?? null) : null,
251
+ ...(row.error === undefined && row.mark !== undefined ? { mark: row.mark } : {}),
252
+ });
253
+ }
254
+ return named;
255
+ }
@@ -0,0 +1,452 @@
1
+ /**
2
+ * Settings read and written through the client API: the sections of
3
+ * `config.json` plugins declare a schema for (global), and the files plugins
4
+ * keep under a registered repository's `.operad/` (project).
5
+ */
6
+
7
+ import { randomUUID } from "node:crypto";
8
+ import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
9
+ import { basename, dirname, join } from "node:path";
10
+ import { ActionArgsError, validateSchemaValue } from "../plugin/action-schema.ts";
11
+ import { configPath } from "../config/config.ts";
12
+ import { withLockFile } from "../platform/index.ts";
13
+ import type { JsonValue } from "../log/types.ts";
14
+ import type { PluginRegistry } from "../plugin/registry.ts";
15
+ import type {
16
+ ActionArgSchema,
17
+ ActionArgsSchema,
18
+ ObjectStore,
19
+ } from "../plugin/types.ts";
20
+ import { isRecord } from "../util.ts";
21
+
22
+ /** The scope of a setting in `config.json`. */
23
+ export const GLOBAL_SCOPE = "global";
24
+
25
+ /** One setting, as a client lists it. */
26
+ export interface SettingInfo {
27
+ /**
28
+ * `<plugin>.<path>`; a project file whose name differs from its plugin adds
29
+ * that name: `<plugin>.<file>.<path>`.
30
+ */
31
+ readonly name: string;
32
+ /** `global`, or the name of the repository the file is in. */
33
+ readonly scope: string;
34
+ readonly value?: JsonValue | undefined;
35
+ readonly default?: JsonValue | undefined;
36
+ readonly description?: string | undefined;
37
+ /** The schema's type and allowed values, so a client can offer a choice list. */
38
+ readonly type?: string | undefined;
39
+ readonly enum?: readonly (string | number | boolean)[] | undefined;
40
+ readonly editable: boolean;
41
+ readonly confirm: boolean;
42
+ }
43
+
44
+ export type SettingsErrorKind =
45
+ | "not-found"
46
+ | "args"
47
+ | "not-available"
48
+ | "confirm"
49
+ | "ambiguous";
50
+
51
+ /** A settings call refused; nothing was written. */
52
+ export class SettingsError extends Error {
53
+ readonly kind: SettingsErrorKind;
54
+
55
+ constructor(kind: SettingsErrorKind, message: string, options?: ErrorOptions) {
56
+ super(message, options);
57
+ this.name = "SettingsError";
58
+ this.kind = kind;
59
+ }
60
+ }
61
+
62
+ export interface SettingsOptions {
63
+ readonly registry: PluginRegistry;
64
+ readonly store: ObjectStore;
65
+ readonly home: string;
66
+ }
67
+
68
+ /** Hooks a test uses to stop a write between its two steps. */
69
+ export interface AtomicWriteHooks {
70
+ /** Called once the temporary file is complete, before it replaces the target. */
71
+ readonly beforeRename?: (() => Promise<void> | void) | undefined;
72
+ }
73
+
74
+ function isMissing(error: unknown): boolean {
75
+ return (
76
+ typeof error === "object" &&
77
+ error !== null &&
78
+ "code" in error &&
79
+ error.code === "ENOENT"
80
+ );
81
+ }
82
+
83
+ /**
84
+ * Writes a file by writing a temporary file in the same directory and renaming
85
+ * it over the target, so a crash leaves the old file whole.
86
+ */
87
+ export async function writeFileAtomic(
88
+ path: string,
89
+ text: string,
90
+ hooks: AtomicWriteHooks = {},
91
+ ): Promise<void> {
92
+ await mkdir(dirname(path), { recursive: true });
93
+ const temp = join(
94
+ dirname(path),
95
+ `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`,
96
+ );
97
+ const mode = await stat(path).then(
98
+ (info) => info.mode & 0o777,
99
+ () => undefined,
100
+ );
101
+ try {
102
+ const handle = await open(temp, "w");
103
+ try {
104
+ await handle.writeFile(text);
105
+ await handle.sync();
106
+ } finally {
107
+ await handle.close();
108
+ }
109
+ if (mode !== undefined) await chmod(temp, mode);
110
+ await hooks.beforeRename?.();
111
+ await rename(temp, path);
112
+ } catch (error) {
113
+ await rm(temp, { force: true }).catch(() => undefined);
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ interface Leaf {
119
+ /** The dotted path inside the file's JSON. */
120
+ readonly path: readonly string[];
121
+ readonly schema: ActionArgSchema;
122
+ }
123
+
124
+ /** The settings a schema offers: each property that is not a group of properties. */
125
+ function leaves(schema: ActionArgsSchema): Leaf[] {
126
+ const found: Leaf[] = [];
127
+ const walk = (node: ActionArgSchema, path: readonly string[]): void => {
128
+ for (const [name, property] of Object.entries(node.properties ?? {})) {
129
+ const here = [...path, name];
130
+ if (property.properties !== undefined && property.editable !== true) {
131
+ walk(property, here);
132
+ } else {
133
+ found.push({ path: here, schema: property });
134
+ }
135
+ }
136
+ };
137
+ walk(schema, []);
138
+ return found;
139
+ }
140
+
141
+ function valueAt(root: unknown, path: readonly string[]): unknown {
142
+ let node = root;
143
+ for (const key of path) {
144
+ if (!isRecord(node)) return undefined;
145
+ node = node[key];
146
+ }
147
+ return node;
148
+ }
149
+
150
+ /** Sets a value in place, keeping the order of the keys already there. */
151
+ function setAt(
152
+ root: Record<string, unknown>,
153
+ path: readonly string[],
154
+ value: unknown,
155
+ ): void {
156
+ let node = root;
157
+ for (const key of path.slice(0, -1)) {
158
+ const next = node[key];
159
+ if (isRecord(next)) {
160
+ node = next;
161
+ } else {
162
+ const created: Record<string, unknown> = {};
163
+ node[key] = created;
164
+ node = created;
165
+ }
166
+ }
167
+ const last = path[path.length - 1];
168
+ if (last !== undefined) node[last] = value;
169
+ }
170
+
171
+ interface JsonFile {
172
+ readonly value: Record<string, unknown>;
173
+ readonly indent: string;
174
+ readonly newline: boolean;
175
+ }
176
+
177
+ async function readJsonFile(path: string, absent: () => Record<string, unknown>): Promise<JsonFile> {
178
+ let text: string;
179
+ try {
180
+ text = await readFile(path, "utf8");
181
+ } catch (error) {
182
+ if (isMissing(error)) return { value: absent(), indent: " ", newline: true };
183
+ throw error;
184
+ }
185
+ let parsed: unknown;
186
+ try {
187
+ parsed = JSON.parse(text);
188
+ } catch (error) {
189
+ throw new SettingsError("args", `${path}: invalid JSON: ${String(error)}`, {
190
+ cause: error,
191
+ });
192
+ }
193
+ if (!isRecord(parsed)) {
194
+ throw new SettingsError("args", `${path}: must be a JSON object`);
195
+ }
196
+ const match = /^[ \t]+(?=")/m.exec(text);
197
+ return {
198
+ value: parsed,
199
+ indent: match?.[0] ?? " ",
200
+ newline: text.endsWith("\n"),
201
+ };
202
+ }
203
+
204
+ function render(file: JsonFile): string {
205
+ return `${JSON.stringify(file.value, null, file.indent)}${file.newline ? "\n" : ""}`;
206
+ }
207
+
208
+ interface Place {
209
+ readonly scope: string;
210
+ readonly prefix: string;
211
+ readonly schema: ActionArgsSchema;
212
+ /** The file, and where the plugin's settings are inside it. */
213
+ readonly file: string;
214
+ readonly inside: readonly string[];
215
+ readonly fresh: () => Record<string, unknown>;
216
+ }
217
+
218
+ async function readPlace(place: Place): Promise<unknown> {
219
+ try {
220
+ const file = await readJsonFile(place.file, place.fresh);
221
+ return valueAt(file.value, place.inside);
222
+ } catch (error) {
223
+ if (error instanceof SettingsError) return undefined;
224
+ throw error;
225
+ }
226
+ }
227
+
228
+ async function places(
229
+ options: SettingsOptions,
230
+ scope: string | undefined,
231
+ ): Promise<Place[]> {
232
+ const found: Place[] = [];
233
+ const declarations = options.registry.settingsDeclarations();
234
+ if (scope === undefined || scope === GLOBAL_SCOPE) {
235
+ for (const declaration of declarations) {
236
+ if (declaration.schema === undefined) continue;
237
+ found.push({
238
+ scope: GLOBAL_SCOPE,
239
+ prefix: declaration.plugin,
240
+ schema: declaration.schema,
241
+ file: configPath(options.home),
242
+ inside: ["plugins", declaration.plugin, "settings"],
243
+ fresh: () => ({}),
244
+ });
245
+ }
246
+ }
247
+ if (scope === GLOBAL_SCOPE) {
248
+ checkAmbiguous(found);
249
+ return found;
250
+ }
251
+
252
+ let named = false;
253
+ const known: string[] = [];
254
+ for (const declaration of declarations) {
255
+ const project = declaration.project;
256
+ if (project === undefined) continue;
257
+ const repositories = await project.repositories({ store: options.store });
258
+ for (const repository of repositories) {
259
+ if (!known.includes(repository.name)) known.push(repository.name);
260
+ if (scope !== undefined && repository.name !== scope) continue;
261
+ named = true;
262
+ for (const file of project.files) {
263
+ found.push({
264
+ scope: repository.name,
265
+ prefix:
266
+ file.name === declaration.plugin
267
+ ? declaration.plugin
268
+ : `${declaration.plugin}.${file.name}`,
269
+ schema: file.schema,
270
+ file: join(repository.path, ".operad", file.path),
271
+ inside: [],
272
+ fresh: () => ({}),
273
+ });
274
+ }
275
+ }
276
+ }
277
+ if (scope !== undefined && !named) {
278
+ throw new SettingsError(
279
+ "not-found",
280
+ known.length === 0
281
+ ? `no registered repository "${scope}", and none is registered`
282
+ : `no registered repository "${scope}"; registered: ${known.join(", ")}`,
283
+ );
284
+ }
285
+ checkAmbiguous(found);
286
+ return found;
287
+ }
288
+
289
+ function declaredAt(place: Place): string {
290
+ return place.scope === GLOBAL_SCOPE
291
+ ? `the global settings of "${place.prefix}"`
292
+ : `"${place.file}" (${place.prefix})`;
293
+ }
294
+
295
+ /** Refuses names two places in one scope would both claim, before either wins. */
296
+ function checkAmbiguous(places: readonly Place[]): void {
297
+ const byScope = new Map<string, Map<string, Place>>();
298
+ for (const place of places) {
299
+ let names = byScope.get(place.scope);
300
+ if (names === undefined) {
301
+ names = new Map();
302
+ byScope.set(place.scope, names);
303
+ }
304
+ for (const leaf of leaves(place.schema)) {
305
+ const name = `${place.prefix}.${leaf.path.join(".")}`;
306
+ const earlier = names.get(name);
307
+ if (earlier !== undefined) {
308
+ throw new SettingsError(
309
+ "ambiguous",
310
+ `setting "${name}" is declared twice in ${
311
+ place.scope === GLOBAL_SCOPE
312
+ ? "the global scope"
313
+ : `repository "${place.scope}"`
314
+ }: ${declaredAt(earlier)} and ${declaredAt(place)}`,
315
+ );
316
+ }
317
+ names.set(name, place);
318
+ }
319
+ }
320
+ }
321
+
322
+ function infoOf(place: Place, leaf: Leaf, section: unknown): SettingInfo {
323
+ const current = valueAt(section, leaf.path) ?? leaf.schema.default;
324
+ return {
325
+ name: `${place.prefix}.${leaf.path.join(".")}`,
326
+ scope: place.scope,
327
+ ...(current === undefined ? {} : { value: current as JsonValue }),
328
+ ...(leaf.schema.default === undefined
329
+ ? {}
330
+ : { default: leaf.schema.default as JsonValue }),
331
+ ...(leaf.schema.description === undefined
332
+ ? {}
333
+ : { description: leaf.schema.description }),
334
+ ...(leaf.schema.type === undefined ? {} : { type: leaf.schema.type }),
335
+ ...(leaf.schema.enum === undefined ? {} : { enum: leaf.schema.enum }),
336
+ editable: leaf.schema.editable === true,
337
+ confirm: leaf.schema.confirm === true,
338
+ };
339
+ }
340
+
341
+ /** Every setting in a scope (all scopes when omitted), with its current value. */
342
+ export async function listSettings(
343
+ options: SettingsOptions,
344
+ scope?: string | undefined,
345
+ ): Promise<SettingInfo[]> {
346
+ const infos: SettingInfo[] = [];
347
+ for (const place of await places(options, scope)) {
348
+ const section = await readPlace(place);
349
+ for (const leaf of leaves(place.schema)) {
350
+ infos.push(infoOf(place, leaf, section));
351
+ }
352
+ }
353
+ return infos;
354
+ }
355
+
356
+ export interface SetOptions {
357
+ readonly scope?: string | undefined;
358
+ readonly confirmed?: boolean | undefined;
359
+ readonly hooks?: AtomicWriteHooks | undefined;
360
+ }
361
+
362
+ /** Changes one setting; refuses, writing nothing, when the value does not fit. */
363
+ export async function setSetting(
364
+ options: SettingsOptions,
365
+ name: string,
366
+ value: unknown,
367
+ set: SetOptions = {},
368
+ ): Promise<SettingInfo> {
369
+ const scope = set.scope ?? GLOBAL_SCOPE;
370
+ let match: { readonly place: Place; readonly leaf: Leaf } | undefined;
371
+ for (const place of await places(options, scope)) {
372
+ const prefix = `${place.prefix}.`;
373
+ if (!name.startsWith(prefix)) continue;
374
+ const path = name.slice(prefix.length);
375
+ const leaf = leaves(place.schema).find((item) => item.path.join(".") === path);
376
+ if (leaf !== undefined) {
377
+ match = { place, leaf };
378
+ break;
379
+ }
380
+ }
381
+ if (match === undefined) {
382
+ throw new SettingsError(
383
+ "not-found",
384
+ scope === GLOBAL_SCOPE
385
+ ? `no setting "${name}"`
386
+ : `no setting "${name}" for repository "${scope}"`,
387
+ );
388
+ }
389
+ const { place, leaf } = match;
390
+
391
+ if (leaf.schema.editable !== true) {
392
+ throw new SettingsError("not-available", `setting "${name}" cannot be changed here`);
393
+ }
394
+ try {
395
+ validateSchemaValue(leaf.schema, value, name, "value");
396
+ } catch (error) {
397
+ if (error instanceof ActionArgsError) {
398
+ throw new SettingsError("args", error.message.replace(": args.", ": "), {
399
+ cause: error,
400
+ });
401
+ }
402
+ throw error;
403
+ }
404
+ if (leaf.schema.confirm === true && set.confirmed !== true) {
405
+ throw new SettingsError(
406
+ "confirm",
407
+ `setting "${name}" needs confirmation`,
408
+ );
409
+ }
410
+
411
+ return withLockFile(`${place.file}.lock`, async () => {
412
+ const file = await readJsonFile(place.file, place.fresh);
413
+ if (place.scope === GLOBAL_SCOPE) {
414
+ const plugins = file.value.plugins;
415
+ const plugin = place.inside[1] ?? "";
416
+ if (!isRecord(plugins)) {
417
+ throw new SettingsError(
418
+ "args",
419
+ `${place.file}: plugins must be an object keyed by plugin name to change a setting`,
420
+ );
421
+ }
422
+ const entry = plugins[plugin];
423
+ if (typeof entry === "string") {
424
+ plugins[plugin] = { module: entry, enabled: true };
425
+ } else if (!isRecord(entry)) {
426
+ throw new SettingsError(
427
+ "not-found",
428
+ `${place.file}: plugin "${plugin}" is not listed`,
429
+ );
430
+ }
431
+ }
432
+ setAt(file.value, [...place.inside, ...leaf.path], value);
433
+ try {
434
+ validateSchemaValue(
435
+ place.schema,
436
+ valueAt(file.value, place.inside),
437
+ name,
438
+ "settings",
439
+ );
440
+ } catch (error) {
441
+ if (error instanceof ActionArgsError) {
442
+ throw new SettingsError("args", error.message.replace(": args.", ": "), {
443
+ cause: error,
444
+ });
445
+ }
446
+ throw error;
447
+ }
448
+ await writeFileAtomic(place.file, render(file), set.hooks);
449
+
450
+ return infoOf(place, leaf, valueAt(file.value, place.inside));
451
+ });
452
+ }