@intellectual-frontiers/ergonex 0.3.0 → 0.3.2

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 (65) hide show
  1. package/dist/desired.d.ts +1 -1
  2. package/dist/mod.js +2029 -2461
  3. package/dist/modules/external.d.ts +1 -1
  4. package/dist/modules/registry.d.ts +1 -1
  5. package/dist/modules/types.d.ts +6 -6
  6. package/dist/plan.d.ts +1 -1
  7. package/dist/platform/k-args.d.ts +3 -24
  8. package/dist/render.d.ts +2 -2
  9. package/dist/state-record.d.ts +2 -2
  10. package/dist/tools/catalog.d.ts +1 -1
  11. package/dist/vendor/ts/runtime/http-client.d.ts +1 -1
  12. package/ergonex.mjs +3484 -3769
  13. package/package.json +5 -2
  14. package/dist/vendor/ts/kernel/archive.d.ts +0 -147
  15. package/dist/vendor/ts/kernel/args.d.ts +0 -240
  16. package/dist/vendor/ts/kernel/assess.d.ts +0 -247
  17. package/dist/vendor/ts/kernel/attest.d.ts +0 -164
  18. package/dist/vendor/ts/kernel/base64.d.ts +0 -24
  19. package/dist/vendor/ts/kernel/cbor.d.ts +0 -39
  20. package/dist/vendor/ts/kernel/cms.d.ts +0 -106
  21. package/dist/vendor/ts/kernel/commands.d.ts +0 -103
  22. package/dist/vendor/ts/kernel/cose.d.ts +0 -34
  23. package/dist/vendor/ts/kernel/crypt.d.ts +0 -30
  24. package/dist/vendor/ts/kernel/csv.d.ts +0 -38
  25. package/dist/vendor/ts/kernel/der.d.ts +0 -67
  26. package/dist/vendor/ts/kernel/documentation.d.ts +0 -118
  27. package/dist/vendor/ts/kernel/dsse.d.ts +0 -137
  28. package/dist/vendor/ts/kernel/evidence.d.ts +0 -212
  29. package/dist/vendor/ts/kernel/glob.d.ts +0 -64
  30. package/dist/vendor/ts/kernel/grc.d.ts +0 -356
  31. package/dist/vendor/ts/kernel/http.d.ts +0 -46
  32. package/dist/vendor/ts/kernel/json5.d.ts +0 -46
  33. package/dist/vendor/ts/kernel/layers.d.ts +0 -35
  34. package/dist/vendor/ts/kernel/md5.d.ts +0 -19
  35. package/dist/vendor/ts/kernel/media-types.d.ts +0 -28
  36. package/dist/vendor/ts/kernel/mod.d.ts +0 -95
  37. package/dist/vendor/ts/kernel/ocsf-types.auto.d.ts +0 -4374
  38. package/dist/vendor/ts/kernel/ocsf.d.ts +0 -160
  39. package/dist/vendor/ts/kernel/oscal.d.ts +0 -356
  40. package/dist/vendor/ts/kernel/otel.d.ts +0 -365
  41. package/dist/vendor/ts/kernel/otlp.d.ts +0 -83
  42. package/dist/vendor/ts/kernel/palette.d.ts +0 -44
  43. package/dist/vendor/ts/kernel/png.d.ts +0 -124
  44. package/dist/vendor/ts/kernel/rdf-schema.d.ts +0 -190
  45. package/dist/vendor/ts/kernel/rdf-term.d.ts +0 -162
  46. package/dist/vendor/ts/kernel/rdf-vocabularies.d.ts +0 -148
  47. package/dist/vendor/ts/kernel/rdf-write.d.ts +0 -25
  48. package/dist/vendor/ts/kernel/rdf.d.ts +0 -35
  49. package/dist/vendor/ts/kernel/render.d.ts +0 -111
  50. package/dist/vendor/ts/kernel/schedule.d.ts +0 -207
  51. package/dist/vendor/ts/kernel/semver.d.ts +0 -94
  52. package/dist/vendor/ts/kernel/sha256.d.ts +0 -29
  53. package/dist/vendor/ts/kernel/signals.d.ts +0 -371
  54. package/dist/vendor/ts/kernel/sigv4.d.ts +0 -67
  55. package/dist/vendor/ts/kernel/test-record.d.ts +0 -222
  56. package/dist/vendor/ts/kernel/test-report.d.ts +0 -294
  57. package/dist/vendor/ts/kernel/toml.d.ts +0 -51
  58. package/dist/vendor/ts/kernel/trace.d.ts +0 -169
  59. package/dist/vendor/ts/kernel/ts-literal.d.ts +0 -62
  60. package/dist/vendor/ts/kernel/uuid.d.ts +0 -53
  61. package/dist/vendor/ts/kernel/vt.d.ts +0 -78
  62. package/dist/vendor/ts/kernel/webauthn.d.ts +0 -212
  63. package/dist/vendor/ts/kernel/width.d.ts +0 -63
  64. package/dist/vendor/ts/kernel/xml.d.ts +0 -73
  65. package/dist/vendor/ts/kernel/yaml.d.ts +0 -44
package/dist/mod.js CHANGED
@@ -189,20 +189,6 @@ function oneOf(...alternatives) {
189
189
  return fail(path, `one of ${alternatives.length} alternatives`, input);
190
190
  };
191
191
  }
192
- function mapDecoder(base, f) {
193
- return (input, path = "$") => {
194
- const r = base(input, path);
195
- return r.kind === "ok" ? ok(f(r.value)) : r;
196
- };
197
- }
198
- function refine(base, name, valid) {
199
- return (input, path = "$") => {
200
- const r = base(input, path);
201
- if (r.kind === "err")
202
- return r;
203
- return valid(r.value) ? ok(r.value) : fail(path, `a ${name}`, input);
204
- };
205
- }
206
192
  function json(text, decoder) {
207
193
  let value;
208
194
  try {
@@ -214,7 +200,19 @@ function json(text, decoder) {
214
200
  }
215
201
  // ../core/src/text.ts
216
202
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;?]*[A-Za-z]`, "g");
217
- // ../ts/kernel/archive.ts
203
+ // ../formats/src/base64.ts
204
+ function fromBase64(text) {
205
+ const t = text.replace(/[\t\n\r ]/g, "");
206
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))
207
+ return err("the text is not padded standard base64");
208
+ const s = atob(t);
209
+ const out = new Uint8Array(s.length);
210
+ for (let i = 0;i < s.length; i++)
211
+ out[i] = s.charCodeAt(i);
212
+ return ok(out);
213
+ }
214
+
215
+ // ../formats/src/archive.ts
218
216
  var CRC_TABLE = Array.from({ length: 256 }, (_, i) => {
219
217
  let c = i;
220
218
  for (let k = 0;k < 8; k++)
@@ -227,445 +225,339 @@ function dosDate(year, month, day) {
227
225
  var ZIP_EPOCH = dosDate(1980, 1, 1);
228
226
  var NO_PENDING = { pax: new Map, longName: undefined, longLink: undefined };
229
227
  var MAX_META = 1 << 20;
230
- // ../ts/kernel/base64.ts
231
- function fromBase64(text) {
232
- const t = text.replace(/[\t\n\r ]/g, "");
233
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))
234
- return err("the text is not padded standard base64");
235
- const s = atob(t);
236
- const out = new Uint8Array(s.length);
237
- for (let i = 0;i < s.length; i++)
238
- out[i] = s.charCodeAt(i);
239
- return ok(out);
228
+
229
+ // ../formats/src/hex.ts
230
+ function toHex(bytes) {
231
+ let out = "";
232
+ for (const b of bytes)
233
+ out += b.toString(16).padStart(2, "0");
234
+ return out;
240
235
  }
241
- // ../ts/kernel/args.ts
242
- function flag(o) {
243
- const negatable = o.negatable === true;
244
- return {
245
- kind: "flag",
246
- short: o.short,
247
- help: o.help,
248
- negatable,
249
- fallback: negatable && o.default === undefined ? { kind: "none" } : { kind: "default", value: o.default ?? false }
250
- };
236
+ // ../formats/src/cbor.ts
237
+ var UTF8 = new TextDecoder("utf-8", { fatal: true });
238
+ // ../crypto/src/sha256.ts
239
+ var SHA256 = /^[0-9a-f]{64}$/;
240
+ function sha256Of(text) {
241
+ const t = text.trim().toLowerCase();
242
+ return SHA256.test(t) ? t : undefined;
251
243
  }
252
- function value(o) {
253
- return {
254
- kind: "value",
255
- short: o.short,
256
- help: o.help,
257
- valueName: o.valueName ?? "VALUE",
258
- parse: o.parse ?? text,
259
- fallback: o.required === true ? { kind: "required" } : ("default" in o) ? { kind: "default", value: o.default } : { kind: "none" }
260
- };
244
+ async function sha256(data) {
245
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
246
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
247
+ return toHex(new Uint8Array(digest));
261
248
  }
262
- var text = (t) => ok(t);
263
- function longName(key) {
264
- return `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
249
+
250
+ // ../crypto/src/dsse.ts
251
+ var utf8 = new TextEncoder;
252
+ var lowerHex = (input, path = "$") => typeof input === "string" && /^(?:[0-9a-f]{2})+$/.test(input) ? ok(input) : err({ kind: "decode", path, expected: "lower-case hexadecimal", found: describe(input) });
253
+ var resourceDescriptorDecoder = object({ name: string, digest: record(lowerHex) }, { uri: string, mediaType: string, annotations: record(unknownValue) });
254
+ var base64Text = (input, path = "$") => typeof input === "string" && fromBase64(input).kind === "ok" ? ok(input) : err({ kind: "decode", path, expected: "standard base64", found: describe(input) });
255
+ var envelopeDecoder = object({
256
+ payload: base64Text,
257
+ payloadType: string,
258
+ signatures: array(object({ sig: base64Text }, { keyid: string }))
259
+ });
260
+ // ../crypto/src/md5.ts
261
+ var T = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0);
262
+ // ../crypto/src/sigv4.ts
263
+ var UNSIGNED_HEADERS = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id", "traceparent", "tracestate"]);
264
+ var encoder = new TextEncoder;
265
+ // ../crypto/src/uuid.ts
266
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
267
+ function uuidOf(text) {
268
+ const t = text.trim().toLowerCase();
269
+ const bare = t.startsWith("urn:uuid:") ? t.slice("urn:uuid:".length) : t;
270
+ return UUID.test(bare) ? bare : undefined;
265
271
  }
266
- function editDistance(a, b) {
267
- let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
268
- for (let i = 1;i <= a.length; i++) {
269
- const row = [i];
270
- for (let j = 1;j <= b.length; j++) {
271
- row.push(Math.min((prev[j] ?? 0) + 1, (row[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1)));
272
- }
273
- prev = row;
272
+ function constant(text) {
273
+ const u = uuidOf(text);
274
+ if (u === undefined)
275
+ throw new Error(`not a UUID: ${text}`);
276
+ return u;
277
+ }
278
+ var NIL_UUID = constant("00000000-0000-0000-0000-000000000000");
279
+ var NAMESPACE_DNS = constant("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
280
+ var NAMESPACE_URL = constant("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
281
+ var NAMESPACE_OID = constant("6ba7b812-9dad-11d1-80b4-00c04fd430c8");
282
+ var NAMESPACE_X500 = constant("6ba7b814-9dad-11d1-80b4-00c04fd430c8");
283
+ var utf82 = new TextEncoder;
284
+ // ../crypto/src/webauthn.ts
285
+ var clientData = object({ type: string, challenge: string, origin: string }, { crossOrigin: boolean, topOrigin: string });
286
+ var kind = literal("public-key");
287
+ var extensionResults = record(unknownValue);
288
+ // src/portable.ts
289
+ function describePortableError(e) {
290
+ switch (e.kind) {
291
+ case "empty":
292
+ return "a path segment is empty";
293
+ case "dot":
294
+ return `the path segment ${JSON.stringify(e.segment)} would leave its folder`;
295
+ case "forbidden-character":
296
+ return `the path segment ${JSON.stringify(e.segment)} holds ${JSON.stringify(e.character)}, which Windows does not allow in a name`;
297
+ case "control-character":
298
+ return `the path segment ${JSON.stringify(e.segment)} holds a control character`;
299
+ case "trailing-dot-or-space":
300
+ return `the path segment ${JSON.stringify(e.segment)} ends in a dot or a space, which Windows drops`;
301
+ case "device-name":
302
+ return `the path segment ${JSON.stringify(e.segment)} is the Windows device name ${e.device}, with or without an extension, in any case`;
303
+ case "too-long":
304
+ return `the path segment is ${e.bytes} bytes in UTF-8, and a name may have 255`;
305
+ case "not-nfc":
306
+ return `the path segment ${JSON.stringify(e.segment)} is not in Unicode normalization form NFC, so it would be another name on macOS`;
307
+ default:
308
+ return absurd(e);
274
309
  }
275
- return prev[b.length] ?? 0;
276
310
  }
277
- function suggest(word, candidates) {
278
- let best;
279
- let bestDistance = Number.POSITIVE_INFINITY;
280
- for (const c of candidates) {
281
- const d = editDistance(word, c);
282
- if (d < bestDistance) {
283
- best = c;
284
- bestDistance = d;
285
- }
311
+ var FORBIDDEN = new Set(["<", ">", ":", '"', "/", "\\", "|", "?", "*"]);
312
+ var DEVICE = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])$/i;
313
+ function isDeviceName(name) {
314
+ return DEVICE.test((name.split(".")[0] ?? "").replace(/ +$/, ""));
315
+ }
316
+ var MAX_SEGMENT_BYTES = 255;
317
+ function segment(text) {
318
+ if (text === "")
319
+ return err({ kind: "empty" });
320
+ if (text === "." || text === "..")
321
+ return err({ kind: "dot", segment: text });
322
+ for (const ch of text) {
323
+ const code = ch.codePointAt(0) ?? 0;
324
+ if (code < 32 || code === 127)
325
+ return err({ kind: "control-character", segment: text });
326
+ if (FORBIDDEN.has(ch))
327
+ return err({ kind: "forbidden-character", segment: text, character: ch });
286
328
  }
287
- return bestDistance <= Math.max(2, Math.floor(word.length / 2)) ? best : undefined;
329
+ if (text.endsWith(".") || text.endsWith(" "))
330
+ return err({ kind: "trailing-dot-or-space", segment: text });
331
+ const stem = (text.split(".")[0] ?? "").replace(/ +$/, "");
332
+ if (isDeviceName(text))
333
+ return err({
334
+ kind: "device-name",
335
+ segment: text,
336
+ device: stem.toUpperCase()
337
+ });
338
+ const bytes = new TextEncoder().encode(text).length;
339
+ if (bytes > MAX_SEGMENT_BYTES)
340
+ return err({ kind: "too-long", segment: text.slice(0, 40), bytes });
341
+ if (text !== text.normalize("NFC"))
342
+ return err({ kind: "not-nfc", segment: text });
343
+ return ok(text);
288
344
  }
289
- function asksHelp(word) {
290
- return word === "--help" || /^-[A-Za-z]*h[A-Za-z]*$/.test(word);
345
+ function repoPath(segments) {
346
+ if (segments.length === 0)
347
+ return err({ kind: "empty" });
348
+ const made = [];
349
+ for (const s of segments) {
350
+ const r = segment(s);
351
+ if (r.kind === "err")
352
+ return r;
353
+ made.push(r.value);
354
+ }
355
+ return ok(made.join("/"));
291
356
  }
292
- function operandWord(o) {
293
- switch (o.arity) {
294
- case "one":
295
- return o.name;
296
- case "optional":
297
- return `[${o.name}]`;
298
- case "many":
299
- return `[${o.name}...]`;
300
- default:
301
- return absurd(o.arity);
357
+ function segmentsOf(path) {
358
+ return path.split("/");
359
+ }
360
+ function child(path, name) {
361
+ return `${path}/${name}`;
362
+ }
363
+ function nativePath(root, path, separator) {
364
+ const base = root.replace(/[\\/]+$/, "");
365
+ return [base, ...segmentsOf(path)].join(separator);
366
+ }
367
+ function foldKey(path) {
368
+ return path.normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
369
+ }
370
+ function collisions(items) {
371
+ const groups = new Map;
372
+ for (const item of items) {
373
+ const key = foldKey(item.path);
374
+ const group = groups.get(key);
375
+ if (group === undefined)
376
+ groups.set(key, [{ ...item }]);
377
+ else
378
+ group.push({ ...item });
302
379
  }
380
+ return [...groups.entries()].filter(([, members]) => members.length > 1).map(([key, members]) => ({ key, members }));
303
381
  }
304
- function parseArgs(argv, spec, operands = []) {
305
- const end = argv.indexOf("--");
306
- if ((end < 0 ? argv : argv.slice(0, end)).some(asksHelp))
307
- return ok({ kind: "help" });
308
- const entries = Object.keys(spec).flatMap((key) => {
309
- const option = spec[key];
310
- return option === undefined ? [] : [{ key, long: longName(key), option }];
382
+ var WINDOWS_PATH_LIMIT = 259;
383
+ function checkPathLength(windowsPath, longPathsEnabled) {
384
+ if (longPathsEnabled || windowsPath.length <= WINDOWS_PATH_LIMIT)
385
+ return ok(windowsPath);
386
+ return err({
387
+ kind: "path-too-long",
388
+ path: windowsPath,
389
+ length: windowsPath.length,
390
+ limit: WINDOWS_PATH_LIMIT
311
391
  });
312
- const longs = [
313
- ...entries.flatMap((e) => e.option.kind === "flag" && e.option.negatable ? [e.long, `--no-${e.long.slice(2)}`] : [e.long]),
314
- "--help"
315
- ];
316
- const given = new Map;
317
- const listed = new Map;
318
- const positionals = [];
319
- let rest = [];
320
- let i = 0;
321
- const take = (e, written, inline, negated) => {
322
- const o = e.option;
323
- if (o.kind !== "many" && given.has(e.key))
324
- return { kind: "repeated-option", option: e.long };
325
- if (o.kind === "flag") {
326
- if (inline !== undefined)
327
- return { kind: "unexpected-value", option: written, value: inline };
328
- given.set(e.key, !negated);
329
- return;
330
- }
331
- const t = inline ?? argv[++i];
332
- if (t === undefined)
333
- return { kind: "missing-value", option: written };
334
- const parsed = o.parse(t);
335
- if (parsed.kind === "err") {
336
- const reason = typeof parsed.error === "string" ? parsed.error : `expected ${parsed.error.expected}, found ${parsed.error.found}`;
337
- return { kind: "invalid-value", option: written, value: t, reason };
338
- }
339
- if (o.kind === "value")
340
- given.set(e.key, parsed.value);
341
- else
342
- listed.set(e.key, [...listed.get(e.key) ?? [], parsed.value]);
343
- return;
344
- };
345
- for (;i < argv.length; i++) {
346
- const word = argv[i] ?? "";
347
- if (word === "--") {
348
- rest = argv.slice(i + 1);
349
- break;
350
- }
351
- if (word.startsWith("--")) {
352
- const eq = word.indexOf("=");
353
- const name = eq < 0 ? word : word.slice(0, eq);
354
- const inline = eq < 0 ? undefined : word.slice(eq + 1);
355
- if (name === "--help")
356
- return err({ kind: "unexpected-value", option: name, value: inline ?? "" });
357
- const direct = entries.find((e) => e.long === name);
358
- const positive = name.startsWith("--no-") ? entries.find((e) => e.long === `--${name.slice(5)}`) : undefined;
359
- const negated = direct === undefined && positive !== undefined && positive.option.kind === "flag" && positive.option.negatable;
360
- const e = direct ?? (negated ? positive : undefined);
361
- if (e === undefined)
362
- return err({ kind: "unknown-option", option: name, suggestion: suggest(name, longs) });
363
- const problem = take(e, name, inline, negated);
364
- if (problem !== undefined)
365
- return err(problem);
366
- continue;
367
- }
368
- if (word.length < 2 || !word.startsWith("-") || /^-[0-9]/.test(word)) {
369
- positionals.push(word);
370
- continue;
371
- }
372
- for (let j = 1;j < word.length; j++) {
373
- const letter = word.charAt(j);
374
- const written = `-${letter}`;
375
- const e = entries.find((x) => x.option.short === letter);
376
- if (e === undefined)
377
- return err({ kind: "unknown-option", option: written, suggestion: suggest(`-${word}`, longs) });
378
- const after = word.slice(j + 1);
379
- if (e.option.kind === "flag") {
380
- if (after.startsWith("="))
381
- return err({ kind: "unexpected-value", option: written, value: after.slice(1) });
382
- } else if (after !== "") {
383
- return err({ kind: "attached-value", option: written, word });
384
- }
385
- const problem = take(e, written, undefined, false);
386
- if (problem !== undefined)
387
- return err(problem);
388
- }
389
- }
390
- const values = [];
391
- for (const e of entries) {
392
- const o = e.option;
393
- switch (o.kind) {
394
- case "many":
395
- values.push([e.key, listed.get(e.key) ?? []]);
396
- break;
397
- case "flag":
398
- case "value": {
399
- if (given.has(e.key)) {
400
- values.push([e.key, given.get(e.key)]);
401
- break;
402
- }
403
- const f = o.fallback;
404
- switch (f.kind) {
405
- case "none":
406
- values.push([e.key, undefined]);
407
- break;
408
- case "default":
409
- values.push([e.key, f.value]);
410
- break;
411
- case "required":
412
- return err({ kind: "missing-option", option: e.long });
413
- default:
414
- return absurd(f);
415
- }
416
- break;
417
- }
418
- default:
419
- return absurd(o);
420
- }
421
- }
422
- const least = operands.filter((o) => o.arity === "one");
423
- const most = operands.some((o) => o.arity === "many") ? Number.POSITIVE_INFINITY : operands.filter((o) => o.arity !== "many").length;
424
- const missing = least[positionals.length];
425
- if (missing !== undefined)
426
- return err({ kind: "missing-argument", argument: missing.name });
427
- const extra = positionals[most];
428
- if (extra !== undefined)
429
- return err({ kind: "unexpected-argument", argument: extra, takes: operands.map(operandWord) });
430
- const options = Object.fromEntries(values);
431
- return ok({ kind: "args", options, positionals, rest });
432
392
  }
433
- function formatUsageError(e, command = "this command") {
393
+ var REPO_PATH_ROOM = 150;
394
+ function repoPathLength(root, path, separator) {
395
+ const length = nativePath(root, path, separator).length;
396
+ if (length > WINDOWS_PATH_LIMIT)
397
+ return { kind: "too-long", length };
398
+ if (length > REPO_PATH_ROOM)
399
+ return { kind: "no-room", length };
400
+ return { kind: "fits", length };
401
+ }
402
+
403
+ // src/render.ts
404
+ function describeGenerateError(e) {
434
405
  switch (e.kind) {
435
- case "unknown-option":
436
- return `${e.option} is not an option of ${command}${e.suggestion === undefined ? "" : `; did you mean ${e.suggestion}?`}`;
437
- case "missing-value":
438
- return `${e.option} needs a value`;
439
- case "unexpected-value":
440
- return `${e.option} takes no value, but was given ${JSON.stringify(e.value)}`;
441
- case "attached-value":
442
- return `${e.option} takes its value as the next word, not attached as in ${e.word}`;
443
- case "invalid-value":
444
- return `${JSON.stringify(e.value)} is not a valid value of ${e.option}: ${e.reason}`;
445
- case "repeated-option":
446
- return `${e.option} is given more than once`;
447
- case "missing-option":
448
- return `${e.option} is required`;
449
- case "missing-argument":
450
- return `${command} needs ${e.argument}`;
451
- case "unexpected-argument":
452
- return `${command} does not take ${e.argument}: ${e.takes.length === 0 ? "it takes no arguments" : `it takes ${e.takes.join(" ")}`}`;
406
+ case "bad-path":
407
+ return `${JSON.stringify(e.path)} cannot be the path of a generated file: ${e.reason}`;
408
+ case "not-auto":
409
+ return `${e.path} is a generated file whose name does not carry .auto. (only a Git hook in .ergonex/hooks/ may lack it)`;
410
+ case "collision":
411
+ return `${e.path} is the same path as ${e.other} after Unicode normalization and case folding; both are refused`;
412
+ case "inside-repository":
413
+ return `${e.path} is inside the working tree of ${e.repository}; a generated file is never written into a repository`;
414
+ case "bad-data":
415
+ return `${e.what}: ${e.reason}`;
453
416
  default:
454
417
  return absurd(e);
455
418
  }
456
419
  }
457
- function shown(v) {
458
- return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : JSON.stringify(v);
459
- }
460
- function optionLine(e) {
461
- const o = e.option;
462
- const short = o.short === undefined ? " " : `-${o.short}, `;
463
- switch (o.kind) {
464
- case "flag":
465
- return {
466
- left: `${short}${o.negatable ? `--[no-]${e.long.slice(2)}` : e.long}`,
467
- note: o.negatable && o.fallback.kind === "default" ? ` (default: ${o.fallback.value ? e.long : `--no-${e.long.slice(2)}`})` : ""
468
- };
469
- case "value": {
470
- const f = o.fallback;
471
- const note = f.kind === "default" ? ` (default: ${shown(f.value)})` : f.kind === "required" ? " (required)" : "";
472
- return { left: `${short}${e.long} ${o.valueName}`, note };
473
- }
474
- case "many":
475
- return { left: `${short}${e.long} ${o.valueName}`, note: " (repeatable)" };
476
- default:
477
- return absurd(o);
478
- }
479
- }
480
- function columns(rows) {
481
- const width = Math.max(0, ...rows.map(([l]) => l.length));
482
- return rows.map(([l, r]) => ` ${l.padEnd(width)} ${r}`.trimEnd());
420
+ var HOOKS_FOLDER = ".ergonex/hooks";
421
+ function headerText(generator) {
422
+ return `Generated by ${generator}. Do not edit by hand: change workspace.ts and run \`ergonex render\`.`;
483
423
  }
484
- function helpOf(program, summary, spec, operands = []) {
485
- const entries = Object.keys(spec).flatMap((key) => {
486
- const option = spec[key];
487
- return option === undefined ? [] : [{ key, long: longName(key), option }];
488
- });
489
- const required = entries.flatMap((e) => e.option.kind === "value" && e.option.fallback.kind === "required" ? [`${e.long} ${e.option.valueName}`] : []);
490
- const usage = [program, "[OPTIONS]", ...required, ...operands.map(operandWord)].join(" ");
491
- const rows = entries.map((e) => {
492
- const line = optionLine(e);
493
- return [line.left, `${e.option.help}${line.note}`];
494
- });
495
- return [
496
- `${program}: ${summary}`,
497
- "",
498
- `Usage: ${usage}`,
499
- "",
500
- "Options:",
501
- ...columns([...rows, ["-h, --help", "Show this help and do nothing else."]]),
502
- ...operands.length === 0 ? [] : ["", "Arguments:", ...columns(operands.map((o) => [operandWord(o), o.help]))]
503
- ].join(`
424
+ function normalizeText(text) {
425
+ const lf = text.replace(/^/, "").replaceAll(`\r
426
+ `, `
427
+ `).replaceAll("\r", `
504
428
  `);
429
+ return `${lf.replace(/\n+$/, "")}
430
+ `;
505
431
  }
506
- // ../ts/kernel/grc.ts
507
- var INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/i;
508
- var CANONICAL_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
509
- function instantOf(text) {
510
- const m = INSTANT.exec(text.trim());
511
- if (m === null)
512
- return;
513
- const [y, mo, d, h, mi, s] = [m[1], m[2], m[3], m[4], m[5], m[6]].map((x) => Number(x ?? ""));
514
- if (y === undefined || mo === undefined || d === undefined || h === undefined || mi === undefined || s === undefined)
515
- return;
516
- const ms = Number((m[7] ?? "").padEnd(3, "0").slice(0, 3));
517
- if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo) || h > 23 || mi > 59 || s > 59)
518
- return;
519
- const zone = (m[8] ?? "Z").toUpperCase();
520
- let offset = 0;
521
- if (zone !== "Z") {
522
- const oh = Number(zone.slice(1, 3));
523
- const om = Number(zone.slice(4, 6));
524
- if (oh > 23 || om > 59)
525
- return;
526
- offset = (zone.startsWith("-") ? -1 : 1) * (oh * 60 + om) * 60000;
527
- }
528
- const date = new Date(0);
529
- date.setUTCFullYear(y, mo - 1, d);
530
- date.setUTCHours(h, mi, s, ms);
531
- return instantFromEpochMs(date.getTime() - offset);
432
+ function isAutoName(name) {
433
+ return name.includes(".auto.") || name.endsWith(".auto");
532
434
  }
533
- function instantFromEpochMs(ms) {
534
- if (!Number.isFinite(ms))
535
- return;
536
- const date = new Date(Math.trunc(ms));
537
- if (Number.isNaN(date.getTime()))
538
- return;
539
- const text = date.toISOString();
540
- return CANONICAL_INSTANT.test(text) ? text : undefined;
541
- }
542
- function daysInMonth(year, month) {
543
- const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
544
- return month === 2 ? leap ? 29 : 28 : [4, 6, 9, 11].includes(month) ? 30 : 31;
545
- }
546
- var DURATION = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;
547
- function parseDuration(text) {
548
- const m = DURATION.exec(text);
549
- if (m === null || text === "P" || text.endsWith("T"))
550
- return err({ kind: "duration", text });
551
- const n = (i) => Number((m[i] ?? "0").replace(",", "."));
552
- return ok({ text, years: n(1), months: n(2), weeks: n(3), days: n(4), hours: n(5), minutes: n(6), seconds: n(7) });
553
- }
554
- var ROLE = /^[a-z][a-z0-9]*(?:[-_./][a-z0-9]+)*$/;
555
- function roleOf(text) {
556
- return ROLE.test(text) ? text : undefined;
557
- }
558
- var SEVERITIES = ["info", "low", "medium", "high", "critical"];
559
- var refined = (name, f) => {
560
- return (input, path = "$") => {
561
- if (typeof input === "string") {
562
- const v = f(input);
563
- if (v !== undefined)
564
- return ok(v);
565
- }
435
+ function generatedPath(path) {
436
+ const made = repoPath(path.split("/"));
437
+ if (made.kind === "err")
566
438
  return err({
567
- kind: "decode",
439
+ kind: "bad-path",
568
440
  path,
569
- expected: name,
570
- found: typeof input === "string" ? `the string ${JSON.stringify(input).slice(0, 60)}` : typeof input
441
+ reason: describePortableError(made.error)
571
442
  });
572
- };
573
- };
574
- var instantDecoder = refined("an ISO 8601 date-time with a zone", instantOf);
575
- var roleDecoder = refined("a role (lower-case words joined by - _ . or /)", roleOf);
576
- var durationDecoder = refined("an ISO 8601 duration", (t) => {
577
- const r = parseDuration(t);
578
- return r.kind === "ok" ? r.value : undefined;
579
- });
580
- var severityDecoder = literal(...SEVERITIES);
581
- var waiverInput = mapDecoder(object({ id: string, control: string, subjects: array(string), reason: string, approvedBy: roleDecoder, grantedAt: instantDecoder }, { expiresAt: instantDecoder }), (w) => w);
582
-
583
- // ../ts/kernel/assess.ts
584
- var impactDeclarationDecoder = object({ paths: array(string), controls: array(string) });
585
- var RISK_LEVELS = ["very-low", "low", "moderate", "high", "very-high"];
586
- var levelDecoder = literal(...RISK_LEVELS);
587
- var riskDecoder = object({
588
- id: string,
589
- title: string,
590
- likelihood: levelDecoder,
591
- impact: levelDecoder,
592
- treatment: literal("accept", "mitigate", "transfer", "avoid"),
593
- owner: roleDecoder,
594
- reviewBy: instantDecoder
595
- }, { description: string, controls: array(string) });
596
- // ../ts/kernel/sha256.ts
597
- var SHA256 = /^[0-9a-f]{64}$/;
598
- function sha256Of(text) {
599
- const t = text.trim().toLowerCase();
600
- return SHA256.test(t) ? t : undefined;
601
- }
602
- function toHex(bytes) {
603
- let out = "";
604
- for (const b of bytes)
605
- out += b.toString(16).padStart(2, "0");
606
- return out;
607
- }
608
- async function sha256(data) {
609
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
610
- const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
611
- return toHex(new Uint8Array(digest));
443
+ return made;
612
444
  }
445
+ var noBom = (text) => text.replace(/^\uFEFF/, "");
446
+ function contentOf(body, generator) {
447
+ const header = headerText(generator);
448
+ switch (body.format) {
449
+ case "json":
450
+ return normalizeText(JSON.stringify({ _generated: header, ...body.value }, null, 2));
451
+ case "markdown":
452
+ return normalizeText(`<!-- ${header} -->
613
453
 
614
- // ../ts/kernel/dsse.ts
615
- var utf8 = new TextEncoder;
616
- var lowerHex = (input, path = "$") => typeof input === "string" && /^(?:[0-9a-f]{2})+$/.test(input) ? ok(input) : err({ kind: "decode", path, expected: "lower-case hexadecimal", found: describe(input) });
617
- var resourceDescriptorDecoder = object({ name: string, digest: record(lowerHex) }, { uri: string, mediaType: string, annotations: record(unknownValue) });
618
- var base64Text = (input, path = "$") => typeof input === "string" && fromBase64(input).kind === "ok" ? ok(input) : err({ kind: "decode", path, expected: "standard base64", found: describe(input) });
619
- var envelopeDecoder = object({
620
- payload: base64Text,
621
- payloadType: string,
622
- signatures: array(object({ sig: base64Text }, { keyid: string }))
623
- });
624
-
625
- // ../ts/kernel/evidence.ts
626
- var GENESIS = "0".repeat(64);
627
- var sha256Decoder = (input, path = "$") => {
628
- const s = typeof input === "string" && /^[0-9a-f]{64}$/.test(input) ? sha256Of(input) : undefined;
629
- return s === undefined ? err({ kind: "decode", path, expected: "a SHA-256 (64 lower-case hexadecimal digits)", found: typeof input }) : ok(s);
630
- };
631
- var ledgerEntryDecoder = object({
632
- seq: refine(integer, "positive", (n) => n >= 1),
633
- prev: sha256Decoder,
634
- at: instantDecoder,
635
- kind: string,
636
- subject: object({ kind: string, id: string }),
637
- evidence: sha256Decoder,
638
- digest: sha256Decoder
639
- });
640
- var manifestDecoder = object({
641
- files: array(object({ path: string, size: refine(integer, "size", (n) => n >= 0), sha256: sha256Decoder }))
642
- });
454
+ ${noBom(body.text)}`);
455
+ case "yaml":
456
+ case "gitconfig":
457
+ case "envrc":
458
+ return normalizeText(`# ${header}
643
459
 
644
- // ../ts/kernel/uuid.ts
645
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
646
- function uuidOf(text) {
647
- const t = text.trim().toLowerCase();
648
- const bare = t.startsWith("urn:uuid:") ? t.slice("urn:uuid:".length) : t;
649
- return UUID.test(bare) ? bare : undefined;
460
+ ${noBom(body.text)}`);
461
+ case "sh": {
462
+ const text = noBom(body.text);
463
+ const m = /^(#![^\n]*)\n/.exec(text);
464
+ return m === null ? normalizeText(`# ${header}
465
+ ${text}`) : normalizeText(`${m[1]}
466
+ # ${header}
467
+ ${text.slice(m[0].length)}`);
468
+ }
469
+ default:
470
+ return absurd(body);
471
+ }
650
472
  }
651
- function constant(text) {
652
- const u = uuidOf(text);
653
- if (u === undefined)
654
- throw new Error(`not a UUID: ${text}`);
655
- return u;
473
+ function generated(path, body, options) {
474
+ const made = generatedPath(path);
475
+ if (made.kind === "err")
476
+ return made;
477
+ const name = made.value.split("/").at(-1) ?? "";
478
+ const isHook = made.value.startsWith(`${HOOKS_FOLDER}/`) && made.value.split("/").length === 3;
479
+ if (!isAutoName(name) && !isHook)
480
+ return err({ kind: "not-auto", path });
481
+ return ok({
482
+ path: made.value,
483
+ content: contentOf(body, options.generator),
484
+ mode: options.mode ?? "0644",
485
+ generator: options.generator
486
+ });
487
+ }
488
+ function fileDigest(file) {
489
+ return sha256(file.content);
490
+ }
491
+ function checkFiles(files, repositories) {
492
+ const errors = [];
493
+ for (const c of collisions(files.map((f) => ({ id: f.path, path: f.path })))) {
494
+ for (const m of c.members) {
495
+ const other = c.members.find((o) => o !== m);
496
+ errors.push({
497
+ kind: "collision",
498
+ path: m.path,
499
+ other: other?.path ?? m.path
500
+ });
501
+ }
502
+ }
503
+ for (const f of files) {
504
+ const key = foldKey(f.path);
505
+ const inside = repositories.find((r) => key.startsWith(`${foldKey(r)}/`));
506
+ if (inside !== undefined)
507
+ errors.push({
508
+ kind: "inside-repository",
509
+ path: f.path,
510
+ repository: inside
511
+ });
512
+ }
513
+ if (errors.length > 0)
514
+ return err(errors);
515
+ return ok([...files].sort((a, b) => foldKey(a.path) < foldKey(b.path) ? -1 : foldKey(a.path) > foldKey(b.path) ? 1 : 0));
656
516
  }
657
- var NIL_UUID = constant("00000000-0000-0000-0000-000000000000");
658
- var NAMESPACE_DNS = constant("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
659
- var NAMESPACE_URL = constant("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
660
- var NAMESPACE_OID = constant("6ba7b812-9dad-11d1-80b4-00c04fd430c8");
661
- var NAMESPACE_X500 = constant("6ba7b814-9dad-11d1-80b4-00c04fd430c8");
662
- var utf82 = new TextEncoder;
663
517
 
664
- // ../ts/kernel/attest.ts
665
- var PASSING = new Set(["pass"]);
666
- // ../ts/kernel/cbor.ts
667
- var UTF8 = new TextDecoder("utf-8", { fatal: true });
668
- // ../ts/kernel/glob.ts
518
+ // src/desired.ts
519
+ function settingsOf(manifest, facts) {
520
+ const settings = {
521
+ "core.hooksPath": `${facts.homePosix.replace(/\/+$/, "")}/.ergonex/hooks`
522
+ };
523
+ if (manifest.policy.requiresSignedCommits) {
524
+ settings["commit.gpgsign"] = "true";
525
+ if (manifest.signing !== undefined) {
526
+ settings["gpg.format"] = manifest.signing.format;
527
+ if (manifest.signing.key !== undefined)
528
+ settings["user.signingkey"] = manifest.signing.key;
529
+ }
530
+ }
531
+ if (manifest.identity !== undefined) {
532
+ settings["user.name"] = manifest.identity.name;
533
+ settings["user.email"] = manifest.identity.email;
534
+ }
535
+ if (facts.windows)
536
+ settings["core.longpaths"] = "true";
537
+ return settings;
538
+ }
539
+ async function desiredOf(manifest, files, facts) {
540
+ const settings = settingsOf(manifest, facts);
541
+ const repos = manifest.repositories.map((r) => ({
542
+ path: r.path,
543
+ ref: r.ref,
544
+ cloneUrl: r.cloneUrl,
545
+ branch: r.branch,
546
+ settings
547
+ }));
548
+ const worktrees = manifest.repositories.flatMap((r) => r.worktrees.map((w) => ({ path: w.path, repo: r.path, branch: w.branch })));
549
+ const desiredFiles = [];
550
+ for (const f of files)
551
+ desiredFiles.push({ path: f.path, sha256: await fileDigest(f) });
552
+ return { repos, worktrees, files: desiredFiles, hostChanges: [] };
553
+ }
554
+ async function digestsOf(files) {
555
+ const out = new Map;
556
+ for (const f of files)
557
+ out.set(f.path, await fileDigest(f));
558
+ return out;
559
+ }
560
+ // ../formats/src/glob.ts
669
561
  var ESCAPE_OUTSIDE = new Set(["!", "$", "(", ")", "*", "+", ".", "=", "?", "[", "\\", "^", "{", "|"]);
670
562
  var ESCAPE_INSIDE = new Set(["-", "\\", "]"]);
671
563
  var CLASSES = new Map([
@@ -684,11 +576,9 @@ var CLASSES = new Map([
684
576
  ["word", "\\w"],
685
577
  ["xdigit", "\\dA-Fa-f"]
686
578
  ]);
687
- // ../ts/kernel/http.ts
579
+ // ../formats/src/http.ts
688
580
  var SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS", "TRACE"]);
689
- // ../ts/kernel/md5.ts
690
- var T = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0);
691
- // ../ts/kernel/semver.ts
581
+ // ../formats/src/semver.ts
692
582
  var PATTERN = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
693
583
  function parseSemVer(text) {
694
584
  const m = PATTERN.exec(text.trim());
@@ -717,2163 +607,1423 @@ var ver = (major, minor, patch, pre) => ({
717
607
  });
718
608
  var at = (op, version) => ({ op, version });
719
609
  var NOTHING = [at("<", ver(0, 0, 0, "0"))];
720
- // ../ts/kernel/oscal.ts
721
- var OPEN_OUTCOMES = new Set(["fail", "warn", "gap", "error", "accepted"]);
722
- // ../ts/kernel/otel.ts
723
- var TRACE_ID = /^[0-9a-f]{32}$/;
724
- var SPAN_ID = /^[0-9a-f]{16}$/;
725
- var ZEROS = /^0+$/;
726
- function parseTraceId(text) {
727
- if (!TRACE_ID.test(text))
728
- return err("a trace id is 32 lower-case hexadecimal digits");
729
- if (ZEROS.test(text))
730
- return err("a trace id of all zeros is not valid");
731
- return ok(text);
732
- }
733
- function parseSpanId(text) {
734
- if (!SPAN_ID.test(text))
735
- return err("a span id is 16 lower-case hexadecimal digits");
736
- if (ZEROS.test(text))
737
- return err("a span id of all zeros is not valid");
738
- return ok(text);
610
+ // ../formats/src/png.ts
611
+ var MAX_PIXELS = 2 ** 24;
612
+ var COLOUR_TYPES = new Map([
613
+ [0, { samples: 1, depths: [1, 2, 4, 8, 16], name: "greyscale" }],
614
+ [2, { samples: 3, depths: [8, 16], name: "RGB" }],
615
+ [3, { samples: 1, depths: [1, 2, 4, 8], name: "palette" }],
616
+ [4, { samples: 2, depths: [8, 16], name: "greyscale with alpha" }],
617
+ [6, { samples: 4, depths: [8, 16], name: "RGBA" }]
618
+ ]);
619
+ var PRECISION_BITS = 32 - 8 - 2;
620
+ var ONE = 2 ** PRECISION_BITS;
621
+ // ../formats/src/toml.ts
622
+ var CONTROL = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8, 10)}-${String.fromCharCode(31, 127)}]`);
623
+ // ../formats/src/xml.ts
624
+ var FORBIDDEN2 = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11, 12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}\\ufffe\\uffff]`, "g");
625
+ // src/doctor.ts
626
+ function severityOf(level) {
627
+ switch (level) {
628
+ case "ok":
629
+ return;
630
+ case "suggest":
631
+ return "Informational";
632
+ case "warn":
633
+ return "Warning";
634
+ case "error":
635
+ return "Error";
636
+ default:
637
+ return absurd(level);
638
+ }
739
639
  }
740
- var SAMPLED = 1;
741
- var RANDOM = 2;
742
- var KNOWN_FLAGS = SAMPLED | RANDOM;
743
- var TRACESTATE_MAX_MEMBERS = 32;
744
- var KEY_CHAR = "[a-z0-9_\\-*/]";
745
- var TRACESTATE_KEY = new RegExp(`^(?:[a-z]${KEY_CHAR}{0,255}|[a-z0-9]${KEY_CHAR}{0,240}@[a-z]${KEY_CHAR}{0,13})$`);
746
- var TRACESTATE_VALUE = /^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;
747
- function isTraceStateKey(key) {
748
- return TRACESTATE_KEY.test(key);
640
+ function findingsOf(checks, today) {
641
+ return checks.flatMap((c) => {
642
+ const severity = severityOf(c.level);
643
+ return severity === undefined ? [] : [
644
+ {
645
+ ruleId: c.id,
646
+ severity,
647
+ message: c.message,
648
+ subject: c.subject,
649
+ firstSeen: today
650
+ }
651
+ ];
652
+ });
749
653
  }
750
- function isTraceStateValue(value) {
751
- return TRACESTATE_VALUE.test(value);
654
+ function classifyFs(type, wsl) {
655
+ const t = type.toLowerCase();
656
+ if (["msdos", "vfat", "fat", "fat32", "fat16"].includes(t))
657
+ return "fat";
658
+ if (t === "exfat")
659
+ return "exfat";
660
+ if (["9p", "drvfs", "v9fs"].includes(t) && wsl)
661
+ return "wsl-windows-drive";
662
+ if ([
663
+ "nfs",
664
+ "nfs3",
665
+ "nfs4",
666
+ "cifs",
667
+ "smb",
668
+ "smb2",
669
+ "smb3",
670
+ "smbfs",
671
+ "afpfs",
672
+ "9p",
673
+ "v9fs",
674
+ "sshfs",
675
+ "fuse.sshfs",
676
+ "webdav",
677
+ "ncpfs",
678
+ "fuse.rclone"
679
+ ].includes(t))
680
+ return "network";
681
+ return "ok";
752
682
  }
753
- function parseTracestate(header) {
754
- const out = [];
755
- const seen = new Set;
756
- for (const raw of header.split(",")) {
757
- if (out.length >= TRACESTATE_MAX_MEMBERS)
758
- break;
759
- const member = raw.replace(/^[ \t]+|[ \t]+$/g, "");
760
- if (member === "")
761
- continue;
762
- const eq = member.indexOf("=");
763
- if (eq < 0)
764
- continue;
765
- const key = member.slice(0, eq);
766
- const value = member.slice(eq + 1);
767
- if (!isTraceStateKey(key) || !isTraceStateValue(value) || seen.has(key))
768
- continue;
769
- seen.add(key);
770
- out.push({ key, value });
683
+ function fsCheck(probe, home) {
684
+ if (probe.kind === "not-run")
685
+ return {
686
+ id: "ergonex/filesystem",
687
+ level: "suggest",
688
+ subject: home,
689
+ message: `the file system of the root was not probed: ${probe.reason}`
690
+ };
691
+ const kind = classifyFs(probe.type, probe.wsl);
692
+ const at = (level, message) => ({
693
+ id: "ergonex/filesystem",
694
+ level,
695
+ subject: home,
696
+ message
697
+ });
698
+ switch (kind) {
699
+ case "ok":
700
+ return at("ok", `the root is on a file system of type ${probe.type}`);
701
+ case "fat":
702
+ return at("warn", `the root is on a FAT file system (${probe.type}): it has no execute bit and a two-second time resolution, so hooks may not run; move the root to NTFS, APFS or ext4`);
703
+ case "exfat":
704
+ return at("warn", "the root is on an exFAT file system: it has no execute bit and a two-second time resolution, so hooks may not run; move the root to NTFS, APFS or ext4");
705
+ case "network":
706
+ return at("warn", `the root is on a network share (${probe.type}): its locks are not reliable, so two runs may write at once; move the root to a local disk`);
707
+ case "wsl-windows-drive":
708
+ return at("warn", "the root is on a Windows drive seen from WSL (/mnt/c): it is slow and case-insensitive; keep the root in the Linux file system, or run ergonex from Windows");
709
+ default:
710
+ return absurd(kind);
771
711
  }
772
- return out;
773
712
  }
774
- var SEVERITY = { TRACE: 1, DEBUG: 5, INFO: 9, WARN: 13, ERROR: 17, FATAL: 21 };
775
- function isSeverityNumber(n) {
776
- return Number.isInteger(n) && n >= 1 && n <= 24;
777
- }
778
- var TWO_56 = 2 ** 56;
779
- var CREDENTIAL_WORDS = new Set(["key", "code", "sig", "pwd", "pass", "session", "sid", "otp", "awsaccesskeyid", "sas", "se", "sp", "sv"]);
780
- // ../ts/kernel/otlp.ts
781
- var SPAN_KINDS = ["internal", "server", "client", "producer", "consumer"];
782
- class Failure extends Error {
783
- error;
784
- constructor(error) {
785
- super(error.path);
786
- this.error = error;
713
+ var MIN_NODE_MAJOR = 26;
714
+ function runtimeChecks(runtime, tools) {
715
+ const out = [];
716
+ const major = parseSemVer(runtime.version.replace(/^v/, ""));
717
+ if (runtime.name === "node" && major.kind === "ok" && major.value.major < MIN_NODE_MAJOR)
718
+ out.push({
719
+ id: "ergonex/runtime",
720
+ level: "error",
721
+ subject: "node",
722
+ message: `ergonex runs on Node ${MIN_NODE_MAJOR} or later, and this is Node ${runtime.version}; install Node ${MIN_NODE_MAJOR} or run ergonex with Bun`
723
+ });
724
+ else
725
+ out.push({
726
+ id: "ergonex/runtime",
727
+ level: "ok",
728
+ subject: runtime.name,
729
+ message: `running on ${runtime.name} ${runtime.version}`
730
+ });
731
+ for (const t of tools) {
732
+ if (t.version === undefined) {
733
+ const needed = t.name === "git";
734
+ const isRuntime = t.name === runtime.name;
735
+ out.push({
736
+ id: "ergonex/tool",
737
+ level: needed ? "error" : isRuntime ? "ok" : "suggest",
738
+ subject: t.name,
739
+ message: needed ? `git is not installed or not on the PATH; ergonex needs it, and does not install it: install git from your system's package manager` : `${t.name} was not found on the PATH; ${t.name === "bun" ? "Bun is the default runtime" : `Node ${MIN_NODE_MAJOR} is the backup runtime`}, and ergonex does not install it: install it to have both`
740
+ });
741
+ } else
742
+ out.push({
743
+ id: "ergonex/tool",
744
+ level: "ok",
745
+ subject: t.name,
746
+ message: `${t.name} ${t.version}`
747
+ });
787
748
  }
749
+ return out;
788
750
  }
789
- function failure(path, expected, input) {
790
- return { kind: "decode", path, expected, found: describe(input) };
791
- }
792
- function message(build) {
793
- return (input, path = "$") => {
794
- if (typeof input !== "object" || input === null || Array.isArray(input))
795
- return err(failure(path, "an object", input));
796
- const read = (key, decoder) => {
797
- const r = decoder(Reflect.get(input, key), `${path}.${key}`);
798
- if (r.kind === "err")
799
- throw new Failure(r.error);
800
- return r.value;
801
- };
802
- const f = {
803
- req: read,
804
- opt: (key, decoder, fallback) => {
805
- const v = Reflect.get(input, key);
806
- return v === undefined || v === null ? fallback : read(key, decoder);
751
+ function pathChecks(f) {
752
+ if (!f.windows)
753
+ return [
754
+ {
755
+ id: "ergonex/path-length",
756
+ level: "ok",
757
+ subject: f.home,
758
+ message: "the 259-character limit of Windows does not apply on this system"
807
759
  }
808
- };
809
- try {
810
- return ok(build(f, path));
811
- } catch (e) {
812
- if (e instanceof Failure)
813
- return err(e.error);
814
- throw e;
815
- }
816
- };
760
+ ];
761
+ const long = f.longPaths === "enabled";
762
+ const tooLong = f.paths.flatMap((p) => {
763
+ const native = nativePath(f.home, p, "\\");
764
+ const r = checkPathLength(native, long);
765
+ return r.kind === "err" ? [r.error] : [];
766
+ });
767
+ const out = tooLong.map((e) => ({
768
+ id: "ergonex/path-too-long",
769
+ level: "error",
770
+ subject: e.path,
771
+ message: `${e.path} is ${e.length} characters, over the ${WINDOWS_PATH_LIMIT} Windows allows while long paths are off; run \`ergonex setup\` to turn long paths on, or move the root to a shorter path`
772
+ }));
773
+ if (!long && tooLong.length === 0)
774
+ out.push({
775
+ id: "ergonex/windows-long-paths",
776
+ level: "suggest",
777
+ subject: f.home,
778
+ message: f.longPaths === "unknown" ? "Windows long paths are not known to be enabled (the setting could not be read); no path of the workspace exceeds 259 characters yet; run `ergonex setup` to turn them on" : "Windows long paths not enabled; no path of the workspace exceeds 259 characters yet; run `ergonex setup` to turn them on"
779
+ });
780
+ if (long)
781
+ out.push({
782
+ id: "ergonex/windows-long-paths",
783
+ level: "ok",
784
+ subject: f.home,
785
+ message: "Windows long paths are enabled"
786
+ });
787
+ return out;
817
788
  }
818
- function list(element) {
819
- return (input, path = "$") => {
820
- if (!Array.isArray(input))
821
- return err(failure(path, "an array", input));
822
- const out = [];
823
- for (const [i, value] of input.entries()) {
824
- const r = element(value, `${path}[${i}]`);
825
- if (r.kind === "err")
826
- return r;
827
- out.push(r.value);
789
+ function repoPathChecks(f) {
790
+ const out = [];
791
+ for (const repo of f.repositories) {
792
+ const native = nativePath(f.home, repo, f.windows ? "\\" : "/");
793
+ const r = repoPathLength(f.home, repo, f.windows ? "\\" : "/");
794
+ switch (r.kind) {
795
+ case "fits":
796
+ break;
797
+ case "no-room":
798
+ out.push({
799
+ id: "ergonex/repo-path-room",
800
+ level: "suggest",
801
+ subject: native,
802
+ message: `${native} is ${r.length} characters, over ${REPO_PATH_ROOM}: that leaves little room for the files inside the repository; move the root to a shorter path`
803
+ });
804
+ break;
805
+ case "too-long":
806
+ out.push({
807
+ id: "ergonex/repo-path-too-long",
808
+ level: "error",
809
+ subject: native,
810
+ message: `${native} is ${r.length} characters, over ${WINDOWS_PATH_LIMIT}, which is too long for a repository whether or not long paths are enabled; move the root to a shorter path or shorten the repository's path in the manifest`
811
+ });
812
+ break;
813
+ default:
814
+ return absurd(r);
828
815
  }
829
- return ok(out);
816
+ }
817
+ return out;
818
+ }
819
+ function hookChecks(facts, wantedHooksPath) {
820
+ return facts.filter((f) => f.present).map((f) => f.hooksPath === wantedHooksPath ? {
821
+ id: "ergonex/hooks",
822
+ level: "ok",
823
+ subject: f.repo,
824
+ message: "the workspace's hooks are set"
825
+ } : {
826
+ id: "ergonex/hooks",
827
+ level: "warn",
828
+ subject: f.repo,
829
+ message: f.hooksPath === undefined ? `${f.repo} does not use the workspace's hooks (core.hooksPath is not set in its local configuration); run \`ergonex apply\`` : `${f.repo} uses other hooks than the workspace's (its core.hooksPath is elsewhere); run \`ergonex apply\` to replace it`
830
+ });
831
+ }
832
+ // src/findings.ts
833
+ var SEVERITIES = ["Informational", "Warning", "Error"];
834
+ function sarifLevel(severity) {
835
+ switch (severity) {
836
+ case "Informational":
837
+ return "note";
838
+ case "Warning":
839
+ return "warning";
840
+ case "Error":
841
+ return "error";
842
+ default:
843
+ return absurd(severity);
844
+ }
845
+ }
846
+ function worst(findings) {
847
+ let top;
848
+ for (const f of findings)
849
+ if (top === undefined || SEVERITIES.indexOf(f.severity) > SEVERITIES.indexOf(top))
850
+ top = f.severity;
851
+ return top;
852
+ }
853
+ function exitStatusOf(findings) {
854
+ const top = worst(findings);
855
+ return top === "Warning" || top === "Error" ? "Findings" : "Ok";
856
+ }
857
+ var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
858
+ function dayNumber(day) {
859
+ const m = DAY.exec(day);
860
+ if (m === null)
861
+ return;
862
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
863
+ const ms = Date.UTC(y, mo - 1, d);
864
+ const back = new Date(ms);
865
+ if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d)
866
+ return;
867
+ return Math.round(ms / 86400000);
868
+ }
869
+ function daysBetween(from, to) {
870
+ const a = dayNumber(from);
871
+ const b = dayNumber(to);
872
+ if (a === undefined)
873
+ return err(`${JSON.stringify(from)} is not a day (YYYY-MM-DD)`);
874
+ if (b === undefined)
875
+ return err(`${JSON.stringify(to)} is not a day (YYYY-MM-DD)`);
876
+ return ok(b - a);
877
+ }
878
+ var UNAPPROVED_GRACE_DAYS = 90;
879
+ function unapprovedSeverity(firstSeen, today, graceDays = UNAPPROVED_GRACE_DAYS) {
880
+ const age = daysBetween(firstSeen, today);
881
+ return age.kind === "ok" && age.value > graceDays ? "Warning" : "Informational";
882
+ }
883
+ function firstSeenOf(previous, key, today) {
884
+ const before = Object.hasOwn(previous, key) ? previous[key] : undefined;
885
+ return before !== undefined && dayNumber(before) !== undefined ? before : today;
886
+ }
887
+ function toSarif(findings, tool = "ergonex") {
888
+ const rules = [...new Set(findings.map((f) => f.ruleId))].sort().map((id) => ({ id }));
889
+ return {
890
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
891
+ version: "2.1.0",
892
+ runs: [
893
+ {
894
+ tool: {
895
+ driver: {
896
+ name: tool,
897
+ informationUri: "https://intellectual-frontiers.github.io/.github/",
898
+ rules
899
+ }
900
+ },
901
+ results: findings.map((f) => ({
902
+ ruleId: f.ruleId,
903
+ level: sarifLevel(f.severity),
904
+ message: { text: f.message },
905
+ locations: [{ logicalLocations: [{ name: f.subject }] }],
906
+ properties: { firstSeen: f.firstSeen }
907
+ }))
908
+ }
909
+ ]
830
910
  };
831
911
  }
832
- var str = (input, path = "$") => typeof input === "string" ? ok(input) : err(failure(path, "a string", input));
833
- var bool = (input, path = "$") => typeof input === "boolean" ? ok(input) : err(failure(path, "a boolean", input));
834
- var int64 = (input, path = "$") => {
835
- if (typeof input === "number" && Number.isInteger(input))
836
- return ok(BigInt(input));
837
- if (typeof input === "string" && /^-?[0-9]+$/.test(input))
838
- return ok(BigInt(input));
839
- return err(failure(path, "a 64-bit integer (a number or a decimal string)", input));
912
+
913
+ // src/state-record.ts
914
+ var ERGONEX_VERSION = "0.3.2";
915
+ var STATE_RECORD_PATH = ".ergonex/state.auto.json";
916
+ var EMPTY_RECORD = {
917
+ ergonex: ERGONEX_VERSION,
918
+ files: {},
919
+ firstSeen: {}
840
920
  };
841
- var count = (input, path = "$") => {
842
- const r = int64(input, path);
843
- if (r.kind === "err")
844
- return r;
845
- return r.value >= 0n && r.value <= BigInt(Number.MAX_SAFE_INTEGER) ? ok(Number(r.value)) : err(failure(path, "a count", input));
846
- };
847
- var double = (input, path = "$") => {
848
- if (typeof input === "number")
849
- return ok(input);
850
- if (input === "NaN")
851
- return ok(NaN);
852
- if (input === "Infinity")
853
- return ok(Infinity);
854
- if (input === "-Infinity")
855
- return ok(-Infinity);
856
- return err(failure(path, "a double", input));
857
- };
858
- var bytes = (input, path = "$") => {
859
- if (typeof input !== "string")
860
- return err(failure(path, "base64", input));
861
- const r = fromBase64(input);
862
- return r.kind === "ok" ? r : err(failure(path, "base64", input));
863
- };
864
- var traceId = (input, path = "$") => {
865
- const r = typeof input === "string" ? parseTraceId(input.toLowerCase()) : err("");
866
- return r.kind === "ok" ? r : err(failure(path, "a trace id (32 hexadecimal digits, not all zeros)", input));
867
- };
868
- var spanId = (input, path = "$") => {
869
- const r = typeof input === "string" ? parseSpanId(input.toLowerCase()) : err("");
870
- return r.kind === "ok" ? r : err(failure(path, "a span id (16 hexadecimal digits, not all zeros)", input));
921
+ var hash = (input, path = "$") => {
922
+ const s = typeof input === "string" ? sha256Of(input) : undefined;
923
+ return s === undefined ? err({
924
+ kind: "decode",
925
+ path,
926
+ expected: "a SHA-256 (64 hexadecimal digits)",
927
+ found: typeof input
928
+ }) : ok(s);
871
929
  };
872
- function enumeration(names) {
873
- return (input, path = "$") => {
874
- if (typeof input === "number" && Number.isInteger(input) && input >= 0 && input < names.length)
875
- return ok(input);
876
- if (typeof input === "string") {
877
- const i = names.indexOf(input);
878
- if (i >= 0)
879
- return ok(i);
930
+ var day = (input, path = "$") => typeof input === "string" && dayNumber(input) !== undefined ? ok(input) : err({
931
+ kind: "decode",
932
+ path,
933
+ expected: "a day (YYYY-MM-DD)",
934
+ found: typeof input
935
+ });
936
+ var shape = object({
937
+ ergonex: string,
938
+ files: record(object({ sha256: hash, generator: string })),
939
+ firstSeen: record(day)
940
+ }, { plan: hash });
941
+ function decodeStateRecord(text) {
942
+ const r = json(text, shape);
943
+ return r.kind === "ok" ? ok(r.value) : err(formatDecodeError(r.error));
944
+ }
945
+ function encodeStateRecord(r) {
946
+ const sorted = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
947
+ const value = {
948
+ _generated: headerText("ergonex state"),
949
+ ergonex: r.ergonex,
950
+ ...r.plan === undefined ? {} : { plan: r.plan },
951
+ files: sorted(r.files),
952
+ firstSeen: sorted(r.firstSeen)
953
+ };
954
+ return `${JSON.stringify(value, null, 2)}
955
+ `;
956
+ }
957
+ function withFile(r, file, digest) {
958
+ return {
959
+ ...r,
960
+ files: {
961
+ ...r.files,
962
+ [file.path]: { sha256: digest, generator: file.generator }
880
963
  }
881
- return err(failure(path, `one of ${names.join(", ")} or its number`, input));
882
964
  };
883
965
  }
884
- var spanKindEnum = enumeration([
885
- "SPAN_KIND_UNSPECIFIED",
886
- "SPAN_KIND_INTERNAL",
887
- "SPAN_KIND_SERVER",
888
- "SPAN_KIND_CLIENT",
889
- "SPAN_KIND_PRODUCER",
890
- "SPAN_KIND_CONSUMER"
891
- ]);
892
- var statusCodeEnum = enumeration(["STATUS_CODE_UNSET", "STATUS_CODE_OK", "STATUS_CODE_ERROR"]);
893
- var temporalityEnum = enumeration([
894
- "AGGREGATION_TEMPORALITY_UNSPECIFIED",
895
- "AGGREGATION_TEMPORALITY_DELTA",
896
- "AGGREGATION_TEMPORALITY_CUMULATIVE"
897
- ]);
898
- var SEVERITY_NAMES = ["SEVERITY_NUMBER_UNSPECIFIED"].concat(["TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"].flatMap((r) => ["", "2", "3", "4"].map((n) => `SEVERITY_NUMBER_${r}${n}`)));
899
- var severityEnum = (input, path = "$") => {
900
- const r = enumeration(SEVERITY_NAMES)(input, path);
901
- if (r.kind === "err")
902
- return r;
903
- return isSeverityNumber(r.value) ? ok(r.value) : err(failure(path, "a severity number from 1 to 24", input));
904
- };
905
- var decodeAnyValue = (input, path = "$") => {
906
- if (typeof input !== "object" || input === null || Array.isArray(input))
907
- return err(failure(path, "an AnyValue object", input));
908
- const has = (key) => {
909
- const v = Reflect.get(input, key);
910
- return v !== undefined && v !== null;
966
+ function withoutFile(r, path) {
967
+ return {
968
+ ...r,
969
+ files: Object.fromEntries(Object.entries(r.files).filter(([p]) => p !== path))
911
970
  };
912
- const at = (key) => Reflect.get(input, key);
913
- if (has("stringValue"))
914
- return str(at("stringValue"), `${path}.stringValue`);
915
- if (has("boolValue"))
916
- return bool(at("boolValue"), `${path}.boolValue`);
917
- if (has("intValue"))
918
- return int64(at("intValue"), `${path}.intValue`);
919
- if (has("doubleValue"))
920
- return double(at("doubleValue"), `${path}.doubleValue`);
921
- if (has("bytesValue"))
922
- return bytes(at("bytesValue"), `${path}.bytesValue`);
923
- if (has("arrayValue"))
924
- return message((f) => f.opt("values", list(decodeAnyValue), []))(at("arrayValue"), `${path}.arrayValue`);
925
- if (has("kvlistValue")) {
926
- return message((f) => {
927
- const out = {};
928
- for (const kv of f.opt("values", list(keyValue(decodeAnyValue)), [])) {
929
- Object.defineProperty(out, kv.key, { value: kv.value, enumerable: true, writable: true, configurable: true });
930
- }
931
- return out;
932
- })(at("kvlistValue"), `${path}.kvlistValue`);
933
- }
934
- return err(failure(path, "an AnyValue holding a value", input));
935
- };
936
- function keyValue(value) {
937
- return message((f) => ({ key: f.req("key", str), value: f.req("value", value) }));
938
971
  }
939
- var decodeAttributeValue = (input, path = "$") => {
940
- const r = decodeAnyValue(input, path);
941
- if (r.kind === "err")
942
- return r;
943
- const v = r.value;
944
- if (typeof v !== "object" || v instanceof Uint8Array)
945
- return ok(v);
946
- if (Array.isArray(v)) {
947
- const values = v;
948
- if (values.every((e) => typeof e === "string"))
949
- return ok(values.filter((e) => typeof e === "string"));
950
- if (values.every((e) => typeof e === "boolean"))
951
- return ok(values.filter((e) => typeof e === "boolean"));
952
- if (values.every((e) => typeof e === "bigint"))
953
- return ok(values.filter((e) => typeof e === "bigint"));
954
- if (values.every((e) => typeof e === "number"))
955
- return ok(values.filter((e) => typeof e === "number"));
972
+ function verifyFindings(facts, today) {
973
+ const out = [];
974
+ for (const f of facts) {
975
+ const at = (ruleId, severity, message) => void out.push({
976
+ ruleId,
977
+ severity,
978
+ message,
979
+ subject: f.path,
980
+ firstSeen: today
981
+ });
982
+ if (f.recorded !== undefined && f.onDisk === undefined) {
983
+ at("ergonex/generated-missing", "Warning", `${f.path} is recorded as written and is not there; run \`ergonex render\` to write it again`);
984
+ } else if (f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded) {
985
+ at("ergonex/generated-edited", "Error", `${f.path} was edited by hand (its bytes are not the ones recorded); \`ergonex render --force\` replaces it`);
986
+ } else if (f.recorded === undefined && f.onDisk !== undefined) {
987
+ at("ergonex/generated-unrecorded", "Warning", `${f.path} is a generated file the state record does not hold; run \`ergonex render\` to record it, or remove it`);
988
+ }
989
+ const edited = f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded;
990
+ const missing = f.recorded !== undefined && f.onDisk === undefined;
991
+ if (f.wanted !== undefined && f.onDisk !== f.wanted && !edited && !missing) {
992
+ at("ergonex/generated-drift", "Warning", f.onDisk === undefined ? `${f.path} is not written yet; run \`ergonex render\`` : `${f.path} would be written differently by the templates now; run \`ergonex render\``);
993
+ }
956
994
  }
957
- return err(failure(path, "an attribute value (a primitive or a homogeneous array of primitives)", input));
958
- };
959
- var decodeAttributes = (input, path = "$") => {
960
- const r = list(keyValue(decodeAttributeValue))(input, path);
961
- if (r.kind === "err")
962
- return r;
963
- const out = {};
964
- for (const kv of r.value)
965
- Object.defineProperty(out, kv.key, { value: kv.value, enumerable: true, writable: true, configurable: true });
966
- return ok(out);
967
- };
968
- var resource = message((f) => ({ attributes: f.opt("attributes", decodeAttributes, {}) }));
969
- var scope = message((f) => {
970
- const version = f.opt("version", str, undefined);
971
- const attributes = f.opt("attributes", decodeAttributes, undefined);
995
+ return out;
996
+ }
997
+ // ../terminal/src/args.ts
998
+ function flag(o) {
999
+ const negatable = o.negatable === true;
972
1000
  return {
973
- name: f.opt("name", str, ""),
974
- ...version === undefined ? {} : { version },
975
- ...attributes === undefined ? {} : { attributes }
1001
+ kind: "flag",
1002
+ short: o.short,
1003
+ help: o.help,
1004
+ negatable,
1005
+ fallback: negatable && o.default === undefined ? { kind: "none" } : { kind: "default", value: o.default ?? false }
976
1006
  };
977
- });
978
- var event = message((f) => ({
979
- name: f.opt("name", str, ""),
980
- time: f.opt("timeUnixNano", int64, 0n),
981
- attributes: f.opt("attributes", decodeAttributes, {}),
982
- droppedAttributesCount: f.opt("droppedAttributesCount", count, 0)
983
- }));
984
- var link = message((f) => ({
985
- traceId: f.req("traceId", traceId),
986
- spanId: f.req("spanId", spanId),
987
- traceState: parseTracestate(f.opt("traceState", str, "")),
988
- traceFlags: f.opt("flags", count, 0) & 255,
989
- attributes: f.opt("attributes", decodeAttributes, {}),
990
- droppedAttributesCount: f.opt("droppedAttributesCount", count, 0)
991
- }));
992
- var status = message((f) => {
993
- const code = f.opt("code", statusCodeEnum, 0);
994
- if (code === 1)
995
- return { kind: "ok" };
996
- if (code === 2)
997
- return { kind: "error", message: f.opt("message", str, "") };
998
- return { kind: "unset" };
999
- });
1000
- var optionalSpanId = (input, path = "$") => input === "" ? ok(undefined) : spanId(input, path);
1001
- var decodeSpan = message((f) => {
1002
- const parentSpanId = f.opt("parentSpanId", optionalSpanId, undefined);
1003
- const kind = f.opt("kind", spanKindEnum, 1);
1007
+ }
1008
+ function value(o) {
1004
1009
  return {
1005
- name: f.opt("name", str, ""),
1006
- context: {
1007
- traceId: f.req("traceId", traceId),
1008
- spanId: f.req("spanId", spanId),
1009
- traceFlags: f.opt("flags", count, 0) & 255,
1010
- traceState: parseTracestate(f.opt("traceState", str, "")),
1011
- isRemote: false
1012
- },
1013
- ...parentSpanId === undefined ? {} : { parentSpanId },
1014
- kind: SPAN_KINDS[kind - 1] ?? "internal",
1015
- startTime: f.opt("startTimeUnixNano", int64, 0n),
1016
- endTime: f.opt("endTimeUnixNano", int64, 0n),
1017
- attributes: f.opt("attributes", decodeAttributes, {}),
1018
- events: f.opt("events", list(event), []),
1019
- links: f.opt("links", list(link), []),
1020
- status: f.opt("status", status, { kind: "unset" }),
1021
- droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
1022
- droppedEventsCount: f.opt("droppedEventsCount", count, 0),
1023
- droppedLinksCount: f.opt("droppedLinksCount", count, 0)
1010
+ kind: "value",
1011
+ short: o.short,
1012
+ help: o.help,
1013
+ valueName: o.valueName ?? "VALUE",
1014
+ parse: o.parse ?? text,
1015
+ fallback: o.required === true ? { kind: "required" } : ("default" in o) ? { kind: "default", value: o.default } : { kind: "none" }
1024
1016
  };
1025
- });
1026
- var optionalTraceId = (input, path = "$") => input === "" ? ok(undefined) : traceId(input, path);
1027
- var decodeLogRecord = message((f) => {
1028
- const body = f.opt("body", decodeAnyValue, undefined);
1029
- const traceFlags = f.opt("flags", count, undefined);
1030
- const tid = f.opt("traceId", optionalTraceId, undefined);
1031
- const sid = f.opt("spanId", optionalSpanId, undefined);
1032
- const eventName = f.opt("eventName", str, undefined);
1033
- return {
1034
- time: f.opt("timeUnixNano", int64, 0n),
1035
- observedTime: f.opt("observedTimeUnixNano", int64, 0n),
1036
- severityNumber: f.req("severityNumber", severityEnum),
1037
- severityText: f.opt("severityText", str, ""),
1038
- ...body === undefined ? {} : { body },
1039
- attributes: f.opt("attributes", decodeAttributes, {}),
1040
- droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
1041
- ...eventName === undefined ? {} : { eventName },
1042
- ...tid === undefined ? {} : { traceId: tid },
1043
- ...sid === undefined ? {} : { spanId: sid },
1044
- ...traceFlags === undefined ? {} : { traceFlags: traceFlags & 255 }
1045
- };
1046
- });
1047
- var numberPoint = message((f, path) => {
1048
- const asInt = f.opt("asInt", int64, undefined);
1049
- const asDouble = f.opt("asDouble", double, undefined);
1050
- const value = asInt ?? asDouble;
1051
- if (value === undefined)
1052
- throw new Failure(failure(`${path}.asDouble`, "asInt or asDouble", undefined));
1053
- return {
1054
- attributes: f.opt("attributes", decodeAttributes, {}),
1055
- startTime: f.opt("startTimeUnixNano", int64, 0n),
1056
- time: f.opt("timeUnixNano", int64, 0n),
1057
- value
1058
- };
1059
- });
1060
- var histogramPoint = message((f, path) => {
1061
- const sum = f.opt("sum", double, undefined);
1062
- const min = f.opt("min", double, undefined);
1063
- const max = f.opt("max", double, undefined);
1064
- const bounds = f.opt("explicitBounds", list(double), []);
1065
- const bucketCounts = f.opt("bucketCounts", list(count), []);
1066
- if (bucketCounts.length !== 0 && bucketCounts.length !== bounds.length + 1) {
1067
- throw new Failure(failure(`${path}.bucketCounts`, `${bounds.length + 1} bucket counts`, bucketCounts.length));
1068
- }
1069
- return {
1070
- attributes: f.opt("attributes", decodeAttributes, {}),
1071
- startTime: f.opt("startTimeUnixNano", int64, 0n),
1072
- time: f.opt("timeUnixNano", int64, 0n),
1073
- count: f.opt("count", count, 0),
1074
- ...sum === undefined ? {} : { sum },
1075
- ...min === undefined ? {} : { min },
1076
- ...max === undefined ? {} : { max },
1077
- bounds,
1078
- bucketCounts
1079
- };
1080
- });
1081
- function temporalityOf(n) {
1082
- return n === 1 ? "delta" : "cumulative";
1083
1017
  }
1084
- var decodeMetric = message((f, path) => {
1085
- const head = { name: f.opt("name", str, ""), description: f.opt("description", str, ""), unit: f.opt("unit", str, "") };
1086
- const sum = f.opt("sum", message((g) => ({
1087
- kind: "sum",
1088
- points: g.opt("dataPoints", list(numberPoint), []),
1089
- temporality: temporalityOf(g.opt("aggregationTemporality", temporalityEnum, 2)),
1090
- monotonic: g.opt("isMonotonic", bool, false)
1091
- })), undefined);
1092
- if (sum !== undefined)
1093
- return { ...head, data: sum };
1094
- const gauge = f.opt("gauge", message((g) => ({ kind: "gauge", points: g.opt("dataPoints", list(numberPoint), []) })), undefined);
1095
- if (gauge !== undefined)
1096
- return { ...head, data: gauge };
1097
- const histogram = f.opt("histogram", message((g) => ({
1098
- kind: "histogram",
1099
- points: g.opt("dataPoints", list(histogramPoint), []),
1100
- temporality: temporalityOf(g.opt("aggregationTemporality", temporalityEnum, 2))
1101
- })), undefined);
1102
- if (histogram !== undefined)
1103
- return { ...head, data: histogram };
1104
- throw new Failure(failure(`${path}.sum`, "a sum, a gauge or a histogram", undefined));
1105
- });
1106
- // ../ts/kernel/palette.ts
1107
- var ESC = String.fromCharCode(27);
1108
- // ../ts/kernel/png.ts
1109
- var MAX_PIXELS = 2 ** 24;
1110
- var COLOUR_TYPES = new Map([
1111
- [0, { samples: 1, depths: [1, 2, 4, 8, 16], name: "greyscale" }],
1112
- [2, { samples: 3, depths: [8, 16], name: "RGB" }],
1113
- [3, { samples: 1, depths: [1, 2, 4, 8], name: "palette" }],
1114
- [4, { samples: 2, depths: [8, 16], name: "greyscale with alpha" }],
1115
- [6, { samples: 4, depths: [8, 16], name: "RGBA" }]
1116
- ]);
1117
- var PRECISION_BITS = 32 - 8 - 2;
1118
- var ONE = 2 ** PRECISION_BITS;
1119
- // ../ts/kernel/rdf-term.ts
1120
- var SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:/;
1121
- var FORBIDDEN = new Set([...'<>"{}|^`\\']);
1122
- function parseIri(text) {
1123
- for (let at = 0;at < text.length; at++) {
1124
- if (text.charCodeAt(at) <= 32 || FORBIDDEN.has(text.charAt(at)))
1125
- return err({ kind: "forbidden-character", text, at });
1126
- }
1127
- if (!SCHEME.test(text))
1128
- return err({ kind: "not-absolute", text });
1129
- return ok(text);
1018
+ var text = (t) => ok(t);
1019
+ function longName(key) {
1020
+ return `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1130
1021
  }
1131
- function formatIriError(e) {
1132
- switch (e.kind) {
1133
- case "not-absolute":
1134
- return `${JSON.stringify(e.text)} is not an absolute IRI: it has no scheme`;
1135
- case "forbidden-character":
1136
- return `${JSON.stringify(e.text)} is not an IRI: the character at ${e.at} may not be in one`;
1137
- default:
1138
- return absurd(e);
1022
+ function editDistance(a, b) {
1023
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
1024
+ for (let i = 1;i <= a.length; i++) {
1025
+ const row = [i];
1026
+ for (let j = 1;j <= b.length; j++) {
1027
+ row.push(Math.min((prev[j] ?? 0) + 1, (row[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1)));
1028
+ }
1029
+ prev = row;
1139
1030
  }
1031
+ return prev[b.length] ?? 0;
1140
1032
  }
1141
-
1142
- class RdfFault extends Error {
1143
- constructor(message) {
1144
- super(message);
1145
- this.name = "RdfFault";
1033
+ function suggest(word, candidates) {
1034
+ let best;
1035
+ let bestDistance = Number.POSITIVE_INFINITY;
1036
+ for (const c of candidates) {
1037
+ const d = editDistance(word, c);
1038
+ if (d < bestDistance) {
1039
+ best = c;
1040
+ bestDistance = d;
1041
+ }
1146
1042
  }
1043
+ return bestDistance <= Math.max(2, Math.floor(word.length / 2)) ? best : undefined;
1147
1044
  }
1148
- function checked(text) {
1149
- const r = parseIri(text);
1150
- if (r.kind === "err")
1151
- throw new RdfFault(formatIriError(r.error));
1152
- return r.value;
1153
- }
1154
- function named(iri) {
1155
- return { kind: "named", iri };
1156
- }
1157
- var PREFIX = /^(?:[A-Za-z][A-Za-z0-9_-]*)?$/;
1158
- function namespace(prefix, iri) {
1159
- if (!PREFIX.test(prefix))
1160
- throw new RdfFault(`${JSON.stringify(prefix)} is not a prefix`);
1161
- return { prefix, iri: checked(iri) };
1162
- }
1163
- function iriIn(ns, local) {
1164
- return checked(`${ns.iri}${local}`);
1165
- }
1166
- function vocabulary(ns, terms) {
1167
- const out = {};
1168
- for (const local of Object.keys(terms))
1169
- out[local] = { kind: "named", iri: iriIn(ns, local), curie: `${ns.prefix}:${local}` };
1170
- return out;
1171
- }
1172
- var XSD = "http://www.w3.org/2001/XMLSchema#";
1173
- var XSD_STRING = `${XSD}string`;
1174
- var XSD_INTEGER = `${XSD}integer`;
1175
- var XSD_BOOLEAN = `${XSD}boolean`;
1176
- var RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
1177
- var ESCAPES = new Map([
1178
- ["\b", "\\b"],
1179
- ["\t", "\\t"],
1180
- [`
1181
- `, "\\n"],
1182
- ["\f", "\\f"],
1183
- ["\r", "\\r"],
1184
- ['"', "\\\""],
1185
- ["\\", "\\\\"]
1186
- ]);
1187
- // ../ts/kernel/rdf-vocabularies.ts
1188
- var RDF = namespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
1189
- var rdf = vocabulary(RDF, {
1190
- type: "rdf:Property",
1191
- first: "rdf:Property",
1192
- rest: "rdf:Property",
1193
- value: "rdf:Property",
1194
- Property: "rdfs:Class",
1195
- List: "rdfs:Class",
1196
- nil: "rdf:List",
1197
- langString: "rdfs:Datatype"
1198
- });
1199
- var RDFS = namespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
1200
- var rdfs = vocabulary(RDFS, {
1201
- Resource: "rdfs:Class",
1202
- Class: "rdfs:Class",
1203
- Datatype: "rdfs:Class",
1204
- Literal: "rdfs:Class",
1205
- label: "rdf:Property",
1206
- comment: "rdf:Property",
1207
- domain: "rdf:Property",
1208
- range: "rdf:Property",
1209
- subClassOf: "rdf:Property",
1210
- subPropertyOf: "rdf:Property",
1211
- seeAlso: "rdf:Property",
1212
- isDefinedBy: "rdf:Property"
1213
- });
1214
- var OWL = namespace("owl", "http://www.w3.org/2002/07/owl#");
1215
- var owl = vocabulary(OWL, {
1216
- Ontology: "rdfs:Class",
1217
- Class: "rdfs:Class",
1218
- ObjectProperty: "rdfs:Class",
1219
- DatatypeProperty: "rdfs:Class",
1220
- AnnotationProperty: "rdfs:Class",
1221
- NamedIndividual: "rdfs:Class",
1222
- Thing: "rdfs:Class",
1223
- versionInfo: "rdf:Property",
1224
- versionIRI: "rdf:Property",
1225
- imports: "rdf:Property",
1226
- sameAs: "rdf:Property",
1227
- equivalentClass: "rdf:Property"
1228
- });
1229
- var XSD2 = namespace("xsd", "http://www.w3.org/2001/XMLSchema#");
1230
- var xsd = vocabulary(XSD2, {
1231
- string: "rdfs:Datatype",
1232
- boolean: "rdfs:Datatype",
1233
- integer: "rdfs:Datatype",
1234
- nonNegativeInteger: "rdfs:Datatype",
1235
- positiveInteger: "rdfs:Datatype",
1236
- decimal: "rdfs:Datatype",
1237
- double: "rdfs:Datatype",
1238
- date: "rdfs:Datatype",
1239
- dateTime: "rdfs:Datatype",
1240
- duration: "rdfs:Datatype",
1241
- anyURI: "rdfs:Datatype",
1242
- language: "rdfs:Datatype"
1243
- });
1244
- var SKOS = namespace("skos", "http://www.w3.org/2004/02/skos/core#");
1245
- var skos = vocabulary(SKOS, {
1246
- Concept: "rdfs:Class",
1247
- ConceptScheme: "rdfs:Class",
1248
- Collection: "rdfs:Class",
1249
- inScheme: "rdf:Property",
1250
- hasTopConcept: "rdf:Property",
1251
- topConceptOf: "rdf:Property",
1252
- prefLabel: "rdf:Property",
1253
- altLabel: "rdf:Property",
1254
- definition: "rdf:Property",
1255
- notation: "rdf:Property",
1256
- broader: "rdf:Property",
1257
- narrower: "rdf:Property",
1258
- related: "rdf:Property",
1259
- note: "rdf:Property",
1260
- scopeNote: "rdf:Property",
1261
- example: "rdf:Property"
1262
- });
1263
- var DCTERMS = namespace("dcterms", "http://purl.org/dc/terms/");
1264
- var dcterms = vocabulary(DCTERMS, {
1265
- identifier: "rdf:Property",
1266
- title: "rdf:Property",
1267
- description: "rdf:Property",
1268
- source: "rdf:Property",
1269
- license: "rdf:Property",
1270
- created: "rdf:Property",
1271
- modified: "rdf:Property",
1272
- date: "rdf:Property",
1273
- creator: "rdf:Property",
1274
- publisher: "rdf:Property",
1275
- isPartOf: "rdf:Property",
1276
- hasPart: "rdf:Property",
1277
- references: "rdf:Property",
1278
- conformsTo: "rdf:Property",
1279
- Standard: "rdfs:Class"
1280
- });
1281
- var PROV = namespace("prov", "http://www.w3.org/ns/prov#");
1282
- var prov = vocabulary(PROV, {
1283
- Entity: "rdfs:Class",
1284
- Activity: "rdfs:Class",
1285
- Agent: "rdfs:Class",
1286
- Person: "rdfs:Class",
1287
- Organization: "rdfs:Class",
1288
- SoftwareAgent: "rdfs:Class",
1289
- wasGeneratedBy: "rdf:Property",
1290
- wasDerivedFrom: "rdf:Property",
1291
- wasAttributedTo: "rdf:Property",
1292
- wasAssociatedWith: "rdf:Property",
1293
- wasInformedBy: "rdf:Property",
1294
- actedOnBehalfOf: "rdf:Property",
1295
- used: "rdf:Property",
1296
- startedAtTime: "rdf:Property",
1297
- endedAtTime: "rdf:Property",
1298
- generatedAtTime: "rdf:Property",
1299
- atLocation: "rdf:Property",
1300
- value: "rdf:Property"
1301
- });
1302
- var SH = namespace("sh", "http://www.w3.org/ns/shacl#");
1303
- var sh = vocabulary(SH, {
1304
- NodeShape: "rdfs:Class",
1305
- PropertyShape: "rdfs:Class",
1306
- targetClass: "rdf:Property",
1307
- property: "rdf:Property",
1308
- path: "rdf:Property",
1309
- datatype: "rdf:Property",
1310
- class: "rdf:Property",
1311
- node: "rdf:Property",
1312
- minCount: "rdf:Property",
1313
- maxCount: "rdf:Property",
1314
- pattern: "rdf:Property",
1315
- in: "rdf:Property",
1316
- order: "rdf:Property",
1317
- name: "rdf:Property",
1318
- description: "rdf:Property"
1319
- });
1320
- // ../ts/kernel/rdf-schema.ts
1321
- function rangeOf(kind, words) {
1322
- return words === undefined ? { kind } : { kind, words };
1323
- }
1324
- var range = {
1325
- string: rangeOf("string"),
1326
- langString: rangeOf("lang"),
1327
- text: rangeOf("text"),
1328
- boolean: rangeOf("boolean"),
1329
- integer: rangeOf("integer"),
1330
- ref: () => rangeOf("ref"),
1331
- oneOf: (words) => rangeOf("string", words)
1332
- };
1333
- function one(property, r) {
1334
- return { property, range: r, cardinality: "one" };
1335
- }
1336
- function optional(property, r) {
1337
- return { property, range: r, cardinality: "optional" };
1338
- }
1339
- function many(property, r) {
1340
- return { property, range: r, cardinality: "many" };
1341
- }
1342
- function isValue(x) {
1343
- return typeof x === "string" || typeof x === "number" || typeof x === "boolean" || typeof x === "object" && x !== null && "kind" in x;
1045
+ function asksHelp(word) {
1046
+ return word === "--help" || /^-[A-Za-z]*h[A-Za-z]*$/.test(word);
1344
1047
  }
1345
- function valuesIn(x) {
1346
- if (x === undefined)
1347
- return [];
1348
- if (Array.isArray(x))
1349
- return x.filter(isValue);
1350
- return isValue(x) ? [x] : [];
1048
+ function operandWord(o) {
1049
+ switch (o.arity) {
1050
+ case "one":
1051
+ return o.name;
1052
+ case "optional":
1053
+ return `[${o.name}]`;
1054
+ case "many":
1055
+ return `[${o.name}...]`;
1056
+ default:
1057
+ return absurd(o.arity);
1058
+ }
1351
1059
  }
1352
- function classSchema(cls, fields) {
1353
- const klass = named(cls.iri);
1354
- return {
1355
- class: klass,
1356
- curie: cls.curie,
1357
- fields,
1358
- make: (subject, values) => {
1359
- const own = values;
1360
- const statements = [{ predicate: named(RDF_TYPE), objects: [klass] }];
1361
- for (const [name, f] of Object.entries(fields)) {
1362
- const objects = valuesIn(own[name]);
1363
- if (objects.length === 0)
1364
- continue;
1365
- statements.push(f.range.words === undefined ? { predicate: f.property, objects } : { predicate: f.property, objects, words: f.range.words });
1366
- }
1367
- const made = { ...named(subject.iri), class: klass, values, statements };
1368
- return made;
1060
+ function parseArgs(argv, spec, operands = []) {
1061
+ const end = argv.indexOf("--");
1062
+ if ((end < 0 ? argv : argv.slice(0, end)).some(asksHelp))
1063
+ return ok({ kind: "help" });
1064
+ const entries = Object.keys(spec).flatMap((key) => {
1065
+ const option = spec[key];
1066
+ return option === undefined ? [] : [{ key, long: longName(key), option }];
1067
+ });
1068
+ const longs = [
1069
+ ...entries.flatMap((e) => e.option.kind === "flag" && e.option.negatable ? [e.long, `--no-${e.long.slice(2)}`] : [e.long]),
1070
+ "--help"
1071
+ ];
1072
+ const given = new Map;
1073
+ const listed = new Map;
1074
+ const positionals = [];
1075
+ let rest = [];
1076
+ let i = 0;
1077
+ const take = (e, written, inline, negated) => {
1078
+ const o = e.option;
1079
+ if (o.kind !== "many" && given.has(e.key))
1080
+ return { kind: "repeated-option", option: e.long };
1081
+ if (o.kind === "flag") {
1082
+ if (inline !== undefined)
1083
+ return { kind: "unexpected-value", option: written, value: inline };
1084
+ given.set(e.key, !negated);
1085
+ return;
1086
+ }
1087
+ const t = inline ?? argv[++i];
1088
+ if (t === undefined)
1089
+ return { kind: "missing-value", option: written };
1090
+ const parsed = o.parse(t);
1091
+ if (parsed.kind === "err") {
1092
+ const reason = typeof parsed.error === "string" ? parsed.error : `expected ${parsed.error.expected}, found ${parsed.error.found}`;
1093
+ return { kind: "invalid-value", option: written, value: t, reason };
1369
1094
  }
1095
+ if (o.kind === "value")
1096
+ given.set(e.key, parsed.value);
1097
+ else
1098
+ listed.set(e.key, [...listed.get(e.key) ?? [], parsed.value]);
1099
+ return;
1370
1100
  };
1371
- }
1372
- var OwlOntology = classSchema(owl.Ontology, {
1373
- label: optional(rdfs.label, range.langString),
1374
- comment: optional(rdfs.comment, range.langString),
1375
- description: optional(dcterms.description, range.langString),
1376
- versionInfo: optional(owl.versionInfo, range.string),
1377
- versionIri: optional(owl.versionIRI, range.ref())
1378
- });
1379
- var OwlClass = classSchema(owl.Class, {
1380
- label: optional(rdfs.label, range.langString),
1381
- comment: optional(rdfs.comment, range.langString),
1382
- subClassOf: many(rdfs.subClassOf, range.ref()),
1383
- definition: optional(skos.definition, range.langString)
1384
- });
1385
- var PROPERTY = {
1386
- label: optional(rdfs.label, range.langString),
1387
- comment: optional(rdfs.comment, range.langString),
1388
- domain: optional(rdfs.domain, range.ref()),
1389
- range: optional(rdfs.range, range.ref()),
1390
- definition: optional(skos.definition, range.langString)
1391
- };
1392
- var ObjectProperty = classSchema(owl.ObjectProperty, PROPERTY);
1393
- var DatatypeProperty = classSchema(owl.DatatypeProperty, PROPERTY);
1394
- var ConceptSchemeSchema = classSchema(skos.ConceptScheme, {
1395
- prefLabel: one(skos.prefLabel, range.langString),
1396
- definition: optional(skos.definition, range.langString)
1397
- });
1398
- var ConceptSchema = classSchema(skos.Concept, {
1399
- inScheme: one(skos.inScheme, range.ref()),
1400
- notation: one(skos.notation, range.string),
1401
- prefLabel: one(skos.prefLabel, range.langString),
1402
- definition: optional(skos.definition, range.langString)
1403
- });
1404
- // ../ts/kernel/signals.ts
1405
- var ATTRIBUTE_TYPES = new Set([
1406
- "string",
1407
- "boolean",
1408
- "int",
1409
- "double",
1410
- "bytes",
1411
- "string[]",
1412
- "boolean[]",
1413
- "int[]",
1414
- "double[]"
1415
- ]);
1416
- function defineSignals(kinds) {
1417
- for (const [name, d] of Object.entries(kinds)) {
1418
- const declared = new Set(Object.keys(d.attributes).map((k) => k.replace(/\?$/, "")));
1419
- for (const [k, t] of Object.entries(d.attributes)) {
1420
- if (!ATTRIBUTE_TYPES.has(t))
1421
- throw new Error(`${name}: the attribute ${k} has the type ${t}, which does not exist`);
1101
+ for (;i < argv.length; i++) {
1102
+ const word = argv[i] ?? "";
1103
+ if (word === "--") {
1104
+ rest = argv.slice(i + 1);
1105
+ break;
1422
1106
  }
1423
- for (const s of d.secret ?? [])
1424
- if (!declared.has(s))
1425
- throw new Error(`${name}: the secret attribute ${s} is not declared`);
1426
- if (d.signal === "histogram" && d.bounds !== undefined) {
1427
- const b = d.bounds;
1428
- if (b.some((x, i) => !Number.isFinite(x) || i > 0 && x <= (b[i - 1] ?? -Infinity))) {
1429
- throw new Error(`${name}: the histogram bounds do not increase`);
1430
- }
1107
+ if (word.startsWith("--")) {
1108
+ const eq = word.indexOf("=");
1109
+ const name = eq < 0 ? word : word.slice(0, eq);
1110
+ const inline = eq < 0 ? undefined : word.slice(eq + 1);
1111
+ if (name === "--help")
1112
+ return err({ kind: "unexpected-value", option: name, value: inline ?? "" });
1113
+ const direct = entries.find((e) => e.long === name);
1114
+ const positive = name.startsWith("--no-") ? entries.find((e) => e.long === `--${name.slice(5)}`) : undefined;
1115
+ const negated = direct === undefined && positive !== undefined && positive.option.kind === "flag" && positive.option.negatable;
1116
+ const e = direct ?? (negated ? positive : undefined);
1117
+ if (e === undefined)
1118
+ return err({ kind: "unknown-option", option: name, suggestion: suggest(name, longs) });
1119
+ const problem = take(e, name, inline, negated);
1120
+ if (problem !== undefined)
1121
+ return err(problem);
1122
+ continue;
1431
1123
  }
1432
- }
1433
- return { kinds };
1434
- }
1435
-
1436
- // ../ts/kernel/width.ts
1437
- var ESC2 = String.fromCharCode(27);
1438
- var BEL = String.fromCharCode(7);
1439
- var ESCAPE = new RegExp(`${ESC2}(?:\\[[0-?]*[ -/]*[@-~]?|[\\]PX^_][^${BEL}${ESC2}]*(?:${BEL}|${ESC2}\\\\)?|[ -/]*[0-~]|)`, "g");
1440
- var segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
1441
- var SGR = new RegExp(`^${ESC2}\\[([0-9;:]*)m$`);
1442
- var RESET = `${ESC2}[0m`;
1443
-
1444
- // ../ts/kernel/render.ts
1445
- var ESC3 = String.fromCharCode(27);
1446
- var CONTROL = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}-${String.fromCharCode(159)}]`, "g");
1447
- // ../ts/kernel/xml.ts
1448
- var FORBIDDEN2 = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11, 12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}\\ufffe\\uffff]`, "g");
1449
- // ../ts/kernel/sigv4.ts
1450
- var UNSIGNED_HEADERS = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id", "traceparent", "tracestate"]);
1451
- var encoder = new TextEncoder;
1452
- // ../ts/kernel/test-report.ts
1453
- var STYLE = "body{font:15px/1.5 system-ui,sans-serif;margin:2rem auto;max-width:72rem;padding:0 1rem;color:#1b1b1b;background:#fff}" + "table{border-collapse:collapse;margin:.5rem 0;width:100%}th,td{border:1px solid #c8c8c8;padding:.25rem .5rem;text-align:left;vertical-align:top;overflow-wrap:anywhere}" + "th{background:#f0f0f0}h1{font-size:1.6rem}h2{font-size:1.2rem;margin-top:2rem}" + "@media (prefers-color-scheme:dark){body{color:#e8e8e8;background:#161616}th{background:#2a2a2a}th,td{border-color:#444}}";
1454
- // ../ts/kernel/toml.ts
1455
- var CONTROL2 = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8, 10)}-${String.fromCharCode(31, 127)}]`);
1456
- // ../ts/kernel/webauthn.ts
1457
- var clientData = object({ type: string, challenge: string, origin: string }, { crossOrigin: boolean, topOrigin: string });
1458
- var kind = literal("public-key");
1459
- var extensionResults = record(unknownValue);
1460
- // src/portable.ts
1461
- function describePortableError(e) {
1124
+ if (word.length < 2 || !word.startsWith("-") || /^-[0-9]/.test(word)) {
1125
+ positionals.push(word);
1126
+ continue;
1127
+ }
1128
+ for (let j = 1;j < word.length; j++) {
1129
+ const letter = word.charAt(j);
1130
+ const written = `-${letter}`;
1131
+ const e = entries.find((x) => x.option.short === letter);
1132
+ if (e === undefined)
1133
+ return err({ kind: "unknown-option", option: written, suggestion: suggest(`-${word}`, longs) });
1134
+ const after = word.slice(j + 1);
1135
+ if (e.option.kind === "flag") {
1136
+ if (after.startsWith("="))
1137
+ return err({ kind: "unexpected-value", option: written, value: after.slice(1) });
1138
+ } else if (after !== "") {
1139
+ return err({ kind: "attached-value", option: written, word });
1140
+ }
1141
+ const problem = take(e, written, undefined, false);
1142
+ if (problem !== undefined)
1143
+ return err(problem);
1144
+ }
1145
+ }
1146
+ const values = [];
1147
+ for (const e of entries) {
1148
+ const o = e.option;
1149
+ switch (o.kind) {
1150
+ case "many":
1151
+ values.push([e.key, listed.get(e.key) ?? []]);
1152
+ break;
1153
+ case "flag":
1154
+ case "value": {
1155
+ if (given.has(e.key)) {
1156
+ values.push([e.key, given.get(e.key)]);
1157
+ break;
1158
+ }
1159
+ const f = o.fallback;
1160
+ switch (f.kind) {
1161
+ case "none":
1162
+ values.push([e.key, undefined]);
1163
+ break;
1164
+ case "default":
1165
+ values.push([e.key, f.value]);
1166
+ break;
1167
+ case "required":
1168
+ return err({ kind: "missing-option", option: e.long });
1169
+ default:
1170
+ return absurd(f);
1171
+ }
1172
+ break;
1173
+ }
1174
+ default:
1175
+ return absurd(o);
1176
+ }
1177
+ }
1178
+ const least = operands.filter((o) => o.arity === "one");
1179
+ const most = operands.some((o) => o.arity === "many") ? Number.POSITIVE_INFINITY : operands.filter((o) => o.arity !== "many").length;
1180
+ const missing = least[positionals.length];
1181
+ if (missing !== undefined)
1182
+ return err({ kind: "missing-argument", argument: missing.name });
1183
+ const extra = positionals[most];
1184
+ if (extra !== undefined)
1185
+ return err({ kind: "unexpected-argument", argument: extra, takes: operands.map(operandWord) });
1186
+ const options = Object.fromEntries(values);
1187
+ return ok({ kind: "args", options, positionals, rest });
1188
+ }
1189
+ function formatUsageError(e, command = "this command") {
1462
1190
  switch (e.kind) {
1463
- case "empty":
1464
- return "a path segment is empty";
1465
- case "dot":
1466
- return `the path segment ${JSON.stringify(e.segment)} would leave its folder`;
1467
- case "forbidden-character":
1468
- return `the path segment ${JSON.stringify(e.segment)} holds ${JSON.stringify(e.character)}, which Windows does not allow in a name`;
1469
- case "control-character":
1470
- return `the path segment ${JSON.stringify(e.segment)} holds a control character`;
1471
- case "trailing-dot-or-space":
1472
- return `the path segment ${JSON.stringify(e.segment)} ends in a dot or a space, which Windows drops`;
1473
- case "device-name":
1474
- return `the path segment ${JSON.stringify(e.segment)} is the Windows device name ${e.device}, with or without an extension, in any case`;
1475
- case "too-long":
1476
- return `the path segment is ${e.bytes} bytes in UTF-8, and a name may have 255`;
1477
- case "not-nfc":
1478
- return `the path segment ${JSON.stringify(e.segment)} is not in Unicode normalization form NFC, so it would be another name on macOS`;
1191
+ case "unknown-option":
1192
+ return `${e.option} is not an option of ${command}${e.suggestion === undefined ? "" : `; did you mean ${e.suggestion}?`}`;
1193
+ case "missing-value":
1194
+ return `${e.option} needs a value`;
1195
+ case "unexpected-value":
1196
+ return `${e.option} takes no value, but was given ${JSON.stringify(e.value)}`;
1197
+ case "attached-value":
1198
+ return `${e.option} takes its value as the next word, not attached as in ${e.word}`;
1199
+ case "invalid-value":
1200
+ return `${JSON.stringify(e.value)} is not a valid value of ${e.option}: ${e.reason}`;
1201
+ case "repeated-option":
1202
+ return `${e.option} is given more than once`;
1203
+ case "missing-option":
1204
+ return `${e.option} is required`;
1205
+ case "missing-argument":
1206
+ return `${command} needs ${e.argument}`;
1207
+ case "unexpected-argument":
1208
+ return `${command} does not take ${e.argument}: ${e.takes.length === 0 ? "it takes no arguments" : `it takes ${e.takes.join(" ")}`}`;
1479
1209
  default:
1480
1210
  return absurd(e);
1481
1211
  }
1482
1212
  }
1483
- var FORBIDDEN3 = new Set(["<", ">", ":", '"', "/", "\\", "|", "?", "*"]);
1484
- var DEVICE = /^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[0-9\u00b9\u00b2\u00b3]|LPT[0-9\u00b9\u00b2\u00b3])$/i;
1485
- function isDeviceName(name) {
1486
- return DEVICE.test((name.split(".")[0] ?? "").replace(/ +$/, ""));
1487
- }
1488
- var MAX_SEGMENT_BYTES = 255;
1489
- function segment(text) {
1490
- if (text === "")
1491
- return err({ kind: "empty" });
1492
- if (text === "." || text === "..")
1493
- return err({ kind: "dot", segment: text });
1494
- for (const ch of text) {
1495
- const code = ch.codePointAt(0) ?? 0;
1496
- if (code < 32 || code === 127)
1497
- return err({ kind: "control-character", segment: text });
1498
- if (FORBIDDEN3.has(ch))
1499
- return err({ kind: "forbidden-character", segment: text, character: ch });
1500
- }
1501
- if (text.endsWith(".") || text.endsWith(" "))
1502
- return err({ kind: "trailing-dot-or-space", segment: text });
1503
- const stem = (text.split(".")[0] ?? "").replace(/ +$/, "");
1504
- if (isDeviceName(text))
1505
- return err({
1506
- kind: "device-name",
1507
- segment: text,
1508
- device: stem.toUpperCase()
1509
- });
1510
- const bytes = new TextEncoder().encode(text).length;
1511
- if (bytes > MAX_SEGMENT_BYTES)
1512
- return err({ kind: "too-long", segment: text.slice(0, 40), bytes });
1513
- if (text !== text.normalize("NFC"))
1514
- return err({ kind: "not-nfc", segment: text });
1515
- return ok(text);
1213
+ function shown(v) {
1214
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : JSON.stringify(v);
1516
1215
  }
1517
- function repoPath(segments) {
1518
- if (segments.length === 0)
1519
- return err({ kind: "empty" });
1520
- const made = [];
1521
- for (const s of segments) {
1522
- const r = segment(s);
1523
- if (r.kind === "err")
1524
- return r;
1525
- made.push(r.value);
1216
+ function optionLine(e) {
1217
+ const o = e.option;
1218
+ const short = o.short === undefined ? " " : `-${o.short}, `;
1219
+ switch (o.kind) {
1220
+ case "flag":
1221
+ return {
1222
+ left: `${short}${o.negatable ? `--[no-]${e.long.slice(2)}` : e.long}`,
1223
+ note: o.negatable && o.fallback.kind === "default" ? ` (default: ${o.fallback.value ? e.long : `--no-${e.long.slice(2)}`})` : ""
1224
+ };
1225
+ case "value": {
1226
+ const f = o.fallback;
1227
+ const note = f.kind === "default" ? ` (default: ${shown(f.value)})` : f.kind === "required" ? " (required)" : "";
1228
+ return { left: `${short}${e.long} ${o.valueName}`, note };
1229
+ }
1230
+ case "many":
1231
+ return { left: `${short}${e.long} ${o.valueName}`, note: " (repeatable)" };
1232
+ default:
1233
+ return absurd(o);
1526
1234
  }
1527
- return ok(made.join("/"));
1528
- }
1529
- function segmentsOf(path) {
1530
- return path.split("/");
1531
- }
1532
- function child2(path, name) {
1533
- return `${path}/${name}`;
1534
- }
1535
- function nativePath(root, path, separator) {
1536
- const base = root.replace(/[\\/]+$/, "");
1537
- return [base, ...segmentsOf(path)].join(separator);
1538
- }
1539
- function foldKey(path) {
1540
- return path.normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
1541
1235
  }
1542
- function collisions(items) {
1543
- const groups = new Map;
1544
- for (const item of items) {
1545
- const key = foldKey(item.path);
1546
- const group = groups.get(key);
1547
- if (group === undefined)
1548
- groups.set(key, [{ ...item }]);
1549
- else
1550
- group.push({ ...item });
1551
- }
1552
- return [...groups.entries()].filter(([, members]) => members.length > 1).map(([key, members]) => ({ key, members }));
1236
+ function columns(rows) {
1237
+ const width = Math.max(0, ...rows.map(([l]) => l.length));
1238
+ return rows.map(([l, r]) => ` ${l.padEnd(width)} ${r}`.trimEnd());
1553
1239
  }
1554
- var WINDOWS_PATH_LIMIT = 259;
1555
- function checkPathLength(windowsPath, longPathsEnabled) {
1556
- if (longPathsEnabled || windowsPath.length <= WINDOWS_PATH_LIMIT)
1557
- return ok(windowsPath);
1558
- return err({
1559
- kind: "path-too-long",
1560
- path: windowsPath,
1561
- length: windowsPath.length,
1562
- limit: WINDOWS_PATH_LIMIT
1240
+ function helpOf(program, summary, spec, operands = []) {
1241
+ const entries = Object.keys(spec).flatMap((key) => {
1242
+ const option = spec[key];
1243
+ return option === undefined ? [] : [{ key, long: longName(key), option }];
1563
1244
  });
1245
+ const required = entries.flatMap((e) => e.option.kind === "value" && e.option.fallback.kind === "required" ? [`${e.long} ${e.option.valueName}`] : []);
1246
+ const usage = [program, "[OPTIONS]", ...required, ...operands.map(operandWord)].join(" ");
1247
+ const rows = entries.map((e) => {
1248
+ const line = optionLine(e);
1249
+ return [line.left, `${e.option.help}${line.note}`];
1250
+ });
1251
+ return [
1252
+ `${program}: ${summary}`,
1253
+ "",
1254
+ `Usage: ${usage}`,
1255
+ "",
1256
+ "Options:",
1257
+ ...columns([...rows, ["-h, --help", "Show this help and do nothing else."]]),
1258
+ ...operands.length === 0 ? [] : ["", "Arguments:", ...columns(operands.map((o) => [operandWord(o), o.help]))]
1259
+ ].join(`
1260
+ `);
1564
1261
  }
1565
- var REPO_PATH_ROOM = 150;
1566
- function repoPathLength(root, path, separator) {
1567
- const length = nativePath(root, path, separator).length;
1568
- if (length > WINDOWS_PATH_LIMIT)
1569
- return { kind: "too-long", length };
1570
- if (length > REPO_PATH_ROOM)
1571
- return { kind: "no-room", length };
1572
- return { kind: "fits", length };
1573
- }
1574
-
1575
- // src/render.ts
1576
- function describeGenerateError(e) {
1262
+ // src/modules/name.ts
1263
+ var MAX_MODULE_NAME = 32;
1264
+ function describeNameError(e) {
1577
1265
  switch (e.kind) {
1578
- case "bad-path":
1579
- return `${JSON.stringify(e.path)} cannot be the path of a generated file: ${e.reason}`;
1580
- case "not-auto":
1581
- return `${e.path} is a generated file whose name does not carry .auto. (only a Git hook in .ergonex/hooks/ may lack it)`;
1582
- case "collision":
1583
- return `${e.path} is the same path as ${e.other} after Unicode normalization and case folding; both are refused`;
1584
- case "inside-repository":
1585
- return `${e.path} is inside the working tree of ${e.repository}; a generated file is never written into a repository`;
1586
- case "bad-data":
1587
- return `${e.what}: ${e.reason}`;
1266
+ case "empty":
1267
+ return "a module name is not empty";
1268
+ case "too-long":
1269
+ return `a module name has at most ${MAX_MODULE_NAME} characters, not ${e.length}`;
1270
+ case "bad-start":
1271
+ return `${JSON.stringify(e.text)} does not begin with a lower-case letter, as a module name must`;
1272
+ case "bad-character":
1273
+ return `${JSON.stringify(e.text)} holds ${JSON.stringify(e.character)}, and a module name is lower-case letters, digits and hyphens`;
1588
1274
  default:
1589
1275
  return absurd(e);
1590
1276
  }
1591
1277
  }
1592
- var HOOKS_FOLDER = ".ergonex/hooks";
1593
- function headerText(generator) {
1594
- return `Generated by ${generator}. Do not edit by hand: change workspace.ts and run \`ergonex render\`.`;
1595
- }
1596
- function normalizeText(text) {
1597
- const lf = text.replace(/^/, "").replaceAll(`\r
1598
- `, `
1599
- `).replaceAll("\r", `
1600
- `);
1601
- return `${lf.replace(/\n+$/, "")}
1602
- `;
1603
- }
1604
- function isAutoName(name) {
1605
- return name.includes(".auto.") || name.endsWith(".auto");
1278
+ function moduleName(text) {
1279
+ if (text === "")
1280
+ return err({ kind: "empty" });
1281
+ if (text.length > MAX_MODULE_NAME)
1282
+ return err({ kind: "too-long", length: text.length });
1283
+ if (!/^[a-z]/.test(text))
1284
+ return err({ kind: "bad-start", text });
1285
+ const bad = /[^a-z0-9-]/u.exec(text);
1286
+ if (bad !== null)
1287
+ return err({ kind: "bad-character", text, character: bad[0] });
1288
+ return ok(text);
1606
1289
  }
1607
- function generatedPath(path) {
1608
- const made = repoPath(path.split("/"));
1609
- if (made.kind === "err")
1610
- return err({
1611
- kind: "bad-path",
1612
- path,
1613
- reason: describePortableError(made.error)
1614
- });
1615
- return made;
1290
+ function nearestNames(word, names) {
1291
+ return names.map((n) => ({ n, d: editDistance(word, n) })).filter((x) => x.d <= 2).sort((a, b) => a.d - b.d || (a.n < b.n ? -1 : a.n > b.n ? 1 : 0)).slice(0, 3).map((x) => x.n);
1616
1292
  }
1617
- var noBom = (text) => text.replace(/^\uFEFF/, "");
1618
- function contentOf(body, generator) {
1619
- const header = headerText(generator);
1620
- switch (body.format) {
1621
- case "json":
1622
- return normalizeText(JSON.stringify({ _generated: header, ...body.value }, null, 2));
1623
- case "markdown":
1624
- return normalizeText(`<!-- ${header} -->
1625
1293
 
1626
- ${noBom(body.text)}`);
1627
- case "yaml":
1628
- case "gitconfig":
1629
- case "envrc":
1630
- return normalizeText(`# ${header}
1631
-
1632
- ${noBom(body.text)}`);
1633
- case "sh": {
1634
- const text = noBom(body.text);
1635
- const m = /^(#![^\n]*)\n/.exec(text);
1636
- return m === null ? normalizeText(`# ${header}
1637
- ${text}`) : normalizeText(`${m[1]}
1638
- # ${header}
1639
- ${text.slice(m[0].length)}`);
1640
- }
1641
- default:
1642
- return absurd(body);
1294
+ // src/modules/external.ts
1295
+ var CONTRACT_VERSION = 1;
1296
+ var FIELDS = {
1297
+ contract: {
1298
+ type: "integer",
1299
+ description: "The version of this contract the module speaks."
1300
+ },
1301
+ name: {
1302
+ type: "string",
1303
+ description: "The module's name, as `ergonex <name>` runs it."
1304
+ },
1305
+ summary: {
1306
+ type: "string",
1307
+ description: "One sentence on what the module does."
1308
+ },
1309
+ commands: { type: "array", description: "The commands the module has." }
1310
+ };
1311
+ var COMMAND_FIELDS = {
1312
+ name: { type: "string", description: "The command's name." },
1313
+ summary: {
1314
+ type: "string",
1315
+ description: "One sentence on what the command does."
1643
1316
  }
1317
+ };
1318
+ var commandDecoder = object({
1319
+ name: string,
1320
+ summary: string
1321
+ });
1322
+ var manifestDecoder = object({
1323
+ contract: integer,
1324
+ name: string,
1325
+ summary: string,
1326
+ commands: array(commandDecoder)
1327
+ });
1328
+ function decodeExternalManifest(text) {
1329
+ const r = json(text, manifestDecoder);
1330
+ if (r.kind === "err")
1331
+ return err(formatDecodeError(r.error));
1332
+ const m = r.value;
1333
+ if (m.contract !== CONTRACT_VERSION)
1334
+ return err(`the module speaks contract ${m.contract}, and this ergonex speaks ${CONTRACT_VERSION}`);
1335
+ const name = moduleName(m.name);
1336
+ if (name.kind === "err")
1337
+ return err(`the module names itself ${JSON.stringify(m.name)}, which is not a module name`);
1338
+ return ok(m);
1644
1339
  }
1645
- function generated(path, body, options) {
1646
- const made = generatedPath(path);
1647
- if (made.kind === "err")
1648
- return made;
1649
- const name = made.value.split("/").at(-1) ?? "";
1650
- const isHook = made.value.startsWith(`${HOOKS_FOLDER}/`) && made.value.split("/").length === 3;
1651
- if (!isAutoName(name) && !isHook)
1652
- return err({ kind: "not-auto", path });
1653
- return ok({
1654
- path: made.value,
1655
- content: contentOf(body, options.generator),
1656
- mode: options.mode ?? "0644",
1657
- generator: options.generator
1340
+ function externalManifestSchema() {
1341
+ const property = (f) => ({
1342
+ type: f.type,
1343
+ description: f.description
1658
1344
  });
1659
- }
1660
- function fileDigest(file) {
1661
- return sha256(file.content);
1662
- }
1663
- function checkFiles(files, repositories) {
1664
- const errors = [];
1665
- for (const c of collisions(files.map((f) => ({ id: f.path, path: f.path })))) {
1666
- for (const m of c.members) {
1667
- const other = c.members.find((o) => o !== m);
1668
- errors.push({
1669
- kind: "collision",
1670
- path: m.path,
1671
- other: other?.path ?? m.path
1672
- });
1345
+ return {
1346
+ $schema: "https://json-schema.org/draft/2020-12/schema",
1347
+ $id: "https://intellectual-frontiers.github.io/.github/schemas/ergonex-manifest.json",
1348
+ title: "The answer of an ergonex module to --ergonex-manifest",
1349
+ type: "object",
1350
+ required: Object.keys(FIELDS),
1351
+ additionalProperties: true,
1352
+ properties: {
1353
+ contract: { ...property(FIELDS.contract), const: CONTRACT_VERSION },
1354
+ name: { ...property(FIELDS.name), pattern: "^[a-z][a-z0-9-]{0,31}$" },
1355
+ summary: property(FIELDS.summary),
1356
+ commands: {
1357
+ ...property(FIELDS.commands),
1358
+ items: {
1359
+ type: "object",
1360
+ required: Object.keys(COMMAND_FIELDS),
1361
+ additionalProperties: true,
1362
+ properties: {
1363
+ name: property(COMMAND_FIELDS.name),
1364
+ summary: property(COMMAND_FIELDS.summary)
1365
+ }
1366
+ }
1367
+ }
1673
1368
  }
1674
- }
1675
- for (const f of files) {
1676
- const key = foldKey(f.path);
1677
- const inside = repositories.find((r) => key.startsWith(`${foldKey(r)}/`));
1678
- if (inside !== undefined)
1679
- errors.push({
1680
- kind: "inside-repository",
1681
- path: f.path,
1682
- repository: inside
1683
- });
1684
- }
1685
- if (errors.length > 0)
1686
- return err(errors);
1687
- return ok([...files].sort((a, b) => foldKey(a.path) < foldKey(b.path) ? -1 : foldKey(a.path) > foldKey(b.path) ? 1 : 0));
1688
- }
1689
-
1690
- // src/desired.ts
1691
- function settingsOf(manifest, facts) {
1692
- const settings = {
1693
- "core.hooksPath": `${facts.homePosix.replace(/\/+$/, "")}/.ergonex/hooks`
1694
1369
  };
1695
- if (manifest.policy.requiresSignedCommits) {
1696
- settings["commit.gpgsign"] = "true";
1697
- if (manifest.signing !== undefined) {
1698
- settings["gpg.format"] = manifest.signing.format;
1699
- if (manifest.signing.key !== undefined)
1700
- settings["user.signingkey"] = manifest.signing.key;
1701
- }
1702
- }
1703
- if (manifest.identity !== undefined) {
1704
- settings["user.name"] = manifest.identity.name;
1705
- settings["user.email"] = manifest.identity.email;
1706
- }
1707
- if (facts.windows)
1708
- settings["core.longpaths"] = "true";
1709
- return settings;
1710
- }
1711
- async function desiredOf(manifest, files, facts) {
1712
- const settings = settingsOf(manifest, facts);
1713
- const repos = manifest.repositories.map((r) => ({
1714
- path: r.path,
1715
- ref: r.ref,
1716
- cloneUrl: r.cloneUrl,
1717
- branch: r.branch,
1718
- settings
1719
- }));
1720
- const worktrees = manifest.repositories.flatMap((r) => r.worktrees.map((w) => ({ path: w.path, repo: r.path, branch: w.branch })));
1721
- const desiredFiles = [];
1722
- for (const f of files)
1723
- desiredFiles.push({ path: f.path, sha256: await fileDigest(f) });
1724
- return { repos, worktrees, files: desiredFiles, hostChanges: [] };
1725
1370
  }
1726
- async function digestsOf(files) {
1727
- const out = new Map;
1728
- for (const f of files)
1729
- out.set(f.path, await fileDigest(f));
1730
- return out;
1371
+ // src/modules/types.ts
1372
+ var EXIT_STATUSES = ["Ok", "Findings", "Usage", "Environment"];
1373
+ function exitCodeOf(status) {
1374
+ switch (status) {
1375
+ case "Ok":
1376
+ return 0;
1377
+ case "Findings":
1378
+ return 1;
1379
+ case "Usage":
1380
+ return 2;
1381
+ case "Environment":
1382
+ return 3;
1383
+ default:
1384
+ return absurd(status);
1385
+ }
1731
1386
  }
1732
- // src/doctor.ts
1733
- function severityOf(level) {
1734
- switch (level) {
1735
- case "ok":
1736
- return;
1737
- case "suggest":
1738
- return "Informational";
1739
- case "warn":
1740
- return "Warning";
1741
- case "error":
1742
- return "Error";
1387
+ var MODULE_SOURCES = ["BuiltIn", "Registered", "Path"];
1388
+ function precedenceOf(source) {
1389
+ switch (source) {
1390
+ case "BuiltIn":
1391
+ return 1;
1392
+ case "Registered":
1393
+ return 2;
1394
+ case "Path":
1395
+ return 3;
1743
1396
  default:
1744
- return absurd(level);
1397
+ return absurd(source);
1745
1398
  }
1746
1399
  }
1747
- function findingsOf(checks, today) {
1748
- return checks.flatMap((c) => {
1749
- const severity = severityOf(c.level);
1750
- return severity === undefined ? [] : [
1751
- {
1752
- ruleId: c.id,
1753
- severity,
1754
- message: c.message,
1755
- subject: c.subject,
1756
- firstSeen: today
1757
- }
1758
- ];
1759
- });
1400
+ var GLOBAL_OPTIONS = {
1401
+ home: value({
1402
+ help: "The root of the workspace for this run (else $ERGONEX_HOME, else $HOME/workspaces).",
1403
+ valueName: "DIR"
1404
+ }),
1405
+ json: flag({ help: "Write the report as JSON." }),
1406
+ sarif: flag({ help: "Write the findings as a SARIF 2.1.0 log." }),
1407
+ noColor: flag({ help: "Write no colour." })
1408
+ };
1409
+ function globalsOf(options) {
1410
+ const home = options["home"];
1411
+ return {
1412
+ ...typeof home === "string" && home !== "" ? { home } : {},
1413
+ json: options["json"] === true,
1414
+ sarif: options["sarif"] === true,
1415
+ noColor: options["noColor"] === true
1416
+ };
1760
1417
  }
1761
- function classifyFs(type, wsl) {
1762
- const t = type.toLowerCase();
1763
- if (["msdos", "vfat", "fat", "fat32", "fat16"].includes(t))
1764
- return "fat";
1765
- if (t === "exfat")
1766
- return "exfat";
1767
- if (["9p", "drvfs", "v9fs"].includes(t) && wsl)
1768
- return "wsl-windows-drive";
1769
- if ([
1770
- "nfs",
1771
- "nfs3",
1772
- "nfs4",
1773
- "cifs",
1774
- "smb",
1775
- "smb2",
1776
- "smb3",
1777
- "smbfs",
1778
- "afpfs",
1779
- "9p",
1780
- "v9fs",
1781
- "sshfs",
1782
- "fuse.sshfs",
1783
- "webdav",
1784
- "ncpfs",
1785
- "fuse.rclone"
1786
- ].includes(t))
1787
- return "network";
1788
- return "ok";
1418
+ function defineCommand(d) {
1419
+ const operands = d.operands ?? [];
1420
+ const help = (program) => helpOf(program, d.summary, d.options, operands);
1421
+ return {
1422
+ name: d.name,
1423
+ summary: d.summary,
1424
+ help,
1425
+ execute: async (words, base) => {
1426
+ const program = `ergonex ${d.name}`;
1427
+ const parsed = parseArgs(words, d.options, operands);
1428
+ if (parsed.kind === "err") {
1429
+ return {
1430
+ command: d.name,
1431
+ outcome: err({
1432
+ kind: "usage",
1433
+ message: `${formatUsageError(parsed.error, program)}
1434
+
1435
+ ${help(program)}`
1436
+ })
1437
+ };
1438
+ }
1439
+ if (parsed.value.kind === "help") {
1440
+ return {
1441
+ command: d.name,
1442
+ outcome: ok({
1443
+ text: help(program),
1444
+ data: null,
1445
+ findings: [],
1446
+ noEvidence: true
1447
+ })
1448
+ };
1449
+ }
1450
+ const globals = globalsOf(parsed.value.options);
1451
+ const ctx = {
1452
+ ...base,
1453
+ globals,
1454
+ home: base.homeFor(globals.home)
1455
+ };
1456
+ return {
1457
+ command: d.name,
1458
+ globals,
1459
+ outcome: await d.run(ctx, parsed.value)
1460
+ };
1461
+ }
1462
+ };
1789
1463
  }
1790
- function fsCheck(probe, home) {
1791
- if (probe.kind === "not-run")
1464
+ function dispatch(m, words) {
1465
+ const only = m.commands.length === 1 ? m.commands[0] : undefined;
1466
+ if (only !== undefined && only.name === m.name)
1467
+ return { kind: "command", command: only, words };
1468
+ const [first, ...rest] = words;
1469
+ if (first === undefined || first === "--help" || first === "-h")
1470
+ return { kind: "help" };
1471
+ const command = m.commands.find((c) => c.name === first);
1472
+ if (command === undefined)
1792
1473
  return {
1793
- id: "ergonex/filesystem",
1794
- level: "suggest",
1795
- subject: home,
1796
- message: `the file system of the root was not probed: ${probe.reason}`
1474
+ kind: "unknown",
1475
+ word: first,
1476
+ known: m.commands.map((c) => c.name)
1797
1477
  };
1798
- const kind = classifyFs(probe.type, probe.wsl);
1799
- const at = (level, message) => ({
1800
- id: "ergonex/filesystem",
1801
- level,
1802
- subject: home,
1803
- message
1804
- });
1805
- switch (kind) {
1806
- case "ok":
1807
- return at("ok", `the root is on a file system of type ${probe.type}`);
1808
- case "fat":
1809
- return at("warn", `the root is on a FAT file system (${probe.type}): it has no execute bit and a two-second time resolution, so hooks may not run; move the root to NTFS, APFS or ext4`);
1810
- case "exfat":
1811
- return at("warn", "the root is on an exFAT file system: it has no execute bit and a two-second time resolution, so hooks may not run; move the root to NTFS, APFS or ext4");
1812
- case "network":
1813
- return at("warn", `the root is on a network share (${probe.type}): its locks are not reliable, so two runs may write at once; move the root to a local disk`);
1814
- case "wsl-windows-drive":
1815
- return at("warn", "the root is on a Windows drive seen from WSL (/mnt/c): it is slow and case-insensitive; keep the root in the Linux file system, or run ergonex from Windows");
1816
- default:
1817
- return absurd(kind);
1818
- }
1478
+ return { kind: "command", command, words: rest };
1819
1479
  }
1820
- var MIN_NODE_MAJOR = 26;
1821
- function runtimeChecks(runtime, tools) {
1480
+
1481
+ // src/modules/registry.ts
1482
+ var registeredShape = object({
1483
+ modules: array(object({ name: string, program: string }, { sha256: string, summary: string }))
1484
+ });
1485
+ function decodeRegistered(text) {
1486
+ const r = json(text, registeredShape);
1487
+ if (r.kind === "err")
1488
+ return err(formatDecodeError(r.error));
1822
1489
  const out = [];
1823
- const major = parseSemVer(runtime.version.replace(/^v/, ""));
1824
- if (runtime.name === "node" && major.kind === "ok" && major.value.major < MIN_NODE_MAJOR)
1825
- out.push({
1826
- id: "ergonex/runtime",
1827
- level: "error",
1828
- subject: "node",
1829
- message: `ergonex runs on Node ${MIN_NODE_MAJOR} or later, and this is Node ${runtime.version}; install Node ${MIN_NODE_MAJOR} or run ergonex with Bun`
1830
- });
1831
- else
1490
+ const seen = new Set;
1491
+ for (const [i, m] of r.value.modules.entries()) {
1492
+ const name = moduleName(m.name);
1493
+ if (name.kind === "err")
1494
+ return err(`$.modules[${i}].name: ${JSON.stringify(m.name)} is not a module name`);
1495
+ if (seen.has(m.name))
1496
+ return err(`$.modules[${i}].name: ${m.name} is registered twice`);
1497
+ seen.add(m.name);
1498
+ const hash = m.sha256 === undefined ? undefined : sha256Of(m.sha256);
1499
+ if (m.sha256 !== undefined && hash === undefined)
1500
+ return err(`$.modules[${i}].sha256: not a SHA-256 (64 hexadecimal digits)`);
1832
1501
  out.push({
1833
- id: "ergonex/runtime",
1834
- level: "ok",
1835
- subject: runtime.name,
1836
- message: `running on ${runtime.name} ${runtime.version}`
1502
+ name: m.name,
1503
+ program: m.program,
1504
+ ...hash === undefined ? {} : { sha256: hash },
1505
+ ...m.summary === undefined ? {} : { summary: m.summary }
1837
1506
  });
1838
- for (const t of tools) {
1839
- if (t.version === undefined) {
1840
- const needed = t.name === "git";
1841
- const isRuntime = t.name === runtime.name;
1842
- out.push({
1843
- id: "ergonex/tool",
1844
- level: needed ? "error" : isRuntime ? "ok" : "suggest",
1845
- subject: t.name,
1846
- message: needed ? `git is not installed or not on the PATH; ergonex needs it, and does not install it: install git from your system's package manager` : `${t.name} was not found on the PATH; ${t.name === "bun" ? "Bun is the default runtime" : `Node ${MIN_NODE_MAJOR} is the backup runtime`}, and ergonex does not install it: install it to have both`
1847
- });
1848
- } else
1849
- out.push({
1850
- id: "ergonex/tool",
1851
- level: "ok",
1852
- subject: t.name,
1853
- message: `${t.name} ${t.version}`
1854
- });
1855
1507
  }
1856
- return out;
1508
+ return ok(out);
1857
1509
  }
1858
- function pathChecks(f) {
1859
- if (!f.windows)
1860
- return [
1861
- {
1862
- id: "ergonex/path-length",
1863
- level: "ok",
1864
- subject: f.home,
1865
- message: "the 259-character limit of Windows does not apply on this system"
1866
- }
1867
- ];
1868
- const long = f.longPaths === "enabled";
1869
- const tooLong = f.paths.flatMap((p) => {
1870
- const native = nativePath(f.home, p, "\\");
1871
- const r = checkPathLength(native, long);
1872
- return r.kind === "err" ? [r.error] : [];
1873
- });
1874
- const out = tooLong.map((e) => ({
1875
- id: "ergonex/path-too-long",
1876
- level: "error",
1877
- subject: e.path,
1878
- message: `${e.path} is ${e.length} characters, over the ${WINDOWS_PATH_LIMIT} Windows allows while long paths are off; run \`ergonex setup\` to turn long paths on, or move the root to a shorter path`
1879
- }));
1880
- if (!long && tooLong.length === 0)
1881
- out.push({
1882
- id: "ergonex/windows-long-paths",
1883
- level: "suggest",
1884
- subject: f.home,
1885
- message: f.longPaths === "unknown" ? "Windows long paths are not known to be enabled (the setting could not be read); no path of the workspace exceeds 259 characters yet; run `ergonex setup` to turn them on" : "Windows long paths not enabled; no path of the workspace exceeds 259 characters yet; run `ergonex setup` to turn them on"
1886
- });
1887
- if (long)
1888
- out.push({
1889
- id: "ergonex/windows-long-paths",
1890
- level: "ok",
1891
- subject: f.home,
1892
- message: "Windows long paths are enabled"
1893
- });
1894
- return out;
1510
+ function resolveAll(c) {
1511
+ const chosen = new Map;
1512
+ const hidden = [];
1513
+ const bySource = (s) => {
1514
+ switch (s) {
1515
+ case "BuiltIn":
1516
+ return c.builtIn;
1517
+ case "Registered":
1518
+ return c.registered;
1519
+ case "Path":
1520
+ return c.path;
1521
+ default:
1522
+ return absurd(s);
1523
+ }
1524
+ };
1525
+ for (const source of [...MODULE_SOURCES].sort((a, b) => precedenceOf(a) - precedenceOf(b))) {
1526
+ for (const m of bySource(source)) {
1527
+ const first = chosen.get(m.name);
1528
+ if (first === undefined)
1529
+ chosen.set(m.name, m);
1530
+ else
1531
+ hidden.push({ module: m, by: first });
1532
+ }
1533
+ }
1534
+ return {
1535
+ modules: [...chosen.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
1536
+ hidden
1537
+ };
1895
1538
  }
1896
- function repoPathChecks(f) {
1897
- const out = [];
1898
- for (const repo of f.repositories) {
1899
- const native = nativePath(f.home, repo, f.windows ? "\\" : "/");
1900
- const r = repoPathLength(f.home, repo, f.windows ? "\\" : "/");
1901
- switch (r.kind) {
1902
- case "fits":
1903
- break;
1904
- case "no-room":
1905
- out.push({
1906
- id: "ergonex/repo-path-room",
1907
- level: "suggest",
1908
- subject: native,
1909
- message: `${native} is ${r.length} characters, over ${REPO_PATH_ROOM}: that leaves little room for the files inside the repository; move the root to a shorter path`
1910
- });
1911
- break;
1912
- case "too-long":
1913
- out.push({
1914
- id: "ergonex/repo-path-too-long",
1915
- level: "error",
1916
- subject: native,
1917
- message: `${native} is ${r.length} characters, over ${WINDOWS_PATH_LIMIT}, which is too long for a repository whether or not long paths are enabled; move the root to a shorter path or shorten the repository's path in the manifest`
1918
- });
1919
- break;
1920
- default:
1921
- return absurd(r);
1922
- }
1923
- }
1924
- return out;
1925
- }
1926
- function hookChecks(facts, wantedHooksPath) {
1927
- return facts.filter((f) => f.present).map((f) => f.hooksPath === wantedHooksPath ? {
1928
- id: "ergonex/hooks",
1929
- level: "ok",
1930
- subject: f.repo,
1931
- message: "the workspace's hooks are set"
1932
- } : {
1933
- id: "ergonex/hooks",
1934
- level: "warn",
1935
- subject: f.repo,
1936
- message: f.hooksPath === undefined ? `${f.repo} does not use the workspace's hooks (core.hooksPath is not set in its local configuration); run \`ergonex apply\`` : `${f.repo} uses other hooks than the workspace's (its core.hooksPath is elsewhere); run \`ergonex apply\` to replace it`
1937
- });
1539
+ function findModule(c, name) {
1540
+ return resolveAll(c).modules.find((m) => m.name === name);
1938
1541
  }
1939
- // src/findings.ts
1940
- var SEVERITIES2 = ["Informational", "Warning", "Error"];
1941
- function sarifLevel(severity) {
1942
- switch (severity) {
1943
- case "Informational":
1944
- return "note";
1945
- case "Warning":
1946
- return "warning";
1947
- case "Error":
1948
- return "error";
1949
- default:
1950
- return absurd(severity);
1951
- }
1542
+ function hiddenFindings(r, today) {
1543
+ return r.hidden.map(({ module, by }) => ({
1544
+ ruleId: "ergonex/module-hidden",
1545
+ severity: "Informational",
1546
+ message: `the module ${module.name} (${module.source}: ${module.where}) is hidden by the one of the same name that is ${by.source} (${by.where}), which runs`,
1547
+ subject: module.name,
1548
+ firstSeen: today
1549
+ }));
1952
1550
  }
1953
- function worst(findings) {
1954
- let top;
1955
- for (const f of findings)
1956
- if (top === undefined || SEVERITIES2.indexOf(f.severity) > SEVERITIES2.indexOf(top))
1957
- top = f.severity;
1958
- return top;
1551
+ // src/policy.ts
1552
+ function policyOf(input = {}) {
1553
+ const regulatedDomain = input.regulatedDomain ?? [];
1554
+ return {
1555
+ requiresSignedCommits: regulatedDomain.length > 0 || input.requiresSignedCommits === true,
1556
+ regulatedDomain,
1557
+ unapprovedGraceDays: input.unapprovedGraceDays ?? UNAPPROVED_GRACE_DAYS,
1558
+ allowedGitHost: (input.allowedGitHost ?? []).map((h) => h.toLowerCase())
1559
+ };
1959
1560
  }
1960
- function exitStatusOf(findings) {
1961
- const top = worst(findings);
1962
- return top === "Warning" || top === "Error" ? "Findings" : "Ok";
1561
+ function isRegulated(policy) {
1562
+ return policy.regulatedDomain.length > 0;
1963
1563
  }
1964
- var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
1965
- function dayNumber(day) {
1966
- const m = DAY.exec(day);
1967
- if (m === null)
1968
- return;
1969
- const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
1970
- const ms = Date.UTC(y, mo - 1, d);
1971
- const back = new Date(ms);
1972
- if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d)
1564
+ function unsignedCommitSeverity(policy, signedAndVerified) {
1565
+ if (signedAndVerified)
1973
1566
  return;
1974
- return Math.round(ms / 86400000);
1567
+ return isRegulated(policy) ? "Error" : "Warning";
1975
1568
  }
1976
- function daysBetween(from, to) {
1977
- const a = dayNumber(from);
1978
- const b = dayNumber(to);
1979
- if (a === undefined)
1980
- return err(`${JSON.stringify(from)} is not a day (YYYY-MM-DD)`);
1981
- if (b === undefined)
1982
- return err(`${JSON.stringify(to)} is not a day (YYYY-MM-DD)`);
1983
- return ok(b - a);
1569
+ function hookFailsWhenUnableToCheck(policy) {
1570
+ return isRegulated(policy);
1984
1571
  }
1985
- var UNAPPROVED_GRACE_DAYS = 90;
1986
- function unapprovedSeverity(firstSeen, today, graceDays = UNAPPROVED_GRACE_DAYS) {
1987
- const age = daysBetween(firstSeen, today);
1988
- return age.kind === "ok" && age.value > graceDays ? "Warning" : "Informational";
1572
+ function hostAllowed(policy, host) {
1573
+ return policy.allowedGitHost.length === 0 || policy.allowedGitHost.includes(host.toLowerCase());
1989
1574
  }
1990
- function firstSeenOf(previous, key, today) {
1991
- const before = Object.hasOwn(previous, key) ? previous[key] : undefined;
1992
- return before !== undefined && dayNumber(before) !== undefined ? before : today;
1575
+
1576
+ // src/templates/agents.ts
1577
+ function agentsText(data) {
1578
+ const { manifest } = data;
1579
+ const groups = [...new Set(manifest.repositories.map((r) => r.group ?? ""))].sort();
1580
+ const repositories = groups.flatMap((g) => [
1581
+ g === "" ? "Repositories in no group:" : `Group \`${g}\` (opens as \`${g}.auto.code-workspace\`):`,
1582
+ "",
1583
+ ...manifest.repositories.filter((r) => (r.group ?? "") === g).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map((r) => `- \`${r.path}\` (${r.cloneUrl})`),
1584
+ ""
1585
+ ]);
1586
+ return [
1587
+ "# Workspace guide for agents",
1588
+ "",
1589
+ "This is an Intellectual Frontiers workspace, managed by `ergonex`. It is the place a person or an agent works in; read this before you change anything here.",
1590
+ "",
1591
+ "## Layout",
1592
+ "",
1593
+ "- The root is `$ERGONEX_HOME` (the folder this file is in). A repository is at `<host>/<path>/<repo>` below it and mirrors its remote.",
1594
+ "- A worktree is at `.worktrees/<host>/<path>/<repo>/<branch>`. Make one only where another person or agent, or uncommitted work, is on the repository; otherwise work in the repository's own checkout.",
1595
+ "- The workspace's own folder is `.ergonex/`: the manifest `workspace.ts` (the source of everything generated), the generated Git configuration, the hooks and the lists of tools and modules. What ergonex remembers (the state record, the evidence of every run) is in its state folder, and the tools it installs are in its data folder (`ergonex paths` says where).",
1596
+ "- A file whose name carries `.auto.` is generated. Do not edit it: change `workspace.ts` and run `ergonex render`.",
1597
+ "",
1598
+ "## The repositories",
1599
+ "",
1600
+ ...manifest.repositories.length === 0 ? ["The manifest names none yet.", ""] : repositories,
1601
+ "## Rules",
1602
+ "",
1603
+ "- Plan before apply: `ergonex plan` shows what would change and changes nothing; `ergonex apply` carries it out.",
1604
+ "- Fast-forward only: nothing here rebases, resets, merges, forces or discards. A repository with changes of its own, or one that has diverged, is left as it is and reported.",
1605
+ "- One issue for every commit: each commit message names its issue on a line of its own (`Refs #N`, and `Closes #N` on the commit that finishes it); the `commit-msg` hook checks it.",
1606
+ "- No credential in a file: never write a token, a password or a private key into the manifest, a generated file, a remote URL or a repository's configuration; the `pre-commit` hook scans for them.",
1607
+ ...isRegulated(manifest.policy) ? [
1608
+ `- Signed commits: this workspace names a regulated domain (${manifest.policy.regulatedDomain.join(", ")}); every commit must be signed and verified, and the hooks fail where they cannot check.`
1609
+ ] : manifest.policy.requiresSignedCommits ? ["- Signed commits: the policy requires every commit to be signed and verified."] : [],
1610
+ "",
1611
+ "## Commands",
1612
+ "",
1613
+ "- `ergonex status`: every repository, its state, how far it is ahead and behind, whether it is locked.",
1614
+ "- `ergonex plan`, `ergonex apply`: the typed plan, and carrying it out.",
1615
+ "- `ergonex render`, `ergonex verify`: write the generated files, and check them against the state record.",
1616
+ "- `ergonex doctor`: check the runtime, the layout, the file system, the policy and the generated files.",
1617
+ "- `ergonex worktree create|list|prune`: worktrees, named for their issue.",
1618
+ "- `ergonex list`, `ergonex help`: the modules.",
1619
+ "",
1620
+ "Every run writes one evidence record into ergonex's state folder (`ergonex paths` says where); none holds a credential."
1621
+ ].join(`
1622
+ `);
1993
1623
  }
1994
- function toSarif(findings, tool = "ergonex") {
1995
- const rules = [...new Set(findings.map((f) => f.ruleId))].sort().map((id) => ({ id }));
1996
- return {
1997
- $schema: "https://json.schemastore.org/sarif-2.1.0.json",
1998
- version: "2.1.0",
1999
- runs: [
2000
- {
2001
- tool: {
2002
- driver: {
2003
- name: tool,
2004
- informationUri: "https://intellectual-frontiers.github.io/.github/",
2005
- rules
2006
- }
2007
- },
2008
- results: findings.map((f) => ({
2009
- ruleId: f.ruleId,
2010
- level: sarifLevel(f.severity),
2011
- message: { text: f.message },
2012
- locations: [{ logicalLocations: [{ name: f.subject }] }],
2013
- properties: { firstSeen: f.firstSeen }
2014
- }))
1624
+ var agentsTemplate = {
1625
+ name: "agents",
1626
+ render: (data) => {
1627
+ const file = generated("AGENTS.auto.md", { format: "markdown", text: agentsText(data) }, { generator: "ergonex templates/agents" });
1628
+ return file.kind === "err" ? err([file.error]) : ok([file.value]);
1629
+ }
1630
+ };
1631
+
1632
+ // src/templates/code-workspace.ts
1633
+ var GENERATOR = "ergonex templates/code-workspace";
1634
+ var codeWorkspaceTemplate = {
1635
+ name: "code-workspace",
1636
+ render: (data) => {
1637
+ const groups = [...new Set(data.manifest.repositories.flatMap((r) => r.group === undefined ? [] : [r.group]))].sort();
1638
+ const files = [];
1639
+ const errors = [];
1640
+ for (const group of groups) {
1641
+ if (group.includes("/") || group.includes("\\")) {
1642
+ errors.push({
1643
+ kind: "bad-path",
1644
+ path: `${group}.auto.code-workspace`,
1645
+ reason: "a group's name is one name, with no path separator in it"
1646
+ });
1647
+ continue;
2015
1648
  }
2016
- ]
2017
- };
2018
- }
1649
+ const folders = data.manifest.repositories.filter((r) => r.group === group).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map((r) => ({
1650
+ name: segmentsOf(r.path).at(-1) ?? r.path,
1651
+ path: r.path
1652
+ }));
1653
+ const file = generated(`${group}.auto.code-workspace`, { format: "json", value: { folders, settings: {} } }, { generator: GENERATOR });
1654
+ if (file.kind === "err")
1655
+ errors.push(file.error);
1656
+ else
1657
+ files.push(file.value);
1658
+ }
1659
+ return errors.length > 0 ? err(errors) : ok(files);
1660
+ }
1661
+ };
2019
1662
 
2020
- // src/state-record.ts
2021
- var ERGONEX_VERSION = "0.3.0";
2022
- var STATE_RECORD_PATH = ".ergonex/state.auto.json";
2023
- var EMPTY_RECORD = {
2024
- ergonex: ERGONEX_VERSION,
2025
- files: {},
2026
- firstSeen: {}
1663
+ // src/templates/envrc.ts
1664
+ var envrcTemplate = {
1665
+ name: "envrc",
1666
+ render: (data) => {
1667
+ if (!data.direnv)
1668
+ return ok([]);
1669
+ const file = generated(".envrc.auto", { format: "envrc", text: 'PATH_add "$HOME/.local/bin"' }, { generator: "ergonex templates/envrc" });
1670
+ return file.kind === "err" ? err([file.error]) : ok([file.value]);
1671
+ }
2027
1672
  };
2028
- var hash = (input, path = "$") => {
2029
- const s = typeof input === "string" ? sha256Of(input) : undefined;
2030
- return s === undefined ? err({
2031
- kind: "decode",
2032
- path,
2033
- expected: "a SHA-256 (64 hexadecimal digits)",
2034
- found: typeof input
2035
- }) : ok(s);
1673
+
1674
+ // src/templates/git-include.ts
1675
+ var gitIncludeTemplate = {
1676
+ name: "git-include",
1677
+ render: (data) => {
1678
+ const id = data.manifest.identity;
1679
+ const text = id === undefined || /[\r\n"\\]/.test(`${id.name}${id.email}`) ? "# The manifest names no identity, so this file sets nothing." : `[user]
1680
+ name = "${id.name}"
1681
+ email = "${id.email}"`;
1682
+ const file = generated(".ergonex/git.auto.conf", { format: "gitconfig", text }, { generator: "ergonex templates/git-include" });
1683
+ return file.kind === "err" ? err([file.error]) : ok([file.value]);
1684
+ }
2036
1685
  };
2037
- var day = (input, path = "$") => typeof input === "string" && dayNumber(input) !== undefined ? ok(input) : err({
2038
- kind: "decode",
2039
- path,
2040
- expected: "a day (YYYY-MM-DD)",
2041
- found: typeof input
2042
- });
2043
- var shape = object({
2044
- ergonex: string,
2045
- files: record(object({ sha256: hash, generator: string })),
2046
- firstSeen: record(day)
2047
- }, { plan: hash });
2048
- function decodeStateRecord(text) {
2049
- const r = json(text, shape);
2050
- return r.kind === "ok" ? ok(r.value) : err(formatDecodeError(r.error));
2051
- }
2052
- function encodeStateRecord(r) {
2053
- const sorted = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
2054
- const value = {
2055
- _generated: headerText("ergonex state"),
2056
- ergonex: r.ergonex,
2057
- ...r.plan === undefined ? {} : { plan: r.plan },
2058
- files: sorted(r.files),
2059
- firstSeen: sorted(r.firstSeen)
2060
- };
2061
- return `${JSON.stringify(value, null, 2)}
2062
- `;
2063
- }
2064
- function withFile(r, file, digest) {
2065
- return {
2066
- ...r,
2067
- files: {
2068
- ...r.files,
2069
- [file.path]: { sha256: digest, generator: file.generator }
2070
- }
2071
- };
2072
- }
2073
- function withoutFile(r, path) {
2074
- return {
2075
- ...r,
2076
- files: Object.fromEntries(Object.entries(r.files).filter(([p]) => p !== path))
2077
- };
1686
+
1687
+ // src/templates/hooks.ts
1688
+ var HOOK_NAMES = ["pre-commit", "commit-msg", "pre-push"];
1689
+ var HOOK_PURPOSE = {
1690
+ "pre-commit": "the plaintext-token scan of the staged changes (0002-workspace-model FR-031)",
1691
+ "commit-msg": "the issue every commit names (0020-ifccm)",
1692
+ "pre-push": "signed commits where the policy requires them (0002-workspace-model FR-032)"
1693
+ };
1694
+ function hookScript(name, strict) {
1695
+ return [
1696
+ "#!/bin/sh",
1697
+ `# ${name}: ${HOOK_PURPOSE[name]}.`,
1698
+ "# It only reads: it changes no commit, no tree and no configuration, and it uses no network.",
1699
+ 'ERGONEX_HOME=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)',
1700
+ "unable() {",
1701
+ ` echo "ergonex ${name} hook: cannot run its checker: $1" >&2`,
1702
+ ...strict ? [' echo "ergonex: this workspace names a regulated domain, so the hook stops here; fix the cause and try again." >&2', " exit 1"] : [' echo "ergonex: this workspace names no regulated domain, so the hook lets it pass." >&2', " exit 0"],
1703
+ "}",
1704
+ "if ! command -v bun >/dev/null 2>&1 && ! command -v node >/dev/null 2>&1; then",
1705
+ ' unable "neither bun nor node is on the PATH"',
1706
+ "fi",
1707
+ "if ! command -v ergonex >/dev/null 2>&1; then",
1708
+ ' unable "ergonex is not on the PATH (install it with: bun add -g @intellectual-frontiers/ergonex, or run: ergonex shell --install)"',
1709
+ "fi",
1710
+ `ergonex hook ${name} --home "$ERGONEX_HOME" -- "$@" >&2`,
1711
+ "status=$?",
1712
+ 'case "$status" in',
1713
+ " 0) exit 0 ;;",
1714
+ " 1) exit 1 ;;",
1715
+ ' *) unable "ergonex ended with status $status" ;;',
1716
+ "esac"
1717
+ ].join(`
1718
+ `);
2078
1719
  }
2079
- function verifyFindings(facts, today) {
2080
- const out = [];
2081
- for (const f of facts) {
2082
- const at = (ruleId, severity, message) => void out.push({
2083
- ruleId,
2084
- severity,
2085
- message,
2086
- subject: f.path,
2087
- firstSeen: today
2088
- });
2089
- if (f.recorded !== undefined && f.onDisk === undefined) {
2090
- at("ergonex/generated-missing", "Warning", `${f.path} is recorded as written and is not there; run \`ergonex render\` to write it again`);
2091
- } else if (f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded) {
2092
- at("ergonex/generated-edited", "Error", `${f.path} was edited by hand (its bytes are not the ones recorded); \`ergonex render --force\` replaces it`);
2093
- } else if (f.recorded === undefined && f.onDisk !== undefined) {
2094
- at("ergonex/generated-unrecorded", "Warning", `${f.path} is a generated file the state record does not hold; run \`ergonex render\` to record it, or remove it`);
2095
- }
2096
- const edited = f.recorded !== undefined && f.onDisk !== undefined && f.onDisk !== f.recorded;
2097
- const missing = f.recorded !== undefined && f.onDisk === undefined;
2098
- if (f.wanted !== undefined && f.onDisk !== f.wanted && !edited && !missing) {
2099
- at("ergonex/generated-drift", "Warning", f.onDisk === undefined ? `${f.path} is not written yet; run \`ergonex render\`` : `${f.path} would be written differently by the templates now; run \`ergonex render\``);
1720
+ var hooksTemplate = {
1721
+ name: "hooks",
1722
+ render: (data) => {
1723
+ const strict = hookFailsWhenUnableToCheck(data.manifest.policy);
1724
+ const files = [];
1725
+ const errors = [];
1726
+ for (const name of HOOK_NAMES) {
1727
+ const file = generated(`${HOOKS_FOLDER}/${name}`, { format: "sh", text: hookScript(name, strict) }, { generator: "ergonex templates/hooks", mode: "0755" });
1728
+ if (file.kind === "err")
1729
+ errors.push(file.error);
1730
+ else
1731
+ files.push(file.value);
2100
1732
  }
1733
+ return errors.length > 0 ? err(errors) : ok(files);
2101
1734
  }
2102
- return out;
2103
- }
2104
- // src/platform/k-args.ts
2105
- var editDistance2 = editDistance;
2106
- var flag2 = flag;
2107
- var formatUsageError2 = formatUsageError;
2108
- var helpOf2 = helpOf;
2109
- var parseArgs2 = parseArgs;
2110
- var value2 = value;
1735
+ };
2111
1736
 
2112
- // src/modules/name.ts
2113
- var MAX_MODULE_NAME = 32;
2114
- function describeNameError(e) {
2115
- switch (e.kind) {
2116
- case "empty":
2117
- return "a module name is not empty";
2118
- case "too-long":
2119
- return `a module name has at most ${MAX_MODULE_NAME} characters, not ${e.length}`;
2120
- case "bad-start":
2121
- return `${JSON.stringify(e.text)} does not begin with a lower-case letter, as a module name must`;
2122
- case "bad-character":
2123
- return `${JSON.stringify(e.text)} holds ${JSON.stringify(e.character)}, and a module name is lower-case letters, digits and hyphens`;
2124
- default:
2125
- return absurd(e);
1737
+ // src/templates/json-files.ts
1738
+ var toolsJsonTemplate = {
1739
+ name: "tools-json",
1740
+ render: (data) => {
1741
+ const file = generated(".ergonex/tools.auto.json", {
1742
+ format: "json",
1743
+ value: {
1744
+ tools: [...data.tools].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((t) => ({
1745
+ name: t.name,
1746
+ version: t.version,
1747
+ provides: [...t.provides],
1748
+ artifacts: [...t.artifacts].sort((x, y) => `${x.os}/${x.arch}` < `${y.os}/${y.arch}` ? -1 : 1).map((a) => ({
1749
+ os: a.os,
1750
+ arch: a.arch,
1751
+ url: a.url,
1752
+ sha256: a.sha256,
1753
+ kind: a.kind,
1754
+ bin: a.bin
1755
+ }))
1756
+ }))
1757
+ }
1758
+ }, { generator: "ergonex templates/tools-json" });
1759
+ return file.kind === "err" ? err([file.error]) : ok([file.value]);
2126
1760
  }
2127
- }
2128
- function moduleName(text) {
2129
- if (text === "")
2130
- return err({ kind: "empty" });
2131
- if (text.length > MAX_MODULE_NAME)
2132
- return err({ kind: "too-long", length: text.length });
2133
- if (!/^[a-z]/.test(text))
2134
- return err({ kind: "bad-start", text });
2135
- const bad = /[^a-z0-9-]/u.exec(text);
2136
- if (bad !== null)
2137
- return err({ kind: "bad-character", text, character: bad[0] });
2138
- return ok(text);
2139
- }
2140
- function nearestNames(word, names) {
2141
- return names.map((n) => ({ n, d: editDistance2(word, n) })).filter((x) => x.d <= 2).sort((a, b) => a.d - b.d || (a.n < b.n ? -1 : a.n > b.n ? 1 : 0)).slice(0, 3).map((x) => x.n);
2142
- }
2143
-
2144
- // src/modules/external.ts
2145
- var CONTRACT_VERSION = 1;
2146
- var FIELDS = {
2147
- contract: {
2148
- type: "integer",
2149
- description: "The version of this contract the module speaks."
2150
- },
2151
- name: {
2152
- type: "string",
2153
- description: "The module's name, as `ergonex <name>` runs it."
2154
- },
2155
- summary: {
2156
- type: "string",
2157
- description: "One sentence on what the module does."
2158
- },
2159
- commands: { type: "array", description: "The commands the module has." }
2160
1761
  };
2161
- var COMMAND_FIELDS = {
2162
- name: { type: "string", description: "The command's name." },
2163
- summary: {
2164
- type: "string",
2165
- description: "One sentence on what the command does."
1762
+ var modulesJsonTemplate = {
1763
+ name: "modules-json",
1764
+ render: (data) => {
1765
+ const modules = [...data.manifest.modules].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((m) => ({
1766
+ name: m.name,
1767
+ program: m.program,
1768
+ ...m.sha256 === undefined ? {} : { sha256: m.sha256 },
1769
+ ...m.summary === undefined ? {} : { summary: m.summary }
1770
+ }));
1771
+ const file = generated(".ergonex/modules.auto.json", { format: "json", value: { modules } }, { generator: "ergonex templates/modules-json" });
1772
+ return file.kind === "err" ? err([file.error]) : ok([file.value]);
2166
1773
  }
2167
1774
  };
2168
- var commandDecoder = object({
2169
- name: string,
2170
- summary: string
2171
- });
2172
- var manifestDecoder2 = object({
2173
- contract: integer,
2174
- name: string,
2175
- summary: string,
2176
- commands: array(commandDecoder)
2177
- });
2178
- function decodeExternalManifest(text) {
2179
- const r = json(text, manifestDecoder2);
2180
- if (r.kind === "err")
2181
- return err(formatDecodeError(r.error));
2182
- const m = r.value;
2183
- if (m.contract !== CONTRACT_VERSION)
2184
- return err(`the module speaks contract ${m.contract}, and this ergonex speaks ${CONTRACT_VERSION}`);
2185
- const name = moduleName(m.name);
2186
- if (name.kind === "err")
2187
- return err(`the module names itself ${JSON.stringify(m.name)}, which is not a module name`);
2188
- return ok(m);
1775
+
1776
+ // src/templates/lefthook.ts
1777
+ var argument = (name) => name === "commit-msg" ? " {1}" : "";
1778
+ var lefthookTemplate = {
1779
+ name: "lefthook",
1780
+ render: () => {
1781
+ const text = HOOK_NAMES.flatMap((name) => [
1782
+ `${name}:`,
1783
+ " commands:",
1784
+ " ergonex:",
1785
+ ` run: sh .ergonex/hooks/${name}${argument(name)}`
1786
+ ]).join(`
1787
+ `);
1788
+ const file = generated("lefthook.auto.yml", { format: "yaml", text }, { generator: "ergonex templates/lefthook" });
1789
+ return file.kind === "err" ? err([file.error]) : ok([file.value]);
1790
+ }
1791
+ };
1792
+
1793
+ // src/templates/mod.ts
1794
+ var TEMPLATES = [
1795
+ agentsTemplate,
1796
+ codeWorkspaceTemplate,
1797
+ envrcTemplate,
1798
+ gitIncludeTemplate,
1799
+ hooksTemplate,
1800
+ lefthookTemplate,
1801
+ modulesJsonTemplate,
1802
+ toolsJsonTemplate
1803
+ ];
1804
+ function renderAll(data) {
1805
+ const files = [];
1806
+ const errors = [];
1807
+ for (const t of TEMPLATES) {
1808
+ const r = t.render(data);
1809
+ if (r.kind === "err")
1810
+ errors.push(...r.error);
1811
+ else
1812
+ files.push(...r.value);
1813
+ }
1814
+ if (errors.length > 0)
1815
+ return err(errors);
1816
+ return checkFiles(files, data.manifest.repositories.map((r) => r.path));
2189
1817
  }
2190
- function externalManifestSchema() {
2191
- const property = (f) => ({
2192
- type: f.type,
2193
- description: f.description
2194
- });
2195
- return {
2196
- $schema: "https://json-schema.org/draft/2020-12/schema",
2197
- $id: "https://intellectual-frontiers.github.io/.github/schemas/ergonex-manifest.json",
2198
- title: "The answer of an ergonex module to --ergonex-manifest",
2199
- type: "object",
2200
- required: Object.keys(FIELDS),
2201
- additionalProperties: true,
2202
- properties: {
2203
- contract: { ...property(FIELDS.contract), const: CONTRACT_VERSION },
2204
- name: { ...property(FIELDS.name), pattern: "^[a-z][a-z0-9-]{0,31}$" },
2205
- summary: property(FIELDS.summary),
2206
- commands: {
2207
- ...property(FIELDS.commands),
2208
- items: {
2209
- type: "object",
2210
- required: Object.keys(COMMAND_FIELDS),
2211
- additionalProperties: true,
2212
- properties: {
2213
- name: property(COMMAND_FIELDS.name),
2214
- summary: property(COMMAND_FIELDS.summary)
2215
- }
2216
- }
2217
- }
2218
- }
2219
- };
2220
- }
2221
- // src/modules/types.ts
2222
- var EXIT_STATUSES = ["Ok", "Findings", "Usage", "Environment"];
2223
- function exitCodeOf(status) {
2224
- switch (status) {
2225
- case "Ok":
2226
- return 0;
2227
- case "Findings":
2228
- return 1;
2229
- case "Usage":
2230
- return 2;
2231
- case "Environment":
2232
- return 3;
2233
- default:
2234
- return absurd(status);
2235
- }
2236
- }
2237
- var MODULE_SOURCES = ["BuiltIn", "Registered", "Path"];
2238
- function precedenceOf(source) {
2239
- switch (source) {
2240
- case "BuiltIn":
2241
- return 1;
2242
- case "Registered":
2243
- return 2;
2244
- case "Path":
2245
- return 3;
2246
- default:
2247
- return absurd(source);
2248
- }
2249
- }
2250
- var GLOBAL_OPTIONS = {
2251
- home: value2({
2252
- help: "The root of the workspace for this run (else $ERGONEX_HOME, else $HOME/workspaces).",
2253
- valueName: "DIR"
2254
- }),
2255
- json: flag2({ help: "Write the report as JSON." }),
2256
- sarif: flag2({ help: "Write the findings as a SARIF 2.1.0 log." }),
2257
- noColor: flag2({ help: "Write no colour." })
2258
- };
2259
- function globalsOf(options) {
2260
- const home = options["home"];
2261
- return {
2262
- ...typeof home === "string" && home !== "" ? { home } : {},
2263
- json: options["json"] === true,
2264
- sarif: options["sarif"] === true,
2265
- noColor: options["noColor"] === true
2266
- };
1818
+ // src/shell/block.ts
1819
+ var BEGIN = "# >>> ergonex >>>";
1820
+ var END = "# <<< ergonex <<<";
1821
+ function linesKept(text) {
1822
+ return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
2267
1823
  }
2268
- function defineCommand(d) {
2269
- const operands = d.operands ?? [];
2270
- const help = (program) => helpOf2(program, d.summary, d.options, operands);
2271
- return {
2272
- name: d.name,
2273
- summary: d.summary,
2274
- help,
2275
- execute: async (words, base) => {
2276
- const program = `ergonex ${d.name}`;
2277
- const parsed = parseArgs2(words, d.options, operands);
2278
- if (parsed.kind === "err") {
2279
- return {
2280
- command: d.name,
2281
- outcome: err({
2282
- kind: "usage",
2283
- message: `${formatUsageError2(parsed.error, program)}
2284
-
2285
- ${help(program)}`
2286
- })
2287
- };
2288
- }
2289
- if (parsed.value.kind === "help") {
2290
- return {
2291
- command: d.name,
2292
- outcome: ok({
2293
- text: help(program),
2294
- data: null,
2295
- findings: [],
2296
- noEvidence: true
2297
- })
2298
- };
2299
- }
2300
- const globals = globalsOf(parsed.value.options);
2301
- const ctx = {
2302
- ...base,
2303
- globals,
2304
- home: base.homeFor(globals.home)
2305
- };
2306
- return {
2307
- command: d.name,
2308
- globals,
2309
- outcome: await d.run(ctx, parsed.value)
2310
- };
1824
+ function blocks(lines) {
1825
+ const spans = [];
1826
+ let open;
1827
+ for (const [i, raw] of lines.entries()) {
1828
+ const line = raw.replace(/\r?\n$/, "");
1829
+ if (line === BEGIN) {
1830
+ if (open !== undefined)
1831
+ return err({ kind: "unterminated", line: open + 1 });
1832
+ open = i;
1833
+ } else if (line === END) {
1834
+ if (open === undefined)
1835
+ return err({ kind: "unopened", line: i + 1 });
1836
+ spans.push({ from: open, to: i + 1 });
1837
+ open = undefined;
2311
1838
  }
2312
- };
1839
+ }
1840
+ if (open !== undefined)
1841
+ return err({ kind: "unterminated", line: open + 1 });
1842
+ return ok(spans);
2313
1843
  }
2314
- function dispatch(m, words) {
2315
- const only = m.commands.length === 1 ? m.commands[0] : undefined;
2316
- if (only !== undefined && only.name === m.name)
2317
- return { kind: "command", command: only, words };
2318
- const [first, ...rest] = words;
2319
- if (first === undefined || first === "--help" || first === "-h")
2320
- return { kind: "help" };
2321
- const command = m.commands.find((c) => c.name === first);
2322
- if (command === undefined)
2323
- return {
2324
- kind: "unknown",
2325
- word: first,
2326
- known: m.commands.map((c) => c.name)
2327
- };
2328
- return { kind: "command", command, words: rest };
1844
+ function blockText(snippet, eol = `
1845
+ `) {
1846
+ const body = snippet.replace(/\r?\n$/, "").split(/\r?\n/);
1847
+ return [BEGIN, ...body, END].map((l) => `${l}${eol}`).join("");
2329
1848
  }
2330
-
2331
- // src/modules/registry.ts
2332
- var registeredShape = object({
2333
- modules: array(object({ name: string, program: string }, { sha256: string, summary: string }))
2334
- });
2335
- function decodeRegistered(text) {
2336
- const r = json(text, registeredShape);
2337
- if (r.kind === "err")
2338
- return err(formatDecodeError(r.error));
2339
- const out = [];
2340
- const seen = new Set;
2341
- for (const [i, m] of r.value.modules.entries()) {
2342
- const name = moduleName(m.name);
2343
- if (name.kind === "err")
2344
- return err(`$.modules[${i}].name: ${JSON.stringify(m.name)} is not a module name`);
2345
- if (seen.has(m.name))
2346
- return err(`$.modules[${i}].name: ${m.name} is registered twice`);
2347
- seen.add(m.name);
2348
- const hash = m.sha256 === undefined ? undefined : sha256Of(m.sha256);
2349
- if (m.sha256 !== undefined && hash === undefined)
2350
- return err(`$.modules[${i}].sha256: not a SHA-256 (64 hexadecimal digits)`);
2351
- out.push({
2352
- name: m.name,
2353
- program: m.program,
2354
- ...hash === undefined ? {} : { sha256: hash },
2355
- ...m.summary === undefined ? {} : { summary: m.summary }
2356
- });
1849
+ function installBlock(existing, snippet) {
1850
+ if (existing === undefined)
1851
+ return err({ kind: "absent" });
1852
+ const text = existing;
1853
+ const eol = text.includes(`\r
1854
+ `) ? `\r
1855
+ ` : `
1856
+ `;
1857
+ const block = blockText(snippet, eol);
1858
+ const lines = linesKept(text);
1859
+ const found = blocks(lines);
1860
+ if (found.kind === "err")
1861
+ return found;
1862
+ const spans = found.value;
1863
+ if (spans.length === 0) {
1864
+ const lead = text === "" || text.endsWith(`
1865
+ `) ? "" : eol;
1866
+ return ok({ text: `${text}${lead}${block}`, changed: true });
2357
1867
  }
2358
- return ok(out);
2359
- }
2360
- function resolveAll(c) {
2361
- const chosen = new Map;
2362
- const hidden = [];
2363
- const bySource = (s) => {
2364
- switch (s) {
2365
- case "BuiltIn":
2366
- return c.builtIn;
2367
- case "Registered":
2368
- return c.registered;
2369
- case "Path":
2370
- return c.path;
2371
- default:
2372
- return absurd(s);
2373
- }
2374
- };
2375
- for (const source of [...MODULE_SOURCES].sort((a, b) => precedenceOf(a) - precedenceOf(b))) {
2376
- for (const m of bySource(source)) {
2377
- const first = chosen.get(m.name);
2378
- if (first === undefined)
2379
- chosen.set(m.name, m);
2380
- else
2381
- hidden.push({ module: m, by: first });
2382
- }
1868
+ const out = [];
1869
+ let at = 0;
1870
+ for (const [i, s] of spans.entries()) {
1871
+ out.push(...lines.slice(at, s.from));
1872
+ if (i === 0)
1873
+ out.push(block);
1874
+ at = s.to;
2383
1875
  }
2384
- return {
2385
- modules: [...chosen.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
2386
- hidden
2387
- };
1876
+ out.push(...lines.slice(at));
1877
+ const next = out.join("");
1878
+ return ok({ text: next, changed: next !== text });
2388
1879
  }
2389
- function findModule(c, name) {
2390
- return resolveAll(c).modules.find((m) => m.name === name);
1880
+ function removeBlock(existing) {
1881
+ const lines = linesKept(existing);
1882
+ const found = blocks(lines);
1883
+ if (found.kind === "err")
1884
+ return found;
1885
+ if (found.value.length === 0)
1886
+ return ok({ text: existing, changed: false });
1887
+ const drop = new Set(found.value.flatMap((s) => Array.from({ length: s.to - s.from }, (_, k) => s.from + k)));
1888
+ return ok({
1889
+ text: lines.filter((_, i) => !drop.has(i)).join(""),
1890
+ changed: true
1891
+ });
2391
1892
  }
2392
- function hiddenFindings(r, today) {
2393
- return r.hidden.map(({ module, by }) => ({
2394
- ruleId: "ergonex/module-hidden",
2395
- severity: "Informational",
2396
- message: `the module ${module.name} (${module.source}: ${module.where}) is hidden by the one of the same name that is ${by.source} (${by.where}), which runs`,
2397
- subject: module.name,
2398
- firstSeen: today
2399
- }));
2400
- }
2401
- // src/policy.ts
2402
- function policyOf(input = {}) {
2403
- const regulatedDomain = input.regulatedDomain ?? [];
2404
- return {
2405
- requiresSignedCommits: regulatedDomain.length > 0 || input.requiresSignedCommits === true,
2406
- regulatedDomain,
2407
- unapprovedGraceDays: input.unapprovedGraceDays ?? UNAPPROVED_GRACE_DAYS,
2408
- allowedGitHost: (input.allowedGitHost ?? []).map((h) => h.toLowerCase())
2409
- };
2410
- }
2411
- function isRegulated(policy) {
2412
- return policy.regulatedDomain.length > 0;
2413
- }
2414
- function unsignedCommitSeverity(policy, signedAndVerified) {
2415
- if (signedAndVerified)
2416
- return;
2417
- return isRegulated(policy) ? "Error" : "Warning";
2418
- }
2419
- function hookFailsWhenUnableToCheck(policy) {
2420
- return isRegulated(policy);
2421
- }
2422
- function hostAllowed(policy, host) {
2423
- return policy.allowedGitHost.length === 0 || policy.allowedGitHost.includes(host.toLowerCase());
2424
- }
2425
-
2426
- // src/templates/agents.ts
2427
- function agentsText(data) {
2428
- const { manifest } = data;
2429
- const groups = [...new Set(manifest.repositories.map((r) => r.group ?? ""))].sort();
2430
- const repositories = groups.flatMap((g) => [
2431
- g === "" ? "Repositories in no group:" : `Group \`${g}\` (opens as \`${g}.auto.code-workspace\`):`,
2432
- "",
2433
- ...manifest.repositories.filter((r) => (r.group ?? "") === g).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map((r) => `- \`${r.path}\` (${r.cloneUrl})`),
2434
- ""
2435
- ]);
1893
+ // src/shell/snippet.ts
1894
+ var SHELLS = ["bash", "zsh", "fish", "pwsh", "nu"];
1895
+ var posixQuote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
1896
+ var fishQuote = (s) => `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
1897
+ var pwshQuote = (s) => `'${s.replaceAll("'", "''")}'`;
1898
+ var nuQuote = (s) => `"${s.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
1899
+ var words = (c) => c.map((m) => m.module).join(" ");
1900
+ function posix(f, shell) {
1901
+ const home = f.home.kind === "default" ? "" : posixQuote(f.home.path);
1902
+ const several = f.completions.filter((m) => m.commands.length > 1);
1903
+ const completion = shell === "bash" ? [
1904
+ "_ergonex_complete() {",
1905
+ ' local cur="${COMP_WORDS[COMP_CWORD]}"',
1906
+ ' if [ "$COMP_CWORD" -eq 1 ]; then',
1907
+ ` COMPREPLY=($(compgen -W ${posixQuote(words(f.completions))} -- "$cur"))`,
1908
+ ' elif [ "$COMP_CWORD" -eq 2 ]; then',
1909
+ ' case "${COMP_WORDS[1]}" in',
1910
+ ...several.map((m) => ` ${m.module}) COMPREPLY=($(compgen -W ${posixQuote(m.commands.join(" "))} -- "$cur")) ;;`),
1911
+ " esac",
1912
+ " fi",
1913
+ "}",
1914
+ "complete -F _ergonex_complete ergonex"
1915
+ ] : [
1916
+ "_ergonex_complete() {",
1917
+ " if (( CURRENT == 2 )); then",
1918
+ ` compadd -- ${words(f.completions)}`,
1919
+ " elif (( CURRENT == 3 )); then",
1920
+ ' case "${words[2]}" in',
1921
+ ...several.map((m) => ` ${m.module}) compadd -- ${m.commands.join(" ")} ;;`),
1922
+ " esac",
1923
+ " fi",
1924
+ "}",
1925
+ "if (( $+functions[compdef] )); then compdef _ergonex_complete ergonex; fi"
1926
+ ];
2436
1927
  return [
2437
- "# Workspace guide for agents",
2438
- "",
2439
- "This is an Intellectual Frontiers workspace, managed by `ergonex`. It is the place a person or an agent works in; read this before you change anything here.",
2440
- "",
2441
- "## Layout",
2442
- "",
2443
- "- The root is `$ERGONEX_HOME` (the folder this file is in). A repository is at `<host>/<path>/<repo>` below it and mirrors its remote.",
2444
- "- A worktree is at `.worktrees/<host>/<path>/<repo>/<branch>`. Make one only where another person or agent, or uncommitted work, is on the repository; otherwise work in the repository's own checkout.",
2445
- "- The workspace's own folder is `.ergonex/`: the manifest `workspace.ts` (the source of everything generated), the generated Git configuration, the hooks and the lists of tools and modules. What ergonex remembers (the state record, the evidence of every run) is in its state folder, and the tools it installs are in its data folder (`ergonex paths` says where).",
2446
- "- A file whose name carries `.auto.` is generated. Do not edit it: change `workspace.ts` and run `ergonex render`.",
2447
- "",
2448
- "## The repositories",
2449
- "",
2450
- ...manifest.repositories.length === 0 ? ["The manifest names none yet.", ""] : repositories,
2451
- "## Rules",
2452
- "",
2453
- "- Plan before apply: `ergonex plan` shows what would change and changes nothing; `ergonex apply` carries it out.",
2454
- "- Fast-forward only: nothing here rebases, resets, merges, forces or discards. A repository with changes of its own, or one that has diverged, is left as it is and reported.",
2455
- "- One issue for every commit: each commit message names its issue on a line of its own (`Refs #N`, and `Closes #N` on the commit that finishes it); the `commit-msg` hook checks it.",
2456
- "- No credential in a file: never write a token, a password or a private key into the manifest, a generated file, a remote URL or a repository's configuration; the `pre-commit` hook scans for them.",
2457
- ...isRegulated(manifest.policy) ? [
2458
- `- Signed commits: this workspace names a regulated domain (${manifest.policy.regulatedDomain.join(", ")}); every commit must be signed and verified, and the hooks fail where they cannot check.`
2459
- ] : manifest.policy.requiresSignedCommits ? ["- Signed commits: the policy requires every commit to be signed and verified."] : [],
2460
- "",
2461
- "## Commands",
2462
- "",
2463
- "- `ergonex status`: every repository, its state, how far it is ahead and behind, whether it is locked.",
2464
- "- `ergonex plan`, `ergonex apply`: the typed plan, and carrying it out.",
2465
- "- `ergonex render`, `ergonex verify`: write the generated files, and check them against the state record.",
2466
- "- `ergonex doctor`: check the runtime, the layout, the file system, the policy and the generated files.",
2467
- "- `ergonex worktree create|list|prune`: worktrees, named for their issue.",
2468
- "- `ergonex list`, `ergonex help`: the modules.",
2469
- "",
2470
- "Every run writes one evidence record into ergonex's state folder (`ergonex paths` says where); none holds a credential."
1928
+ "# IF Workspaces (ergonex): the root, the pinned tools on the PATH, the completions of ergonex, and wcd.",
1929
+ f.home.kind === "default" ? 'export ERGONEX_HOME="${ERGONEX_HOME:-$HOME/workspaces}"' : `if [ -z "\${ERGONEX_HOME:-}" ]; then export ERGONEX_HOME=${home}; fi`,
1930
+ "# the shims of the tools ergonex installs are in ~/.local/bin, which the XDG specification names for a person's own programs (0031-install-locations)",
1931
+ 'case ":$PATH:" in',
1932
+ ' *":$HOME/.local/bin:"*) ;;',
1933
+ ' *) export PATH="$HOME/.local/bin:$PATH" ;;',
1934
+ "esac",
1935
+ "# the person's GitHub sign-in as the token for reading packages, kept in the environment of this shell and never in a file (ergonex 0004-onboarding FR-004).",
1936
+ 'if [ -z "${ERGONEX_GITHUB_TOKEN:-}" ] && command -v gh >/dev/null 2>&1; then',
1937
+ ' if ERGONEX_GITHUB_TOKEN="$(gh auth token 2>/dev/null)" && [ -n "$ERGONEX_GITHUB_TOKEN" ]; then export ERGONEX_GITHUB_TOKEN; else unset ERGONEX_GITHUB_TOKEN; fi',
1938
+ "fi",
1939
+ ...completion,
1940
+ "wcd() {",
1941
+ ' if [ -z "$1" ]; then echo "usage: wcd NAME" >&2; return 2; fi',
1942
+ ` _ergonex_hits=$(find "$ERGONEX_HOME" -maxdepth 8 \\( -name .worktrees -o -name .ergonex -o -name .git \\) -prune -o -type d -name "$1" -exec test -e '{}/.git' \\; -print 2>/dev/null | sort)`,
1943
+ ' if [ -z "$_ergonex_hits" ]; then',
1944
+ ' echo "wcd: no repository named $1 in $ERGONEX_HOME" >&2; unset _ergonex_hits; return 1',
1945
+ " fi",
1946
+ ` if [ "$(printf '%s\\n' "$_ergonex_hits" | wc -l)" -gt 1 ]; then`,
1947
+ ` echo "wcd: more than one repository is named $1:" >&2; printf '%s\\n' "$_ergonex_hits" >&2; unset _ergonex_hits; return 1`,
1948
+ " fi",
1949
+ ' cd "$_ergonex_hits" || { unset _ergonex_hits; return 1; }',
1950
+ " unset _ergonex_hits",
1951
+ "}"
2471
1952
  ].join(`
2472
1953
  `);
2473
1954
  }
2474
- var agentsTemplate = {
2475
- name: "agents",
2476
- render: (data) => {
2477
- const file = generated("AGENTS.auto.md", { format: "markdown", text: agentsText(data) }, { generator: "ergonex templates/agents" });
2478
- return file.kind === "err" ? err([file.error]) : ok([file.value]);
2479
- }
2480
- };
2481
-
2482
- // src/templates/code-workspace.ts
2483
- var GENERATOR = "ergonex templates/code-workspace";
2484
- var codeWorkspaceTemplate = {
2485
- name: "code-workspace",
2486
- render: (data) => {
2487
- const groups = [...new Set(data.manifest.repositories.flatMap((r) => r.group === undefined ? [] : [r.group]))].sort();
2488
- const files = [];
2489
- const errors = [];
2490
- for (const group of groups) {
2491
- if (group.includes("/") || group.includes("\\")) {
2492
- errors.push({
2493
- kind: "bad-path",
2494
- path: `${group}.auto.code-workspace`,
2495
- reason: "a group's name is one name, with no path separator in it"
2496
- });
2497
- continue;
2498
- }
2499
- const folders = data.manifest.repositories.filter((r) => r.group === group).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map((r) => ({
2500
- name: segmentsOf(r.path).at(-1) ?? r.path,
2501
- path: r.path
2502
- }));
2503
- const file = generated(`${group}.auto.code-workspace`, { format: "json", value: { folders, settings: {} } }, { generator: GENERATOR });
2504
- if (file.kind === "err")
2505
- errors.push(file.error);
2506
- else
2507
- files.push(file.value);
2508
- }
2509
- return errors.length > 0 ? err(errors) : ok(files);
2510
- }
2511
- };
2512
-
2513
- // src/templates/envrc.ts
2514
- var envrcTemplate = {
2515
- name: "envrc",
2516
- render: (data) => {
2517
- if (!data.direnv)
2518
- return ok([]);
2519
- const file = generated(".envrc.auto", { format: "envrc", text: 'PATH_add "$HOME/.local/bin"' }, { generator: "ergonex templates/envrc" });
2520
- return file.kind === "err" ? err([file.error]) : ok([file.value]);
2521
- }
2522
- };
2523
-
2524
- // src/templates/git-include.ts
2525
- var gitIncludeTemplate = {
2526
- name: "git-include",
2527
- render: (data) => {
2528
- const id = data.manifest.identity;
2529
- const text = id === undefined || /[\r\n"\\]/.test(`${id.name}${id.email}`) ? "# The manifest names no identity, so this file sets nothing." : `[user]
2530
- name = "${id.name}"
2531
- email = "${id.email}"`;
2532
- const file = generated(".ergonex/git.auto.conf", { format: "gitconfig", text }, { generator: "ergonex templates/git-include" });
2533
- return file.kind === "err" ? err([file.error]) : ok([file.value]);
2534
- }
2535
- };
2536
-
2537
- // src/templates/hooks.ts
2538
- var HOOK_NAMES = ["pre-commit", "commit-msg", "pre-push"];
2539
- var HOOK_PURPOSE = {
2540
- "pre-commit": "the plaintext-token scan of the staged changes (0002-workspace-model FR-031)",
2541
- "commit-msg": "the issue every commit names (0020-ifccm)",
2542
- "pre-push": "signed commits where the policy requires them (0002-workspace-model FR-032)"
2543
- };
2544
- function hookScript(name, strict) {
1955
+ function fish(f) {
1956
+ const home = f.home.kind === "default" ? '"$HOME/workspaces"' : fishQuote(f.home.path);
1957
+ const several = f.completions.filter((m) => m.commands.length > 1);
2545
1958
  return [
2546
- "#!/bin/sh",
2547
- `# ${name}: ${HOOK_PURPOSE[name]}.`,
2548
- "# It only reads: it changes no commit, no tree and no configuration, and it uses no network.",
2549
- 'ERGONEX_HOME=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)',
2550
- "unable() {",
2551
- ` echo "ergonex ${name} hook: cannot run its checker: $1" >&2`,
2552
- ...strict ? [' echo "ergonex: this workspace names a regulated domain, so the hook stops here; fix the cause and try again." >&2', " exit 1"] : [' echo "ergonex: this workspace names no regulated domain, so the hook lets it pass." >&2', " exit 0"],
2553
- "}",
2554
- "if ! command -v bun >/dev/null 2>&1 && ! command -v node >/dev/null 2>&1; then",
2555
- ' unable "neither bun nor node is on the PATH"',
2556
- "fi",
2557
- "if ! command -v ergonex >/dev/null 2>&1; then",
2558
- ' unable "ergonex is not on the PATH (install it with: bun add -g @intellectual-frontiers/ergonex, or run: ergonex shell --install)"',
2559
- "fi",
2560
- `ergonex hook ${name} --home "$ERGONEX_HOME" -- "$@" >&2`,
2561
- "status=$?",
2562
- 'case "$status" in',
2563
- " 0) exit 0 ;;",
2564
- " 1) exit 1 ;;",
2565
- ' *) unable "ergonex ended with status $status" ;;',
2566
- "esac"
1959
+ "# IF Workspaces (ergonex): the root, the pinned tools on the PATH, the completions of ergonex, and wcd.",
1960
+ `set -q ERGONEX_HOME; or set -gx ERGONEX_HOME ${home}`,
1961
+ "# the shims of the tools ergonex installs are in ~/.local/bin, which the XDG specification names for a person's own programs (0031-install-locations)",
1962
+ 'fish_add_path -g "$HOME/.local/bin"',
1963
+ "# the person's GitHub sign-in as the token for reading packages, kept in the environment of this shell and never in a file (ergonex 0004-onboarding FR-004).",
1964
+ "if not set -q ERGONEX_GITHUB_TOKEN; and command -q gh",
1965
+ ' set -l token (gh auth token 2>/dev/null); and test -n "$token"; and set -gx ERGONEX_GITHUB_TOKEN $token',
1966
+ "end",
1967
+ `complete -c ergonex -f -n __fish_use_subcommand -a ${fishQuote(words(f.completions))}`,
1968
+ ...several.map((m) => `complete -c ergonex -f -n '__fish_seen_subcommand_from ${m.module}' -a ${fishQuote(m.commands.join(" "))}`),
1969
+ "function wcd",
1970
+ " if test (count $argv) -lt 1",
1971
+ " echo 'usage: wcd NAME' >&2; return 2",
1972
+ " end",
1973
+ " set -l hits (find $ERGONEX_HOME -maxdepth 8 '(' -name .worktrees -o -name .ergonex -o -name .git ')' -prune -o -type d -name $argv[1] -exec test -e '{}/.git' ';' -print 2>/dev/null | sort)",
1974
+ " if test (count $hits) -eq 0",
1975
+ ' echo "wcd: no repository named $argv[1] in $ERGONEX_HOME" >&2; return 1',
1976
+ " end",
1977
+ " if test (count $hits) -gt 1",
1978
+ ` echo "wcd: more than one repository is named $argv[1]:" >&2; printf '%s\\n' $hits >&2; return 1`,
1979
+ " end",
1980
+ " cd $hits[1]",
1981
+ "end"
2567
1982
  ].join(`
2568
1983
  `);
2569
1984
  }
2570
- var hooksTemplate = {
2571
- name: "hooks",
2572
- render: (data) => {
2573
- const strict = hookFailsWhenUnableToCheck(data.manifest.policy);
2574
- const files = [];
2575
- const errors = [];
2576
- for (const name of HOOK_NAMES) {
2577
- const file = generated(`${HOOKS_FOLDER}/${name}`, { format: "sh", text: hookScript(name, strict) }, { generator: "ergonex templates/hooks", mode: "0755" });
2578
- if (file.kind === "err")
2579
- errors.push(file.error);
2580
- else
2581
- files.push(file.value);
2582
- }
2583
- return errors.length > 0 ? err(errors) : ok(files);
2584
- }
2585
- };
2586
-
2587
- // src/templates/json-files.ts
2588
- var toolsJsonTemplate = {
2589
- name: "tools-json",
2590
- render: (data) => {
2591
- const file = generated(".ergonex/tools.auto.json", {
2592
- format: "json",
2593
- value: {
2594
- tools: [...data.tools].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((t) => ({
2595
- name: t.name,
2596
- version: t.version,
2597
- provides: [...t.provides],
2598
- artifacts: [...t.artifacts].sort((x, y) => `${x.os}/${x.arch}` < `${y.os}/${y.arch}` ? -1 : 1).map((a) => ({
2599
- os: a.os,
2600
- arch: a.arch,
2601
- url: a.url,
2602
- sha256: a.sha256,
2603
- kind: a.kind,
2604
- bin: a.bin
2605
- }))
2606
- }))
2607
- }
2608
- }, { generator: "ergonex templates/tools-json" });
2609
- return file.kind === "err" ? err([file.error]) : ok([file.value]);
2610
- }
2611
- };
2612
- var modulesJsonTemplate = {
2613
- name: "modules-json",
2614
- render: (data) => {
2615
- const modules = [...data.manifest.modules].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((m) => ({
2616
- name: m.name,
2617
- program: m.program,
2618
- ...m.sha256 === undefined ? {} : { sha256: m.sha256 },
2619
- ...m.summary === undefined ? {} : { summary: m.summary }
2620
- }));
2621
- const file = generated(".ergonex/modules.auto.json", { format: "json", value: { modules } }, { generator: "ergonex templates/modules-json" });
2622
- return file.kind === "err" ? err([file.error]) : ok([file.value]);
2623
- }
2624
- };
2625
-
2626
- // src/templates/lefthook.ts
2627
- var argument = (name) => name === "commit-msg" ? " {1}" : "";
2628
- var lefthookTemplate = {
2629
- name: "lefthook",
2630
- render: () => {
2631
- const text = HOOK_NAMES.flatMap((name) => [
2632
- `${name}:`,
2633
- " commands:",
2634
- " ergonex:",
2635
- ` run: sh .ergonex/hooks/${name}${argument(name)}`
2636
- ]).join(`
2637
- `);
2638
- const file = generated("lefthook.auto.yml", { format: "yaml", text }, { generator: "ergonex templates/lefthook" });
2639
- return file.kind === "err" ? err([file.error]) : ok([file.value]);
2640
- }
2641
- };
2642
-
2643
- // src/templates/mod.ts
2644
- var TEMPLATES = [
2645
- agentsTemplate,
2646
- codeWorkspaceTemplate,
2647
- envrcTemplate,
2648
- gitIncludeTemplate,
2649
- hooksTemplate,
2650
- lefthookTemplate,
2651
- modulesJsonTemplate,
2652
- toolsJsonTemplate
2653
- ];
2654
- function renderAll(data) {
2655
- const files = [];
2656
- const errors = [];
2657
- for (const t of TEMPLATES) {
2658
- const r = t.render(data);
2659
- if (r.kind === "err")
2660
- errors.push(...r.error);
2661
- else
2662
- files.push(...r.value);
2663
- }
2664
- if (errors.length > 0)
2665
- return err(errors);
2666
- return checkFiles(files, data.manifest.repositories.map((r) => r.path));
2667
- }
2668
- // src/shell/block.ts
2669
- var BEGIN = "# >>> ergonex >>>";
2670
- var END = "# <<< ergonex <<<";
2671
- function linesKept(text) {
2672
- return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
2673
- }
2674
- function blocks(lines) {
2675
- const spans = [];
2676
- let open;
2677
- for (const [i, raw] of lines.entries()) {
2678
- const line = raw.replace(/\r?\n$/, "");
2679
- if (line === BEGIN) {
2680
- if (open !== undefined)
2681
- return err({ kind: "unterminated", line: open + 1 });
2682
- open = i;
2683
- } else if (line === END) {
2684
- if (open === undefined)
2685
- return err({ kind: "unopened", line: i + 1 });
2686
- spans.push({ from: open, to: i + 1 });
2687
- open = undefined;
2688
- }
2689
- }
2690
- if (open !== undefined)
2691
- return err({ kind: "unterminated", line: open + 1 });
2692
- return ok(spans);
2693
- }
2694
- function blockText(snippet, eol = `
2695
- `) {
2696
- const body = snippet.replace(/\r?\n$/, "").split(/\r?\n/);
2697
- return [BEGIN, ...body, END].map((l) => `${l}${eol}`).join("");
2698
- }
2699
- function installBlock(existing, snippet) {
2700
- if (existing === undefined)
2701
- return err({ kind: "absent" });
2702
- const text = existing;
2703
- const eol = text.includes(`\r
2704
- `) ? `\r
2705
- ` : `
2706
- `;
2707
- const block = blockText(snippet, eol);
2708
- const lines = linesKept(text);
2709
- const found = blocks(lines);
2710
- if (found.kind === "err")
2711
- return found;
2712
- const spans = found.value;
2713
- if (spans.length === 0) {
2714
- const lead = text === "" || text.endsWith(`
2715
- `) ? "" : eol;
2716
- return ok({ text: `${text}${lead}${block}`, changed: true });
2717
- }
2718
- const out = [];
2719
- let at = 0;
2720
- for (const [i, s] of spans.entries()) {
2721
- out.push(...lines.slice(at, s.from));
2722
- if (i === 0)
2723
- out.push(block);
2724
- at = s.to;
2725
- }
2726
- out.push(...lines.slice(at));
2727
- const next = out.join("");
2728
- return ok({ text: next, changed: next !== text });
2729
- }
2730
- function removeBlock(existing) {
2731
- const lines = linesKept(existing);
2732
- const found = blocks(lines);
2733
- if (found.kind === "err")
2734
- return found;
2735
- if (found.value.length === 0)
2736
- return ok({ text: existing, changed: false });
2737
- const drop = new Set(found.value.flatMap((s) => Array.from({ length: s.to - s.from }, (_, k) => s.from + k)));
2738
- return ok({
2739
- text: lines.filter((_, i) => !drop.has(i)).join(""),
2740
- changed: true
2741
- });
2742
- }
2743
- // src/shell/snippet.ts
2744
- var SHELLS = ["bash", "zsh", "fish", "pwsh", "nu"];
2745
- var posixQuote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
2746
- var fishQuote = (s) => `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
2747
- var pwshQuote = (s) => `'${s.replaceAll("'", "''")}'`;
2748
- var nuQuote = (s) => `"${s.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
2749
- var words = (c) => c.map((m) => m.module).join(" ");
2750
- function posix(f, shell) {
2751
- const home = f.home.kind === "default" ? "" : posixQuote(f.home.path);
1985
+ function pwsh(f) {
1986
+ const home = f.home.kind === "default" ? "(Join-Path $HOME 'workspaces')" : pwshQuote(f.home.path);
2752
1987
  const several = f.completions.filter((m) => m.commands.length > 1);
2753
- const completion = shell === "bash" ? [
2754
- "_ergonex_complete() {",
2755
- ' local cur="${COMP_WORDS[COMP_CWORD]}"',
2756
- ' if [ "$COMP_CWORD" -eq 1 ]; then',
2757
- ` COMPREPLY=($(compgen -W ${posixQuote(words(f.completions))} -- "$cur"))`,
2758
- ' elif [ "$COMP_CWORD" -eq 2 ]; then',
2759
- ' case "${COMP_WORDS[1]}" in',
2760
- ...several.map((m) => ` ${m.module}) COMPREPLY=($(compgen -W ${posixQuote(m.commands.join(" "))} -- "$cur")) ;;`),
2761
- " esac",
2762
- " fi",
2763
- "}",
2764
- "complete -F _ergonex_complete ergonex"
2765
- ] : [
2766
- "_ergonex_complete() {",
2767
- " if (( CURRENT == 2 )); then",
2768
- ` compadd -- ${words(f.completions)}`,
2769
- " elif (( CURRENT == 3 )); then",
2770
- ' case "${words[2]}" in',
2771
- ...several.map((m) => ` ${m.module}) compadd -- ${m.commands.join(" ")} ;;`),
2772
- " esac",
2773
- " fi",
2774
- "}",
2775
- "if (( $+functions[compdef] )); then compdef _ergonex_complete ergonex; fi"
2776
- ];
2777
1988
  return [
2778
1989
  "# IF Workspaces (ergonex): the root, the pinned tools on the PATH, the completions of ergonex, and wcd.",
2779
- f.home.kind === "default" ? 'export ERGONEX_HOME="${ERGONEX_HOME:-$HOME/workspaces}"' : `if [ -z "\${ERGONEX_HOME:-}" ]; then export ERGONEX_HOME=${home}; fi`,
2780
- "# the shims of the tools ergonex installs are in ~/.local/bin, which the XDG specification names for a person's own programs (0031-install-locations)",
2781
- 'case ":$PATH:" in',
2782
- ' *":$HOME/.local/bin:"*) ;;',
2783
- ' *) export PATH="$HOME/.local/bin:$PATH" ;;',
2784
- "esac",
1990
+ `if (-not $env:ERGONEX_HOME) { $env:ERGONEX_HOME = ${home} }`,
1991
+ "# the shims of the tools ergonex installs: ~/.local/bin (XDG) on Linux and macOS, and the tools folder of ergonex's data on Windows (0031-install-locations)",
1992
+ "$ergonexBin = if ($IsLinux -or $IsMacOS) { Join-Path $HOME '.local/bin' } else { Join-Path $(if ($env:XDG_DATA_HOME) { $env:XDG_DATA_HOME } else { $env:LOCALAPPDATA }) 'ergonex\\tools\\bin' }",
1993
+ "if (($env:PATH -split [IO.Path]::PathSeparator) -notcontains $ergonexBin) { $env:PATH = $ergonexBin + [IO.Path]::PathSeparator + $env:PATH }",
2785
1994
  "# the person's GitHub sign-in as the token for reading packages, kept in the environment of this shell and never in a file (ergonex 0004-onboarding FR-004).",
2786
- 'if [ -z "${ERGONEX_GITHUB_TOKEN:-}" ] && command -v gh >/dev/null 2>&1; then',
2787
- ' if ERGONEX_GITHUB_TOKEN="$(gh auth token 2>/dev/null)" && [ -n "$ERGONEX_GITHUB_TOKEN" ]; then export ERGONEX_GITHUB_TOKEN; else unset ERGONEX_GITHUB_TOKEN; fi',
2788
- "fi",
2789
- ...completion,
2790
- "wcd() {",
2791
- ' if [ -z "$1" ]; then echo "usage: wcd NAME" >&2; return 2; fi',
2792
- ` _ergonex_hits=$(find "$ERGONEX_HOME" -maxdepth 8 \\( -name .worktrees -o -name .ergonex -o -name .git \\) -prune -o -type d -name "$1" -exec test -e '{}/.git' \\; -print 2>/dev/null | sort)`,
2793
- ' if [ -z "$_ergonex_hits" ]; then',
2794
- ' echo "wcd: no repository named $1 in $ERGONEX_HOME" >&2; unset _ergonex_hits; return 1',
2795
- " fi",
2796
- ` if [ "$(printf '%s\\n' "$_ergonex_hits" | wc -l)" -gt 1 ]; then`,
2797
- ` echo "wcd: more than one repository is named $1:" >&2; printf '%s\\n' "$_ergonex_hits" >&2; unset _ergonex_hits; return 1`,
2798
- " fi",
2799
- ' cd "$_ergonex_hits" || { unset _ergonex_hits; return 1; }',
2800
- " unset _ergonex_hits",
1995
+ "if (-not $env:ERGONEX_GITHUB_TOKEN -and (Get-Command gh -ErrorAction SilentlyContinue)) {",
1996
+ " $ergonexToken = (& gh auth token 2>$null)",
1997
+ ' if ($LASTEXITCODE -eq 0 -and $ergonexToken) { $env:ERGONEX_GITHUB_TOKEN = "$ergonexToken".Trim() }',
1998
+ "}",
1999
+ "Register-ArgumentCompleter -Native -CommandName ergonex -ScriptBlock {",
2000
+ " param($wordToComplete, $commandAst, $cursorPosition)",
2001
+ " $parts = @($commandAst.CommandElements | ForEach-Object { $_.ToString() })",
2002
+ ` $choices = if ($parts.Count -le 1 -or ($parts.Count -eq 2 -and $wordToComplete)) { ${pwshQuote(words(f.completions))} -split ' ' }`,
2003
+ ...several.map((m) => ` elseif ($parts[1] -eq '${m.module}') { ${pwshQuote(m.commands.join(" "))} -split ' ' }`),
2004
+ " else { @() }",
2005
+ ` $choices | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }`,
2006
+ "}",
2007
+ "function wcd {",
2008
+ " param([Parameter(Mandatory = $true)][string]$Name)",
2009
+ " $hits = @(Get-ChildItem -Path $env:ERGONEX_HOME -Directory -Recurse -Depth 7 -Filter $Name -ErrorAction SilentlyContinue |",
2010
+ " Where-Object { (Test-Path (Join-Path $_.FullName '.git')) -and $_.FullName -notmatch '[\\\\/]\\.(worktrees|ergonex)[\\\\/]' })",
2011
+ ' if ($hits.Count -eq 0) { Write-Error "wcd: no repository named $Name in $env:ERGONEX_HOME"; return }',
2012
+ ' if ($hits.Count -gt 1) { Write-Error ("wcd: more than one repository is named ${Name}: " + ($hits.FullName -join ", ")); return }',
2013
+ " Set-Location $hits[0].FullName",
2801
2014
  "}"
2802
2015
  ].join(`
2803
2016
  `);
2804
2017
  }
2805
- function fish(f) {
2806
- const home = f.home.kind === "default" ? '"$HOME/workspaces"' : fishQuote(f.home.path);
2018
+ function nu(f) {
2019
+ const home = f.home.kind === "default" ? '($nu.home-path | path join "workspaces")' : nuQuote(f.home.path);
2807
2020
  const several = f.completions.filter((m) => m.commands.length > 1);
2808
2021
  return [
2809
2022
  "# IF Workspaces (ergonex): the root, the pinned tools on the PATH, the completions of ergonex, and wcd.",
2810
- `set -q ERGONEX_HOME; or set -gx ERGONEX_HOME ${home}`,
2811
- "# the shims of the tools ergonex installs are in ~/.local/bin, which the XDG specification names for a person's own programs (0031-install-locations)",
2812
- 'fish_add_path -g "$HOME/.local/bin"',
2813
- "# the person's GitHub sign-in as the token for reading packages, kept in the environment of this shell and never in a file (ergonex 0004-onboarding FR-004).",
2814
- "if not set -q ERGONEX_GITHUB_TOKEN; and command -q gh",
2815
- ' set -l token (gh auth token 2>/dev/null); and test -n "$token"; and set -gx ERGONEX_GITHUB_TOKEN $token',
2816
- "end",
2817
- `complete -c ergonex -f -n __fish_use_subcommand -a ${fishQuote(words(f.completions))}`,
2818
- ...several.map((m) => `complete -c ergonex -f -n '__fish_seen_subcommand_from ${m.module}' -a ${fishQuote(m.commands.join(" "))}`),
2819
- "function wcd",
2820
- " if test (count $argv) -lt 1",
2821
- " echo 'usage: wcd NAME' >&2; return 2",
2822
- " end",
2823
- " set -l hits (find $ERGONEX_HOME -maxdepth 8 '(' -name .worktrees -o -name .ergonex -o -name .git ')' -prune -o -type d -name $argv[1] -exec test -e '{}/.git' ';' -print 2>/dev/null | sort)",
2824
- " if test (count $hits) -eq 0",
2825
- ' echo "wcd: no repository named $argv[1] in $ERGONEX_HOME" >&2; return 1',
2826
- " end",
2827
- " if test (count $hits) -gt 1",
2828
- ` echo "wcd: more than one repository is named $argv[1]:" >&2; printf '%s\\n' $hits >&2; return 1`,
2829
- " end",
2830
- " cd $hits[1]",
2831
- "end"
2832
- ].join(`
2833
- `);
2834
- }
2835
- function pwsh(f) {
2836
- const home = f.home.kind === "default" ? "(Join-Path $HOME 'workspaces')" : pwshQuote(f.home.path);
2837
- const several = f.completions.filter((m) => m.commands.length > 1);
2838
- return [
2839
- "# IF Workspaces (ergonex): the root, the pinned tools on the PATH, the completions of ergonex, and wcd.",
2840
- `if (-not $env:ERGONEX_HOME) { $env:ERGONEX_HOME = ${home} }`,
2841
- "# the shims of the tools ergonex installs: ~/.local/bin (XDG) on Linux and macOS, and the tools folder of ergonex's data on Windows (0031-install-locations)",
2842
- "$ergonexBin = if ($IsLinux -or $IsMacOS) { Join-Path $HOME '.local/bin' } else { Join-Path $(if ($env:XDG_DATA_HOME) { $env:XDG_DATA_HOME } else { $env:LOCALAPPDATA }) 'ergonex\\tools\\bin' }",
2843
- "if (($env:PATH -split [IO.Path]::PathSeparator) -notcontains $ergonexBin) { $env:PATH = $ergonexBin + [IO.Path]::PathSeparator + $env:PATH }",
2844
- "# the person's GitHub sign-in as the token for reading packages, kept in the environment of this shell and never in a file (ergonex 0004-onboarding FR-004).",
2845
- "if (-not $env:ERGONEX_GITHUB_TOKEN -and (Get-Command gh -ErrorAction SilentlyContinue)) {",
2846
- " $ergonexToken = (& gh auth token 2>$null)",
2847
- ' if ($LASTEXITCODE -eq 0 -and $ergonexToken) { $env:ERGONEX_GITHUB_TOKEN = "$ergonexToken".Trim() }',
2848
- "}",
2849
- "Register-ArgumentCompleter -Native -CommandName ergonex -ScriptBlock {",
2850
- " param($wordToComplete, $commandAst, $cursorPosition)",
2851
- " $parts = @($commandAst.CommandElements | ForEach-Object { $_.ToString() })",
2852
- ` $choices = if ($parts.Count -le 1 -or ($parts.Count -eq 2 -and $wordToComplete)) { ${pwshQuote(words(f.completions))} -split ' ' }`,
2853
- ...several.map((m) => ` elseif ($parts[1] -eq '${m.module}') { ${pwshQuote(m.commands.join(" "))} -split ' ' }`),
2854
- " else { @() }",
2855
- ` $choices | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }`,
2856
- "}",
2857
- "function wcd {",
2858
- " param([Parameter(Mandatory = $true)][string]$Name)",
2859
- " $hits = @(Get-ChildItem -Path $env:ERGONEX_HOME -Directory -Recurse -Depth 7 -Filter $Name -ErrorAction SilentlyContinue |",
2860
- " Where-Object { (Test-Path (Join-Path $_.FullName '.git')) -and $_.FullName -notmatch '[\\\\/]\\.(worktrees|ergonex)[\\\\/]' })",
2861
- ' if ($hits.Count -eq 0) { Write-Error "wcd: no repository named $Name in $env:ERGONEX_HOME"; return }',
2862
- ' if ($hits.Count -gt 1) { Write-Error ("wcd: more than one repository is named ${Name}: " + ($hits.FullName -join ", ")); return }',
2863
- " Set-Location $hits[0].FullName",
2864
- "}"
2865
- ].join(`
2866
- `);
2867
- }
2868
- function nu(f) {
2869
- const home = f.home.kind === "default" ? '($nu.home-path | path join "workspaces")' : nuQuote(f.home.path);
2870
- const several = f.completions.filter((m) => m.commands.length > 1);
2871
- return [
2872
- "# IF Workspaces (ergonex): the root, the pinned tools on the PATH, the completions of ergonex, and wcd.",
2873
- `$env.ERGONEX_HOME = ($env.ERGONEX_HOME? | default ${home})`,
2874
- "# the shims of the tools ergonex installs: ~/.local/bin (XDG) on Linux and macOS, and the tools folder of ergonex's data on Windows (0031-install-locations)",
2875
- `let ergonex_bin = (if ($nu.os-info.name == "windows") { (($env.XDG_DATA_HOME? | default $env.LOCALAPPDATA) | path join "ergonex" "tools" "bin") } else { ($env.HOME | path join ".local" "bin") })`,
2876
- "$env.PATH = ($env.PATH | split row (char esep) | where { |p| $p != $ergonex_bin } | prepend $ergonex_bin)",
2023
+ `$env.ERGONEX_HOME = ($env.ERGONEX_HOME? | default ${home})`,
2024
+ "# the shims of the tools ergonex installs: ~/.local/bin (XDG) on Linux and macOS, and the tools folder of ergonex's data on Windows (0031-install-locations)",
2025
+ `let ergonex_bin = (if ($nu.os-info.name == "windows") { (($env.XDG_DATA_HOME? | default $env.LOCALAPPDATA) | path join "ergonex" "tools" "bin") } else { ($env.HOME | path join ".local" "bin") })`,
2026
+ "$env.PATH = ($env.PATH | split row (char esep) | where { |p| $p != $ergonex_bin } | prepend $ergonex_bin)",
2877
2027
  "# the person's GitHub sign-in as the token for reading packages, kept in the environment of this shell and never in a file (ergonex 0004-onboarding FR-004).",
2878
2028
  'if (($env.ERGONEX_GITHUB_TOKEN? | default "") == "") and (which gh | is-not-empty) {',
2879
2029
  " let result = (do { gh auth token } | complete)",
@@ -2928,6 +2078,424 @@ function rcFileFor(shell, f) {
2928
2078
  return absurd(shell);
2929
2079
  }
2930
2080
  }
2081
+ // ../ts/kernel/otel.ts
2082
+ var TRACE_ID = /^[0-9a-f]{32}$/;
2083
+ var SPAN_ID = /^[0-9a-f]{16}$/;
2084
+ var ZEROS = /^0+$/;
2085
+ function parseTraceId(text) {
2086
+ if (!TRACE_ID.test(text))
2087
+ return err("a trace id is 32 lower-case hexadecimal digits");
2088
+ if (ZEROS.test(text))
2089
+ return err("a trace id of all zeros is not valid");
2090
+ return ok(text);
2091
+ }
2092
+ function parseSpanId(text) {
2093
+ if (!SPAN_ID.test(text))
2094
+ return err("a span id is 16 lower-case hexadecimal digits");
2095
+ if (ZEROS.test(text))
2096
+ return err("a span id of all zeros is not valid");
2097
+ return ok(text);
2098
+ }
2099
+ var SAMPLED = 1;
2100
+ var RANDOM = 2;
2101
+ var KNOWN_FLAGS = SAMPLED | RANDOM;
2102
+ var TRACESTATE_MAX_MEMBERS = 32;
2103
+ var KEY_CHAR = "[a-z0-9_\\-*/]";
2104
+ var TRACESTATE_KEY = new RegExp(`^(?:[a-z]${KEY_CHAR}{0,255}|[a-z0-9]${KEY_CHAR}{0,240}@[a-z]${KEY_CHAR}{0,13})$`);
2105
+ var TRACESTATE_VALUE = /^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;
2106
+ function isTraceStateKey(key) {
2107
+ return TRACESTATE_KEY.test(key);
2108
+ }
2109
+ function isTraceStateValue(value) {
2110
+ return TRACESTATE_VALUE.test(value);
2111
+ }
2112
+ function parseTracestate(header) {
2113
+ const out = [];
2114
+ const seen = new Set;
2115
+ for (const raw of header.split(",")) {
2116
+ if (out.length >= TRACESTATE_MAX_MEMBERS)
2117
+ break;
2118
+ const member = raw.replace(/^[ \t]+|[ \t]+$/g, "");
2119
+ if (member === "")
2120
+ continue;
2121
+ const eq = member.indexOf("=");
2122
+ if (eq < 0)
2123
+ continue;
2124
+ const key = member.slice(0, eq);
2125
+ const value = member.slice(eq + 1);
2126
+ if (!isTraceStateKey(key) || !isTraceStateValue(value) || seen.has(key))
2127
+ continue;
2128
+ seen.add(key);
2129
+ out.push({ key, value });
2130
+ }
2131
+ return out;
2132
+ }
2133
+ var SEVERITY = { TRACE: 1, DEBUG: 5, INFO: 9, WARN: 13, ERROR: 17, FATAL: 21 };
2134
+ function isSeverityNumber(n) {
2135
+ return Number.isInteger(n) && n >= 1 && n <= 24;
2136
+ }
2137
+ var TWO_56 = 2 ** 56;
2138
+ var CREDENTIAL_WORDS = new Set(["key", "code", "sig", "pwd", "pass", "session", "sid", "otp", "awsaccesskeyid", "sas", "se", "sp", "sv"]);
2139
+
2140
+ // ../ts/kernel/otlp.ts
2141
+ var SPAN_KINDS = ["internal", "server", "client", "producer", "consumer"];
2142
+ class Failure extends Error {
2143
+ error;
2144
+ constructor(error) {
2145
+ super(error.path);
2146
+ this.error = error;
2147
+ }
2148
+ }
2149
+ function failure(path, expected, input) {
2150
+ return { kind: "decode", path, expected, found: describe(input) };
2151
+ }
2152
+ function message(build) {
2153
+ return (input, path = "$") => {
2154
+ if (typeof input !== "object" || input === null || Array.isArray(input))
2155
+ return err(failure(path, "an object", input));
2156
+ const read = (key, decoder) => {
2157
+ const r = decoder(Reflect.get(input, key), `${path}.${key}`);
2158
+ if (r.kind === "err")
2159
+ throw new Failure(r.error);
2160
+ return r.value;
2161
+ };
2162
+ const f = {
2163
+ req: read,
2164
+ opt: (key, decoder, fallback) => {
2165
+ const v = Reflect.get(input, key);
2166
+ return v === undefined || v === null ? fallback : read(key, decoder);
2167
+ }
2168
+ };
2169
+ try {
2170
+ return ok(build(f, path));
2171
+ } catch (e) {
2172
+ if (e instanceof Failure)
2173
+ return err(e.error);
2174
+ throw e;
2175
+ }
2176
+ };
2177
+ }
2178
+ function list(element) {
2179
+ return (input, path = "$") => {
2180
+ if (!Array.isArray(input))
2181
+ return err(failure(path, "an array", input));
2182
+ const out = [];
2183
+ for (const [i, value] of input.entries()) {
2184
+ const r = element(value, `${path}[${i}]`);
2185
+ if (r.kind === "err")
2186
+ return r;
2187
+ out.push(r.value);
2188
+ }
2189
+ return ok(out);
2190
+ };
2191
+ }
2192
+ var str = (input, path = "$") => typeof input === "string" ? ok(input) : err(failure(path, "a string", input));
2193
+ var bool = (input, path = "$") => typeof input === "boolean" ? ok(input) : err(failure(path, "a boolean", input));
2194
+ var int64 = (input, path = "$") => {
2195
+ if (typeof input === "number" && Number.isInteger(input))
2196
+ return ok(BigInt(input));
2197
+ if (typeof input === "string" && /^-?[0-9]+$/.test(input))
2198
+ return ok(BigInt(input));
2199
+ return err(failure(path, "a 64-bit integer (a number or a decimal string)", input));
2200
+ };
2201
+ var count = (input, path = "$") => {
2202
+ const r = int64(input, path);
2203
+ if (r.kind === "err")
2204
+ return r;
2205
+ return r.value >= 0n && r.value <= BigInt(Number.MAX_SAFE_INTEGER) ? ok(Number(r.value)) : err(failure(path, "a count", input));
2206
+ };
2207
+ var double = (input, path = "$") => {
2208
+ if (typeof input === "number")
2209
+ return ok(input);
2210
+ if (input === "NaN")
2211
+ return ok(NaN);
2212
+ if (input === "Infinity")
2213
+ return ok(Infinity);
2214
+ if (input === "-Infinity")
2215
+ return ok(-Infinity);
2216
+ return err(failure(path, "a double", input));
2217
+ };
2218
+ var bytes = (input, path = "$") => {
2219
+ if (typeof input !== "string")
2220
+ return err(failure(path, "base64", input));
2221
+ const r = fromBase64(input);
2222
+ return r.kind === "ok" ? r : err(failure(path, "base64", input));
2223
+ };
2224
+ var traceId = (input, path = "$") => {
2225
+ const r = typeof input === "string" ? parseTraceId(input.toLowerCase()) : err("");
2226
+ return r.kind === "ok" ? r : err(failure(path, "a trace id (32 hexadecimal digits, not all zeros)", input));
2227
+ };
2228
+ var spanId = (input, path = "$") => {
2229
+ const r = typeof input === "string" ? parseSpanId(input.toLowerCase()) : err("");
2230
+ return r.kind === "ok" ? r : err(failure(path, "a span id (16 hexadecimal digits, not all zeros)", input));
2231
+ };
2232
+ function enumeration(names) {
2233
+ return (input, path = "$") => {
2234
+ if (typeof input === "number" && Number.isInteger(input) && input >= 0 && input < names.length)
2235
+ return ok(input);
2236
+ if (typeof input === "string") {
2237
+ const i = names.indexOf(input);
2238
+ if (i >= 0)
2239
+ return ok(i);
2240
+ }
2241
+ return err(failure(path, `one of ${names.join(", ")} or its number`, input));
2242
+ };
2243
+ }
2244
+ var spanKindEnum = enumeration([
2245
+ "SPAN_KIND_UNSPECIFIED",
2246
+ "SPAN_KIND_INTERNAL",
2247
+ "SPAN_KIND_SERVER",
2248
+ "SPAN_KIND_CLIENT",
2249
+ "SPAN_KIND_PRODUCER",
2250
+ "SPAN_KIND_CONSUMER"
2251
+ ]);
2252
+ var statusCodeEnum = enumeration(["STATUS_CODE_UNSET", "STATUS_CODE_OK", "STATUS_CODE_ERROR"]);
2253
+ var temporalityEnum = enumeration([
2254
+ "AGGREGATION_TEMPORALITY_UNSPECIFIED",
2255
+ "AGGREGATION_TEMPORALITY_DELTA",
2256
+ "AGGREGATION_TEMPORALITY_CUMULATIVE"
2257
+ ]);
2258
+ var SEVERITY_NAMES = ["SEVERITY_NUMBER_UNSPECIFIED"].concat(["TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"].flatMap((r) => ["", "2", "3", "4"].map((n) => `SEVERITY_NUMBER_${r}${n}`)));
2259
+ var severityEnum = (input, path = "$") => {
2260
+ const r = enumeration(SEVERITY_NAMES)(input, path);
2261
+ if (r.kind === "err")
2262
+ return r;
2263
+ return isSeverityNumber(r.value) ? ok(r.value) : err(failure(path, "a severity number from 1 to 24", input));
2264
+ };
2265
+ var decodeAnyValue = (input, path = "$") => {
2266
+ if (typeof input !== "object" || input === null || Array.isArray(input))
2267
+ return err(failure(path, "an AnyValue object", input));
2268
+ const has = (key) => {
2269
+ const v = Reflect.get(input, key);
2270
+ return v !== undefined && v !== null;
2271
+ };
2272
+ const at = (key) => Reflect.get(input, key);
2273
+ if (has("stringValue"))
2274
+ return str(at("stringValue"), `${path}.stringValue`);
2275
+ if (has("boolValue"))
2276
+ return bool(at("boolValue"), `${path}.boolValue`);
2277
+ if (has("intValue"))
2278
+ return int64(at("intValue"), `${path}.intValue`);
2279
+ if (has("doubleValue"))
2280
+ return double(at("doubleValue"), `${path}.doubleValue`);
2281
+ if (has("bytesValue"))
2282
+ return bytes(at("bytesValue"), `${path}.bytesValue`);
2283
+ if (has("arrayValue"))
2284
+ return message((f) => f.opt("values", list(decodeAnyValue), []))(at("arrayValue"), `${path}.arrayValue`);
2285
+ if (has("kvlistValue")) {
2286
+ return message((f) => {
2287
+ const out = {};
2288
+ for (const kv of f.opt("values", list(keyValue(decodeAnyValue)), [])) {
2289
+ Object.defineProperty(out, kv.key, { value: kv.value, enumerable: true, writable: true, configurable: true });
2290
+ }
2291
+ return out;
2292
+ })(at("kvlistValue"), `${path}.kvlistValue`);
2293
+ }
2294
+ return err(failure(path, "an AnyValue holding a value", input));
2295
+ };
2296
+ function keyValue(value) {
2297
+ return message((f) => ({ key: f.req("key", str), value: f.req("value", value) }));
2298
+ }
2299
+ var decodeAttributeValue = (input, path = "$") => {
2300
+ const r = decodeAnyValue(input, path);
2301
+ if (r.kind === "err")
2302
+ return r;
2303
+ const v = r.value;
2304
+ if (typeof v !== "object" || v instanceof Uint8Array)
2305
+ return ok(v);
2306
+ if (Array.isArray(v)) {
2307
+ const values = v;
2308
+ if (values.every((e) => typeof e === "string"))
2309
+ return ok(values.filter((e) => typeof e === "string"));
2310
+ if (values.every((e) => typeof e === "boolean"))
2311
+ return ok(values.filter((e) => typeof e === "boolean"));
2312
+ if (values.every((e) => typeof e === "bigint"))
2313
+ return ok(values.filter((e) => typeof e === "bigint"));
2314
+ if (values.every((e) => typeof e === "number"))
2315
+ return ok(values.filter((e) => typeof e === "number"));
2316
+ }
2317
+ return err(failure(path, "an attribute value (a primitive or a homogeneous array of primitives)", input));
2318
+ };
2319
+ var decodeAttributes = (input, path = "$") => {
2320
+ const r = list(keyValue(decodeAttributeValue))(input, path);
2321
+ if (r.kind === "err")
2322
+ return r;
2323
+ const out = {};
2324
+ for (const kv of r.value)
2325
+ Object.defineProperty(out, kv.key, { value: kv.value, enumerable: true, writable: true, configurable: true });
2326
+ return ok(out);
2327
+ };
2328
+ var resource = message((f) => ({ attributes: f.opt("attributes", decodeAttributes, {}) }));
2329
+ var scope = message((f) => {
2330
+ const version = f.opt("version", str, undefined);
2331
+ const attributes = f.opt("attributes", decodeAttributes, undefined);
2332
+ return {
2333
+ name: f.opt("name", str, ""),
2334
+ ...version === undefined ? {} : { version },
2335
+ ...attributes === undefined ? {} : { attributes }
2336
+ };
2337
+ });
2338
+ var event = message((f) => ({
2339
+ name: f.opt("name", str, ""),
2340
+ time: f.opt("timeUnixNano", int64, 0n),
2341
+ attributes: f.opt("attributes", decodeAttributes, {}),
2342
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0)
2343
+ }));
2344
+ var link = message((f) => ({
2345
+ traceId: f.req("traceId", traceId),
2346
+ spanId: f.req("spanId", spanId),
2347
+ traceState: parseTracestate(f.opt("traceState", str, "")),
2348
+ traceFlags: f.opt("flags", count, 0) & 255,
2349
+ attributes: f.opt("attributes", decodeAttributes, {}),
2350
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0)
2351
+ }));
2352
+ var status = message((f) => {
2353
+ const code = f.opt("code", statusCodeEnum, 0);
2354
+ if (code === 1)
2355
+ return { kind: "ok" };
2356
+ if (code === 2)
2357
+ return { kind: "error", message: f.opt("message", str, "") };
2358
+ return { kind: "unset" };
2359
+ });
2360
+ var optionalSpanId = (input, path = "$") => input === "" ? ok(undefined) : spanId(input, path);
2361
+ var decodeSpan = message((f) => {
2362
+ const parentSpanId = f.opt("parentSpanId", optionalSpanId, undefined);
2363
+ const kind = f.opt("kind", spanKindEnum, 1);
2364
+ return {
2365
+ name: f.opt("name", str, ""),
2366
+ context: {
2367
+ traceId: f.req("traceId", traceId),
2368
+ spanId: f.req("spanId", spanId),
2369
+ traceFlags: f.opt("flags", count, 0) & 255,
2370
+ traceState: parseTracestate(f.opt("traceState", str, "")),
2371
+ isRemote: false
2372
+ },
2373
+ ...parentSpanId === undefined ? {} : { parentSpanId },
2374
+ kind: SPAN_KINDS[kind - 1] ?? "internal",
2375
+ startTime: f.opt("startTimeUnixNano", int64, 0n),
2376
+ endTime: f.opt("endTimeUnixNano", int64, 0n),
2377
+ attributes: f.opt("attributes", decodeAttributes, {}),
2378
+ events: f.opt("events", list(event), []),
2379
+ links: f.opt("links", list(link), []),
2380
+ status: f.opt("status", status, { kind: "unset" }),
2381
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
2382
+ droppedEventsCount: f.opt("droppedEventsCount", count, 0),
2383
+ droppedLinksCount: f.opt("droppedLinksCount", count, 0)
2384
+ };
2385
+ });
2386
+ var optionalTraceId = (input, path = "$") => input === "" ? ok(undefined) : traceId(input, path);
2387
+ var decodeLogRecord = message((f) => {
2388
+ const body = f.opt("body", decodeAnyValue, undefined);
2389
+ const traceFlags = f.opt("flags", count, undefined);
2390
+ const tid = f.opt("traceId", optionalTraceId, undefined);
2391
+ const sid = f.opt("spanId", optionalSpanId, undefined);
2392
+ const eventName = f.opt("eventName", str, undefined);
2393
+ return {
2394
+ time: f.opt("timeUnixNano", int64, 0n),
2395
+ observedTime: f.opt("observedTimeUnixNano", int64, 0n),
2396
+ severityNumber: f.req("severityNumber", severityEnum),
2397
+ severityText: f.opt("severityText", str, ""),
2398
+ ...body === undefined ? {} : { body },
2399
+ attributes: f.opt("attributes", decodeAttributes, {}),
2400
+ droppedAttributesCount: f.opt("droppedAttributesCount", count, 0),
2401
+ ...eventName === undefined ? {} : { eventName },
2402
+ ...tid === undefined ? {} : { traceId: tid },
2403
+ ...sid === undefined ? {} : { spanId: sid },
2404
+ ...traceFlags === undefined ? {} : { traceFlags: traceFlags & 255 }
2405
+ };
2406
+ });
2407
+ var numberPoint = message((f, path) => {
2408
+ const asInt = f.opt("asInt", int64, undefined);
2409
+ const asDouble = f.opt("asDouble", double, undefined);
2410
+ const value = asInt ?? asDouble;
2411
+ if (value === undefined)
2412
+ throw new Failure(failure(`${path}.asDouble`, "asInt or asDouble", undefined));
2413
+ return {
2414
+ attributes: f.opt("attributes", decodeAttributes, {}),
2415
+ startTime: f.opt("startTimeUnixNano", int64, 0n),
2416
+ time: f.opt("timeUnixNano", int64, 0n),
2417
+ value
2418
+ };
2419
+ });
2420
+ var histogramPoint = message((f, path) => {
2421
+ const sum = f.opt("sum", double, undefined);
2422
+ const min = f.opt("min", double, undefined);
2423
+ const max = f.opt("max", double, undefined);
2424
+ const bounds = f.opt("explicitBounds", list(double), []);
2425
+ const bucketCounts = f.opt("bucketCounts", list(count), []);
2426
+ if (bucketCounts.length !== 0 && bucketCounts.length !== bounds.length + 1) {
2427
+ throw new Failure(failure(`${path}.bucketCounts`, `${bounds.length + 1} bucket counts`, bucketCounts.length));
2428
+ }
2429
+ return {
2430
+ attributes: f.opt("attributes", decodeAttributes, {}),
2431
+ startTime: f.opt("startTimeUnixNano", int64, 0n),
2432
+ time: f.opt("timeUnixNano", int64, 0n),
2433
+ count: f.opt("count", count, 0),
2434
+ ...sum === undefined ? {} : { sum },
2435
+ ...min === undefined ? {} : { min },
2436
+ ...max === undefined ? {} : { max },
2437
+ bounds,
2438
+ bucketCounts
2439
+ };
2440
+ });
2441
+ function temporalityOf(n) {
2442
+ return n === 1 ? "delta" : "cumulative";
2443
+ }
2444
+ var decodeMetric = message((f, path) => {
2445
+ const head = { name: f.opt("name", str, ""), description: f.opt("description", str, ""), unit: f.opt("unit", str, "") };
2446
+ const sum = f.opt("sum", message((g) => ({
2447
+ kind: "sum",
2448
+ points: g.opt("dataPoints", list(numberPoint), []),
2449
+ temporality: temporalityOf(g.opt("aggregationTemporality", temporalityEnum, 2)),
2450
+ monotonic: g.opt("isMonotonic", bool, false)
2451
+ })), undefined);
2452
+ if (sum !== undefined)
2453
+ return { ...head, data: sum };
2454
+ const gauge = f.opt("gauge", message((g) => ({ kind: "gauge", points: g.opt("dataPoints", list(numberPoint), []) })), undefined);
2455
+ if (gauge !== undefined)
2456
+ return { ...head, data: gauge };
2457
+ const histogram = f.opt("histogram", message((g) => ({
2458
+ kind: "histogram",
2459
+ points: g.opt("dataPoints", list(histogramPoint), []),
2460
+ temporality: temporalityOf(g.opt("aggregationTemporality", temporalityEnum, 2))
2461
+ })), undefined);
2462
+ if (histogram !== undefined)
2463
+ return { ...head, data: histogram };
2464
+ throw new Failure(failure(`${path}.sum`, "a sum, a gauge or a histogram", undefined));
2465
+ });
2466
+
2467
+ // ../ts/kernel/signals.ts
2468
+ var ATTRIBUTE_TYPES = new Set([
2469
+ "string",
2470
+ "boolean",
2471
+ "int",
2472
+ "double",
2473
+ "bytes",
2474
+ "string[]",
2475
+ "boolean[]",
2476
+ "int[]",
2477
+ "double[]"
2478
+ ]);
2479
+ function defineSignals(kinds) {
2480
+ for (const [name, d] of Object.entries(kinds)) {
2481
+ const declared = new Set(Object.keys(d.attributes).map((k) => k.replace(/\?$/, "")));
2482
+ for (const [k, t] of Object.entries(d.attributes)) {
2483
+ if (!ATTRIBUTE_TYPES.has(t))
2484
+ throw new Error(`${name}: the attribute ${k} has the type ${t}, which does not exist`);
2485
+ }
2486
+ for (const s of d.secret ?? [])
2487
+ if (!declared.has(s))
2488
+ throw new Error(`${name}: the secret attribute ${s} is not declared`);
2489
+ if (d.signal === "histogram" && d.bounds !== undefined) {
2490
+ const b = d.bounds;
2491
+ if (b.some((x, i) => !Number.isFinite(x) || i > 0 && x <= (b[i - 1] ?? -Infinity))) {
2492
+ throw new Error(`${name}: the histogram bounds do not increase`);
2493
+ }
2494
+ }
2495
+ }
2496
+ return { kinds };
2497
+ }
2498
+
2931
2499
  // ../ts/runtime/otel.ts
2932
2500
  var RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
2933
2501
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -4112,7 +3680,7 @@ export {
4112
3680
  MODULE_SOURCES,
4113
3681
  REPO_PATH_ROOM,
4114
3682
  REPO_STATE_KINDS,
4115
- SEVERITIES2 as SEVERITIES,
3683
+ SEVERITIES,
4116
3684
  SHELLS,
4117
3685
  STATE_RECORD_PATH,
4118
3686
  TEMPLATES,
@@ -4122,7 +3690,7 @@ export {
4122
3690
  branchName,
4123
3691
  checkFiles,
4124
3692
  checkPathLength,
4125
- child2 as child,
3693
+ child,
4126
3694
  classify,
4127
3695
  classifyFs,
4128
3696
  collisions,