0field 0.0.0-stage → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/0field.js ADDED
@@ -0,0 +1,4120 @@
1
+ // @ts-self-types="./0field.d.ts"
2
+ //#region dependencies/metatrom-ag/Manu/main/SmartObject.ts
3
+ const habitat = globalThis;
4
+ const Substrate = habitat.HTMLElement ?? class {};
5
+ /**
6
+ * The class above, its model's keys typed as its fields: exported as `SmartObject`, which every SmartObject extends,
7
+ * while the class keeps the name the Descriptor's Generator recognises; a class generic over its model extends
8
+ * {@link SmartObject.Class}, so its subclasses' keys read as fields without their types. A rule over a key
9
+ * is the class's own accessor pair: `get key() { return super.key }` beside a setter that calls `super.key = value`, as
10
+ * a setter alone hides the read.
11
+ */
12
+ const TypedSmartObject = class SmartObject extends Substrate {
13
+ #model;
14
+ static #below = Object.getPrototypeOf(SmartObject.prototype);
15
+ static {
16
+ Object.setPrototypeOf(SmartObject.prototype, new Proxy(Object.create(SmartObject.#below), {
17
+ get: (below, key, receiver) => SmartObject.#holds(receiver, key) ? SmartObject.#view(() => receiver.#model[key], (value) => receiver[key] = value) : Reflect.get(below, key, receiver),
18
+ set: (below, key, value, receiver) => {
19
+ if (typeof key !== "string" || key in below || !(#model in receiver) || !SmartObject.#isRecord(receiver.#model)) return Reflect.set(below, key, value, receiver);
20
+ if (key.startsWith("@")) throw new TypeError(`${receiver.constructor.name}'s ${key} is written only by its class, through update`);
21
+ SmartObject.#replace(receiver, SmartObject.#checked({
22
+ ...receiver.#model,
23
+ [key]: value
24
+ }));
25
+ return true;
26
+ }
27
+ }));
28
+ }
29
+ static #loaded = /* @__PURE__ */ new WeakMap();
30
+ #observers = /* @__PURE__ */ new Set();
31
+ /**
32
+ * The class itself, without its model's keys as fields: what a class generic over its model extends,
33
+ * `class JsonObject<M> extends SmartObject.Class<M>`, as its fields are known only once its model is. Typed as
34
+ * SmartObject's class, so a typed export extended this way declares its own, as View's does.
35
+ */
36
+ static get Class() {
37
+ return this;
38
+ }
39
+ /** Has `by` observe each change to `object`'s model, for as long as anything else holds `by`; a view calls it as it shows `object`. */
40
+ static observe(object, by) {
41
+ object.#observers.add(new WeakRef(by));
42
+ }
43
+ /** Has `by` observe no more of `object`'s changes; a view calls it as it shows another. */
44
+ static unobserve(object, by) {
45
+ for (const each of object.#observers) if (each.deref() === by) object.#observers.delete(each);
46
+ }
47
+ /**
48
+ * Takes `key` out of `object`'s model, telling its observers, where the model holds it: a removal said as one, as a
49
+ * key written `undefined` is refused. Refused for a JSON-LD keyword, which only the class writes, and where the model
50
+ * is no record.
51
+ */
52
+ static remove(object, key) {
53
+ if (key.startsWith("@")) throw new TypeError(`${object.constructor.name}'s ${key} is written only by its class, through update`);
54
+ const model = object.#model;
55
+ if (!SmartObject.#isRecord(model)) throw new TypeError(`${object.constructor.name}'s model is no record, so it holds no key ${key}`);
56
+ if (!Object.hasOwn(model, key)) return;
57
+ const { [key]: _removed, ...rest } = model;
58
+ SmartObject.#replace(object, SmartObject.#checked(rest));
59
+ }
60
+ /**
61
+ * Records the namespace and version a class was loaded from, so in a browser it registers as
62
+ * `<namespace>.<class>-<version>`; a class no loader recorded registers as `<class>-0.0.0`.
63
+ * Refused for a class already recorded, and for one already registered, as its name is then given.
64
+ */
65
+ static loaded(type, from) {
66
+ const recorded = SmartObject.#loaded.get(type);
67
+ if (recorded !== void 0) throw new Error(`${type.name} is already recorded as loaded from ${recorded.namespace} ${recorded.version}`);
68
+ const registered = habitat.customElements?.getName(type) ?? null;
69
+ if (registered !== null) throw new Error(`${type.name} is already registered as ${registered}, too late to record where it was loaded from`);
70
+ SmartObject.#loaded.set(type, from);
71
+ }
72
+ /**
73
+ * Takes the model; without one it holds `{}`, where the model's type allows it. In a browser
74
+ * it first registers its class with `customElements`, refusing a name another class holds.
75
+ */
76
+ constructor(...given) {
77
+ if (habitat.customElements !== void 0) SmartObject.#register(habitat.customElements, new.target);
78
+ super();
79
+ this.#model = SmartObject.#checked(given.length === 0 ? {} : given[0]);
80
+ }
81
+ /** The model, frozen, apart from the object it was given as; a change replaces it through {@link SmartObject.update} or a field, checked as the first. */
82
+ get model() {
83
+ return this.#model;
84
+ }
85
+ /** Replaces the model, checked and frozen like the first. */
86
+ update(model) {
87
+ SmartObject.#replace(this, SmartObject.#checked(model));
88
+ }
89
+ /** Does nothing, until a SmartObject overrides it. */
90
+ start() {}
91
+ /** Does nothing, until a SmartObject overrides it. */
92
+ stop() {}
93
+ /** Does nothing, until a SmartObject overrides it. */
94
+ restored() {}
95
+ /** Does nothing, until a SmartObject overrides it. */
96
+ connected() {}
97
+ /** Does nothing, until a SmartObject overrides it. */
98
+ disconnected() {}
99
+ /** Called by the browser as this element enters a document. */
100
+ connectedCallback() {
101
+ this.connected();
102
+ }
103
+ /** Called by the browser as this element leaves a document. */
104
+ disconnectedCallback() {
105
+ this.disconnected();
106
+ }
107
+ static #register(registry, type) {
108
+ if (registry.getName(type) !== null) return;
109
+ const { namespace, version } = SmartObject.#loaded.get(type) ?? {
110
+ namespace: void 0,
111
+ version: "0.0.0"
112
+ };
113
+ const kebab = type.name.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4").toLowerCase();
114
+ const name = `${namespace === void 0 ? "" : `${namespace}.`}${kebab}-${version}`;
115
+ const holder = registry.get(name);
116
+ if (holder !== void 0) throw new Error(`${name} is held by the class ${holder.name}, so ${type.name} cannot register under it`);
117
+ registry.define(name, type);
118
+ }
119
+ static #replace(object, model) {
120
+ const before = object.#model;
121
+ object.#model = model;
122
+ const keys = SmartObject.#changed(before, model);
123
+ if (keys.length === 0) return;
124
+ const thrown = [];
125
+ for (const each of object.#observers) {
126
+ const by = each.deref();
127
+ if (by === void 0) object.#observers.delete(each);
128
+ else try {
129
+ by.changed(keys);
130
+ } catch (error) {
131
+ thrown.push(error);
132
+ }
133
+ }
134
+ if (thrown.length > 0) throw new AggregateError(thrown, `${thrown.length} of ${object.constructor.name}'s observers failed on its change to ${keys.join(", ")}; the change stands`);
135
+ }
136
+ static #changed(before, after) {
137
+ if (!SmartObject.#isRecord(before) || !SmartObject.#isRecord(after)) return JSON.stringify(before) === JSON.stringify(after) ? [] : [""];
138
+ return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key]));
139
+ }
140
+ static #checked(model) {
141
+ if (!SmartObject.#isSerializable(model)) throw new TypeError("a SmartObject model holds only JSON data");
142
+ return SmartObject.#frozen(JSON.parse(JSON.stringify(model)));
143
+ }
144
+ static #isRecord(model) {
145
+ return typeof model === "object" && model !== null && !Array.isArray(model);
146
+ }
147
+ static #holds(receiver, key) {
148
+ return typeof key === "string" && !key.startsWith("@") && !(key in SmartObject.#below) && #model in receiver && SmartObject.#isRecord(receiver.#model) && Object.hasOwn(receiver.#model, key);
149
+ }
150
+ static #view(read, write) {
151
+ const value = read();
152
+ if (typeof value !== "object" || value === null) return value;
153
+ const at = (key) => read()[key];
154
+ const view = new Proxy(Array.isArray(value) ? [] : {}, {
155
+ get: (_, key) => {
156
+ const current = read();
157
+ if (typeof key === "string" && Object.hasOwn(current, key)) return SmartObject.#view(() => at(key), (inner) => write(SmartObject.#with(read(), key, inner)));
158
+ if (Array.isArray(current) && typeof key === "string" && SmartObject.#changing.has(key)) return (...given) => {
159
+ const copy = [...current];
160
+ const returned = copy[key](...given);
161
+ write(copy);
162
+ return returned === copy ? view : returned;
163
+ };
164
+ return Reflect.get(current, key);
165
+ },
166
+ set: (_, key, inner) => (write(SmartObject.#with(read(), key, inner)), true),
167
+ deleteProperty: (_, key) => (write(SmartObject.#with(read(), key, void 0)), true),
168
+ has: (_, key) => Reflect.has(read(), key),
169
+ ownKeys: () => Reflect.ownKeys(read()),
170
+ getOwnPropertyDescriptor: (target, key) => {
171
+ const descriptor = Reflect.getOwnPropertyDescriptor(read(), key);
172
+ return descriptor && {
173
+ ...descriptor,
174
+ writable: true,
175
+ configurable: !(Array.isArray(target) && key === "length")
176
+ };
177
+ }
178
+ });
179
+ return view;
180
+ }
181
+ static #changing = /* @__PURE__ */ new Set([
182
+ "copyWithin",
183
+ "fill",
184
+ "pop",
185
+ "push",
186
+ "reverse",
187
+ "shift",
188
+ "sort",
189
+ "splice",
190
+ "unshift"
191
+ ]);
192
+ static #with(value, key, inner) {
193
+ if (Array.isArray(value)) {
194
+ const copy = [...value];
195
+ Reflect.set(copy, key, inner);
196
+ return copy;
197
+ }
198
+ const { [key]: _, ...rest } = value;
199
+ return inner === void 0 ? rest : {
200
+ ...rest,
201
+ [key]: inner
202
+ };
203
+ }
204
+ static #isSerializable(value) {
205
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
206
+ if (typeof value === "number") return Number.isFinite(value) && !Object.is(value, -0);
207
+ if (Array.isArray(value)) return value.every(SmartObject.#isSerializable);
208
+ if (typeof value !== "object") return false;
209
+ const prototype = Object.getPrototypeOf(value);
210
+ if (prototype !== Object.prototype && prototype !== null) return false;
211
+ return Object.values(value).every(SmartObject.#isSerializable);
212
+ }
213
+ static #frozen(value) {
214
+ if (typeof value === "object" && value !== null) Object.values(value).forEach(SmartObject.#frozen);
215
+ return Object.freeze(value);
216
+ }
217
+ };
218
+ //#endregion
219
+ //#region dependencies/metatrom-ag/Manu/main/common/loading/Program.ts
220
+ /**
221
+ * Purpose: be one program a realm runs, so whoever started it can await
222
+ * its start, find it from its SmartObject, and stop it.
223
+ *
224
+ * Intention: the kernels make one for each program their realm was started
225
+ * with, and `OField` one more for each it runs beside them;
226
+ * `OField` hands it out and names it for its SmartObject.
227
+ */
228
+ var Program = class extends TypedSmartObject {
229
+ #running;
230
+ #finished = Promise.withResolvers();
231
+ /**
232
+ * Over the file it runs, the words it is given, where its habitat shows what it runs, where it names a place, and the
233
+ * file of the view it shows it in, where it names one.
234
+ */
235
+ constructor(model) {
236
+ super(model);
237
+ this.#finished.promise.catch(() => {});
238
+ }
239
+ /** The SmartObject it runs, once it has begun; none before. */
240
+ get smartObject() {
241
+ return this.#running?.smartObject;
242
+ }
243
+ /**
244
+ * The words its SmartObject hears: every word given where its file names its model, otherwise those after the
245
+ * model's address; none before it has begun.
246
+ */
247
+ get heard() {
248
+ return this.#running?.heard ?? [];
249
+ }
250
+ /** Settles once the start of the SmartObject it runs has finished, failing as that start fails. */
251
+ get finished() {
252
+ return this.#finished.promise;
253
+ }
254
+ /** Runs a SmartObject as this program, hearing the words given: starts it, {@link Program.finished} settling with that start. Refused once it runs one. */
255
+ begin(smartObject, heard) {
256
+ if (this.#running !== void 0) throw new Error(`${this.model.address} runs already`);
257
+ this.#running = {
258
+ smartObject,
259
+ heard
260
+ };
261
+ Promise.resolve().then(() => smartObject.start()).then(this.#finished.resolve, this.#finished.reject);
262
+ }
263
+ /** Stops the SmartObject it runs; nothing before it has begun. */
264
+ async stop() {
265
+ await this.#running?.smartObject.stop();
266
+ }
267
+ };
268
+ //#endregion
269
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/Folder.ts
270
+ /** Whether an {@link Entry} is a {@link Folder} — by the member only a `Folder` declares. */
271
+ function isFolder(entry) {
272
+ return "entries" in entry;
273
+ }
274
+ //#endregion
275
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/git/GitConfig.ts
276
+ /**
277
+ * Purpose: make a Git config file's sections and values available as a model.
278
+ *
279
+ * Intention: {@link GitModules} and {@link GitRepository} use it to read
280
+ * `.gitmodules` and `.git/config`; callers can limit which sections and keys
281
+ * it accepts.
282
+ */
283
+ var GitConfig = class GitConfig extends TypedSmartObject {
284
+ /**
285
+ * Reads Git config sections and keys into a model. A missing file gives an empty model. Throws for invalid UTF-8,
286
+ * malformed syntax, or sections and keys rejected by `refuses`.
287
+ */
288
+ constructor(file, refuses = () => void 0) {
289
+ super(file.exists ? GitConfig.#read(file, refuses) : {});
290
+ }
291
+ static #read(file, refuses) {
292
+ const bytes = file.read();
293
+ let text;
294
+ try {
295
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
296
+ } catch (error) {
297
+ throw new Error(`not UTF-8: ${file.path}`, { cause: error });
298
+ }
299
+ const sections = /* @__PURE__ */ new Map();
300
+ let named;
301
+ let section;
302
+ const lines = text.split(/\r?\n/);
303
+ for (let index = 0; index < lines.length; index++) {
304
+ const at = index + 1;
305
+ const refuse = (fault) => /* @__PURE__ */ new Error(`${fault}, ${file.path}:${at}: ${lines[index].slice(0, 80)}`);
306
+ const line = lines[index].replace(/^\s+/, "");
307
+ if (line === "" || line.startsWith("#") || line.startsWith(";")) continue;
308
+ if (line.startsWith("[")) {
309
+ const header = /^\[([A-Za-z0-9.-]+)(?:\s+"((?:[^"\\\n]|\\.)*)")?\]\s*(?:[#;].*)?$/.exec(line);
310
+ if (header === null) throw refuse(refuses(void 0) ?? "no section git reads");
311
+ named = {
312
+ name: header[1].toLowerCase(),
313
+ ...header[2] === void 0 ? {} : { subsection: header[2].replace(/\\(.)/g, "$1") }
314
+ };
315
+ const fault = refuses(named);
316
+ if (fault !== void 0) throw refuse(fault);
317
+ const key = named.subsection === void 0 ? named.name : `${named.name}.${named.subsection}`;
318
+ section = sections.get(key) ?? /* @__PURE__ */ new Map();
319
+ sections.set(key, section);
320
+ continue;
321
+ }
322
+ const entry = /^([A-Za-z][A-Za-z0-9-]*)\s*(=?)(.*)$/.exec(line);
323
+ if (entry === null) throw refuse(`not a line of ${file.name}`);
324
+ const fault = refuses(named, entry[1]);
325
+ if (fault !== void 0) throw refuse(fault);
326
+ if (section === void 0) throw refuse("a key before any section");
327
+ const key = entry[1].toLowerCase();
328
+ if (entry[2] === "") {
329
+ if (entry[3].trim() !== "" && !/^\s*[#;]/.test(entry[3])) throw refuse(`not a line of ${file.name}`);
330
+ section.set(key, "true");
331
+ continue;
332
+ }
333
+ let raw = entry[3];
334
+ while (/(^|[^\\])(\\\\)*\\$/.test(raw) && index + 1 < lines.length) raw = raw.slice(0, -1) + lines[++index];
335
+ const value = GitConfig.#value(raw);
336
+ if (value === void 0) throw refuse("not a value git reads");
337
+ section.set(key, value);
338
+ }
339
+ return Object.fromEntries([...sections].map(([name, keys]) => [name, Object.fromEntries(keys)]));
340
+ }
341
+ static #value(raw) {
342
+ let value = "";
343
+ let kept = 0;
344
+ let quoted = false;
345
+ const text = raw.replace(/^\s+/, "");
346
+ for (let index = 0; index < text.length; index++) {
347
+ const char = text[index];
348
+ if (char === "\\") {
349
+ const escaped = ESCAPES.get(text[++index]);
350
+ if (escaped === void 0) return void 0;
351
+ value += escaped;
352
+ kept = value.length;
353
+ } else if (char === "\"") {
354
+ quoted = !quoted;
355
+ kept = value.length;
356
+ } else if (!quoted && (char === "#" || char === ";")) break;
357
+ else {
358
+ value += char;
359
+ if (quoted || !/\s/.test(char)) kept = value.length;
360
+ }
361
+ }
362
+ return quoted ? void 0 : value.slice(0, kept);
363
+ }
364
+ };
365
+ const ESCAPES = /* @__PURE__ */ new Map([
366
+ ["\\", "\\"],
367
+ ["\"", "\""],
368
+ ["n", "\n"],
369
+ ["t", " "],
370
+ ["b", "\b"]
371
+ ]);
372
+ //#endregion
373
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/git/GitModules.ts
374
+ /**
375
+ * Purpose: keep what a tree's `.gitmodules` says it takes from other trees.
376
+ *
377
+ * Intention: git's own file, read as {@link GitConfig}; a `Workbench`
378
+ * asks it which dependency sits at which path.
379
+ */
380
+ var GitModules = class extends TypedSmartObject {
381
+ /**
382
+ * Reads `.gitmodules` from a file into a model of each submodule's keys, as gitmodules(5) names them; a missing one
383
+ * holds no submodule. A section that is no submodule's, a key a submodule cannot have, and a line git would not read
384
+ * are refused, naming the file and the line; so is a file that is not UTF-8.
385
+ */
386
+ constructor(file) {
387
+ const sections = new GitConfig(file, submodules).model;
388
+ super(Object.fromEntries(Object.entries(sections).map(([section, keys]) => [section.slice(10), Object.fromEntries(Object.entries(keys).map(([key, value]) => [KEYS.get(key), value]))])));
389
+ }
390
+ /** The path of each submodule that names one. */
391
+ get paths() {
392
+ return Object.values(this.model).flatMap((submodule) => submodule.path === void 0 ? [] : [submodule.path]);
393
+ }
394
+ };
395
+ const KEYS = new Map([
396
+ "path",
397
+ "url",
398
+ "branch",
399
+ "update",
400
+ "fetchRecurseSubmodules",
401
+ "ignore",
402
+ "shallow"
403
+ ].map((key) => [key.toLowerCase(), key]));
404
+ const submodules = (section, key) => {
405
+ if (key === void 0) return section?.name === "submodule" && section.subsection !== void 0 ? void 0 : "no submodule section";
406
+ if (section === void 0) return "a key before any submodule";
407
+ return KEYS.has(key.toLowerCase()) ? void 0 : `no key a submodule has: ${key}`;
408
+ };
409
+ //#endregion
410
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/git/GitRepository.ts
411
+ /**
412
+ * Purpose: read what git keeps for one working tree.
413
+ *
414
+ * Intention: reads git's own layout, as its documentation describes it,
415
+ * and the common dir's config as {@link GitConfig}. It uses the
416
+ * {@link Folder} it sits in, which a subclass kept apart from any tree may lack.
417
+ */
418
+ var GitRepository = class extends TypedSmartObject.Class {
419
+ #folder;
420
+ /**
421
+ * The working tree at a folder; its model holds the folder's path, unless a subclass's holds more. Without a folder
422
+ * — a subclass's model stored apart from any tree — it is given its model.
423
+ */
424
+ constructor(folder, model = { path: folder.path }) {
425
+ super(model);
426
+ this.#folder = folder;
427
+ }
428
+ /** The folder of the working tree; refused where this one has none on this host. */
429
+ get folder() {
430
+ if (this.#folder === void 0) throw new Error("no working tree on this host");
431
+ return this.#folder;
432
+ }
433
+ /** The path of the working tree's folder. */
434
+ get path() {
435
+ return this.folder.path;
436
+ }
437
+ /** The branch checked out here, or the sha where its HEAD is detached; none without a HEAD. */
438
+ get head() {
439
+ const head = this.gitDir?.file("HEAD");
440
+ if (head === void 0 || !head.exists) return void 0;
441
+ const text = head.readText().trim();
442
+ return text.startsWith("ref: refs/heads/") ? text.slice(16) : text;
443
+ }
444
+ /** The git dir a `.git` file names, as git wrote it; none where `.git` is a folder or missing. */
445
+ get pointer() {
446
+ const pointer = this.folder.file(".git");
447
+ return pointer.exists ? /^gitdir:\s*(.+)$/m.exec(pointer.readText())?.[1].trim() : void 0;
448
+ }
449
+ /** The URL of a remote, as the common dir's config names it; none where it names none. */
450
+ remote(name) {
451
+ const git = this.commonDir;
452
+ return git === void 0 ? void 0 : new GitConfig(git.file("config")).model[`remote.${name}`]?.url;
453
+ }
454
+ /**
455
+ * The worktrees the common dir keeps a record of — `<common dir>/worktrees/<name>/gitdir` — each by its record's name
456
+ * and the path git wrote for it, its `/.git` dropped.
457
+ */
458
+ get worktrees() {
459
+ const records = this.commonDir?.folder("worktrees");
460
+ if (records === void 0) return [];
461
+ return records.entries.flatMap((record) => isFolder(record) && record.file("gitdir").exists ? [{
462
+ name: record.name,
463
+ path: record.file("gitdir").readText().trim().replace(/\/\.git$/, "")
464
+ }] : []);
465
+ }
466
+ /** The common dir, which a worktree's git dir names in `commondir`, and is the git dir itself elsewhere; none without one. */
467
+ get commonDir() {
468
+ const gitDir = this.gitDir;
469
+ if (gitDir === void 0) return void 0;
470
+ const common = gitDir.file("commondir");
471
+ return common.exists ? this.#at(common.readText().trim(), gitDir) : gitDir;
472
+ }
473
+ /** The git dir: `.git` itself where it is a folder, the one a `.git` file names, none where there is neither. */
474
+ get gitDir() {
475
+ if (this.folder.folder(".git").exists) return this.folder.folder(".git");
476
+ const named = this.pointer;
477
+ return named === void 0 ? void 0 : this.#at(named, this.folder);
478
+ }
479
+ #at(path, from) {
480
+ const absolute = path.startsWith("/") || /^[A-Za-z]:\//.test(path) ? path : `${from.path}/${path}`;
481
+ const names = [];
482
+ for (const name of absolute.split("/")) {
483
+ if (name === "" || name === ".") continue;
484
+ if (name === "..") names.pop();
485
+ else names.push(name);
486
+ }
487
+ return this.folder.at(/^[A-Za-z]:$/.test(names[0] ?? "") ? names.join("/") : `/${names.join("/")}`);
488
+ }
489
+ };
490
+ //#endregion
491
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/Releases.ts
492
+ /**
493
+ * Purpose: decide which of a thing's versions or tags a ref names: its
494
+ * latest release, or the highest release within a range.
495
+ *
496
+ * Intention: the oField hook asks it over the names a workbench's `Tags` hold, the npm
497
+ * hook over a package's version folders, and `OFieldIri` reads the ranges a
498
+ * ref may name from it. It reads a version by SemVer 2.0, a range as npm
499
+ * does.
500
+ */
501
+ var Releases = class Releases extends TypedSmartObject {
502
+ /** A range a ref may name: `^X[.Y[.Z]]` or `~X.Y[.Z]`, its parts without leading zeros and at most 15 digits. */
503
+ static range = /^(?:\^(0|[1-9]\d{0,14})(?:\.(0|[1-9]\d{0,14})(?:\.(0|[1-9]\d{0,14}))?)?|~(0|[1-9]\d{0,14})\.(0|[1-9]\d{0,14})(?:\.(0|[1-9]\d{0,14}))?)$/;
504
+ /**
505
+ * The highest stable one — `X.Y.Z` or `vX.Y.Z`, each part at most 15 digits, by SemVer 2.0 precedence, as named; a
506
+ * pre-release or any other tag never is.
507
+ */
508
+ get latest() {
509
+ return this.#highest();
510
+ }
511
+ /**
512
+ * The tag or sha a ref names: the latest release for none or `latest`, the highest within a range for one, the ref
513
+ * itself otherwise; none where no release is there to name.
514
+ */
515
+ named(ref) {
516
+ if (ref === void 0 || ref === "latest") return this.latest;
517
+ return Releases.range.test(ref) ? this.within(ref) : ref;
518
+ }
519
+ /**
520
+ * The highest stable one within a range, as named — `^X[.Y[.Z]]` up to the next change of its first part that is
521
+ * not zero, or of its last given part where all are zero; `~X.Y[.Z]` up to the next minor. None where none is
522
+ * within it; refused where the range is none of these.
523
+ */
524
+ within(range) {
525
+ return this.#highest(Releases.#bounds(range));
526
+ }
527
+ #highest(bounds) {
528
+ let highest;
529
+ for (const tag of this.model) {
530
+ const match = STABLE.exec(tag);
531
+ if (match === null) continue;
532
+ const version = match.slice(1).map(Number);
533
+ if (bounds !== void 0 && (Releases.#higher(bounds[0], version) || !Releases.#higher(bounds[1], version))) continue;
534
+ if (highest === void 0 || Releases.#higher(version, highest.version)) highest = {
535
+ tag,
536
+ version
537
+ };
538
+ }
539
+ return highest?.tag;
540
+ }
541
+ static #bounds(range) {
542
+ const match = Releases.range.exec(range);
543
+ if (match === null) throw new Error(`no range: ${range}, but ^X[.Y[.Z]] or ~X.Y[.Z]`);
544
+ const caret = match[1] !== void 0;
545
+ const given = (caret ? match.slice(1, 4) : match.slice(4, 7)).filter((part) => part !== void 0).map(Number);
546
+ const lower = [
547
+ 0,
548
+ 1,
549
+ 2
550
+ ].map((index) => given[index] ?? 0);
551
+ const nonZero = given.findIndex((part) => part !== 0);
552
+ const moves = caret ? nonZero === -1 ? given.length - 1 : nonZero : 1;
553
+ return [lower, lower.map((part, index) => index < moves ? part : index === moves ? part + 1 : 0)];
554
+ }
555
+ static #higher(version, than) {
556
+ const at = version.findIndex((part, index) => part !== than[index]);
557
+ return at !== -1 && version[at] > than[at];
558
+ }
559
+ };
560
+ const STABLE = /^v?(0|[1-9]\d{0,14})\.(0|[1-9]\d{0,14})\.(0|[1-9]\d{0,14})$/;
561
+ //#endregion
562
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/OFieldIri.ts
563
+ /**
564
+ * Purpose: identify a SmartObject, or a version of it, the same way wherever
565
+ * it is stored.
566
+ *
567
+ * Intention: realizes the IRI of a JSON-LD node's `@id` and `@type`; each
568
+ * graph resolves it to its own address, such as a path, a hash or a CID.
569
+ */
570
+ var OFieldIri = class OFieldIri extends TypedSmartObject {
571
+ /** Parses an oField IRI, or takes its parts; refuses either when it is not one, naming the fault. */
572
+ constructor(uri) {
573
+ super(typeof uri === "string" ? parts(uri) : uri);
574
+ this.#refuseUnlessCanonical(uri);
575
+ }
576
+ /**
577
+ * The oField IRI an IRI is; none where it is no oField IRI, or none in canonical form. An IRI of the scheme `oasis:`,
578
+ * the one before `ofield:`, is refused, naming `ofield://`.
579
+ */
580
+ static of(iri) {
581
+ OFieldIri.refuseRetired(iri);
582
+ if (!iri.startsWith(SCHEME)) return void 0;
583
+ try {
584
+ return new OFieldIri(iri);
585
+ } catch {
586
+ return;
587
+ }
588
+ }
589
+ /** Refuses an address of the scheme `oasis:`, the one before `ofield:`, naming `ofield://`; any other passes. */
590
+ static refuseRetired(address) {
591
+ if (address.startsWith(RETIRED)) throw new TypeError(`the scheme is ofield://, not oasis://: ${address}`);
592
+ }
593
+ /** An IRI as it names no ref: an oField IRI without its ref, anything else — no oField IRI — as it stands. */
594
+ static unpinned(iri) {
595
+ const uri = OFieldIri.of(iri);
596
+ if (uri === void 0) return iri;
597
+ const { ref: _ref, ...rest } = uri.model;
598
+ return new OFieldIri(rest).toString();
599
+ }
600
+ /**
601
+ * Whether a ref is a data ref — under `refs/` and no branch — which holds what is stored as data, never code to run;
602
+ * a ref read with what follows it, as a path continues it, is told apart as the ref alone.
603
+ */
604
+ static isDataRef(ref) {
605
+ return ref !== void 0 && ref.startsWith("refs/") && !ref.startsWith("refs/heads/");
606
+ }
607
+ /** Whether a ref pins what it names — a sha, a version or a range of versions — where any other ref names a head that moves. */
608
+ static isPinned(ref) {
609
+ if (ref === void 0) return false;
610
+ return /^[0-9a-f]{40}$/.test(ref) || Releases.range.test(ref) || new Releases([ref]).latest === ref;
611
+ }
612
+ /**
613
+ * The oField IRI a reference naming no scheme names, read against this one as RFC 3986 resolves it — `//`, `/`, `.`
614
+ * and `..` as they read there — with every part kept as written, a range and what a URL would percent-encode among
615
+ * them. A fragment is cut before it is resolved, as no oField IRI has one; no oField IRI has a query either, so a `?`
616
+ * is part of the path. Refused, naming the fault, where it names no oField IRI in canonical form.
617
+ */
618
+ resolve(reference) {
619
+ const unfragmented = reference.split("#")[0];
620
+ if (unfragmented === "") return this;
621
+ if (unfragmented.startsWith("//")) {
622
+ const root = unfragmented.indexOf("/", 2);
623
+ return new OFieldIri(root === -1 ? `ofield:${unfragmented}` : `ofield:${unfragmented.slice(0, root)}${join(withoutDotSegments(unfragmented.slice(root).split("/").slice(1).map(plain$1)))}`);
624
+ }
625
+ const printed = this.toString();
626
+ const root = printed.indexOf("/", SCHEME.length);
627
+ if (unfragmented.startsWith("/")) return new OFieldIri(`${printed.slice(0, root)}${join(withoutDotSegments(unfragmented.split("/").slice(1).map(plain$1)))}`);
628
+ const kept = withoutDotSegments([...[{
629
+ text: "",
630
+ head: true
631
+ }, ...this.model.subpath?.split("/").map(plain$1) ?? []].slice(0, -1), ...unfragmented.split("/").map(plain$1)]);
632
+ if (kept[0]?.head !== true) return new OFieldIri(`${printed.slice(0, root)}${join(kept)}`);
633
+ const rest = kept.slice(1).map(({ text }) => text);
634
+ return new OFieldIri({
635
+ ...this.model,
636
+ subpath: rest.join("/")
637
+ });
638
+ }
639
+ toString() {
640
+ const { namespace, name, ref, subpath } = this.model;
641
+ const from = this.#from();
642
+ if (ref === void 0) return `${SCHEME}${from}${namespace}/${name}${subpath === void 0 ? "" : `/${subpath}`}`;
643
+ const inside = subpath === void 0 ? ref.includes("/") ? ":" : "" : `:${subpath}`;
644
+ return `${SCHEME}${from}${namespace}/${name}@${ref.replaceAll("%", "%25")}${inside}`;
645
+ }
646
+ #refuseUnlessCanonical(uri) {
647
+ if (typeof this.model !== "object" || this.model === null) throw new TypeError("an oField URI model is an object");
648
+ const printed = this.toString();
649
+ if (typeof uri === "string") {
650
+ if (printed !== uri) throw new TypeError(`not in canonical form, which is ${printed}: ${uri}`);
651
+ return;
652
+ }
653
+ const again = parts(printed);
654
+ const given = this.model;
655
+ const differing = [.../* @__PURE__ */ new Set([...Object.keys(again), ...Object.keys(given)])].find((key) => again[key] !== given[key]);
656
+ if (differing !== void 0) throw new TypeError(`${differing} is not a part as given: ${JSON.stringify(uri)}`);
657
+ }
658
+ #from() {
659
+ const { source } = this.model;
660
+ return source === void 0 ? "" : `${source.replaceAll("%", "%25").replaceAll("/", "%2F")}:`;
661
+ }
662
+ };
663
+ const SCHEME = "ofield://";
664
+ const RETIRED = "oasis:";
665
+ const RANGE = /[\^~*\s]/;
666
+ function parts(uri) {
667
+ const refuse = (fault) => {
668
+ throw new TypeError(`${fault}: ${uri}`);
669
+ };
670
+ OFieldIri.refuseRetired(uri);
671
+ if (!uri.startsWith(SCHEME)) refuse("not an oField URI");
672
+ const rest = uri.slice(9);
673
+ const slash = rest.indexOf("/");
674
+ if (slash === -1) refuse("no name");
675
+ const authority = rest.slice(0, slash);
676
+ const colon = authority.lastIndexOf(":");
677
+ const source = colon === -1 ? void 0 : decoded(authority.slice(0, colon), refuse);
678
+ const namespace = authority.slice(colon + 1);
679
+ if (source === "") refuse("empty source");
680
+ if (namespace === "") refuse("no namespace");
681
+ const tail = rest.slice(slash + 1);
682
+ const scoped = namespace === "npm" && tail.startsWith("@");
683
+ const scope = scoped ? tail.indexOf("/") : -1;
684
+ if (scoped && scope === -1) refuse("a scope is no name");
685
+ const ends = tail.slice(scope + 1).search(/[@/]/);
686
+ const name = tail.slice(0, ends === -1 ? tail.length : scope + 1 + ends);
687
+ if (name.split("/").some((segment) => segment === "" || segment === "@")) refuse("no name");
688
+ const after = tail.slice(name.length);
689
+ let refText;
690
+ let path;
691
+ if (after.startsWith("/")) path = after.slice(1);
692
+ else if (after !== "") {
693
+ const text = after.slice(1);
694
+ const colon = text.indexOf(":");
695
+ const cut = colon === -1 ? text.indexOf("/") : colon;
696
+ refText = cut === -1 ? text : text.slice(0, cut);
697
+ path = cut === -1 ? void 0 : text.slice(cut + 1);
698
+ if (colon !== -1 && path === "") path = void 0;
699
+ }
700
+ const ref = refText === void 0 ? void 0 : decoded(refText, refuse);
701
+ if (ref === "") refuse("empty ref");
702
+ if (ref?.includes(":")) refuse("a git ref holds no colon");
703
+ if (ref !== void 0 && RANGE.test(ref) && !Releases.range.test(ref)) refuse("a range is a ref only as ^X[.Y[.Z]] or ~X.Y[.Z]");
704
+ if (path?.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) refuse("bad subpath");
705
+ const subpath = path;
706
+ return {
707
+ ...source === void 0 ? {} : { source },
708
+ namespace,
709
+ name,
710
+ ...ref === void 0 ? {} : { ref },
711
+ ...subpath === void 0 ? {} : { subpath }
712
+ };
713
+ }
714
+ const plain$1 = (text) => ({
715
+ text,
716
+ head: false
717
+ });
718
+ const join = (segments) => `/${segments.map(({ text }) => text).join("/")}`;
719
+ function withoutDotSegments(segments) {
720
+ const kept = [];
721
+ for (const segment of segments) if (segment.text === "..") kept.pop();
722
+ else if (segment.text !== ".") kept.push(segment);
723
+ const last = segments.at(-1)?.text;
724
+ if (last === "." || last === "..") kept.push(plain$1(""));
725
+ return kept;
726
+ }
727
+ function decoded(part, refuse) {
728
+ try {
729
+ return decodeURIComponent(part);
730
+ } catch {
731
+ return refuse("bad percent-encoding");
732
+ }
733
+ }
734
+ //#endregion
735
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/Workbench.ts
736
+ /**
737
+ * Purpose: say what stands under one SmartObject's name — its domain, in its
738
+ * own words — in one stored node that is also the dictionary its nodes name.
739
+ *
740
+ * Intention: a workbench is all that stands under one name. Its
741
+ * model is what is stored — its `@id`, its own `@context`, the dictionary of
742
+ * its words, and the descriptors of its `classes`; the working tree it is
743
+ * read from on this host is no part of it, so a stored one has none. It is
744
+ * the {@link GitRepository} that reads that tree, and uses the
745
+ * {@link GitModules} of its submodules; the oField hook asks it for its own
746
+ * working tree and a SmartObject's checkout, and a storage that realizes
747
+ * one for a persistence names it by an `@id`, so a model relates to it as
748
+ * to any SmartObject. `JsonLd` reads and writes it as
749
+ * the one node that carries its own `@context`. It is made, checked,
750
+ * upgraded, watched and carried by the {@link WorkbenchTools} a program
751
+ * registers, Core when it loads.
752
+ */
753
+ var Workbench = class Workbench extends GitRepository {
754
+ /** The IRI of the type of a workbench node. */
755
+ static type = "ofield://metatrom-ag/Manu/Workbench";
756
+ static #tools;
757
+ /** Registers the tools {@link Workbench.create} and each workbench's `check`, `upgrade`, `watch`, `carry` and `readToken` delegate to; called by Core when it loads. */
758
+ static useTools(tools) {
759
+ Workbench.#tools = tools;
760
+ }
761
+ /** A new workbench named `name`, from a template where one is named, made by the registered tools; the lines they report. */
762
+ static async create(name, template) {
763
+ return Workbench.#registered().create(name, template);
764
+ }
765
+ static #registered() {
766
+ if (Workbench.#tools === void 0) throw new Error("no tools work on a workbench: load ofield://metatrom-ag/Core, which registers them");
767
+ return Workbench.#tools;
768
+ }
769
+ /** A workbench of the model a node stored it as, or one read from the working tree at a folder. */
770
+ constructor(model = {}, folder) {
771
+ super(folder, model);
772
+ }
773
+ /** The workbench at a folder, named by `id` where a persistence restores it. */
774
+ static at(folder, id) {
775
+ return new Workbench(id === void 0 ? {} : { "@id": id }, folder);
776
+ }
777
+ /** The address of the file a workbench named by an `@id` is stored in: `workbench.jsonld` in the root that `@id` names. */
778
+ static stored(id) {
779
+ const named = OFieldIri.of(id);
780
+ if (named !== void 0) return new OFieldIri({
781
+ ...named.model,
782
+ subpath: "workbench.jsonld"
783
+ }).toString();
784
+ return `${id.replace(/\/+$/, "")}/workbench.jsonld`;
785
+ }
786
+ /**
787
+ * The repository of the nearest `.gitmodules` or `.git` at or above a folder, so a dependency answers from its own,
788
+ * as git's recursive submodules do.
789
+ */
790
+ static above(folder) {
791
+ if (folder === void 0) return void 0;
792
+ const found = [folder, ...folder.ancestors].find((entry) => isFolder(entry) && (entry.file(".gitmodules").exists || entry.folder(".git").exists || entry.file(".git").exists));
793
+ return found === void 0 ? void 0 : Workbench.at(found);
794
+ }
795
+ /**
796
+ * Its own working tree, at whatever its HEAD names — a branch or a detached sha — where a SmartObject is the one
797
+ * the `@id` of its root's `workbench.jsonld` names; none for another.
798
+ */
799
+ own(id) {
800
+ return id === this.#named ? this.folder : void 0;
801
+ }
802
+ /** The branch of a SmartObject's one checkout; none where it has none, refused where it has several, so a ref is named. */
803
+ branch(id) {
804
+ const branches = this.#branches(id);
805
+ if (branches.length > 1) throw new Error(`${id} is checked out on ${branches.join(", ")} in ${this.path}: name a ref`);
806
+ return branches[0];
807
+ }
808
+ /**
809
+ * The checkout of a SmartObject's branch: its own working tree for its own SmartObject on the branch checked out
810
+ * here, elsewhere `dependencies/<namespace>/<Name>/<branch>/` where git lists it — as a submodule in `.gitmodules`,
811
+ * or as one of this repository's worktrees, which is how its own hidden refs are checked out; none where git lists
812
+ * it neither.
813
+ */
814
+ checkout(id, branch) {
815
+ if (id === this.#named && branch === this.head) return this.folder;
816
+ return this.#branches(id).includes(branch) ? this.folder.folder(`dependencies/${id}/${branch}`) : void 0;
817
+ }
818
+ /**
819
+ * Its version: the one its model names, otherwise the one its root's `workbench.jsonld` names, as Descriptor's Generator
820
+ * writes it; none where neither names one as text, and refused, as its working tree is, where its model names none
821
+ * and it has no tree on this host.
822
+ */
823
+ get version() {
824
+ if (this.model.version !== void 0) return this.model.version;
825
+ const version = this.#node?.version;
826
+ return typeof version === "string" ? version : void 0;
827
+ }
828
+ /**
829
+ * The module hooks its model names, otherwise those its root's `workbench.jsonld` names; none where neither does.
830
+ * Refused, naming the file, where they are no list of addresses.
831
+ */
832
+ get hooks() {
833
+ const hooks = this.model.hooks ?? this.#node?.hooks;
834
+ if (hooks === void 0) return [];
835
+ if (!Array.isArray(hooks) || !hooks.every((hook) => typeof hook === "string")) throw new Error(`hooks is a list of module addresses: ${this.folder.file("workbench.jsonld").path}`);
836
+ return hooks;
837
+ }
838
+ get #node() {
839
+ const file = this.folder.file("workbench.jsonld");
840
+ return file.exists ? file.readJsonObject() : void 0;
841
+ }
842
+ get #named() {
843
+ const id = this.#node?.["@id"];
844
+ const named = typeof id === "string" ? OFieldIri.of(id)?.model : void 0;
845
+ return named === void 0 ? void 0 : `${named.namespace}/${named.name}`;
846
+ }
847
+ #branches(id) {
848
+ const prefix = `dependencies/${id}/`;
849
+ const paths = [...new GitModules(this.folder.file(".gitmodules")).paths, ...this.#worktrees()].map((path) => path.replace(/^(\.\/)+/, "").replace(/\/+$/, ""));
850
+ return [...new Set(paths.filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length)))];
851
+ }
852
+ /** The lines the registered tools report checking it. */
853
+ async check() {
854
+ return Workbench.#registered().check(this);
855
+ }
856
+ /** The lines the registered tools report upgrading it to what `uri` names. */
857
+ upgrade(uri) {
858
+ return Workbench.#registered().upgrade(this, uri);
859
+ }
860
+ /** Watches it, through the registered tools. */
861
+ watch() {
862
+ Workbench.#registered().watch(this);
863
+ }
864
+ /** Carries the newest `0field.js`, or the one `ref` names, into it through the registered tools; what they carried. */
865
+ async carry(ref) {
866
+ return Workbench.#registered().carry(this, ref);
867
+ }
868
+ /** What the registered tools answer for the read token `token`, passed on to them. */
869
+ async readToken(token) {
870
+ return Workbench.#registered().readToken(token);
871
+ }
872
+ /** The SmartObject this repository develops, `<namespace>/<Name>` as its `origin` remote names it; none without one. */
873
+ get id() {
874
+ const url = this.remote("origin");
875
+ const named = url === void 0 ? null : /[/:]([^/:]+)\/([^/:]+?)(?:\.git)?\/*$/.exec(url);
876
+ return named === null ? void 0 : `${named[1]}/${named[2]}`;
877
+ }
878
+ #worktrees() {
879
+ return this.worktrees.flatMap(({ name, path: worktree }) => {
880
+ const at = worktree.lastIndexOf("/dependencies/");
881
+ if (at === -1) return [];
882
+ const path = worktree.slice(at + 1);
883
+ const named = new GitRepository(this.folder.folder(path)).pointer;
884
+ return named !== void 0 && named.replace(/\/+$/, "").endsWith(`/worktrees/${name}`) ? [path] : [];
885
+ });
886
+ }
887
+ };
888
+ //#endregion
889
+ //#region dependencies/metatrom-ag/Manu/main/common/graphs/GraphNode.ts
890
+ /**
891
+ * Purpose: give every graph its operations once.
892
+ *
893
+ * Intention: a graph's node, as graph theory has it, with no node chosen
894
+ * as root; asks its realization for only its neighbours, the nodes one
895
+ * edge away. A SmartObject, its model the realization's.
896
+ */
897
+ var GraphNode = class extends TypedSmartObject.Class {
898
+ /** Whether `other` is this node; realizations that hand out fresh objects for one node compare their identity. */
899
+ is(other) {
900
+ return other === this;
901
+ }
902
+ /** Every other node a path leads to, each once, nearest first; lazy, so a large graph is read only as far as asked. */
903
+ *reachable() {
904
+ const start = this;
905
+ const seen = [start];
906
+ const queue = [start];
907
+ for (let node = queue.shift(); node !== void 0; node = queue.shift()) for (const neighbour of node.neighbours) {
908
+ if (seen.some((known) => known.is(neighbour))) continue;
909
+ seen.push(neighbour);
910
+ queue.push(neighbour);
911
+ yield neighbour;
912
+ }
913
+ }
914
+ };
915
+ //#endregion
916
+ //#region dependencies/metatrom-ag/Manu/main/common/graphs/RootedTreeNode.ts
917
+ /**
918
+ * Purpose: give every rooted tree its operations once.
919
+ *
920
+ * Intention: a tree's node, as graph theory has it — a {@link GraphNode}
921
+ * with one node chosen as root, so its neighbours are a parent and
922
+ * children; asks its realization for only those two.
923
+ */
924
+ var RootedTreeNode = class extends GraphNode {
925
+ get neighbours() {
926
+ const parent = this.parent;
927
+ return parent === void 0 ? this.children : [parent, ...this.children];
928
+ }
929
+ /** The parent, then each ancestor up to the root, nearest first. */
930
+ get ancestors() {
931
+ const ancestors = [];
932
+ for (let node = this.parent; node !== void 0; node = node.parent) ancestors.push(node);
933
+ return ancestors;
934
+ }
935
+ get root() {
936
+ return this.ancestors.at(-1) ?? this;
937
+ }
938
+ get siblings() {
939
+ return this.parent?.children.filter((node) => !node.is(this)) ?? [];
940
+ }
941
+ get depth() {
942
+ return this.ancestors.length;
943
+ }
944
+ get isLeaf() {
945
+ return this.children.length === 0;
946
+ }
947
+ /** Every node below, pre-order: a node before its children; lazy, so a large tree is read only as far as asked. */
948
+ *descendants() {
949
+ for (const child of this.children) {
950
+ yield child;
951
+ yield* child.descendants();
952
+ }
953
+ }
954
+ };
955
+ //#endregion
956
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/Entry.ts
957
+ /**
958
+ * Purpose: name what a store holds, whatever holds the store.
959
+ *
960
+ * Intention: a node of the file system's rooted tree — a {@link File} or a
961
+ * {@link Folder}, siblings, so neither has to fake a promise of the other;
962
+ * each habitat realizes reading them.
963
+ */
964
+ var Entry = class extends RootedTreeNode {
965
+ /** The entry at a POSIX path. The model holds only the path, so it can travel; the content is read by the habitat's code. */
966
+ constructor(path) {
967
+ super({ path });
968
+ }
969
+ get path() {
970
+ return this.model.path;
971
+ }
972
+ get name() {
973
+ return this.path.slice(this.path.lastIndexOf("/") + 1);
974
+ }
975
+ get parent() {
976
+ if (this.path === "/") return void 0;
977
+ const at = this.path.lastIndexOf("/");
978
+ if (at === -1) return void 0;
979
+ return this.folderAt(at === 0 ? "/" : this.path.slice(0, at));
980
+ }
981
+ /** Whether another entry has the same path, which makes it the same node. */
982
+ is(other) {
983
+ return other.path === this.path;
984
+ }
985
+ /** The {@link Folder} at an absolute path, of this entry's own realization — on another drive as well, where the host has drives. */
986
+ at(path) {
987
+ return this.folderAt(path);
988
+ }
989
+ };
990
+ //#endregion
991
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/file-system/ReadOnlyNodeFile.ts
992
+ /**
993
+ * Purpose: read a file on disk.
994
+ *
995
+ * Intention: realizes {@link File} over `node:fs`, which Node, Deno and Bun
996
+ * all implement, so one realization serves all three.
997
+ */
998
+ var ReadOnlyNodeFile = class extends Entry {
999
+ get children() {
1000
+ return [];
1001
+ }
1002
+ readText() {
1003
+ return new TextDecoder().decode(this.read());
1004
+ }
1005
+ readJson() {
1006
+ try {
1007
+ return JSON.parse(this.readText());
1008
+ } catch (error) {
1009
+ throw new Error(`not JSON: ${this.path}`, { cause: error });
1010
+ }
1011
+ }
1012
+ readJsonObject() {
1013
+ const value = this.readJson();
1014
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`not a JSON object: ${this.path}`);
1015
+ return value;
1016
+ }
1017
+ get exists() {
1018
+ return fs().lstatSync(this.path, { throwIfNoEntry: false })?.isFile() ?? false;
1019
+ }
1020
+ read() {
1021
+ return fs().readFileSync(this.path);
1022
+ }
1023
+ head(length) {
1024
+ const file = fs().openSync(this.path, "r");
1025
+ try {
1026
+ const bytes = new Uint8Array(length);
1027
+ return bytes.subarray(0, fs().readSync(file, bytes, 0, length, 0));
1028
+ } finally {
1029
+ fs().closeSync(file);
1030
+ }
1031
+ }
1032
+ folderAt(path) {
1033
+ return new ReadOnlyNodeFolder(path);
1034
+ }
1035
+ };
1036
+ /** `node:fs`, not imported, so this file still loads where node:fs does not exist. */
1037
+ const fs = () => process.getBuiltinModule("node:fs");
1038
+ //#endregion
1039
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/file-system/ReadOnlyNodeFolder.ts
1040
+ /**
1041
+ * Purpose: read a folder on disk.
1042
+ *
1043
+ * Intention: realizes {@link Folder} over `node:fs`, which Node, Deno and Bun
1044
+ * all implement, so one realization serves all three; it speaks the host's
1045
+ * path notation and the `file:` URL a runtime loads by.
1046
+ */
1047
+ var ReadOnlyNodeFolder = class ReadOnlyNodeFolder extends Entry {
1048
+ /**
1049
+ * The folder at a path in the host's own notation — relative to the working folder, or absolute — holding the POSIX
1050
+ * path every {@link Entry} holds.
1051
+ */
1052
+ static native(path) {
1053
+ const { resolve, sep } = process.getBuiltinModule("node:path");
1054
+ return new ReadOnlyNodeFolder(resolve(path).split(sep).join("/"));
1055
+ }
1056
+ /** The entry a `file:` URL names, as a folder of this realization — its `parent` is the folder holding it. */
1057
+ static fromUrl(url) {
1058
+ return ReadOnlyNodeFolder.native(process.getBuiltinModule("node:url").fileURLToPath(url));
1059
+ }
1060
+ /** The `file:` URL an entry's path is loaded by. */
1061
+ static urlOf(entry) {
1062
+ return process.getBuiltinModule("node:url").pathToFileURL(entry.path).href;
1063
+ }
1064
+ get exists() {
1065
+ return fs().lstatSync(this.path, { throwIfNoEntry: false })?.isDirectory() ?? false;
1066
+ }
1067
+ get entries() {
1068
+ if (!this.exists) return [];
1069
+ return fs().readdirSync(this.path, { withFileTypes: true }).flatMap((entry) => entry.name.includes("\\") ? [] : entry.isDirectory() ? [this.folder(entry.name)] : entry.isFile() ? [this.file(entry.name)] : []);
1070
+ }
1071
+ get children() {
1072
+ return this.entries;
1073
+ }
1074
+ child(path) {
1075
+ const names = path.split("/");
1076
+ if (path.startsWith("/") || names.some((name) => name === "" || name === "." || name === "..")) throw new Error(`not a path inside ${this.path}: ${path}`);
1077
+ const separating = names.find((name) => name.includes("\\"));
1078
+ if (separating !== void 0) throw new Error(`a name holding \\ is no name inside ${this.path}: ${separating}`);
1079
+ return this.path === "/" ? `/${path}` : `${this.path}/${path}`;
1080
+ }
1081
+ /** This folder by its real path, every link on the way followed, so one folder under two paths is one; refused where there is none. */
1082
+ get real() {
1083
+ return ReadOnlyNodeFolder.native(fs().realpathSync(this.path));
1084
+ }
1085
+ file(path) {
1086
+ return new ReadOnlyNodeFile(this.child(path));
1087
+ }
1088
+ folder(path) {
1089
+ return new ReadOnlyNodeFolder(this.child(path));
1090
+ }
1091
+ folderAt(path) {
1092
+ return new ReadOnlyNodeFolder(path);
1093
+ }
1094
+ };
1095
+ //#endregion
1096
+ //#region dependencies/metatrom-ag/Manu/main/common/loading/ModuleHookChain.ts
1097
+ /**
1098
+ * Purpose: let loading in any habitat be extended by hooks.
1099
+ *
1100
+ * Intention: uses {@link ModuleHook}s; each kernel — Node's, Bun's, the
1101
+ * browser's — carries one chain and hands each import to it, and
1102
+ * `OField` hands it to a program as `hooks`.
1103
+ */
1104
+ var ModuleHookChain = class extends TypedSmartObject {
1105
+ #hooks = [];
1106
+ constructor() {
1107
+ super({ hooks: [] });
1108
+ }
1109
+ /** Puts a hook in use after those already in use, its name kept in the model. */
1110
+ use(hook) {
1111
+ this.#hooks.push(hook);
1112
+ this.update({ hooks: [...this.model.hooks, hook.name] });
1113
+ }
1114
+ /**
1115
+ * The first URL a hook resolves the specifier to, the hooks asked in the order they were put in use; `undefined` where
1116
+ * none does. A specifier of the scheme `oasis:`, the one before `ofield:`, is refused before any hook is asked, naming
1117
+ * `ofield://`.
1118
+ */
1119
+ resolve(specifier, parentURL) {
1120
+ OFieldIri.refuseRetired(specifier);
1121
+ for (const hook of this.#hooks) {
1122
+ const url = hook.resolve?.(specifier, parentURL);
1123
+ if (url !== void 0) return url;
1124
+ }
1125
+ }
1126
+ /**
1127
+ * Where an address lies, read from an anchor: a URL or an oField IRI as the hooks resolve it, where one does; a
1128
+ * Windows path from its drive letter, `C:\x.ts` or `C:/x.ts`, as the file it names; any other path read from the
1129
+ * anchor. Refused, naming the address, where it names a data ref ({@link OFieldIri.isDataRef}): a data ref holds data,
1130
+ * and code runs from a branch, a tag or a release.
1131
+ */
1132
+ locate(address, anchor) {
1133
+ if (OFieldIri.isDataRef(OFieldIri.of(address)?.model.ref)) throw new Error(`nothing runs from a data ref: ${address}`);
1134
+ const located = /^[A-Za-z]:[\\/]/.test(address) ? new URL(`file:///${address.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("\\", "/")}`).href : /^[A-Za-z][A-Za-z\d+.-]+:/.test(address) ? address : new URL(address, anchor).href;
1135
+ return this.resolve(located, anchor) ?? located;
1136
+ }
1137
+ /**
1138
+ * The URL of the module a type IRI names, `<type>.ts`, as the hooks resolve it from a parent; refused before anything
1139
+ * resolves where the type names a data ref — a ref under `refs/` that is no branch — as what is stored as data never
1140
+ * runs, and refused, naming it, where no hook resolves it.
1141
+ */
1142
+ moduleOf(type, parentURL) {
1143
+ if (OFieldIri.isDataRef(OFieldIri.of(type)?.model.ref)) throw new Error(`no class is loaded from a data ref: ${type}`);
1144
+ const url = this.resolve(`${type}.ts`, parentURL);
1145
+ if (url === void 0) throw new Error(`no module resolves ${type}.ts`);
1146
+ return url;
1147
+ }
1148
+ /** The first source a hook loads the URL as, the hooks asked in the order they were put in use; `undefined` where none does. */
1149
+ load(url) {
1150
+ for (const hook of this.#hooks) {
1151
+ const module = hook.load?.(url);
1152
+ if (module !== void 0) return module;
1153
+ }
1154
+ }
1155
+ /**
1156
+ * Hands a specifier's final resolution to every hook that observes. A kernel calls it however the specifier was
1157
+ * reached, by a hook or by the environment's own, so a hook that only watches need not resolve anything itself to
1158
+ * see it.
1159
+ */
1160
+ observe(url) {
1161
+ for (const hook of this.#hooks) hook.observe?.(url);
1162
+ }
1163
+ };
1164
+ //#endregion
1165
+ //#region dependencies/metatrom-ag/Manu/main/habitats/browser/BrowserOFieldHook.ts
1166
+ /**
1167
+ * Purpose: load a SmartObject by its oField IRI in a tab.
1168
+ *
1169
+ * Intention: realizes {@link ModuleHook} for the `ofield` scheme, which no
1170
+ * browser imports, by naming the URL a web server serves the file at: the
1171
+ * IRI's own path below the base its model names. A browser extension, or
1172
+ * anything else that reaches a tab's {@link ModuleHookChain}, answers in
1173
+ * its place by coming first.
1174
+ */
1175
+ var BrowserOFieldHook = class extends TypedSmartObject {
1176
+ name = "ofield";
1177
+ schemes = ["ofield"];
1178
+ /**
1179
+ * The URL of the file an oField IRI names, exact in case: `ofield://<namespace>/<Name>[@<ref>]:<subpath>` at
1180
+ * `<base><namespace>/<Name>[@<ref>]/<subpath>`, the ref one segment however many slashes it holds, and `<Name>.ts`
1181
+ * where it names no subpath. `ofield://npm/…` it passes on.
1182
+ */
1183
+ resolve(specifier) {
1184
+ if (!specifier.startsWith("ofield:")) return void 0;
1185
+ const { namespace, name, ref, subpath } = new OFieldIri(specifier).model;
1186
+ if (namespace === "npm") return void 0;
1187
+ const tree = ref === void 0 ? name : `${name}@${encodeURIComponent(ref)}`;
1188
+ return new URL(`${namespace}/${tree}/${subpath ?? `${name}.ts`}`, this.model.base).href;
1189
+ }
1190
+ };
1191
+ //#endregion
1192
+ //#region dependencies/metatrom-ag/Manu/main/habitats/browser/BrowserStorage.ts
1193
+ /**
1194
+ * Purpose: find what a SmartObject is stored as, from a tab.
1195
+ *
1196
+ * Intention: realizes the {@link Storage} a Persistence uses over the
1197
+ * browser's `fetch`, which reads only by waiting: an oField IRI at the URL
1198
+ * the tab's {@link ModuleHookChain} names for it, any other address as a
1199
+ * URL read from the place it anchors to, and a folder as its server lists
1200
+ * it. What a read fetched, the tab's kernel keeps for the reads that answer
1201
+ * at once.
1202
+ */
1203
+ var BrowserStorage = class extends TypedSmartObject {
1204
+ #hooks;
1205
+ #fetched;
1206
+ /** Over the chain an oField IRI resolves through, and the texts the tab's reads have fetched, by location. */
1207
+ constructor(model, hooks, fetched) {
1208
+ super(model);
1209
+ this.#hooks = hooks;
1210
+ this.#fetched = fetched;
1211
+ }
1212
+ /** The location an address names: an oField IRI in canonical form, any other address as the URL it names from the anchor; a fragment dropped. */
1213
+ location(address) {
1214
+ if (address === "") throw new Error("an empty address names no model");
1215
+ const located = address.split("#")[0];
1216
+ if (located.startsWith("ofield:")) return new OFieldIri(located).toString();
1217
+ return new URL(located, this.model.anchor).href;
1218
+ }
1219
+ /**
1220
+ * The text at a location, fetched once and kept, or fetched again where `afresh` asks, past the browser's HTTP cache,
1221
+ * kept in its place; refused, naming it, where the server holds none, and as {@link BrowserStorage.has} is.
1222
+ */
1223
+ async get(location, afresh = false) {
1224
+ const text = await this.#fetch(location, afresh);
1225
+ if (text === void 0) throw new Error(`no model at ${location}`);
1226
+ return text;
1227
+ }
1228
+ /** The text a read has fetched from a location; refused, naming it, where none has, as a tab reads only by waiting. */
1229
+ getSync(location) {
1230
+ const text = this.#fetched.get(location);
1231
+ if (text === void 0) throw new Error(`${location} is read only by waiting, and no read has fetched it yet`);
1232
+ return text;
1233
+ }
1234
+ /** Whether the server holds a text at a location: none where it answers 404 or 410; refused, naming the URL and the status, where it answers any other failure. */
1235
+ async has(location) {
1236
+ return await this.#fetch(location) !== void 0;
1237
+ }
1238
+ /** Whether a read has fetched a text at a location; refused, naming it, where none has. */
1239
+ hasSync(location) {
1240
+ this.getSync(location);
1241
+ return true;
1242
+ }
1243
+ /**
1244
+ * The locations below a folder, as its server names them when asked for the folder's URL ending in `/` as
1245
+ * `application/json`: a JSON list of addresses. None where it answers 404 or 410; refused, naming the URL, where it
1246
+ * answers any other failure or no list of addresses.
1247
+ */
1248
+ async list(address) {
1249
+ const location = this.location(address);
1250
+ const url = location.startsWith("ofield:") ? this.#folderOf(location) : location.endsWith("/") ? location : `${location}/`;
1251
+ const response = await fetch(url, { headers: { accept: "application/json" } });
1252
+ if (response.status === 404 || response.status === 410) return [];
1253
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
1254
+ let named;
1255
+ try {
1256
+ named = await response.json();
1257
+ } catch {
1258
+ named = void 0;
1259
+ }
1260
+ if (!Array.isArray(named) || !named.every((each) => typeof each === "string")) throw new Error(`${url} answered no list of locations`);
1261
+ return named.map((each) => this.location(each));
1262
+ }
1263
+ /** Refused, naming the address: a tab lists only by waiting. */
1264
+ listSync(address) {
1265
+ throw new Error(`a tab lists only by waiting: ${address}`);
1266
+ }
1267
+ /** None: a tab realizes no repository. */
1268
+ realizes() {
1269
+ return false;
1270
+ }
1271
+ /** Refused: a tab realizes no repository. */
1272
+ realized(location) {
1273
+ throw new Error(`a tab realizes nothing at ${location}`);
1274
+ }
1275
+ #folderOf(location) {
1276
+ const named = new OFieldIri(location).model;
1277
+ const below = new OFieldIri({
1278
+ ...named,
1279
+ subpath: named.subpath === void 0 ? "_" : `${named.subpath.replace(/\/$/, "")}/_`
1280
+ }).toString();
1281
+ const url = this.#hooks.resolve(below, this.model.anchor);
1282
+ if (url === void 0) throw new Error(`no hook resolves ${location}`);
1283
+ return url.slice(0, -1);
1284
+ }
1285
+ async #fetch(location, afresh = false) {
1286
+ const kept = afresh ? void 0 : this.#fetched.get(location);
1287
+ if (kept !== void 0) return kept;
1288
+ const url = location.startsWith("ofield:") ? this.#hooks.resolve(location, this.model.anchor) : location;
1289
+ if (url === void 0) throw new Error(`no hook resolves ${location}`);
1290
+ const response = await fetch(url, afresh ? { cache: "no-cache" } : void 0);
1291
+ if (response.status === 404 || response.status === 410) return void 0;
1292
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
1293
+ const text = await response.text();
1294
+ this.#fetched.set(location, text);
1295
+ return text;
1296
+ }
1297
+ };
1298
+ //#endregion
1299
+ //#region dependencies/metatrom-ag/Manu/main/habitats/browser/BrowserKernel.ts
1300
+ var __rewriteRelativeImportExtension$2 = function(path, preserveJsx) {
1301
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
1302
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
1303
+ });
1304
+ return path;
1305
+ };
1306
+ /**
1307
+ * Purpose: make loading work in a tab.
1308
+ *
1309
+ * Intention: realizes {@link Manu} over the page the 0field was
1310
+ * loaded into: the script tags of its own file name the programs a tab is
1311
+ * started with, where each is shown and in which view, its {@link ModuleHookChain} carries
1312
+ * the {@link BrowserOFieldHook}, and its storage, which a Persistence reads,
1313
+ * is a {@link BrowserStorage}. It hands out a {@link Program} for each
1314
+ * tag naming one. Its model names the 0field it loads for.
1315
+ */
1316
+ var BrowserKernel = class BrowserKernel extends TypedSmartObject {
1317
+ hooks = new ModuleHookChain();
1318
+ #fetched = /* @__PURE__ */ new Map();
1319
+ #recorded = /* @__PURE__ */ new WeakMap();
1320
+ #started;
1321
+ /**
1322
+ * Adds the {@link BrowserOFieldHook} to its chain, over the base the tags of its file name in `data-ofield`, or else
1323
+ * the root of the host its file came from; refused, naming them, where its tags name more than one.
1324
+ */
1325
+ async start() {
1326
+ const named = new Set(this.#tags().flatMap((tag) => tag.dataset.ofield === void 0 ? [] : [new URL(tag.dataset.ofield, document.baseURI).href]));
1327
+ if (named.size > 1) throw new Error(`the script tags of ${this.model.oField} name more than one data-ofield: ${[...named].join(", ")}`);
1328
+ this.hooks.use(new BrowserOFieldHook({ base: [...named][0] ?? new URL("/", this.model.oField).href }));
1329
+ }
1330
+ /**
1331
+ * A program for each script tag of its file naming one in `data-start`, in the page's order: its address an oField
1332
+ * IRI as the hooks resolve it, or a URL read from the page; its words the JSON array of strings in `data-words`, none
1333
+ * where it names none, refused, naming it, where it holds anything else; shown where `data-attach` names, in the
1334
+ * view whose file `data-view` names, read as its address is; refused, naming it, where either names a file on a data
1335
+ * ref.
1336
+ */
1337
+ get started() {
1338
+ this.#started ??= this.#tags().flatMap((tag) => {
1339
+ const { start, words, attach, view } = tag.dataset;
1340
+ if (start === void 0) return [];
1341
+ return [new Program({
1342
+ address: this.hooks.locate(start, this.anchor()),
1343
+ words: BrowserKernel.#words(words),
1344
+ ...attach === void 0 ? {} : { attach },
1345
+ ...view === void 0 ? {} : { view: this.hooks.locate(view, this.anchor()) }
1346
+ })];
1347
+ });
1348
+ return this.#started;
1349
+ }
1350
+ /** The URL a place reads from: the page, or a file in the folder a path names from the page, which need not exist. */
1351
+ anchor(place) {
1352
+ return place === void 0 ? document.baseURI : new URL(`${place.replace(/\/?$/, "/")}.started`, document.baseURI).href;
1353
+ }
1354
+ storage(place) {
1355
+ return new BrowserStorage({ anchor: this.anchor(place) }, this.hooks, this.#fetched);
1356
+ }
1357
+ /**
1358
+ * The class a type names, exported by default from its module. A SmartObject class named by an oField IRI is recorded
1359
+ * through its own `loaded`, the first time this kernel loads it and before any program has built it, as loaded from
1360
+ * that IRI's namespace and the version its workbench's `workbench.jsonld` names, so its element is named after that
1361
+ * release; a `workbench.jsonld` that holds no JSON object, or a version no element name holds, is refused, naming it.
1362
+ */
1363
+ async classOf(type, place) {
1364
+ const created = (await import(__rewriteRelativeImportExtension$2(this.hooks.moduleOf(type, this.anchor(place))))).default;
1365
+ if (typeof created === "function" && created.prototype instanceof TypedSmartObject) await this.#record(type, created, place);
1366
+ return created;
1367
+ }
1368
+ /** Fills nothing: a tab keeps no store, and reads what its server serves. */
1369
+ async fill(_address) {}
1370
+ #record(type, created, place) {
1371
+ const known = this.#recorded.get(created);
1372
+ if (known !== void 0) return known;
1373
+ const recording = this.#recording(type, created, place);
1374
+ this.#recorded.set(created, recording);
1375
+ return recording;
1376
+ }
1377
+ async #recording(type, created, place) {
1378
+ const iri = OFieldIri.of(type);
1379
+ if (iri === void 0 || customElements.getName(created) !== null) return;
1380
+ const workbench = Workbench.stored(type);
1381
+ const storage = this.storage(place);
1382
+ if (!await storage.has(workbench)) return;
1383
+ const version = BrowserKernel.#version(workbench, await storage.get(workbench));
1384
+ if (version !== void 0) created.loaded(created, {
1385
+ namespace: iri.model.namespace,
1386
+ version
1387
+ });
1388
+ }
1389
+ static #version(address, text) {
1390
+ let node;
1391
+ try {
1392
+ node = JSON.parse(text);
1393
+ } catch {
1394
+ throw new Error(`${address} holds no JSON`);
1395
+ }
1396
+ if (typeof node !== "object" || node === null || Array.isArray(node)) throw new Error(`${address} holds no JSON object`);
1397
+ const { version } = node;
1398
+ if (version === void 0) return void 0;
1399
+ if (typeof version !== "string" || !/^\d+\.\d+\.\d+(-[0-9a-z.-]+)?$/.test(version)) throw new Error(`${address} names a version no element name holds: ${JSON.stringify(version)}`);
1400
+ return version;
1401
+ }
1402
+ /**
1403
+ * Shows a SmartObject, an element in a tab: as the last child of what a selector or `body` names, or filling the
1404
+ * viewport — html and body at the viewport's size without a margin, the SmartObject at theirs, laid out as its own
1405
+ * sheet lays it out, as a block where that leaves it inline — through a stylesheet it adopts, leaving the page's own;
1406
+ * refused, naming the place, where nothing in the page matches it.
1407
+ */
1408
+ attach(smartObject, where) {
1409
+ const element = smartObject;
1410
+ if (where === "viewport") {
1411
+ const sheet = new CSSStyleSheet();
1412
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
1413
+ document.body.append(element);
1414
+ const display = getComputedStyle(element).display === "inline" ? "display: block; " : "";
1415
+ sheet.replaceSync(`html, body { width: 100%; height: 100%; margin: 0 } ${CSS.escape(element.localName)} { ${display}width: 100%; height: 100% }`);
1416
+ return;
1417
+ }
1418
+ const target = where === "body" ? document.body : document.querySelector(where);
1419
+ if (target === null) throw new Error(`nothing in the page matches the place to attach to: ${where}`);
1420
+ target.append(element);
1421
+ }
1422
+ #tags() {
1423
+ return [...document.querySelectorAll("script[src]")].filter((tag) => new URL(tag.src, document.baseURI).href === this.model.oField);
1424
+ }
1425
+ static #words(written) {
1426
+ if (written === void 0) return [];
1427
+ const refused = /* @__PURE__ */ new Error(`data-words is a JSON array of strings: ${written}`);
1428
+ let words;
1429
+ try {
1430
+ words = JSON.parse(written);
1431
+ } catch {
1432
+ throw refused;
1433
+ }
1434
+ if (!Array.isArray(words) || !words.every((word) => typeof word === "string")) throw refused;
1435
+ return words;
1436
+ }
1437
+ };
1438
+ //#endregion
1439
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/npm/BareSpecifier.ts
1440
+ /**
1441
+ * Purpose: tell a package's name from the path inside it in a bare import.
1442
+ *
1443
+ * Intention: the npm hook splits the bare imports a stored package makes with
1444
+ * it, and a package manifest tells a bare import target by it.
1445
+ */
1446
+ var BareSpecifier = class BareSpecifier extends TypedSmartObject {
1447
+ /** Neither relative, absolute, a URL nor a package's own `#import`. */
1448
+ static is(specifier) {
1449
+ return !/^[./#]/.test(specifier) && !specifier.includes(":");
1450
+ }
1451
+ /**
1452
+ * Splits a bare specifier — `name` or `@scope/name`, either with a path inside — into the package's name and the
1453
+ * subpath `.` or `./<path>`.
1454
+ */
1455
+ constructor(specifier) {
1456
+ if (!BareSpecifier.is(specifier)) throw new TypeError(`not a bare specifier: ${specifier}`);
1457
+ super(BareSpecifier.#parts(specifier));
1458
+ }
1459
+ /** The package's name, read-only, as a parsed specifier is a value: a getter without a setter refuses the field's write. */
1460
+ get name() {
1461
+ return this.model.name;
1462
+ }
1463
+ /** The path inside the package, read-only as its name is. */
1464
+ get subpath() {
1465
+ return this.model.subpath;
1466
+ }
1467
+ static #nameOf(names) {
1468
+ return names.slice(0, names[0]?.startsWith("@") ? 2 : 1).join("/");
1469
+ }
1470
+ static #parts(specifier) {
1471
+ const given = specifier.split("/");
1472
+ const names = given.length > 1 && given.at(-1) === "" ? given.slice(0, -1) : given;
1473
+ const name = BareSpecifier.#nameOf(names);
1474
+ const rest = names.slice(name.split("/").length);
1475
+ return {
1476
+ name,
1477
+ subpath: rest.length === 0 ? "." : `./${rest.join("/")}`
1478
+ };
1479
+ }
1480
+ };
1481
+ //#endregion
1482
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/npm/CommonJsModule.ts
1483
+ /**
1484
+ * Purpose: a stored CommonJS module runs once and hands its exports to an ES
1485
+ * import, the same in every habitat.
1486
+ *
1487
+ * Intention: uses a {@link CommonJsHost} — the npm hook — which hands
1488
+ * its {@link CommonJsModule.source} to the runtime as a {@link ModuleSource}.
1489
+ */
1490
+ var CommonJsModule = class CommonJsModule {
1491
+ static #modules = /* @__PURE__ */ new Map();
1492
+ /** The URL it was first asked for by. */
1493
+ url;
1494
+ /** The CommonJS `module` record its source runs with: its exports, its file's path, and whether it ran to the end. */
1495
+ module;
1496
+ constructor(url, filename) {
1497
+ this.url = url;
1498
+ this.module = {
1499
+ exports: {},
1500
+ filename,
1501
+ loaded: false
1502
+ };
1503
+ }
1504
+ /**
1505
+ * The module at a URL, run the first time it is asked for, as Node runs CommonJS: with its own `module`, `exports`,
1506
+ * `__filename`, `__dirname` and a `require` the host resolves — a builtin by the runtime, a stored file by the
1507
+ * store, JSON parsed, CommonJS run here once per file.
1508
+ */
1509
+ static of(url, host) {
1510
+ const file = host.fileOf(url);
1511
+ const known = file === void 0 ? void 0 : CommonJsModule.#modules.get(file.path);
1512
+ if (known !== void 0) return known;
1513
+ const read = host.read(url);
1514
+ if (file === void 0 || read === void 0) throw new Error(`no CommonJS module at ${url}`);
1515
+ const ran = new CommonJsModule(url, file.path);
1516
+ CommonJsModule.#modules.set(file.path, ran);
1517
+ ran.#run(read.source, file, host);
1518
+ return ran;
1519
+ }
1520
+ /**
1521
+ * The ES module a runtime loads in this one's place: `module.exports` as `default` and as `module.exports`, each own
1522
+ * enumerable key of it by name, as Node's own import of CommonJS gives them. An ES module's names are fixed when it
1523
+ * is loaded, so they are read from the module as it ran by then.
1524
+ */
1525
+ get source() {
1526
+ exported().set(this.url, this.module.exports);
1527
+ const value = this.module.exports;
1528
+ const names = value !== null && (typeof value === "object" || typeof value === "function") ? Object.keys(value).filter((name) => name !== "default") : [];
1529
+ return [
1530
+ `const exported = globalThis[Symbol.for(${JSON.stringify(EXPORTED)})].get(${JSON.stringify(this.url)})`,
1531
+ "export default exported",
1532
+ "export { exported as \"module.exports\" }",
1533
+ ...names.flatMap((name, index) => [`const name${index} = exported[${JSON.stringify(name)}]`, `export { name${index} as ${IDENTIFIER.test(name) ? name : JSON.stringify(name)} }`]),
1534
+ ""
1535
+ ].join("\n");
1536
+ }
1537
+ /**
1538
+ * Whether a source runs as CommonJS: it compiles as the body of the function a CommonJS module runs in, as Node
1539
+ * decides for a file no `package.json` gives a type — `import` and `export` statements, `import.meta` and a
1540
+ * top-level `await` compile only in an ES module, whatever text a string holds.
1541
+ */
1542
+ static runs(source) {
1543
+ try {
1544
+ CommonJsModule.#compiled(source);
1545
+ return true;
1546
+ } catch {
1547
+ return false;
1548
+ }
1549
+ }
1550
+ static #compiled(source) {
1551
+ return new Function("exports", "require", "module", "__filename", "__dirname", source);
1552
+ }
1553
+ #run(source, file, host) {
1554
+ const require = (specifier) => {
1555
+ const target = host.required(specifier, this.url);
1556
+ if ("builtin" in target) return target.builtin;
1557
+ const read = host.read(target.url);
1558
+ if (read?.format === "json") return JSON.parse(read.source);
1559
+ if (read?.format === "commonjs") return CommonJsModule.of(target.url, host).module.exports;
1560
+ return host.esm(target.url);
1561
+ };
1562
+ require.resolve = (specifier) => {
1563
+ const target = host.required(specifier, this.url);
1564
+ return "builtin" in target ? specifier : host.fileOf(target.url)?.path ?? target.url;
1565
+ };
1566
+ CommonJsModule.#compiled(`${source}\n//# sourceURL=${this.url}`)(this.module.exports, require, this.module, file.path, file.parent?.path ?? "");
1567
+ this.module.loaded = true;
1568
+ }
1569
+ };
1570
+ const EXPORTED = "metatrom.oField.commonjs";
1571
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1572
+ function exported() {
1573
+ const global = globalThis;
1574
+ return global[Symbol.for(EXPORTED)] ??= /* @__PURE__ */ new Map();
1575
+ }
1576
+ //#endregion
1577
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/json/JsonObject.ts
1578
+ /**
1579
+ * Purpose: keep the JSON object a file holds as a SmartObject's model.
1580
+ *
1581
+ * Intention: the base of the SmartObjects whose model is a JSON file of the
1582
+ * store or the repository; reads it through {@link File.readJsonObject}.
1583
+ */
1584
+ var JsonObject = class JsonObject extends TypedSmartObject.Class {
1585
+ /** Reads the model from a file — a missing one is empty, anything but a JSON object refused, naming the file — or takes it as given. */
1586
+ constructor(source) {
1587
+ super(source instanceof Entry ? JsonObject.#read(source) : source);
1588
+ }
1589
+ static #read(file) {
1590
+ if (!file.exists) return {};
1591
+ return file.readJsonObject();
1592
+ }
1593
+ };
1594
+ //#endregion
1595
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/npm/PackageManifest.ts
1596
+ /**
1597
+ * Purpose: say which file of a package an import of it gets.
1598
+ *
1599
+ * Intention: a {@link JsonObject} over `package.json`; the npm hook asks it
1600
+ * for the entry of a subpath under the habitat's conditions, by Node's package
1601
+ * entry points, and for the target of a `#…` import its own files make, by
1602
+ * Node's subpath imports, matched the same way.
1603
+ *
1604
+ * @see https://nodejs.org/api/packages.html#package-entry-points
1605
+ * @see https://nodejs.org/api/packages.html#subpath-imports
1606
+ */
1607
+ var PackageManifest = class extends JsonObject {
1608
+ /**
1609
+ * The file it names for a subpath — `.` or `./<path>` — as a path inside the
1610
+ * package: by `exports` under the conditions given, else `main`, else
1611
+ * `index.js`. Undefined where `exports` does not export it.
1612
+ */
1613
+ entry(subpath, conditions) {
1614
+ const { exports, main } = this.model;
1615
+ if (exports === void 0) {
1616
+ if (subpath !== ".") return subpath.slice(2);
1617
+ return typeof main === "string" ? main.replace(/^\.\//, "") : "index.js";
1618
+ }
1619
+ return this.#matched(this.#subpaths(exports) ?? { ".": exports }, subpath, conditions);
1620
+ }
1621
+ /**
1622
+ * The target a `#…` import names under the conditions given, as `imports` writes it: a path inside the package,
1623
+ * starting with `./`, or a bare specifier, for the importer's own dependencies. Undefined where `imports` maps none.
1624
+ */
1625
+ import(specifier, conditions) {
1626
+ if (!specifier.startsWith("#") || specifier === "#" || specifier.startsWith("#/")) throw new Error(`not a subpath import: ${specifier}`);
1627
+ const { imports } = this.model;
1628
+ if (typeof imports !== "object" || imports === null || Array.isArray(imports)) return void 0;
1629
+ return this.#matched(imports, specifier, conditions, true);
1630
+ }
1631
+ #matched(map, subpath, conditions, importing = false) {
1632
+ if (Object.hasOwn(map, subpath)) return this.#target(map[subpath], void 0, conditions, importing);
1633
+ let best;
1634
+ for (const key of Object.keys(map)) {
1635
+ const star = key.indexOf("*");
1636
+ if (star === -1 || subpath.length < key.length) continue;
1637
+ const after = key.slice(star + 1);
1638
+ if (!subpath.startsWith(key.slice(0, star)) || !subpath.endsWith(after)) continue;
1639
+ if (best !== void 0 && (star < best.before || star === best.before && key.length <= best.key.length)) continue;
1640
+ best = {
1641
+ key,
1642
+ before: star,
1643
+ match: subpath.slice(star, subpath.length - after.length)
1644
+ };
1645
+ }
1646
+ return best === void 0 ? void 0 : this.#target(map[best.key], best.match, conditions, importing);
1647
+ }
1648
+ #subpaths(exports) {
1649
+ if (typeof exports !== "object" || exports === null || Array.isArray(exports)) return void 0;
1650
+ const keys = Object.keys(exports);
1651
+ const dotted = keys.filter((key) => key.startsWith(".")).length;
1652
+ if (dotted === 0) return void 0;
1653
+ if (dotted !== keys.length) throw new Error(`exports mixes subpaths and conditions: ${keys.join(", ")}`);
1654
+ return exports;
1655
+ }
1656
+ #target(value, match, conditions, importing = false) {
1657
+ if (value === null) return void 0;
1658
+ if (typeof value === "string") {
1659
+ const target = match === void 0 ? value : value.replaceAll("*", match);
1660
+ if (value.startsWith("./")) return importing ? target : target.slice(2);
1661
+ if (importing && BareSpecifier.is(value)) return target;
1662
+ throw new Error(`an ${importing ? "import" : "export"} target starts with ./: ${value}`);
1663
+ }
1664
+ if (Array.isArray(value)) {
1665
+ for (const fallback of value) {
1666
+ const path = this.#target(fallback, match, conditions, importing);
1667
+ if (path !== void 0) return path;
1668
+ }
1669
+ return;
1670
+ }
1671
+ if (typeof value !== "object") throw new Error(`not an export target: ${JSON.stringify(value)}`);
1672
+ for (const [condition, next] of Object.entries(value)) {
1673
+ if (!conditions.includes(condition)) continue;
1674
+ const path = this.#target(next, match, conditions, importing);
1675
+ if (path !== void 0) return path;
1676
+ }
1677
+ }
1678
+ };
1679
+ //#endregion
1680
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/Tags.ts
1681
+ /**
1682
+ * Purpose: say which releases of a workbench a store holds, each by its tag,
1683
+ * and where its tree stands.
1684
+ *
1685
+ * Intention: reads the trees Core's installer keeps in a store
1686
+ * through a {@link Folder}, each by the version its {@link Workbench} names —
1687
+ * written by Descriptor's Generator, so a tree says its own version;
1688
+ * {@link Releases} chooses the latest. The oField hook uses it to find the
1689
+ * tree a tag or no ref names, and the stores to find the workbenches they hold
1690
+ * a release of.
1691
+ */
1692
+ var Tags = class extends TypedSmartObject {
1693
+ /**
1694
+ * Reads the tags of a workbench, `<namespace>/<Name>`, from its trees in a store, `0field/<namespace>/<Name>/<sha>/`: none
1695
+ * where the store holds no tree of it; refused, naming the tree and saying to rebuild the store, where a tree's
1696
+ * `workbench.jsonld` names no stable version `X.Y.Z` — a store an older installer built. A folder whose name starts with a
1697
+ * dot is the installer's, still being written, and is no tree.
1698
+ */
1699
+ constructor(store, id) {
1700
+ const read = {};
1701
+ for (const tree of store.folder(`0field/${id}`).entries) {
1702
+ if (!isFolder(tree) || tree.name.startsWith(".")) continue;
1703
+ const version = Workbench.at(tree).version;
1704
+ if (version === void 0 || version.startsWith("v") || new Releases([version]).latest !== version) throw new Error(`${tree.path}/workbench.jsonld names no stable version: rebuild the store`);
1705
+ read[`v${version}`] = tree.name;
1706
+ }
1707
+ super(read);
1708
+ }
1709
+ /** The tag of its highest stable release; none where the store holds no tree of it. */
1710
+ get latest() {
1711
+ return new Releases(Object.keys(this.model)).latest;
1712
+ }
1713
+ };
1714
+ //#endregion
1715
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/loading/NodeStores.ts
1716
+ /**
1717
+ * Purpose: find the stores of the host this process runs on, in the order
1718
+ * they are read, and the workbenches they hold.
1719
+ *
1720
+ * Intention: realizes {@link Stores} over Node's API — `process.env`,
1721
+ * `os.homedir()`, {@link ReadOnlyNodeFolder.native} — which Node, Deno and
1722
+ * Bun all implement; {@link NodeStores.of} reads the host into its
1723
+ * {@link StoresModel}, and every store it hands out is a
1724
+ * {@link ReadOnlyNodeFolder}. It uses each workbench's {@link Tags}.
1725
+ */
1726
+ var NodeStores = class NodeStores extends TypedSmartObject {
1727
+ /** The stores of this host, found from its platform, its home folder and `env`. */
1728
+ static of(env = process.env) {
1729
+ const { homedir } = process.getBuiltinModule("node:os");
1730
+ return new NodeStores({
1731
+ platform: process.platform,
1732
+ ...env.OFIELD_HOME ? { oFieldHome: ReadOnlyNodeFolder.native(env.OFIELD_HOME).path } : {},
1733
+ home: ReadOnlyNodeFolder.native(homedir()).path,
1734
+ ...env.ProgramData ? { programData: ReadOnlyNodeFolder.native(env.ProgramData).path } : {}
1735
+ });
1736
+ }
1737
+ get all() {
1738
+ if (this.model.oFieldHome !== void 0) return [this.own];
1739
+ return [this.shared, this.own].filter((store) => store?.exists === true);
1740
+ }
1741
+ get own() {
1742
+ if (this.model.oFieldHome === void 0) return this.folderAt(this.model.home).folder(".0field");
1743
+ const oFieldHome = this.folderAt(this.model.oFieldHome);
1744
+ if (!oFieldHome.exists) throw new Error(`OFIELD_HOME is no folder: ${oFieldHome.path}`);
1745
+ return oFieldHome;
1746
+ }
1747
+ get shared() {
1748
+ if (this.model.platform === "darwin") return this.folderAt("/Users/Shared/.0field");
1749
+ if (this.model.platform === "win32") return this.model.programData === void 0 ? void 0 : this.folderAt(this.model.programData).folder("0field");
1750
+ return this.folderAt("/var/lib/0field");
1751
+ }
1752
+ get workbenches() {
1753
+ const folders = (folder) => folder.entries.filter(isFolder);
1754
+ const named = this.all.flatMap((store) => folders(store.folder("0field")).flatMap((namespace) => folders(namespace).map((workbench) => `${namespace.name}/${workbench.name}`).filter((id) => new Tags(store, id).latest !== void 0)));
1755
+ return [...new Set(named)].sort();
1756
+ }
1757
+ /** The {@link Folder} at an absolute POSIX path, a {@link ReadOnlyNodeFolder}. */
1758
+ folderAt(path) {
1759
+ return new ReadOnlyNodeFolder(path);
1760
+ }
1761
+ };
1762
+ //#endregion
1763
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/loading/NodeNpmHook.ts
1764
+ /**
1765
+ * Purpose: load an npm package from the store on this host's disk, without
1766
+ * `node_modules`.
1767
+ *
1768
+ * Intention: realizes {@link ModuleHook} for `ofield://npm/…` and for the bare
1769
+ * and `#…` imports a stored package makes, over Node's API —
1770
+ * {@link NodeStores}, {@link ReadOnlyNodeFolder}, `node:path`, `node:module` —
1771
+ * which Node, Deno and Bun all implement. It reads a package through its
1772
+ * {@link PackageManifest} and the dependencies the `uses` of its descriptor,
1773
+ * `<version>.descriptor.jsonld` beside its version, names,
1774
+ * a specifier as an {@link OFieldIri} or a {@link BareSpecifier}, a version
1775
+ * through {@link Releases}, and hands a stored CommonJS module on through a
1776
+ * {@link CommonJsModule}.
1777
+ */
1778
+ var NodeNpmHook = class NodeNpmHook extends TypedSmartObject {
1779
+ /** A file inside a stored package below a store: `/npm/<name>/<version>/package/…`, naming the package's name and version. */
1780
+ static stored = /\/npm\/((?:@[^/]+\/)?[^/]+)\/([^/]+)\/package\/./;
1781
+ name = "npm";
1782
+ schemes = ["ofield"];
1783
+ /**
1784
+ * The stored file an import names: `ofield://npm/…` by its version — the latest release without one, the highest
1785
+ * within a range — a bare import by the exact version its package's descriptor names in `uses`, or its own version
1786
+ * where it names the importing package itself, and a `#…` import by the `imports` of the `package.json` governing
1787
+ * the importing file; the {@link PackageManifest} picks the file. A builtin it passes on.
1788
+ */
1789
+ resolve(specifier, parentURL) {
1790
+ return this.#resolved(specifier, parentURL, "import");
1791
+ }
1792
+ #resolved(specifier, parentURL, kind) {
1793
+ if (specifier.startsWith("ofield:")) {
1794
+ const { source, namespace, name, ref, subpath } = new OFieldIri(specifier).model;
1795
+ if (namespace !== "npm") return void 0;
1796
+ if (source !== void 0) throw new Error(`oField sources are not read yet: ${source}`);
1797
+ return this.#entry(name, ref, subpath === void 0 ? "." : `./${subpath}`, kind);
1798
+ }
1799
+ if (parentURL !== void 0 && specifier.startsWith("#")) return this.#imported(specifier, parentURL, kind);
1800
+ if (parentURL === void 0 || !BareSpecifier.is(specifier) || this.#isBuiltin(specifier)) return void 0;
1801
+ const importer = this.#packageOf(this.fileOf(parentURL));
1802
+ if (importer === void 0) return void 0;
1803
+ const { name, subpath } = new BareSpecifier(specifier);
1804
+ if (name === importer.name) {
1805
+ if (new PackageManifest(importer.folder.folder("package").file("package.json")).model.exports === void 0) throw new Error(`npm/${name}@${importer.version} has no exports to import itself by`);
1806
+ return this.#entry(name, importer.version, subpath, kind);
1807
+ }
1808
+ const descriptor = importer.folder.parent?.file(`${importer.version}.descriptor.jsonld`);
1809
+ const version = NodeNpmHook.#used(descriptor).get(name);
1810
+ if (version === void 0) throw new Error(`no ${name} in the uses of ${descriptor.path}, imported by ${parentURL}`);
1811
+ return this.#entry(name, version, subpath, kind);
1812
+ }
1813
+ /**
1814
+ * A stored file's source and its format — never guessed by the runtime's own loader, which takes a `.js` file for
1815
+ * ESM or CommonJS inconsistently across habitats. `.mjs` is always `module`, `.cjs` always `commonjs`, `.json`
1816
+ * always `json`; a `.js` file follows the nearest `package.json` above it within its package — a package bundled
1817
+ * inside another governs its own files, as Node reads it — or, where that names no `type`, whether it compiles as
1818
+ * CommonJS, as Node's own newer detection does for a file no `package.json` governs.
1819
+ *
1820
+ * A stored CommonJS module is handed on as the ES module a {@link CommonJsModule} stands in with, the same in every
1821
+ * habitat, its `require`s resolved here as Node's are: by the `require` condition, a relative one by Node's file
1822
+ * rules. A stored ES module's `import.meta.resolve(…)` is answered here too, as its import would be: the call is
1823
+ * rewritten in its source, as Deno and Bun answer it themselves, past every hook.
1824
+ */
1825
+ load(url) {
1826
+ const read = this.#read(url);
1827
+ if (read?.format === "module" && RESOLVE.test(read.source)) return {
1828
+ source: this.#resolving(read.source),
1829
+ format: "module"
1830
+ };
1831
+ if (read?.format !== "commonjs") return read;
1832
+ return {
1833
+ source: CommonJsModule.of(url, this.#host).source,
1834
+ format: "module"
1835
+ };
1836
+ }
1837
+ #resolving(source) {
1838
+ const global = globalThis;
1839
+ global[Symbol.for(RESOLVER)] = this.#resolver;
1840
+ return source.replace(new RegExp(RESOLVE.source, "g"), `globalThis[Symbol.for(${JSON.stringify(RESOLVER)})](import.meta.url, `);
1841
+ }
1842
+ #resolver = (parentURL, specifier) => {
1843
+ const resolved = this.resolve(specifier, parentURL);
1844
+ if (resolved !== void 0) return resolved;
1845
+ if (/^\.{0,2}\//.test(specifier) || /^[a-z][a-z\d+.-]*:/i.test(specifier)) return new URL(specifier, parentURL).href;
1846
+ if (this.#isBuiltin(specifier)) return specifier.startsWith("node:") ? specifier : `node:${specifier}`;
1847
+ throw new Error(`no ${specifier} to resolve from ${parentURL}`);
1848
+ };
1849
+ #host = {
1850
+ read: (url) => this.#read(url),
1851
+ fileOf: (url) => this.fileOf(url),
1852
+ required: (specifier, parentURL) => this.#required(specifier, parentURL),
1853
+ esm: (url) => this.#esm(url)
1854
+ };
1855
+ #read(url) {
1856
+ const file = this.fileOf(url);
1857
+ const importer = this.#packageOf(file);
1858
+ if (file === void 0 || importer === void 0 || !file.exists || file.path.endsWith(".node")) return void 0;
1859
+ const source = file.readText();
1860
+ if (file.path.endsWith(".json")) return {
1861
+ source,
1862
+ format: "json"
1863
+ };
1864
+ if (file.path.endsWith(".mjs")) return {
1865
+ source,
1866
+ format: "module"
1867
+ };
1868
+ if (file.path.endsWith(".cjs")) return {
1869
+ source,
1870
+ format: "commonjs"
1871
+ };
1872
+ const type = NodeNpmHook.#governing(file, importer.folder.folder("package"))?.readJsonObject().type;
1873
+ return {
1874
+ source,
1875
+ format: type === "commonjs" ? "commonjs" : type === "module" || NodeNpmHook.looksLikeModule(source) ? "module" : "commonjs"
1876
+ };
1877
+ }
1878
+ static #governing(file, root) {
1879
+ for (let folder = file.parent; folder !== void 0 && folder.path.startsWith(root.path); folder = folder.parent) {
1880
+ if (folder.file("package.json").exists) return folder.file("package.json");
1881
+ if (folder.path === root.path) break;
1882
+ }
1883
+ }
1884
+ static looksLikeModule(source) {
1885
+ return !CommonJsModule.runs(source);
1886
+ }
1887
+ #paths = process.getBuiltinModule("node:path");
1888
+ #modules = process.getBuiltinModule("node:module");
1889
+ /** The stores in the order they are read, asked at each import. */
1890
+ #stores() {
1891
+ return NodeStores.of().all;
1892
+ }
1893
+ /**
1894
+ * The file a `file:` URL names. A runtime gives a file it reached by a relative import under its real path, so
1895
+ * inside a store reached through a link the store's own path is given back.
1896
+ * Law: `fileOf(url(file))` is `file`.
1897
+ */
1898
+ fileOf(url) {
1899
+ if (!url.startsWith("file:")) return void 0;
1900
+ const path = this.#given(ReadOnlyNodeFolder.fromUrl(url).path);
1901
+ return ReadOnlyNodeFolder.native(this.#paths.dirname(path)).file(this.#paths.basename(path));
1902
+ }
1903
+ /** The URL the runtime loads a file by. */
1904
+ url(file) {
1905
+ return ReadOnlyNodeFolder.urlOf(file);
1906
+ }
1907
+ /** Whether a bare specifier names a module of the runtime's own, such as `fs`. */
1908
+ #isBuiltin(specifier) {
1909
+ return this.#modules.isBuiltin(specifier);
1910
+ }
1911
+ /** A module of the runtime's own, as a `require` of it hands it. */
1912
+ #builtin(specifier) {
1913
+ return process.getBuiltinModule(specifier);
1914
+ }
1915
+ /** What a stored CommonJS module's `require` of an ES module hands back. */
1916
+ #esm(url) {
1917
+ return this.#modules.createRequire(url)(ReadOnlyNodeFolder.fromUrl(url).path);
1918
+ }
1919
+ #conditions(kind) {
1920
+ return [
1921
+ kind,
1922
+ ...this.model.conditions,
1923
+ "default"
1924
+ ];
1925
+ }
1926
+ #entry(name, ref, subpath, kind) {
1927
+ const homes = this.#stores().map((store) => store.folder(`npm/${name}`));
1928
+ const version = new Releases(homes.flatMap((home) => home.entries.map((version) => version.name))).named(ref);
1929
+ const trees = version === void 0 ? [] : homes.map((home) => home.folder(`${version}/package`));
1930
+ const tree = trees.find((folder) => folder.exists);
1931
+ if (tree === void 0) {
1932
+ const looked = (trees.length === 0 ? homes : trees).map((folder) => folder.path);
1933
+ throw new Error(`no ${ref ?? "latest"} of npm/${name}, looked in: ${looked.join(", ") || "no store"}`);
1934
+ }
1935
+ const manifest = new PackageManifest(tree.file("package.json"));
1936
+ const path = manifest.entry(subpath, this.#conditions(kind));
1937
+ if (path === void 0) throw new Error(`npm/${name}@${version} exports no ${subpath}`);
1938
+ if (kind === "require" && manifest.model.exports === void 0) return this.#relative(`./${path}`, this.url(tree.file("package.json")));
1939
+ const file = tree.file(path);
1940
+ if (!file.exists) throw new Error(`no ${file.path} for npm/${name}@${version}`);
1941
+ return this.url(file);
1942
+ }
1943
+ #imported(specifier, parentURL, kind) {
1944
+ const file = this.fileOf(parentURL);
1945
+ const importer = this.#packageOf(file);
1946
+ if (file === void 0 || importer === void 0) return void 0;
1947
+ const manifest = NodeNpmHook.#governing(file, importer.folder.folder("package"));
1948
+ if (manifest === void 0) throw new Error(`no package.json above ${file.path} maps ${specifier}`);
1949
+ const target = new PackageManifest(manifest).import(specifier, this.#conditions(kind));
1950
+ if (target === void 0) throw new Error(`${manifest.path} imports no ${specifier}`);
1951
+ if (!target.startsWith("./")) return this.#resolved(target, parentURL, kind);
1952
+ const imported = manifest.parent.file(target.slice(2));
1953
+ if (!imported.exists) throw new Error(`no ${imported.path} for ${specifier} of npm/${importer.name}@${importer.version}`);
1954
+ return this.url(imported);
1955
+ }
1956
+ #required(specifier, parentURL) {
1957
+ if (specifier.startsWith("node:") || BareSpecifier.is(specifier) && this.#isBuiltin(specifier)) return { builtin: this.#builtin(specifier) };
1958
+ if (/^(\.{1,2}(\/|$)|\/)/.test(specifier)) return { url: this.#relative(specifier, parentURL) };
1959
+ const url = this.#resolved(specifier, parentURL, "require");
1960
+ if (url === void 0) throw new Error(`no ${specifier}, required by ${parentURL}`);
1961
+ return { url };
1962
+ }
1963
+ #relative(specifier, parentURL) {
1964
+ const base = new URL(specifier, parentURL).href.replace(/\/$/, "");
1965
+ for (const ending of [
1966
+ "",
1967
+ ".js",
1968
+ ".json",
1969
+ ".cjs",
1970
+ "/index.js",
1971
+ "/index.json"
1972
+ ]) {
1973
+ const file = this.fileOf(`${base}${ending}`);
1974
+ if (file?.exists) return this.url(file);
1975
+ if (ending === ".cjs") {
1976
+ const manifest = this.fileOf(`${base}/package.json`);
1977
+ const main = manifest?.exists ? new PackageManifest(manifest).model.main : void 0;
1978
+ if (typeof main === "string") for (const tried of [
1979
+ "",
1980
+ ".js",
1981
+ "/index.js"
1982
+ ]) {
1983
+ const entry = this.fileOf(`${new URL(main, `${base}/`).href.replace(/\/$/, "")}${tried}`);
1984
+ if (entry?.exists) return this.url(entry);
1985
+ }
1986
+ }
1987
+ }
1988
+ throw new Error(`no file for ${specifier}, required by ${parentURL}`);
1989
+ }
1990
+ static #used(descriptor) {
1991
+ const used = /* @__PURE__ */ new Map();
1992
+ if (!descriptor.exists) return used;
1993
+ const uses = descriptor.readJsonObject().uses;
1994
+ if (uses === void 0) return used;
1995
+ if (!Array.isArray(uses)) throw new Error(`uses is no list in ${descriptor.path}`);
1996
+ for (const id of uses) {
1997
+ const iri = typeof id === "string" ? OFieldIri.of(id)?.model : void 0;
1998
+ if (iri?.namespace !== "npm" || iri.ref === void 0) throw new Error(`no npm package at a version in the uses of ${descriptor.path}: ${JSON.stringify(id)}`);
1999
+ used.set(iri.name, iri.ref);
2000
+ }
2001
+ return used;
2002
+ }
2003
+ #packageOf(file) {
2004
+ if (file === void 0) return void 0;
2005
+ for (const store of this.#stores()) {
2006
+ if (!file.path.startsWith(`${store.path}/`)) continue;
2007
+ const match = NodeNpmHook.stored.exec(file.path.slice(store.path.length));
2008
+ if (match?.index === 0) return {
2009
+ folder: store.folder(`npm/${match[1]}/${match[2]}`),
2010
+ name: match[1],
2011
+ version: match[2]
2012
+ };
2013
+ }
2014
+ }
2015
+ #given(path) {
2016
+ if (!NodeNpmHook.stored.test(path)) return path;
2017
+ for (const store of this.#stores()) {
2018
+ const real = new ReadOnlyNodeFolder(store.path).real.path;
2019
+ if (real !== store.path && path.startsWith(`${real}/`)) return `${store.path}${path.slice(real.length)}`;
2020
+ }
2021
+ return path;
2022
+ }
2023
+ };
2024
+ const RESOLVE = /\bimport\.meta\.resolve\s*\(/;
2025
+ const RESOLVER = "metatrom.oField.resolve";
2026
+ //#endregion
2027
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/git/GitNotes.ts
2028
+ /**
2029
+ * Purpose: say where in a notes tree the note of a commit stands, whether git
2030
+ * has fanned the tree out or not.
2031
+ *
2032
+ * Intention: a notes ref's tree as git keeps it, read as a {@link Folder}: a
2033
+ * note is named by its commit's sha, and git splits that name into leading
2034
+ * two-character folders, to any depth, as the tree grows. A storage of a
2035
+ * notes ref asks it for the path of a note, and for the sha a path names.
2036
+ */
2037
+ var GitNotes = class GitNotes extends TypedSmartObject {
2038
+ #folder;
2039
+ /** The notes tree at a folder. */
2040
+ constructor(folder) {
2041
+ super({ path: folder.path });
2042
+ this.#folder = folder;
2043
+ }
2044
+ /** Whether a ref holds notes, as git's `refs/notes/` does. */
2045
+ static held(ref) {
2046
+ return ref?.startsWith("refs/notes/") ?? false;
2047
+ }
2048
+ /** Whether a name is a note's: a commit's sha in full, SHA-1 or SHA-256, as git writes it. */
2049
+ static names(name) {
2050
+ return /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(name);
2051
+ }
2052
+ /**
2053
+ * The path of the note named by a sha: where it stands, flat or fanned out to whatever depth; where there is none,
2054
+ * where a new one goes — as deep as the notes already there are fanned out, flat in a tree with no fan-out.
2055
+ */
2056
+ pathOf(sha) {
2057
+ if (!GitNotes.names(sha)) throw new Error(`a note is named by a commit's full sha: ${sha}`);
2058
+ const deepest = sha.length / 2 - 1;
2059
+ for (let depth = 0; depth <= deepest; depth++) {
2060
+ const path = GitNotes.#fanned(sha, depth);
2061
+ if (this.#folder.file(path).exists) return path;
2062
+ }
2063
+ return GitNotes.#fanned(sha, this.#depth(deepest));
2064
+ }
2065
+ /**
2066
+ * The sha a path below the tree names, its folders joined to the file's name; none for a path that is no note's,
2067
+ * a fan-out folder being no note.
2068
+ */
2069
+ static shaOf(path) {
2070
+ const names = path.split("/");
2071
+ if (!names.slice(0, -1).every((name) => /^[0-9a-f]{2}$/.test(name))) return void 0;
2072
+ const sha = names.join("");
2073
+ return GitNotes.names(sha) ? sha : void 0;
2074
+ }
2075
+ #depth(deepest) {
2076
+ let at = this.#folder;
2077
+ let depth = 0;
2078
+ while (depth < deepest) {
2079
+ const next = at.entries.find((entry) => isFolder(entry) && /^[0-9a-f]{2}$/.test(entry.name));
2080
+ if (next === void 0) break;
2081
+ at = next;
2082
+ depth++;
2083
+ }
2084
+ return depth;
2085
+ }
2086
+ static #fanned(sha, depth) {
2087
+ return [...Array.from({ length: depth }, (_, level) => sha.slice(level * 2, level * 2 + 2)), sha.slice(depth * 2)].join("/");
2088
+ }
2089
+ };
2090
+ //#endregion
2091
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/loading/NodeOFieldHook.ts
2092
+ /**
2093
+ * Purpose: load a SmartObject by its oField IRI from this host's disk.
2094
+ *
2095
+ * Intention: realizes {@link ModuleHook} for the `ofield` scheme over Node's
2096
+ * API — {@link NodeStores}, {@link ReadOnlyNodeFolder} — which Node, Deno and
2097
+ * Bun all implement, leaving to the runtime loading the file it resolves. It
2098
+ * reads a URI as an {@link OFieldIri}, a range through {@link Releases}, a
2099
+ * branch from the {@link Workbench} the importing file belongs to, and a tag, or
2100
+ * a URI naming no ref, by the {@link Tags} of each store.
2101
+ */
2102
+ var NodeOFieldHook = class extends TypedSmartObject {
2103
+ name = "ofield";
2104
+ schemes = ["ofield"];
2105
+ /**
2106
+ * The file an oField IRI names: a tag or a sha from the stores, a range as the highest release of every store's tags
2107
+ * within it; a branch from the {@link Workbench} the importing file belongs to, which also names the branch taken when
2108
+ * the URI names no ref; the importing file's own workbench, named with no ref, from the working tree it stands in;
2109
+ * elsewhere no ref, or `latest`, is the latest release the stores hold. `ofield://npm/…` it passes on.
2110
+ */
2111
+ resolve(specifier, parentURL) {
2112
+ if (!specifier.startsWith("ofield:")) return void 0;
2113
+ const iri = new OFieldIri(specifier);
2114
+ if (iri.model.namespace === "npm") return void 0;
2115
+ const entry = this.tree(specifier, parentURL).file(entryOf(iri));
2116
+ if (!entry.exists) throw new Error(`no ${entry.path} for ${specifier}`);
2117
+ return this.url(entry);
2118
+ }
2119
+ /**
2120
+ * The tree an oField IRI names on this host, as {@link NodeOFieldHook.resolve} finds it, whatever its subpath; refused,
2121
+ * naming where it looked, where there is none.
2122
+ */
2123
+ tree(specifier, parentURL) {
2124
+ const { tree, missing } = this.#lookup(specifier, parentURL);
2125
+ if (tree === void 0) throw new Error(missing());
2126
+ return tree;
2127
+ }
2128
+ /** The tree an oField IRI names on this host, as {@link NodeOFieldHook.tree} finds it; none where this host holds none. */
2129
+ find(specifier, parentURL) {
2130
+ return this.#lookup(specifier, parentURL).tree;
2131
+ }
2132
+ #lookup(specifier, parentURL) {
2133
+ const { source, namespace, name, ref } = new OFieldIri(specifier).model;
2134
+ if (source !== void 0) throw new Error(`oField sources are not read yet: ${source}`);
2135
+ const id = `${namespace}/${name}`;
2136
+ const repository = Workbench.above(parentURL === void 0 ? void 0 : this.folderOf(parentURL));
2137
+ const own = ref === void 0 ? repository?.own(id) : void 0;
2138
+ if (own !== void 0) return {
2139
+ tree: own,
2140
+ missing: () => ""
2141
+ };
2142
+ const wanted = ref ?? repository?.branch(id);
2143
+ const stores = this.stores();
2144
+ const homes = stores.map((store) => store.folder(`0field/${id}`));
2145
+ const tags = new Map(stores.flatMap((store) => Object.entries(new Tags(store, id).model)));
2146
+ const latest = wanted === void 0 || wanted === "latest";
2147
+ const range = !latest && Releases.range.test(wanted);
2148
+ const tag = new Releases([...tags.keys()]).named(wanted);
2149
+ const sha = tag === void 0 ? void 0 : tags.get(tag) ?? (latest ? void 0 : tag);
2150
+ const branch = latest || range || tags.has(wanted) ? void 0 : wanted;
2151
+ const checkout = branch === void 0 ? void 0 : repository?.checkout(id, branch);
2152
+ const trees = [...sha === void 0 ? [] : homes.map((home) => home.folder(sha)), ...checkout === void 0 ? [] : [checkout]];
2153
+ const tree = trees.find((folder) => folder.exists);
2154
+ const missing = () => {
2155
+ const looked = [...homes, ...trees].map((entry) => entry.path);
2156
+ const unlisted = branch === void 0 ? "" : repository === void 0 ? "; no repository above the importing file" : checkout === void 0 ? `; git lists no checkout of ${id} on ${branch} in ${repository.path}` : "";
2157
+ return `no ${wanted ?? "latest"} of ${id}, looked in: ${looked.join(", ") || "no store"}${unlisted}`;
2158
+ };
2159
+ return {
2160
+ tree,
2161
+ missing
2162
+ };
2163
+ }
2164
+ /** The stores in the order they are read, asked at each import. */
2165
+ stores() {
2166
+ return NodeStores.of().all;
2167
+ }
2168
+ /**
2169
+ * The folder holding the file a URL names, when it names one on this host.
2170
+ * Law: `folderOf(url(file))` holds `file`, `url(folderOf(url(file)).file(file.name))` being `url(file)` — sampled
2171
+ * in `NodeOFieldHook.test.ts`.
2172
+ */
2173
+ folderOf(url) {
2174
+ return url.startsWith("file:") ? ReadOnlyNodeFolder.fromUrl(url).parent : void 0;
2175
+ }
2176
+ /**
2177
+ * The `file:` URL of a file: by its real path where its runtime loads by real paths, so one file is one module
2178
+ * however it is reached; elsewhere by the path it is named by.
2179
+ */
2180
+ url(file) {
2181
+ return ReadOnlyNodeFolder.urlOf(this.model.realPaths ? ReadOnlyNodeFolder.native(file.path).real : file);
2182
+ }
2183
+ };
2184
+ /** The file an oField IRI names within its tree: its subpath, or, naming none, the workbench's own SmartObject `<Name>.ts`. */
2185
+ function entryOf(iri) {
2186
+ return iri.model.subpath ?? `${iri.model.name}.ts`;
2187
+ }
2188
+ /**
2189
+ * The descriptor of what an oField IRI names within its tree: the descriptor it names, the one beside the file it names,
2190
+ * or, where it names a data file, that of the workbench's own SmartObject.
2191
+ */
2192
+ function descriptorOf(iri) {
2193
+ const entry = entryOf(iri);
2194
+ if (entry.endsWith(".descriptor.jsonld")) return entry;
2195
+ if (/\.jsonld?$/.test(entry)) return `${iri.model.name}.descriptor.jsonld`;
2196
+ return descriptorBeside(entry) ?? `${entry}.descriptor.jsonld`;
2197
+ }
2198
+ /** The descriptor beside a module's file, by its path or name; none where it names no module. */
2199
+ function descriptorBeside(path) {
2200
+ return /\.[jt]sx?$/.test(path) ? `${path.replace(/\.[jt]sx?$/, "")}.descriptor.jsonld` : void 0;
2201
+ }
2202
+ //#endregion
2203
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/file-system/ReadOnlyNodeStorage.ts
2204
+ /**
2205
+ * Purpose: find what a SmartObject is stored as on this host's disk, and
2206
+ * there the repositories that are SmartObjects themselves.
2207
+ *
2208
+ * Intention: has the shape of the storage a Persistence uses, over
2209
+ * Node's API, which Node, Deno and Bun all implement. It finds a tree
2210
+ * through the {@link NodeOFieldHook}, an npm package's version through
2211
+ * {@link NodeStores} and {@link Releases}, realizes a repository's root as
2212
+ * its {@link Workbench}, and finds a note of a notes ref through {@link GitNotes}.
2213
+ */
2214
+ var ReadOnlyNodeStorage = class ReadOnlyNodeStorage extends TypedSmartObject {
2215
+ /**
2216
+ * The location an address names: an oField IRI as it stands, refused unless in canonical form, a path or a `file:` URL
2217
+ * as its `file:` URL, a fragment dropped; no other scheme is read.
2218
+ */
2219
+ location(address) {
2220
+ if (address === "") throw new Error("an empty address names no model");
2221
+ if (address.startsWith("ofield:")) {
2222
+ const located = address.split("#")[0];
2223
+ if (ReadOnlyNodeStorage.#npm(located) === void 0) this.#parsed(located);
2224
+ return new OFieldIri(located).toString();
2225
+ }
2226
+ const scheme = /^([A-Za-z][A-Za-z\d+.-]+):/.exec(address)?.[1];
2227
+ if (scheme !== void 0 && scheme.toLowerCase() !== "file") throw new Error(`no storage here reads ${scheme}: ${address}`);
2228
+ const url = new URL(/^file:/i.test(address) ? address : ReadOnlyNodeFolder.urlOf(ReadOnlyNodeFolder.native(address)));
2229
+ if (url.search !== "") throw new Error(`a query names no file: ${address}`);
2230
+ url.hash = "";
2231
+ return url.href;
2232
+ }
2233
+ /** Whether a text is stored at a location; none is where this host holds no tree the location names. */
2234
+ async has(location) {
2235
+ return this.hasSync(location);
2236
+ }
2237
+ /** {@link ReadOnlyNodeStorage.has}, answered at once. */
2238
+ hasSync(location) {
2239
+ if (!location.startsWith("ofield:")) return new ReadOnlyNodeFile(ReadOnlyNodeFolder.fromUrl(location).path).exists;
2240
+ const npm = ReadOnlyNodeStorage.#npm(location);
2241
+ if (npm !== void 0) return this.#described(npm) !== void 0;
2242
+ const { subpath, tree: address } = this.#parsed(location);
2243
+ const tree = new NodeOFieldHook().find(location, this.model.main);
2244
+ return tree !== void 0 && subpath !== void 0 && tree.file(ReadOnlyNodeStorage.#noted(tree, address.ref, subpath)).exists;
2245
+ }
2246
+ /**
2247
+ * Whether a location names a repository by its root — a `file:` URL, or an oField IRI naming no subpath whose tree is
2248
+ * a git checkout; a tree in the stores holds no `.git`, whatever it commits, and is none.
2249
+ */
2250
+ realizes(location) {
2251
+ const folder = this.#folder(location);
2252
+ return folder !== void 0 && Workbench.above(folder)?.path === folder.path;
2253
+ }
2254
+ /**
2255
+ * The Workbench a location names by its root, named by its root's real `file:` URL, so every address of one names
2256
+ * one, however a link on the way spells it; refused for a folder below a root, naming the root.
2257
+ */
2258
+ realized(location) {
2259
+ const folder = this.#folder(location);
2260
+ const repository = folder === void 0 ? void 0 : Workbench.above(folder);
2261
+ if (folder === void 0 || repository === void 0) throw new Error(`no repository's root at ${location}`);
2262
+ if (repository.path !== folder.path) throw new Error(this.#below(location, repository));
2263
+ return Workbench.at(folder, ReadOnlyNodeFolder.urlOf(folder));
2264
+ }
2265
+ #folder(location) {
2266
+ let named;
2267
+ if (location.startsWith("ofield:")) {
2268
+ if (ReadOnlyNodeStorage.#npm(location) !== void 0 || new OFieldIri(location).model.source !== void 0) return void 0;
2269
+ if (this.#parsed(location).subpath !== void 0) return void 0;
2270
+ const tree = new NodeOFieldHook().find(location, this.model.main);
2271
+ if (tree === void 0 || !(tree.folder(".git").exists || tree.file(".git").exists)) return void 0;
2272
+ named = ReadOnlyNodeFolder.native(tree.path);
2273
+ } else named = ReadOnlyNodeFolder.fromUrl(location);
2274
+ try {
2275
+ const real = named.real;
2276
+ return real.exists ? real : void 0;
2277
+ } catch {
2278
+ return;
2279
+ }
2280
+ }
2281
+ #below(location, repository) {
2282
+ return `${location} lies in the repository at ${repository.path}, which is named by its root`;
2283
+ }
2284
+ /**
2285
+ * The text at a location, read as UTF-8. An oField IRI names a file in the tree the {@link NodeOFieldHook} finds for
2286
+ * it from the started file's place: a tag or a sha in the stores, a branch in its repository. An npm package's,
2287
+ * `ofield://npm/<name>@<ref>`, names instead the node describing a version, `npm/<name>/<version>.descriptor.jsonld`,
2288
+ * beside the version folder its ref names among those the stores describe: exact, the highest within a range, the
2289
+ * latest for none, as {@link Releases} reads a ref. A file of the package names none.
2290
+ */
2291
+ async get(location) {
2292
+ return this.getSync(location);
2293
+ }
2294
+ /** {@link ReadOnlyNodeStorage.get}, answered at once. */
2295
+ getSync(location) {
2296
+ const file = this.#file(location);
2297
+ if (!file.exists) {
2298
+ const folder = location.startsWith("ofield:") ? void 0 : this.#folder(location);
2299
+ const repository = folder === void 0 ? void 0 : Workbench.above(folder);
2300
+ throw new Error(repository === void 0 || repository.path === folder?.path ? `no model at ${location}` : this.#below(location, repository));
2301
+ }
2302
+ const bytes = file.read();
2303
+ try {
2304
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2305
+ } catch (error) {
2306
+ throw new Error(`a model is UTF-8: ${location}`, { cause: error });
2307
+ }
2308
+ }
2309
+ /**
2310
+ * The location of every text below an address, sorted: every name beginning with `.` skipped — a worktree's `.git`
2311
+ * among them — and, in a tree, every name an oField IRI cannot hold as it stands, one with `#`, `%` or `?`.
2312
+ */
2313
+ async list(address) {
2314
+ return this.listSync(address);
2315
+ }
2316
+ /** {@link ReadOnlyNodeStorage.list}, answered at once. */
2317
+ listSync(address) {
2318
+ const located = this.location(address);
2319
+ const { folder, at, held } = located.startsWith("ofield:") ? this.#oFieldFolder(located) : {
2320
+ folder: ReadOnlyNodeFolder.fromUrl(located),
2321
+ at: (file) => ReadOnlyNodeFolder.urlOf(file),
2322
+ held: () => true
2323
+ };
2324
+ if (!folder.exists) throw new Error(`no folder at ${located}`);
2325
+ return [...new Set([...stored(folder)].filter(held).map(at))].sort();
2326
+ }
2327
+ #file(location) {
2328
+ if (!location.startsWith("ofield:")) return new ReadOnlyNodeFile(ReadOnlyNodeFolder.fromUrl(location).path);
2329
+ const npm = ReadOnlyNodeStorage.#npm(location);
2330
+ if (npm !== void 0) {
2331
+ const described = this.#described(npm);
2332
+ if (described === void 0) throw new Error(`no model at ${location}`);
2333
+ return described;
2334
+ }
2335
+ const { tree, subpath } = this.#tree(location);
2336
+ if (subpath === void 0) throw new Error(`an oField URI names a model by its subpath: ${location}`);
2337
+ return tree.file(subpath);
2338
+ }
2339
+ #oFieldFolder(location) {
2340
+ const { tree, subpath, address } = this.#tree(location);
2341
+ const folder = subpath === void 0 ? tree : tree.folder(subpath);
2342
+ const notes = GitNotes.held(address.ref) && subpath === void 0;
2343
+ const named = (below) => notes ? GitNotes.shaOf(below) ?? below : below;
2344
+ return {
2345
+ folder,
2346
+ at: (file) => `${new OFieldIri({
2347
+ ...address,
2348
+ subpath: named(file.path.slice(tree.path.length + 1))
2349
+ })}`,
2350
+ held: (file) => !/[#%?]/.test(file.path.slice(tree.path.length + 1))
2351
+ };
2352
+ }
2353
+ #tree(location) {
2354
+ const { subpath, tree } = this.#parsed(location);
2355
+ const folder = new NodeOFieldHook().tree(location, this.model.main);
2356
+ return {
2357
+ tree: folder,
2358
+ subpath: subpath === void 0 ? void 0 : ReadOnlyNodeStorage.#noted(folder, tree.ref, subpath),
2359
+ address: tree
2360
+ };
2361
+ }
2362
+ static #npm(location) {
2363
+ const { source, namespace, name, ref, subpath } = new OFieldIri(location).model;
2364
+ if (namespace !== "npm") return void 0;
2365
+ if (source !== void 0 || subpath !== void 0) throw new Error(`a model is stored with a SmartObject, or as an npm package, not in an npm package: ${location}`);
2366
+ return {
2367
+ name,
2368
+ ref
2369
+ };
2370
+ }
2371
+ #described({ name, ref }) {
2372
+ const suffix = ".descriptor.jsonld";
2373
+ const nodes = NodeStores.of().all.flatMap((store) => {
2374
+ return store.folder(`npm/${name}`).entries.filter((entry) => entry.name.endsWith(suffix)).map((entry) => entry);
2375
+ });
2376
+ const version = new Releases(nodes.map((node) => node.name.slice(0, -18))).named(ref);
2377
+ return nodes.find((node) => node.name === `${version}${suffix}`);
2378
+ }
2379
+ #parsed(address) {
2380
+ const { subpath, ...tree } = new OFieldIri(address.split("#")[0]).model;
2381
+ if (tree.namespace === "npm") throw new Error(`a model is stored with a SmartObject, not in an npm package: ${address}`);
2382
+ if (subpath !== void 0 && /[%?]/.test(subpath)) throw new Error(`a model's subpath holds no % or ?: ${address}`);
2383
+ return {
2384
+ subpath,
2385
+ tree
2386
+ };
2387
+ }
2388
+ static #noted(tree, ref, subpath) {
2389
+ return GitNotes.held(ref) && GitNotes.names(subpath) ? new GitNotes(tree).pathOf(subpath) : subpath;
2390
+ }
2391
+ };
2392
+ function* stored(folder) {
2393
+ for (const entry of folder.entries.filter((entry) => !entry.name.startsWith("."))) if (entry instanceof ReadOnlyNodeFolder) yield* stored(entry);
2394
+ else yield entry;
2395
+ }
2396
+ //#endregion
2397
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/relations/Arcs.ts
2398
+ /**
2399
+ * Purpose: lead from one SmartObject to SmartObjects of one class, by the
2400
+ * ids its model names.
2401
+ *
2402
+ * Intention: the abstract SmartObject a relation extends with the shape of
2403
+ * its model; uses a {@link Restoring}, and names no format and no
2404
+ * storage.
2405
+ */
2406
+ var Arcs = class Arcs extends TypedSmartObject.Class {
2407
+ static #restoring;
2408
+ static #made = /* @__PURE__ */ new WeakMap();
2409
+ #type;
2410
+ #from;
2411
+ /**
2412
+ * The arcs its data names, to SmartObjects of `type`. Each is created, once per id, by the {@link Restoring} that
2413
+ * made `from` — where a persistence said so through {@link Arcs.made} — else by the process's one, put in use by
2414
+ * {@link Arcs.use}, so a link resolves where its data came from and a cycle of relations is walked like any graph;
2415
+ * one of another class is refused, as what is restored is input. Given `from` in place of `type`, its class is named
2416
+ * as a type alone, where importing its value would load a second copy of it or fail: what is restored is checked as
2417
+ * a SmartObject, its class the one its stored `@type` names.
2418
+ */
2419
+ constructor(model, type, from) {
2420
+ super(model);
2421
+ const named = typeof type === "function";
2422
+ this.#type = named ? type : TypedSmartObject;
2423
+ this.#from = named ? from : type;
2424
+ }
2425
+ /** Makes `restoring` the one every relation of this process creates its SmartObjects by. */
2426
+ static use(restoring) {
2427
+ Arcs.#restoring = restoring;
2428
+ }
2429
+ /** Records that `restoring` made a SmartObject, so the relations it comes from restore through that one. */
2430
+ static made(made, restoring) {
2431
+ Arcs.#made.set(made, restoring);
2432
+ }
2433
+ /**
2434
+ * The SmartObject of `type` an id names, created by `from` where it is a {@link Restoring} — a persistence kept for
2435
+ * another repository — else by the one that made `from`, else by this process's — only of a vocabulary's types,
2436
+ * where one is named; refused before one is in use, or where it is of another class.
2437
+ */
2438
+ static async restore(id, type, vocabulary, from) {
2439
+ const restored = await Arcs.#by(id, from).restore(id, vocabulary);
2440
+ if (!(restored instanceof type)) throw new TypeError(`${id} restores as a ${restored.constructor.name}, not a ${type.name}`);
2441
+ return restored;
2442
+ }
2443
+ /** Whether anything is stored at an id, as `from` tells it where it is a {@link Restoring}, else the one that made it, else this process's. */
2444
+ static has(id, from) {
2445
+ return Arcs.#by(id, from).has(id);
2446
+ }
2447
+ static #by(id, from) {
2448
+ const restoring = (from instanceof TypedSmartObject ? Arcs.#made.get(from) : void 0) ?? (Arcs.#restores(from) ? from : void 0) ?? Arcs.#restoring;
2449
+ if (restoring === void 0) throw new Error(`no persistence restores ${id}: the 0field has not started one`);
2450
+ return restoring;
2451
+ }
2452
+ static #restores(given) {
2453
+ return typeof given?.restore === "function" && typeof given.has === "function";
2454
+ }
2455
+ /** Whether a value can be the id of a SmartObject: a string, not empty. */
2456
+ static isId(value) {
2457
+ return typeof value === "string" && value !== "";
2458
+ }
2459
+ /** The SmartObject at the head of the arc an id names. */
2460
+ head(id) {
2461
+ return Arcs.restore(id, this.#type, void 0, this.#from);
2462
+ }
2463
+ };
2464
+ //#endregion
2465
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/relations/Relation.ts
2466
+ /**
2467
+ * Purpose: reach the one SmartObject a model names.
2468
+ *
2469
+ * Intention: the {@link Arcs} of one id, its model a relation's data.
2470
+ */
2471
+ var Relation = class Relation extends Arcs {
2472
+ constructor(model, type, from) {
2473
+ if (!Relation.isId(model?.relation)) throw new TypeError(`a Relation names the id of a SmartObject, { "relation": <id> }: ${JSON.stringify(model)}`);
2474
+ super(model, type, from);
2475
+ }
2476
+ /** The SmartObject it names, created only when asked for. */
2477
+ get() {
2478
+ return this.head(this.model.relation);
2479
+ }
2480
+ };
2481
+ //#endregion
2482
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/relations/RelationList.ts
2483
+ /**
2484
+ * Purpose: reach the SmartObjects a model names, in their order.
2485
+ *
2486
+ * Intention: the {@link Arcs} of ids in order, its model a list.
2487
+ */
2488
+ var RelationList = class extends Arcs {
2489
+ constructor(model, type, from) {
2490
+ if (!Array.isArray(model?.list) || !model.list.every(Arcs.isId)) throw new TypeError(`a RelationList names the ids of SmartObjects in order, { "list": [<id>, …] }: ${JSON.stringify(model)}`);
2491
+ super(model, type, from);
2492
+ }
2493
+ /** How many it names. */
2494
+ get length() {
2495
+ return this.model.list.length;
2496
+ }
2497
+ /** The SmartObject at a place, counted from 0; refused where it names none. */
2498
+ at(index) {
2499
+ const id = this.model.list[index];
2500
+ return id === void 0 ? Promise.reject(/* @__PURE__ */ new RangeError(`a RelationList of ${this.length} has no place ${index}`)) : this.head(id);
2501
+ }
2502
+ /** Each SmartObject in order, created as it is reached, a repeated id the same SmartObject. */
2503
+ async *[Symbol.asyncIterator]() {
2504
+ for (const id of this.model.list) yield await this.head(id);
2505
+ }
2506
+ };
2507
+ //#endregion
2508
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/relations/RelationMap.ts
2509
+ /**
2510
+ * Purpose: reach the SmartObjects a model names, each by its key.
2511
+ *
2512
+ * Intention: the {@link Arcs} of ids by key, its model a map.
2513
+ */
2514
+ var RelationMap = class extends Arcs {
2515
+ constructor(model, type, from) {
2516
+ const map = model?.map;
2517
+ if (typeof map !== "object" || map === null || Array.isArray(map) || !Object.values(map).every(Arcs.isId)) throw new TypeError(`a RelationMap names the ids of SmartObjects by key, { "map": { <key>: <id> } }: ${JSON.stringify(model)}`);
2518
+ super(model, type, from);
2519
+ }
2520
+ /** The keys it names a SmartObject by. */
2521
+ get keys() {
2522
+ return Object.keys(this.model.map);
2523
+ }
2524
+ /** The SmartObject of a key; refused where the key names none. */
2525
+ get(key) {
2526
+ const id = Object.hasOwn(this.model.map, key) ? this.model.map[key] : void 0;
2527
+ return id === void 0 ? Promise.reject(/* @__PURE__ */ new RangeError(`a RelationMap has no key ${JSON.stringify(key)}`)) : this.head(id);
2528
+ }
2529
+ /** Each SmartObject with its key, created as it is reached. */
2530
+ async *[Symbol.asyncIterator]() {
2531
+ for (const [key, id] of Object.entries(this.model.map)) yield [key, await this.head(id)];
2532
+ }
2533
+ };
2534
+ //#endregion
2535
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/relations/RelationSet.ts
2536
+ /**
2537
+ * Purpose: reach the SmartObjects a model names, each once.
2538
+ *
2539
+ * Intention: the {@link Arcs} of ids each named once, its model a set.
2540
+ */
2541
+ var RelationSet = class extends Arcs {
2542
+ constructor(model, type, from) {
2543
+ if (!Array.isArray(model?.set) || !model.set.every(Arcs.isId)) throw new TypeError(`a RelationSet names the ids of SmartObjects, { "set": [<id>, …] }: ${JSON.stringify(model)}`);
2544
+ const seen = /* @__PURE__ */ new Set();
2545
+ const twice = model.set.find((id) => seen.size === seen.add(id).size);
2546
+ if (twice !== void 0) throw new TypeError(`a RelationSet names each SmartObject once, ${twice} twice`);
2547
+ super(model, type, from);
2548
+ }
2549
+ /** How many it names. */
2550
+ get size() {
2551
+ return this.model.set.length;
2552
+ }
2553
+ /** Whether it names the SmartObject of an id. */
2554
+ has(id) {
2555
+ return this.model.set.includes(id);
2556
+ }
2557
+ /** Each SmartObject, created as it is reached. */
2558
+ async *[Symbol.asyncIterator]() {
2559
+ for (const id of this.model.set) yield await this.head(id);
2560
+ }
2561
+ };
2562
+ //#endregion
2563
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/JsonLd.ts
2564
+ /**
2565
+ * Purpose: hold a SmartObject's model and type as the JSON-LD a node is
2566
+ * stored as.
2567
+ *
2568
+ * Intention: what a `Persistence` reads and writes a stored text
2569
+ * with, each the other's inverse, but for an empty RelationMap under no
2570
+ * `@index` term, which reads back as an empty RelationSet; its links are the data of
2571
+ * {@link Relation}, {@link RelationList}, {@link RelationSet} and
2572
+ * {@link RelationMap}, its ids {@link OFieldIri}s where they name the 0field.
2573
+ * A {@link Workbench} is the one node that carries its own `@context`, the
2574
+ * dictionary of its words, which a node naming it reads its terms through.
2575
+ */
2576
+ var JsonLd = class JsonLd extends TypedSmartObject {
2577
+ /** The deepest a node nests its arrays and objects. */
2578
+ static depth = 128;
2579
+ /**
2580
+ * The type and model of the node a text holds, read from `location`; `context` hands out the text held at an
2581
+ * address. Refused, naming the location, where the text holds no node.
2582
+ *
2583
+ * A node is one JSON object, nesting at most {@link JsonLd.depth} deep. It keeps its `@id`, or `location` where it
2584
+ * names none, and every id it names is made absolute against `location` — JSON-LD's own base — one naming its
2585
+ * scheme taken as it stands, but for an oField IRI naming no ref of the same SmartObject as a tree read at a ref that
2586
+ * pins it — a sha, a version, a range — which names that tree, its context and its type among them, where at a head
2587
+ * — no ref, `latest`, a branch, a data ref — it stands; a `file:` id is refused in a node not read from a file, so what a tree holds cannot read
2588
+ * this host's disk. Its links become the relations' data: `{"@id"}` a Relation's `{"relation"}`, a plain array of
2589
+ * them a RelationSet's `{"set"}`, `@list` a RelationList's `{"list"}`, an array of `{"@id", "@index"}` a
2590
+ * RelationMap's `{"map"}`, `{"@set"}` a set as well, so an empty one has a form; a blank node's `_:` stays data. `@context` and `@type` leave the model: the type is the
2591
+ * IRI its `@type` names, a term of its context — inline or held at the address it names — as the context defines
2592
+ * it, or else expanded through its `@vocab`; a type naming no ref of the workbench whose context the node names at a
2593
+ * ref that pins it — a version, a range — takes that ref. A context holds `@vocab` and term definitions: an IRI, or an object of
2594
+ * `@id`, `@type: "@id"` and `@container` `@set`, `@list` or `@index`. A value under a term of type `@id` is read
2595
+ * as the links it names — a string a Relation's, an array of strings under `@set` a RelationSet's, under `@list` a
2596
+ * RelationList's, an object of strings under `@index` a RelationMap's, an empty object an empty one — whatever shape it has otherwise reads as
2597
+ * above. A node of type Workbench keeps its inline `@context` in its model, as `@context`: the workbench carries its own.
2598
+ * A context at a root's `corpus.jsonld` or `context.jsonld`, the names of its `workbench.jsonld` before, is refused;
2599
+ * so is an `@id`, `@type` or `@context` of the scheme `oasis:`, the one before `ofield:`, naming `ofield://`.
2600
+ */
2601
+ async read(text, location, context) {
2602
+ const node = object(parsed(text, location), `a node is a JSON object: ${location}`);
2603
+ if (nesting(node) > JsonLd.depth) throw new Error(`a node nests at most ${JsonLd.depth} deep: ${location}`);
2604
+ const { "@context": held, "@type": type, "@id": own, ...data } = node;
2605
+ if (typeof own === "string") OFieldIri.refuseRetired(own);
2606
+ const id = own === void 0 ? location : absolute(own, location);
2607
+ const dictionary = await this.#dictionary(held, location, context);
2608
+ const fields = Object.fromEntries(Object.entries(data).map(([key, value]) => [key, coerced(dictionary.terms.get(key), value, location) ?? this.#data(value, location)]));
2609
+ const expanded = pinnedTo(this.#type(type, dictionary, location), location);
2610
+ const named = typeof held === "string" ? pinnedTo(expanded, absolute(held, location)) : expanded;
2611
+ if (OFieldIri.unpinned(named) !== Workbench.type) return {
2612
+ type: named,
2613
+ model: {
2614
+ "@id": id,
2615
+ ...fields
2616
+ }
2617
+ };
2618
+ if (typeof held !== "object" || held === null || Array.isArray(held)) throw new Error(`a Workbench carries its own @context, inline: ${location}`);
2619
+ return {
2620
+ type: named,
2621
+ model: {
2622
+ "@id": id,
2623
+ "@context": held,
2624
+ ...fields
2625
+ }
2626
+ };
2627
+ }
2628
+ /**
2629
+ * The text a model is stored as, of the type it names, at `location` where one is given; its ids as they stand, a
2630
+ * `file:` one relative to a `file:` location. An empty RelationMap under no `@index` term is written as an empty set's
2631
+ * `{"@set": []}`, so it reads back as an empty RelationSet.
2632
+ *
2633
+ * A model holding an `@context` is a workbench's: the node carries it as its own dictionary, its `@type` the term the
2634
+ * dictionary defines for the type where it defines one. Each field whose term in it is of type `@id` and has the
2635
+ * container its relation takes — none for a Relation, `@set`, `@list`, `@index` — is written as plain strings, an oField
2636
+ * id of the node's own SmartObject and ref relative to `location`.
2637
+ *
2638
+ * A type that is a term at the root of a workbench — `ofield://<namespace>/<Name>/<Term>` — or lies in a folder of it,
2639
+ * each segment a term, names that workbench's `workbench.jsonld`, the dictionary of its words, and is written in them where
2640
+ * that dictionary is given, a type in a folder by its term only where the dictionary defines it as that type, as
2641
+ * {@link JsonLd.dictionary} loads it: each field as a workbench's own is. One pinned to a ref — a sha, a version, a
2642
+ * range — names that workbench's `workbench.jsonld` at the same ref and is written as its IRI, so the ref stays with the
2643
+ * node; one outside an oField vocabulary, or at a head ref — a branch, a data ref — is written as its IRI, with no
2644
+ * context. Written to a `file:`
2645
+ * location, every `file:` id — its own among them — is relative to it, so a tree of nodes committed and read from
2646
+ * anywhere else names its own places there.
2647
+ */
2648
+ write(model, type, location, dictionary) {
2649
+ const { "@id": own, "@context": held, ...data } = model;
2650
+ const id = typeof own === "string" ? relativeTo(own, location) : own;
2651
+ const term = type.slice(type.lastIndexOf("/") + 1);
2652
+ const context = held ?? contextOf$1(type);
2653
+ const terms = dictionaryOf(held ?? (context === void 0 ? void 0 : dictionary))?.terms;
2654
+ const at = OFieldIri.of(type)?.model;
2655
+ const named = held === void 0 && at?.ref === void 0 && at?.subpath === term || terms?.get(term)?.id === type ? term : type;
2656
+ const typed = context === void 0 ? {
2657
+ "@id": id,
2658
+ "@type": type
2659
+ } : {
2660
+ "@context": context,
2661
+ "@id": id,
2662
+ "@type": named
2663
+ };
2664
+ const fields = Object.fromEntries(Object.entries(data).map(([key, value]) => [key, plain(terms?.get(key), value, location) ?? this.#linked(value, location)]));
2665
+ return `${JSON.stringify({
2666
+ ...typed,
2667
+ ...fields
2668
+ }, null, 2)}\n`;
2669
+ }
2670
+ /**
2671
+ * The dictionary a model of a type is written in, its workbench's `workbench.jsonld` loaded as {@link JsonLd.read} loads
2672
+ * the context a node names; none for a model holding its own, a workbench's, or a type written whole.
2673
+ */
2674
+ async dictionary(model, type, location, context) {
2675
+ const address = model["@context"] === void 0 ? contextOf$1(type) : void 0;
2676
+ return address === void 0 ? void 0 : (await this.#dictionary(address, location, context)).held;
2677
+ }
2678
+ /** Every id the relations of a model name, in the order they stand. */
2679
+ relations(model) {
2680
+ const ids = [];
2681
+ const pending = [model];
2682
+ for (let value = pending.pop(); value !== void 0; value = pending.pop()) {
2683
+ const related = relationOf(value);
2684
+ if (related !== void 0) ids.push(...related.ids);
2685
+ else if (typeof value === "object" && value !== null) pending.push(...Object.values(value).reverse());
2686
+ }
2687
+ return ids;
2688
+ }
2689
+ #linked(value, location) {
2690
+ const related = relationOf(value);
2691
+ if (related === void 0) {
2692
+ if (Array.isArray(value)) return value.map((item) => this.#linked(item, location));
2693
+ if (typeof value !== "object" || value === null) return value;
2694
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.#linked(item, location)]));
2695
+ }
2696
+ const links = related.ids.map((id) => ({ "@id": relativeTo(id, location) }));
2697
+ if (related.kind === "relation") return links[0];
2698
+ if (related.kind === "list") return { "@list": links };
2699
+ if (links.length === 0) return { "@set": [] };
2700
+ if (related.kind === "set") return links;
2701
+ return Object.keys(value.map).map((key, at) => ({
2702
+ ...links[at],
2703
+ "@index": key
2704
+ }));
2705
+ }
2706
+ #type(type, dictionary, location) {
2707
+ if (typeof type !== "string" || type === "") throw new Error(`a node names its @type: ${location}`);
2708
+ if (type.includes(":")) return type;
2709
+ if (!isTerm(type)) throw new Error(`not a term: ${type}, in ${location}`);
2710
+ const defined = dictionary.terms.get(type)?.id;
2711
+ if (defined !== void 0 && defined.includes(":")) return defined;
2712
+ if (dictionary.vocab === void 0) throw new Error(`a context holds @vocab and term definitions: ${JSON.stringify(dictionary.held) ?? "none"}, in ${location}`);
2713
+ return `${dictionary.vocab}${type}`;
2714
+ }
2715
+ async #dictionary(held, location, context) {
2716
+ let inline = held;
2717
+ if (typeof held === "string") {
2718
+ const address = absolute(held, location);
2719
+ if (RETIRED_CONTEXTS.includes(OFieldIri.of(address)?.model.subpath ?? "")) throw new Error(`a node names its workbench's workbench.jsonld, not ${address}: ${location}`);
2720
+ inline = object(parsed(await context(address), address), `a context is a JSON object: ${address}`)["@context"];
2721
+ }
2722
+ return dictionaryOf(inline) ?? {
2723
+ terms: /* @__PURE__ */ new Map(),
2724
+ held: inline
2725
+ };
2726
+ }
2727
+ #data(value, location) {
2728
+ if (Array.isArray(value)) {
2729
+ if (value.length > 0 && value.every(isLink)) return { set: value.map((link) => absolute(link["@id"], location)) };
2730
+ if (value.length > 0 && value.every(isIndexed)) return { map: this.#map(value, location) };
2731
+ return value.map((item) => this.#data(item, location));
2732
+ }
2733
+ if (typeof value !== "object" || value === null) return value;
2734
+ if (isLink(value)) return { relation: absolute(value["@id"], location) };
2735
+ const keys = Object.keys(value);
2736
+ if (keys.length === 1 && keys[0] === "@set") {
2737
+ const set = value["@set"];
2738
+ if (!Array.isArray(set) || !set.every(isLink)) throw new Error(`a @set holds links alone, in ${location}`);
2739
+ return { set: set.map((link) => absolute(link["@id"], location)) };
2740
+ }
2741
+ if (keys.length === 1 && keys[0] === "@list") {
2742
+ const list = value["@list"];
2743
+ if (!Array.isArray(list) || !list.every(isLink)) throw new Error(`a @list holds links alone, in ${location}`);
2744
+ return { list: list.map((link) => absolute(link["@id"], location)) };
2745
+ }
2746
+ if (Object.hasOwn(value, "@id") && typeof value["@id"] !== "string") throw new Error(`an @id is a string: ${JSON.stringify(value["@id"])}, in ${location}`);
2747
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.#data(item, location)]));
2748
+ }
2749
+ #map(indexed, location) {
2750
+ const map = /* @__PURE__ */ new Map();
2751
+ for (const link of indexed) {
2752
+ if (map.has(link["@index"])) throw new Error(`an @index names one link, ${link["@index"]} twice, in ${location}`);
2753
+ map.set(link["@index"], absolute(link["@id"], location));
2754
+ }
2755
+ return Object.fromEntries(map);
2756
+ }
2757
+ };
2758
+ const RETIRED_CONTEXTS = ["corpus.jsonld", "context.jsonld"];
2759
+ /** Whether a word is a term a vocabulary may define: a letter or `_`, then letters, digits, `_` or `-`. */
2760
+ function isTerm(word) {
2761
+ return /^[A-Za-z_][\w-]*$/.test(word);
2762
+ }
2763
+ function dictionaryOf(inline) {
2764
+ if (typeof inline !== "object" || inline === null || Array.isArray(inline)) return void 0;
2765
+ let vocab;
2766
+ const terms = /* @__PURE__ */ new Map();
2767
+ for (const [key, value] of Object.entries(inline)) if (key === "@vocab") {
2768
+ if (typeof value !== "string") return void 0;
2769
+ vocab = value;
2770
+ } else {
2771
+ const term = termOf$1(value);
2772
+ if (key.startsWith("@") || term === void 0) return void 0;
2773
+ terms.set(key, term);
2774
+ }
2775
+ return {
2776
+ vocab,
2777
+ terms,
2778
+ held: inline
2779
+ };
2780
+ }
2781
+ function termOf$1(value) {
2782
+ if (typeof value === "string") return { id: value };
2783
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
2784
+ const { "@id": id, "@type": kind, "@container": container, ...rest } = value;
2785
+ if (Object.keys(rest).length > 0 || id !== void 0 && typeof id !== "string" || kind !== void 0 && kind !== "@id") return void 0;
2786
+ const containers = {
2787
+ "@set": "set",
2788
+ "@list": "list",
2789
+ "@index": "index"
2790
+ };
2791
+ if (container !== void 0 && (typeof container !== "string" || !Object.hasOwn(containers, container))) return void 0;
2792
+ const link = kind === void 0 ? void 0 : container === void 0 ? "relation" : containers[container];
2793
+ return {
2794
+ ...id === void 0 ? {} : { id },
2795
+ ...link === void 0 ? {} : { link }
2796
+ };
2797
+ }
2798
+ function coerced(term, value, location) {
2799
+ const link = (item) => typeof item === "string" && !item.startsWith("_:");
2800
+ if (term?.link === "relation") return link(value) ? { relation: absolute(value, location) } : void 0;
2801
+ if ((term?.link === "set" || term?.link === "list") && Array.isArray(value) && value.every(link)) {
2802
+ const ids = value.map((item) => absolute(item, location));
2803
+ return term.link === "set" ? { set: ids } : { list: ids };
2804
+ }
2805
+ if (term?.link === "index" && typeof value === "object" && value !== null && !Array.isArray(value)) {
2806
+ const entries = Object.entries(value);
2807
+ if (entries.every(([, item]) => link(item))) return { map: Object.fromEntries(new Map(entries.map(([key, item]) => [key, absolute(item, location)]))) };
2808
+ }
2809
+ }
2810
+ function contextOf$1(type) {
2811
+ const named = OFieldIri.of(type)?.model;
2812
+ const held = named?.ref === void 0 || OFieldIri.isPinned(named.ref);
2813
+ return named !== void 0 && held && named.subpath !== void 0 && named.subpath.split("/").every(isTerm) ? Workbench.stored(type) : void 0;
2814
+ }
2815
+ function plain(term, value, location) {
2816
+ const related = relationOf(value);
2817
+ if (term?.link === void 0 || related === void 0 || related.kind !== (term.link === "index" ? "map" : term.link)) return void 0;
2818
+ const ids = related.ids.map((id) => relativeIn(id, location));
2819
+ if (related.kind === "relation") return ids[0];
2820
+ if (related.kind !== "map") return ids;
2821
+ const keys = Object.keys(value.map);
2822
+ return Object.fromEntries(new Map(keys.map((key, at) => [key, ids[at]])));
2823
+ }
2824
+ function relativeIn(id, location) {
2825
+ const to = OFieldIri.of(id)?.model;
2826
+ const from = location === void 0 ? void 0 : OFieldIri.of(location)?.model;
2827
+ if (to?.subpath === void 0 || from?.subpath === void 0 || to.source !== from.source || to.namespace !== from.namespace || to.name !== from.name || to.ref !== from.ref) return relativeTo(id, location);
2828
+ const base = from.subpath.split("/").slice(0, -1);
2829
+ const target = to.subpath.split("/");
2830
+ let common = 0;
2831
+ while (common < base.length && common < target.length - 1 && base[common] === target[common]) common++;
2832
+ const path = [...Array(base.length - common).fill(".."), ...target.slice(common)].join("/");
2833
+ return path.split("/")[0].includes(":") ? `./${path}` : path;
2834
+ }
2835
+ function parsed(text, location) {
2836
+ try {
2837
+ return JSON.parse(text);
2838
+ } catch (error) {
2839
+ throw new Error(`not JSON: ${location}`, { cause: error });
2840
+ }
2841
+ }
2842
+ function object(value, refusal) {
2843
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(refusal);
2844
+ return value;
2845
+ }
2846
+ function absolute(reference, location) {
2847
+ if (typeof reference !== "string") throw new Error(`an @id is a string: ${JSON.stringify(reference)}, in ${location}`);
2848
+ let id;
2849
+ if (/^[A-Za-z][A-Za-z\d+.-]*:/.test(reference)) id = reference.split("#")[0];
2850
+ else {
2851
+ const base = OFieldIri.of(location);
2852
+ try {
2853
+ if (base !== void 0) id = base.resolve(reference).toString();
2854
+ else {
2855
+ const url = new URL(reference, location);
2856
+ url.hash = "";
2857
+ id = url.href;
2858
+ }
2859
+ } catch (error) {
2860
+ throw new Error(`not a link: ${reference}, in ${location}`, { cause: error });
2861
+ }
2862
+ }
2863
+ if (/^file:/i.test(id) && !location.startsWith("file:")) throw new Error(`a node not read from a file names no file: ${reference}, in ${location}`);
2864
+ return pinnedTo(id, location);
2865
+ }
2866
+ function pinnedTo(id, location) {
2867
+ const at = OFieldIri.of(location)?.model;
2868
+ if (at?.ref === void 0 || !OFieldIri.isPinned(at.ref)) return id;
2869
+ const named = OFieldIri.of(id)?.model;
2870
+ if (named === void 0 || named.ref !== void 0 || named.source !== at.source || named.namespace !== at.namespace || named.name !== at.name) return id;
2871
+ return `${new OFieldIri({
2872
+ ...named,
2873
+ ref: at.ref
2874
+ })}`;
2875
+ }
2876
+ function relativeTo(id, location) {
2877
+ if (location === void 0 || !/^file:/i.test(location) || !/^file:/i.test(id)) return id;
2878
+ const from = new URL(location).pathname.split("/").slice(0, -1);
2879
+ const to = new URL(id).pathname.split("/");
2880
+ let common = 0;
2881
+ while (common < from.length && common < to.length - 1 && from[common] === to[common]) common++;
2882
+ if (common < 2) return id;
2883
+ const path = [...Array(from.length - common).fill(".."), ...to.slice(common)].join("/");
2884
+ return path.split("/")[0].includes(":") ? `./${path}` : path;
2885
+ }
2886
+ function nesting(value) {
2887
+ let deepest = 0;
2888
+ const pending = [[value, 1]];
2889
+ for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
2890
+ const [item, depth] = next;
2891
+ if (typeof item !== "object" || item === null) continue;
2892
+ deepest = Math.max(deepest, depth);
2893
+ if (deepest > JsonLd.depth) return deepest;
2894
+ for (const child of Object.values(item)) pending.push([child, depth + 1]);
2895
+ }
2896
+ return deepest;
2897
+ }
2898
+ function relationOf(value) {
2899
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
2900
+ const keys = Object.keys(value);
2901
+ if (keys.length !== 1) return void 0;
2902
+ const kind = keys[0];
2903
+ try {
2904
+ if (kind === "relation") return {
2905
+ kind,
2906
+ ids: [new Relation(value, TypedSmartObject).model.relation]
2907
+ };
2908
+ if (kind === "list") return {
2909
+ kind,
2910
+ ids: new RelationList(value, TypedSmartObject).model.list
2911
+ };
2912
+ if (kind === "set") return {
2913
+ kind,
2914
+ ids: new RelationSet(value, TypedSmartObject).model.set
2915
+ };
2916
+ if (kind === "map") return {
2917
+ kind,
2918
+ ids: Object.values(new RelationMap(value, TypedSmartObject).model.map)
2919
+ };
2920
+ } catch {}
2921
+ }
2922
+ function isLink(value) {
2923
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
2924
+ const keys = Object.keys(value);
2925
+ const id = value["@id"];
2926
+ return keys.length === 1 && keys[0] === "@id" && typeof id === "string" && !id.startsWith("_:");
2927
+ }
2928
+ function isIndexed(value) {
2929
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
2930
+ const { "@id": id, "@index": index, ...rest } = value;
2931
+ return Object.keys(rest).length === 0 && typeof id === "string" && !id.startsWith("_:") && typeof index === "string";
2932
+ }
2933
+ //#endregion
2934
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/loading/NodeInstaller.ts
2935
+ /**
2936
+ * Purpose: put what a start lacks into this host's stores, the seed holding
2937
+ * no installer of its own.
2938
+ *
2939
+ * Intention: fetches the installer its model names — Core's, as
2940
+ * {@link NodeInstaller.core} — at its latest release, as
2941
+ * {@link Releases} picks it, with git and the credentials git holds, and runs
2942
+ * it under `node` from the PATH — under Deno, Deno itself; {@link NodeKernel}
2943
+ * asks it to install and to follow descriptors. Node's API, which Deno and Bun implement too.
2944
+ */
2945
+ var NodeInstaller = class NodeInstaller extends TypedSmartObject {
2946
+ /** Core's installer, the one the seed fills the stores through. */
2947
+ static core = new NodeInstaller({
2948
+ repository: "https://github.com/metatrom-ag/Core",
2949
+ installation: "ofield://metatrom-ag/Core/habitats/node/installing/Installation",
2950
+ program: "habitats/node/installing/Installation.ts"
2951
+ });
2952
+ /**
2953
+ * Installs what the oField IRIs name into this host's stores, then follows the descriptors `followed` answers once
2954
+ * they are installed, installing what those use: the installer's latest release, cloned shallow into a temporary
2955
+ * folder removed afterwards, run under `node` from the PATH — Deno's own runtime under Deno — once with the IRIs and
2956
+ * once more with the descriptors `followed` answers, where it answers any, speaking on standard error; refused,
2957
+ * naming why, where git lists or clones nothing, the repository names no release, `node` does not start, or the
2958
+ * installer fails.
2959
+ */
2960
+ install(iris, followed) {
2961
+ const { execFileSync, spawnSync } = process.getBuiltinModule("node:child_process");
2962
+ const { mkdtempSync, rmSync, writeFileSync } = process.getBuiltinModule("node:fs");
2963
+ const { tmpdir } = process.getBuiltinModule("node:os");
2964
+ const { repository, installation, program } = this.model;
2965
+ const lacking = `the stores lack ${iris.join(", ")}`;
2966
+ const git = (args) => execFileSync("git", args, {
2967
+ encoding: "utf8",
2968
+ env: {
2969
+ ...process.env,
2970
+ GIT_TERMINAL_PROMPT: "0"
2971
+ },
2972
+ stdio: [
2973
+ "ignore",
2974
+ "pipe",
2975
+ "pipe"
2976
+ ]
2977
+ });
2978
+ let listed;
2979
+ try {
2980
+ listed = git([
2981
+ "ls-remote",
2982
+ "--tags",
2983
+ "--refs",
2984
+ repository
2985
+ ]);
2986
+ } catch (cause) {
2987
+ throw new Error(`${lacking}, and git could not list the releases of ${repository}; where GitHub refused its credentials, \`gh auth login\` gives git some`, { cause });
2988
+ }
2989
+ const tag = new Releases(listed.split("\n").flatMap((line) => /\trefs\/tags\/(.+)$/.exec(line)?.[1] ?? [])).latest;
2990
+ if (tag === void 0) throw new Error(`${lacking}, and ${repository} names no release to fill them with`);
2991
+ console.error(`${lacking}, so the installer of ${repository} at ${tag} fills them; that takes about a minute`);
2992
+ const folder = mkdtempSync(`${tmpdir()}/ofield-fill-`);
2993
+ try {
2994
+ try {
2995
+ git([
2996
+ "clone",
2997
+ "--quiet",
2998
+ "--depth",
2999
+ "1",
3000
+ "--branch",
3001
+ tag,
3002
+ repository,
3003
+ `${folder}/installer`
3004
+ ]);
3005
+ } catch (cause) {
3006
+ throw new Error(`${lacking}, and git could not clone ${repository} at ${tag}`, { cause });
3007
+ }
3008
+ const run = (model) => {
3009
+ writeFileSync(`${folder}/fill.json`, JSON.stringify({
3010
+ "@type": installation,
3011
+ ...model
3012
+ }));
3013
+ const ran = spawnSync("node", [`${folder}/installer/${program}`, `${folder}/fill.json`], { stdio: [
3014
+ "ignore",
3015
+ 2,
3016
+ 2
3017
+ ] });
3018
+ if (ran.error !== void 0) throw new Error(`${lacking}, and node could not be started to fill them: ${ran.error.message}`, { cause: ran.error });
3019
+ if (ran.status !== 0) throw new Error(`${lacking}, and the installer of ${repository} at ${tag} exits ${ran.status}, having filled them only as far as it says above`);
3020
+ };
3021
+ run({ install: iris });
3022
+ const descriptors = followed();
3023
+ if (descriptors.length > 0) run({ descriptors });
3024
+ } finally {
3025
+ rmSync(folder, {
3026
+ recursive: true,
3027
+ force: true
3028
+ });
3029
+ }
3030
+ }
3031
+ };
3032
+ //#endregion
3033
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/loading/NodeReleaseHook.ts
3034
+ /**
3035
+ * Purpose: run every SmartObject of a process on the one 0field that
3036
+ * started it.
3037
+ *
3038
+ * Intention: realizes {@link ModuleHook} over this host's disk, for the
3039
+ * 0field a SmartObject carries as released.
3040
+ */
3041
+ var NodeReleaseHook = class NodeReleaseHook extends TypedSmartObject {
3042
+ /** The first line of a released 0field. */
3043
+ static banner = "// @ts-self-types=\"./0field.d.ts\"";
3044
+ name = "0field";
3045
+ /**
3046
+ * The running 0field its model names, for a carried release a file on disk imports: a `0field.js` whose
3047
+ * first line is the {@link NodeReleaseHook.banner}, ended by LF or CRLF and after a byte order mark a checkout
3048
+ * may write. So both extend the same SmartObject and nothing starts twice. Any other file of that name is no
3049
+ * release, and passes on.
3050
+ */
3051
+ resolve(specifier, parentURL) {
3052
+ if (!/^(\.{0,2}\/|file:)/.test(specifier) || !specifier.endsWith("/0field.js")) return void 0;
3053
+ if (!parentURL?.startsWith("file:")) return void 0;
3054
+ const url = new URL(specifier, parentURL).href;
3055
+ if (url === this.model.running) return void 0;
3056
+ const release = new ReadOnlyNodeFile(ReadOnlyNodeFolder.fromUrl(url).path);
3057
+ if (!release.exists) return void 0;
3058
+ const head = new TextDecoder().decode(release.head(NodeReleaseHook.banner.length + 5));
3059
+ return /^\uFEFF?(.*?)\r?\n/.exec(head)?.[1] === NodeReleaseHook.banner ? this.model.running : void 0;
3060
+ }
3061
+ };
3062
+ //#endregion
3063
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/loading/NodeKernel.ts
3064
+ var __rewriteRelativeImportExtension$1 = function(path, preserveJsx) {
3065
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
3066
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
3067
+ });
3068
+ return path;
3069
+ };
3070
+ /**
3071
+ * Purpose: make loading work in Node.
3072
+ *
3073
+ * Intention: realizes {@link Manu} over Node's module API, which Deno
3074
+ * realizes too from 2.8, carrying its {@link ModuleHookChain} there: the
3075
+ * {@link NodeReleaseHook}, {@link NodeOFieldHook} and {@link NodeNpmHook}.
3076
+ * Its storage, which a Persistence reads, is a {@link ReadOnlyNodeStorage};
3077
+ * what a model names and no store holds, or what that uses, the
3078
+ * {@link NodeOFieldHook} asked, it fills through {@link NodeInstaller}.
3079
+ * Its model names the 0field it loads for.
3080
+ */
3081
+ var NodeKernel = class NodeKernel extends TypedSmartObject {
3082
+ static #registered = false;
3083
+ hooks = new ModuleHookChain();
3084
+ /** The export conditions this habitat resolves npm packages under. */
3085
+ conditions = ["node"];
3086
+ /** Whether this habitat loads a `file:` URL it resolves itself by its real path, every link on the way followed. */
3087
+ realPaths = true;
3088
+ /**
3089
+ * Registers the chain with `module.registerHooks`, once per process, after adding this kernel's hooks to it. A
3090
+ * request no hook answers goes to the environment's own resolution.
3091
+ */
3092
+ async start() {
3093
+ if (NodeKernel.#registered) throw new Error("Node's module hooks register once per process");
3094
+ const { registerHooks } = process.getBuiltinModule("node:module");
3095
+ if (typeof registerHooks !== "function") throw new Error("this runtime lacks module.registerHooks: Node needs 23.5, Deno 2.8");
3096
+ NodeKernel.#registered = true;
3097
+ this.addHooks();
3098
+ const hooks = this.hooks;
3099
+ registerHooks({
3100
+ resolve: (specifier, context, next) => {
3101
+ const url = hooks.resolve(specifier, context.parentURL);
3102
+ if (url !== void 0) {
3103
+ hooks.observe(url);
3104
+ return {
3105
+ url,
3106
+ shortCircuit: true
3107
+ };
3108
+ }
3109
+ const resolved = next(specifier, context);
3110
+ hooks.observe(resolved.url);
3111
+ return resolved;
3112
+ },
3113
+ load: (url, context, next) => {
3114
+ const module = hooks.load(url);
3115
+ return module === void 0 ? next(url, context) : {
3116
+ ...module,
3117
+ shortCircuit: true
3118
+ };
3119
+ }
3120
+ });
3121
+ }
3122
+ /**
3123
+ * Adds this kernel's hooks to its chain, the oField hook as its {@link NodeKernel.realPaths} say, the npm hook under
3124
+ * its {@link NodeKernel.conditions}.
3125
+ */
3126
+ addHooks() {
3127
+ this.hooks.use(new NodeReleaseHook({ running: this.model.oField }));
3128
+ this.hooks.use(new NodeOFieldHook({ realPaths: this.realPaths }));
3129
+ this.hooks.use(new NodeNpmHook({ conditions: this.conditions }));
3130
+ }
3131
+ /**
3132
+ * The one program a process is started with: the URL of the file the runtime was started with, and the words after it
3133
+ * as the runtime received them; refused where it was started with no file.
3134
+ */
3135
+ get started() {
3136
+ this.#started ??= new Program({
3137
+ address: this.main,
3138
+ words: process.argv.slice(2)
3139
+ });
3140
+ return [this.#started];
3141
+ }
3142
+ #started;
3143
+ /** Refused: a process shows a SmartObject nowhere. */
3144
+ attach(_smartObject, where) {
3145
+ throw new Error(`this habitat shows no SmartObject, at ${where} or elsewhere`);
3146
+ }
3147
+ /** The URL of the file the runtime was started with. */
3148
+ get main() {
3149
+ const file = process.argv[1];
3150
+ if (file === void 0) throw new Error("the runtime was started with no file");
3151
+ return process.getBuiltinModule("node:url").pathToFileURL(file).href;
3152
+ }
3153
+ anchor(place) {
3154
+ return place === void 0 ? this.main : `${ReadOnlyNodeFolder.urlOf(ReadOnlyNodeFolder.native(place))}/.started`;
3155
+ }
3156
+ storage(place) {
3157
+ return new ReadOnlyNodeStorage({ main: this.anchor(place) });
3158
+ }
3159
+ async classOf(type, place) {
3160
+ const url = this.hooks.moduleOf(type, this.anchor(place));
3161
+ if ([...new URL(url).pathname.matchAll(/\/dependencies\/[^/]+\/[^/]+\/(?=(.*))/g)].some(([, ref]) => OFieldIri.isDataRef(ref))) throw new Error(`no class is loaded from a data ref: ${type}`);
3162
+ return (await import(__rewriteRelativeImportExtension$1(url))).default;
3163
+ }
3164
+ /**
3165
+ * Fills, through {@link NodeInstaller.core}, every release the model at the address names by an oField IRI
3166
+ * and no store or working tree holds — its `@context`, its `@type` and each `{"@id"}` it references — and every
3167
+ * release those use, as the `uses` and `realizes` of the descriptors the stores hold say, all the way down; a plain
3168
+ * string is data and fills nothing, and its own `@id`, an npm package, a branch and a data ref — what no installer
3169
+ * installs, a release being what it installs — are left to restoring. Where the address is a module's `file:` URL,
3170
+ * it fills, the same way, what the descriptor beside that module uses and realizes, a relative path read within the
3171
+ * folder of the nearest `workbench.jsonld` above it, or its own folder where none is. Nothing
3172
+ * where each is held, or where no model or descriptor is there; refused, naming the file, where a descriptor it reads
3173
+ * is no JSON object.
3174
+ */
3175
+ async fill(address) {
3176
+ const module = address.startsWith("file:") && descriptorBeside(address) !== void 0 ? ReadOnlyNodeFolder.fromUrl(address) : void 0;
3177
+ let node;
3178
+ if (module === void 0) {
3179
+ const storage = this.storage();
3180
+ const location = storage.location(address);
3181
+ if (!await storage.has(location)) return;
3182
+ try {
3183
+ node = JSON.parse(await storage.get(location));
3184
+ } catch {
3185
+ return;
3186
+ }
3187
+ }
3188
+ const oField = new NodeOFieldHook({});
3189
+ const find = (iri) => {
3190
+ try {
3191
+ return oField.find(iri, this.anchor());
3192
+ } catch {
3193
+ return null;
3194
+ }
3195
+ };
3196
+ const lacking = /* @__PURE__ */ new Set();
3197
+ const named = [];
3198
+ const take = (value) => {
3199
+ const iri = typeof value === "string" ? OFieldIri.of(value) : void 0;
3200
+ const ref = iri?.model.ref;
3201
+ if (iri !== void 0 && iri.model.namespace !== "npm" && (ref === void 0 || ref === "latest" || OFieldIri.isPinned(ref))) named.push(iri);
3202
+ };
3203
+ const reference = (value, depth) => {
3204
+ if (depth > JsonLd.depth) return;
3205
+ if (Array.isArray(value)) value.forEach((each) => reference(each, depth + 1));
3206
+ else if (typeof value === "object" && value !== null) {
3207
+ const { "@id": id, ...rest } = value;
3208
+ take(id);
3209
+ Object.values(rest).forEach((each) => reference(each, depth + 1));
3210
+ }
3211
+ };
3212
+ if (typeof node === "object" && node !== null && !Array.isArray(node)) {
3213
+ const { "@id": _id, "@context": context, "@type": type, ...rest } = node;
3214
+ [context, type].flat().forEach(take);
3215
+ reference(rest, 0);
3216
+ }
3217
+ const read = /* @__PURE__ */ new Set();
3218
+ const follow = (descriptor, tree) => {
3219
+ if (read.has(descriptor.path) || !descriptor.exists) return;
3220
+ read.add(descriptor.path);
3221
+ const { uses, realizes } = descriptor.readJsonObject();
3222
+ for (const related of [uses, realizes].flatMap((list) => Array.isArray(list) ? list : [])) {
3223
+ if (typeof related !== "string") continue;
3224
+ const iri = OFieldIri.of(related);
3225
+ if (iri === void 0) follow(tree.file(within(tree, descriptor, related)), tree);
3226
+ else reach(iri);
3227
+ }
3228
+ };
3229
+ const reach = (iri) => {
3230
+ if (iri.model.namespace === "npm") return;
3231
+ const tree = find(iri.toString());
3232
+ if (tree === null) return;
3233
+ if (tree === void 0) {
3234
+ const { subpath: _subpath, ...release } = iri.model;
3235
+ lacking.add(new OFieldIri(release).toString());
3236
+ } else follow(tree.file(descriptorOf(iri)), tree);
3237
+ };
3238
+ named.forEach(reach);
3239
+ const beside = module?.parent?.file(descriptorBeside(module.name));
3240
+ if (module?.parent !== void 0 && beside !== void 0) {
3241
+ const folder = module.parent;
3242
+ follow(beside, [folder, ...folder.ancestors].find((entry) => isFolder(entry) && entry.file("workbench.jsonld").exists) ?? folder);
3243
+ }
3244
+ if (lacking.size === 0) return;
3245
+ NodeInstaller.core.install([...lacking], () => [...beside?.exists ? [beside.path] : [], ...named.flatMap((iri) => {
3246
+ const tree = find(iri.toString());
3247
+ const descriptor = tree ? tree.file(descriptorOf(iri)) : void 0;
3248
+ return descriptor?.exists ? [descriptor.path] : [];
3249
+ })]);
3250
+ }
3251
+ };
3252
+ function within(tree, descriptor, related) {
3253
+ const refused = (cause) => new Error(`${descriptor.path} names ${related}, which is no path within ${tree.path}`, { cause });
3254
+ let path;
3255
+ try {
3256
+ path = ReadOnlyNodeFolder.fromUrl(new URL(related, ReadOnlyNodeFolder.urlOf(descriptor)).href).path;
3257
+ } catch (cause) {
3258
+ throw refused(cause);
3259
+ }
3260
+ if (!path.startsWith(`${tree.path}/`)) throw refused();
3261
+ return path.slice(tree.path.length + 1);
3262
+ }
3263
+ //#endregion
3264
+ //#region dependencies/metatrom-ag/Manu/main/habitats/bun/BunKernel.ts
3265
+ /**
3266
+ * Purpose: make loading work in Bun.
3267
+ *
3268
+ * Intention: realizes {@link Manu} as the {@link NodeKernel}, its
3269
+ * storage, words and hooks Node's, its npm conditions Bun's — but carries
3270
+ * its {@link ModuleHookChain} in Bun's runtime plugins, since Bun has no
3271
+ * `module.registerHooks`.
3272
+ */
3273
+ var BunKernel = class BunKernel extends NodeKernel {
3274
+ static #registered = false;
3275
+ static #running = "running/0field.js";
3276
+ static #source = /\.(m?[jt]s|[jt]sx)$/;
3277
+ #namespace = "0field";
3278
+ #schemes = /* @__PURE__ */ new Set();
3279
+ hooks;
3280
+ conditions = ["bun", "node"];
3281
+ constructor(model) {
3282
+ super(model);
3283
+ const kernel = this;
3284
+ this.hooks = new class extends ModuleHookChain {
3285
+ use(hook) {
3286
+ super.use(hook);
3287
+ for (const scheme of hook.schemes ?? []) kernel.#listen(scheme);
3288
+ }
3289
+ }();
3290
+ }
3291
+ /**
3292
+ * Carries the chain in Bun's runtime plugins, once per process, after adding the hooks the NodeKernel adds. Bun
3293
+ * reads `ofield:…` as the namespace `0field`, and runs a plugin only for namespaces it was told of — so each scheme a
3294
+ * hook names gets a plugin of its own, also when the hook arrives after the start. A hook's `file:` URL is loaded by
3295
+ * Bun itself; any other URL lives in this kernel's namespace, where only the hooks load it. Bun's `onLoad` cannot
3296
+ * pass a request on, so a hook that only observes is asked through {@link ModuleHookChain.observe}. A stored npm
3297
+ * package's bare imports reach no runtime plugin, so
3298
+ * its files are loaded rewritten, each specifier the hooks resolve replaced by what they resolve it to. Bun keeps a
3299
+ * file's imports as resolved in its transpiler cache, across processes, so a carried release resolves to a name that
3300
+ * is the same in each of them, and loading that name re-exports the release the process runs. Bun keys that cache by
3301
+ * a file's text, so each source file is loaded with where the hooks resolve its imports written below it: a process
3302
+ * whose stores or repository resolve them elsewhere reads the file afresh.
3303
+ */
3304
+ async start() {
3305
+ if (BunKernel.#registered) throw new Error("Bun's runtime plugin registers once per process");
3306
+ this.addHooks();
3307
+ BunKernel.#registered = true;
3308
+ Bun.plugin({
3309
+ name: this.#namespace,
3310
+ setup: (build) => {
3311
+ build.onResolve({ filter: /.*/ }, ({ path, importer }) => this.#uncached(this.#resolve(path, importer)));
3312
+ build.onLoad({
3313
+ filter: /.*/,
3314
+ namespace: this.#namespace
3315
+ }, ({ path }) => {
3316
+ if (path === BunKernel.#running) return {
3317
+ contents: `export * from ${JSON.stringify(this.model.oField)}`,
3318
+ loader: "js"
3319
+ };
3320
+ const module = this.hooks.load(path);
3321
+ if (module === void 0) throw new Error(`no module hook loads ${path}`);
3322
+ return {
3323
+ contents: module.source,
3324
+ loader: module.format === "json" ? "json" : "js"
3325
+ };
3326
+ });
3327
+ const stored = NodeNpmHook.stored.source.replaceAll("\\/", "[\\\\/]");
3328
+ build.onLoad({ filter: new RegExp(`${stored}.*\\.m?js$`) }, ({ path }) => this.#rewrite(path));
3329
+ build.onLoad({ filter: BunKernel.#source }, ({ path }) => this.#keyed(path));
3330
+ }
3331
+ });
3332
+ for (const scheme of this.#schemes) this.#register(scheme);
3333
+ }
3334
+ get main() {
3335
+ return Bun.pathToFileURL(Bun.main).href;
3336
+ }
3337
+ async #rewrite(path) {
3338
+ const loaded = this.hooks.load(Bun.pathToFileURL(path).href);
3339
+ let refused;
3340
+ const built = await Bun.build({
3341
+ entrypoints: [path],
3342
+ target: "bun",
3343
+ format: "esm",
3344
+ plugins: [{
3345
+ name: `${this.#namespace}:rewrite`,
3346
+ setup: (build) => {
3347
+ if (loaded !== void 0) build.onLoad({ filter: /.*/ }, ({ path: built }) => built === path ? {
3348
+ contents: loaded.source,
3349
+ loader: "js"
3350
+ } : void 0);
3351
+ build.onResolve({ filter: /.*/ }, ({ path: specifier, importer, kind }) => {
3352
+ if (kind === "entry-point-build") return void 0;
3353
+ try {
3354
+ return {
3355
+ path: this.#resolve(specifier, importer)?.path ?? specifier,
3356
+ external: true
3357
+ };
3358
+ } catch (error) {
3359
+ refused ??= error;
3360
+ return {
3361
+ path: specifier,
3362
+ external: true
3363
+ };
3364
+ }
3365
+ });
3366
+ }
3367
+ }]
3368
+ });
3369
+ if (refused !== void 0) throw refused;
3370
+ if (!built.success) throw new AggregateError(built.logs, `${path} does not build`);
3371
+ return {
3372
+ contents: await built.outputs[0].text(),
3373
+ loader: "js"
3374
+ };
3375
+ }
3376
+ async #keyed(path) {
3377
+ const source = await Bun.file(path).text();
3378
+ const extension = path.slice(path.lastIndexOf(".") + 1);
3379
+ const loader = extension === "tsx" || extension === "jsx" ? extension : extension.endsWith("ts") ? "ts" : "js";
3380
+ const importer = BunKernel.#url(path);
3381
+ const resolved = new Bun.Transpiler({ loader }).scanImports(source).flatMap(({ path: specifier }) => {
3382
+ try {
3383
+ const url = this.hooks.resolve(BunKernel.#url(specifier), importer);
3384
+ return url === void 0 ? [] : [`${specifier} ${url}`];
3385
+ } catch {
3386
+ return [];
3387
+ }
3388
+ });
3389
+ return {
3390
+ contents: resolved.length === 0 ? source : `${source}\n// resolved: ${resolved.join(", ")}\n`,
3391
+ loader
3392
+ };
3393
+ }
3394
+ #listen(scheme) {
3395
+ if (this.#schemes.has(scheme)) return;
3396
+ this.#schemes.add(scheme);
3397
+ if (BunKernel.#registered) this.#register(scheme);
3398
+ }
3399
+ #register(scheme) {
3400
+ Bun.plugin({
3401
+ name: `${this.#namespace}:${scheme}`,
3402
+ setup: (build) => {
3403
+ build.onResolve({
3404
+ filter: /.*/,
3405
+ namespace: scheme
3406
+ }, ({ path, importer }) => this.#uncached(this.#resolve(`${scheme}:${path}`, importer)));
3407
+ }
3408
+ });
3409
+ }
3410
+ #uncached(resolved) {
3411
+ if (resolved === void 0 || resolved.namespace !== void 0 || resolved.path !== Bun.fileURLToPath(this.model.oField)) return resolved;
3412
+ return {
3413
+ path: BunKernel.#running,
3414
+ namespace: this.#namespace
3415
+ };
3416
+ }
3417
+ #resolve(specifier, importer) {
3418
+ const parentURL = !importer ? void 0 : BunKernel.#url(importer);
3419
+ const requested = BunKernel.#url(specifier);
3420
+ const url = this.hooks.resolve(requested, parentURL);
3421
+ if (url !== void 0) {
3422
+ this.#observe(url);
3423
+ return url.startsWith("file:") ? { path: Bun.fileURLToPath(url) } : {
3424
+ path: url,
3425
+ namespace: this.#namespace
3426
+ };
3427
+ }
3428
+ const native = BunKernel.#native(requested, parentURL);
3429
+ if (native !== void 0) this.#observe(native);
3430
+ }
3431
+ static #url(path) {
3432
+ return process.getBuiltinModule("node:path").isAbsolute(path) ? ReadOnlyNodeFolder.urlOf(ReadOnlyNodeFolder.native(path)) : path;
3433
+ }
3434
+ #observe(url) {
3435
+ queueMicrotask(() => this.hooks.observe(url));
3436
+ }
3437
+ static #native(specifier, parentURL) {
3438
+ if (specifier.startsWith("file:")) return specifier;
3439
+ if (!/^\.{0,2}\//.test(specifier) || !parentURL?.startsWith("file:")) return void 0;
3440
+ return new URL(specifier, parentURL).href;
3441
+ }
3442
+ };
3443
+ //#endregion
3444
+ //#region dependencies/metatrom-ag/Manu/main/habitats/deno/DenoKernel.ts
3445
+ /**
3446
+ * Purpose: load SmartObjects in the Deno habitat.
3447
+ *
3448
+ * Intention: realizes {@link Manu} by extending {@link NodeKernel},
3449
+ * since Deno supports Node's module API from 2.8. It differs in the
3450
+ * `deno` export condition, in `Deno.mainModule` as the starting file,
3451
+ * because a compiled binary does not name it in `process.argv`, and in
3452
+ * loading a file by the path it is named by, links kept.
3453
+ */
3454
+ var DenoKernel = class extends NodeKernel {
3455
+ conditions = ["deno", "node"];
3456
+ realPaths = false;
3457
+ get main() {
3458
+ return Deno.mainModule;
3459
+ }
3460
+ };
3461
+ //#endregion
3462
+ //#region dependencies/metatrom-ag/Manu/main/common/persistence/Persistence.ts
3463
+ /**
3464
+ * Purpose: keep SmartObjects beyond the process that created them.
3465
+ *
3466
+ * Intention: has the shape of the {@link Restoring} every relation asks
3467
+ * for, and uses a {@link Host}: the {@link Storage} of the habitat it
3468
+ * runs in, of the started file's place or of a place a program names; the
3469
+ * class a type IRI names there; and the anchor it reads that place from,
3470
+ * which it hands the habitat's {@link PersistenceWriter}. It reads and
3471
+ * writes a stored text as {@link JsonLd}, and speaks to {@link Relation} and to each SmartObject's
3472
+ * `Lifecycle`; a {@link Workbench} it puts as the `workbench.jsonld` of the root its `@id` names.
3473
+ */
3474
+ var Persistence = class Persistence extends TypedSmartObject {
3475
+ static #writer;
3476
+ static #realmTypes = /* @__PURE__ */ new WeakMap();
3477
+ /** Registers the writer that {@link Persistence.put} delegates I/O to; called by the habitat when it loads. */
3478
+ static useWriter(writer) {
3479
+ Persistence.#writer = writer;
3480
+ }
3481
+ /**
3482
+ * The type IRI a SmartObject was last restored from a stored text or put as, through any persistence of the realm;
3483
+ * `undefined` for one made in memory or realized by its host.
3484
+ */
3485
+ static typeOf(smartObject) {
3486
+ return Persistence.#realmTypes.get(smartObject);
3487
+ }
3488
+ #host;
3489
+ #place;
3490
+ #format = new JsonLd();
3491
+ #instances = /* @__PURE__ */ new Map();
3492
+ #types = /* @__PURE__ */ new WeakMap();
3493
+ #places = /* @__PURE__ */ new WeakMap();
3494
+ #realizing = /* @__PURE__ */ new WeakSet();
3495
+ /** Over a host that may still be starting, each call waiting for it; over the storage of a place where one is named. */
3496
+ constructor(host, place) {
3497
+ super();
3498
+ this.#host = host;
3499
+ this.#place = place;
3500
+ }
3501
+ /**
3502
+ * A persistence over the storage of another place — a folder, as a path — for a program that keeps what belongs to
3503
+ * a repository other than its own; its SmartObjects are its own, apart from this one's.
3504
+ */
3505
+ at(place) {
3506
+ return new Persistence(this.#host, place);
3507
+ }
3508
+ /**
3509
+ * The SmartObject an address names, created once per id, whether reached by where it is stored or by the `@id` it
3510
+ * holds; refused, naming it, where nothing there restores — and, where a vocabulary is named, where its type is no
3511
+ * term of it, before its class is loaded, so reading data runs no code the reader did not choose.
3512
+ *
3513
+ * Each one created is named to {@link Relation} as made here, so its relations restore through this persistence
3514
+ * too, and its `restored()` is awaited before the restore that created it resolves — anyone reaching it meanwhile,
3515
+ * a cycle or another restore, gets it as made — a failure failing that restore, naming its id. What the storage
3516
+ * realizes rather than stores — a repository — is handed out the same way, one instance for every location naming
3517
+ * it, and is of no vocabulary.
3518
+ */
3519
+ async restore(address, vocabulary) {
3520
+ const host = await this.#host;
3521
+ const storage = host.storage(this.#place);
3522
+ const location = located(storage, address);
3523
+ const restored = await this.#once(location, async () => {
3524
+ if (storage.realizes(location)) {
3525
+ if (vocabulary !== void 0) throw new Error(`${location} is what this host realizes, no term of ${vocabulary}`);
3526
+ return this.#realized(storage.realized(location), location);
3527
+ }
3528
+ const { type, model } = await this.#read(storage, location);
3529
+ termOf(type, vocabulary, location);
3530
+ const id = model["@id"];
3531
+ if (id !== location && storage.realizes(storage.location(id))) throw new Error(`${location} claims the @id ${id}, which this host realizes`);
3532
+ return id === location ? this.#created(host, type, model, location) : this.#once(id, () => this.#created(host, type, model, location));
3533
+ });
3534
+ if (vocabulary !== void 0 && this.#realizing.has(restored)) throw new Error(`${location} is a ${restored.constructor.name} this host realizes, no term of ${vocabulary}`);
3535
+ termOf(this.#types.get(restored) ?? "", vocabulary, location);
3536
+ return restored;
3537
+ }
3538
+ /**
3539
+ * Reads the text stored at an address again into the SmartObject held here for it, through its `update`, so whoever
3540
+ * observes it hears the keys a human changed there, and none where a put of its own reads back; nothing where
3541
+ * nothing here was restored from or put at that address. Refused, naming it, where the text there now holds another
3542
+ * type than the SmartObject was restored as, or refuses as a restore refuses.
3543
+ */
3544
+ async reread(address) {
3545
+ const storage = (await this.#host).storage(this.#place);
3546
+ const location = located(storage, address);
3547
+ const held = await this.#instances.get(location)?.catch(() => void 0);
3548
+ if (held === void 0 || this.#realizing.has(held)) return;
3549
+ const { type, model } = await this.#read(storage, location, true);
3550
+ if (type !== this.#types.get(held)) throw new Error(`${location} now holds a ${type}, where a ${this.#types.get(held)} was restored`);
3551
+ held.update(model);
3552
+ }
3553
+ async #read(storage, location, afresh = false) {
3554
+ return this.#format.read(await storage.get(location, afresh), location, contextOf(storage));
3555
+ }
3556
+ #realized(realized, location) {
3557
+ const id = realized.model["@id"];
3558
+ if (typeof id !== "string" || id === "") throw new Error(`a ${realized.constructor.name} realized at ${location} names no @id`);
3559
+ const held = () => {
3560
+ Relation.made(realized, this);
3561
+ this.#realizing.add(realized);
3562
+ this.#places.set(realized, /* @__PURE__ */ new Set([location, id]));
3563
+ return Promise.resolve(realized);
3564
+ };
3565
+ return id === location ? held() : this.#once(id, held);
3566
+ }
3567
+ /**
3568
+ * The type IRI of the node stored at an address, read through its `@context` as {@link Persistence.restore} reads
3569
+ * it, without loading its class; none for what the storage realizes; refused, as a restore is, where nothing there
3570
+ * is stored.
3571
+ */
3572
+ async typeAt(address) {
3573
+ const storage = (await this.#host).storage(this.#place);
3574
+ const location = located(storage, address);
3575
+ if (storage.realizes(location)) return void 0;
3576
+ return (await this.#read(storage, location)).type;
3577
+ }
3578
+ /** Whether anything is stored at an address — nothing where the place it names is not on this host; refused where it names no place. */
3579
+ async has(address) {
3580
+ const storage = (await this.#host).storage(this.#place);
3581
+ const location = located(storage, address);
3582
+ return await storage.has(location) || storage.realizes(location);
3583
+ }
3584
+ /**
3585
+ * Stores SmartObjects at their `@id`s in one put, with every SmartObject held here that a relation of theirs names
3586
+ * and the storage lacks — so SmartObjects new together, a cycle among them, are stored together. A SmartObject
3587
+ * given with its type is put as that type; one alone, as it was restored or put before. It replaces only what this
3588
+ * persistence read or wrote there. Refused, nothing written, where one names no `@id` of its own location or no
3589
+ * type, would not restore as it is put, would take a place this persistence did not read or write, relates to a
3590
+ * place written here that holds nothing and nothing held, or is — or claims the `@id` of — what the storage
3591
+ * realizes. It resolves once the writer has stored them, and rejects as the writer rejects.
3592
+ */
3593
+ async put(...given) {
3594
+ if (Persistence.#writer === void 0) throw new Error("no writer registered");
3595
+ const host = await this.#host;
3596
+ const storage = host.storage(this.#place);
3597
+ const writable = Persistence.#writer.storageFor(host.anchor(this.#place));
3598
+ const putting = /* @__PURE__ */ new Map();
3599
+ for (const item of given) {
3600
+ const [object, type] = Array.isArray(item) ? item : [item, void 0];
3601
+ putting.set(await this.#placed(storage, object), [object, type]);
3602
+ }
3603
+ const written = /* @__PURE__ */ new Map();
3604
+ const pending = [...putting];
3605
+ for (let next = pending.shift(); next !== void 0; next = pending.shift()) {
3606
+ const [location, [object, named]] = next;
3607
+ if (written.has(location)) continue;
3608
+ const model = object.model;
3609
+ const id = model["@id"];
3610
+ const type = named ?? this.#types.get(object);
3611
+ if (type === void 0) throw new Error(`a ${object.constructor.name} is put with its type the first time: ${id}`);
3612
+ const text = this.#format.write(model, type, location, await this.#format.dictionary(model, type, location, contextOf(storage)));
3613
+ await this.#readsBack(storage, text, location, type, model);
3614
+ written.set(location, {
3615
+ smartObject: object,
3616
+ type,
3617
+ text
3618
+ });
3619
+ for (const related of this.#format.relations(model)) {
3620
+ const at = this.#writableAt(storage, writable, related);
3621
+ if (at === void 0 || written.has(at) || putting.has(at) || await storage.has(at) || storage.realizes(at)) continue;
3622
+ const held = await this.#instances.get(at)?.catch(() => void 0);
3623
+ if (held === void 0) throw new Error(`${id} relates to ${related}, which is neither stored nor held`);
3624
+ pending.push([await this.#placed(storage, held), [held, void 0]]);
3625
+ }
3626
+ }
3627
+ await writable.put(new Map([...written].map(([location, { text }]) => [location, text])));
3628
+ for (const [location, { smartObject: object, type }] of written) this.#hold(object, type, location);
3629
+ }
3630
+ async #placed(storage, object) {
3631
+ const id = object.model["@id"];
3632
+ if (typeof id !== "string" || id === "") throw new Error(`a SmartObject is stored at its @id, and this ${object.constructor.name} names none`);
3633
+ if (this.#realizing.has(object)) throw new Error(`${id} is a ${object.constructor.name} this host realizes, so it is never put`);
3634
+ const root = located(storage, id);
3635
+ if (storage.realizes(root)) throw new Error(`${id} names what this host realizes, so nothing is put there`);
3636
+ const location = object instanceof Workbench ? storage.location(Workbench.stored(id)) : root;
3637
+ const known = this.#places.get(object);
3638
+ if (known?.has(location)) return location;
3639
+ if (known !== void 0) throw new Error(`${id} was read from ${[...known][0]}, so it is put there, not at ${location}`);
3640
+ if (this.#instances.has(location) || this.#instances.has(id)) throw new Error(`${id} names a SmartObject held here already, so another is not put there`);
3641
+ if (await storage.has(location)) throw new Error(`${location} holds what this persistence did not read or write, so a put does not replace it`);
3642
+ return location;
3643
+ }
3644
+ async #readsBack(storage, text, location, type, model) {
3645
+ const refused = (cause) => new Error(`${model["@id"]} would not restore as it is put`, cause === void 0 ? void 0 : { cause });
3646
+ let read;
3647
+ try {
3648
+ read = await this.#format.read(text, location, contextOf(storage));
3649
+ } catch (error) {
3650
+ throw refused(error);
3651
+ }
3652
+ if (read.type !== type || !same(read.model, model)) throw refused();
3653
+ }
3654
+ #hold(object, type, location) {
3655
+ const id = object.model["@id"];
3656
+ Relation.made(object, this);
3657
+ this.#types.set(object, type);
3658
+ Persistence.#realmTypes.set(object, type);
3659
+ this.#places.set(object, /* @__PURE__ */ new Set([
3660
+ ...this.#places.get(object) ?? [],
3661
+ location,
3662
+ id
3663
+ ]));
3664
+ this.#instances.set(location, Promise.resolve(object));
3665
+ this.#instances.set(id, Promise.resolve(object));
3666
+ }
3667
+ /** Every SmartObject stored below an address, created as it is reached, each once; refused as {@link Persistence.restore} refuses. */
3668
+ async *all(address, vocabulary) {
3669
+ const storage = (await this.#host).storage(this.#place);
3670
+ OFieldIri.refuseRetired(address);
3671
+ for (const location of await storage.list(address)) yield await this.restore(location, vocabulary);
3672
+ }
3673
+ #writableAt(storage, writable, related) {
3674
+ let location;
3675
+ try {
3676
+ location = storage.location(related);
3677
+ } catch {
3678
+ return;
3679
+ }
3680
+ return writable.writes(location) ? location : void 0;
3681
+ }
3682
+ #once(key, create) {
3683
+ const known = this.#instances.get(key);
3684
+ if (known !== void 0) return known;
3685
+ const created = create();
3686
+ this.#instances.set(key, created);
3687
+ created.catch(() => this.#instances.delete(key));
3688
+ return created;
3689
+ }
3690
+ async #created(host, type, model, location) {
3691
+ const id = model["@id"];
3692
+ let created;
3693
+ try {
3694
+ created = await host.classOf(type, this.#place);
3695
+ } catch (error) {
3696
+ throw new Error(`no module for the type ${type}, of ${id}`, { cause: error });
3697
+ }
3698
+ if (typeof created !== "function" || !(created.prototype instanceof TypedSmartObject)) throw new Error(`${type}.ts exports no SmartObject by default, for ${id}`);
3699
+ let restored;
3700
+ try {
3701
+ restored = new created(model);
3702
+ } catch (error) {
3703
+ throw new Error(`${type} refuses the model of ${id}`, { cause: error });
3704
+ }
3705
+ this.#hold(restored, type, location);
3706
+ try {
3707
+ await restored.restored();
3708
+ } catch (error) {
3709
+ throw new Error(`${id} fails to finish being restored`, { cause: error });
3710
+ }
3711
+ return restored;
3712
+ }
3713
+ };
3714
+ function same(a, b) {
3715
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, at) => same(item, b[at]));
3716
+ if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) return Object.is(a, b);
3717
+ const keys = Object.keys(a);
3718
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && same(a[key], b[key]));
3719
+ }
3720
+ function located(storage, address) {
3721
+ OFieldIri.refuseRetired(address);
3722
+ return storage.location(address);
3723
+ }
3724
+ function contextOf(storage) {
3725
+ return async (address) => storage.get(storage.location(address));
3726
+ }
3727
+ function termOf(type, vocabulary, location) {
3728
+ if (vocabulary === void 0) return;
3729
+ const unpinned = OFieldIri.unpinned(type);
3730
+ if (unpinned.startsWith(vocabulary) && unpinned.slice(vocabulary.length).split("/").every(isTerm)) return;
3731
+ throw new Error(`${location} names the type ${type}, no term of ${vocabulary}, so its class is not loaded`);
3732
+ }
3733
+ /**
3734
+ * A {@link View} typed with its object's model keys as its own fields, as `SmartObject` is with its own model's, the
3735
+ * view's own members left out of them as they win at runtime; a view generic over its object extends `View.Class`.
3736
+ */
3737
+ const TypedView = class View extends TypedSmartObject {
3738
+ #shown;
3739
+ static {
3740
+ const above = Object.getPrototypeOf(View.prototype);
3741
+ Object.setPrototypeOf(View.prototype, new Proxy(Object.create(above), {
3742
+ get: (below, key, receiver) => View.#forwards(below, key, receiver) ? receiver.#shown[key] : Reflect.get(below, key, receiver),
3743
+ set: (below, key, value, receiver) => {
3744
+ if (View.#awaits(below, key, receiver)) throw new Error(`a ${receiver.constructor.name} shows no SmartObject yet, so its ${String(key)} reaches none`);
3745
+ if (!View.#forwards(below, key, receiver)) return Reflect.set(below, key, value, receiver);
3746
+ receiver.#shown[key] = value;
3747
+ return true;
3748
+ }
3749
+ }));
3750
+ }
3751
+ /** The link to the SmartObject it shows, where its model holds one; it restores through whatever restored the view. */
3752
+ get object() {
3753
+ return this.model.object === void 0 ? void 0 : new Relation(this.model.object, this.type, this);
3754
+ }
3755
+ /** The SmartObject it shows, in memory; none before it shows one. */
3756
+ get smartObject() {
3757
+ return this.#shown;
3758
+ }
3759
+ /**
3760
+ * Shows `object`, linking to it where its model names an `@id`; one naming none is held in memory alone, and no link
3761
+ * is kept. From now on it hears each change to `object`, and no more to the one it showed before.
3762
+ */
3763
+ show(object) {
3764
+ const id = object.model["@id"];
3765
+ const { object: _, ...model } = this.model;
3766
+ if (this.#shown !== void 0) TypedSmartObject.unobserve(this.#shown, this);
3767
+ this.#shown = object;
3768
+ TypedSmartObject.observe(object, this);
3769
+ this.update(Relation.isId(id) ? {
3770
+ ...model,
3771
+ object: { relation: id }
3772
+ } : model);
3773
+ }
3774
+ /** Restores the SmartObject it links to before the restore resolves, so a passed-through method calls it at once, and hears its changes; refused where it is of another class than {@link View.type}. */
3775
+ async restored() {
3776
+ this.#shown = await this.object?.get();
3777
+ if (this.#shown !== void 0) TypedSmartObject.observe(this.#shown, this);
3778
+ }
3779
+ /** Does nothing, until a view overrides it; called at once with the keys of the shown object's model that changed. */
3780
+ changed(keys) {}
3781
+ static #awaits(below, key, receiver) {
3782
+ if (typeof key !== "string" || key.startsWith("@") || key in below || !(#shown in receiver) || receiver.#shown !== void 0) return false;
3783
+ const own = receiver.model;
3784
+ return !(typeof own === "object" && own !== null && !Array.isArray(own) && Object.hasOwn(own, key));
3785
+ }
3786
+ static #forwards(below, key, receiver) {
3787
+ if (typeof key !== "string" || key.startsWith("@") || key in below || !(#shown in receiver) || receiver.#shown === void 0) return false;
3788
+ const own = receiver.model;
3789
+ const shown = receiver.#shown.model;
3790
+ const holds = (model) => typeof model === "object" && model !== null && !Array.isArray(model) && Object.hasOwn(model, key);
3791
+ return !holds(own) && holds(shown);
3792
+ }
3793
+ /** The description of the object a view's description shows, the first type argument its `extends` passes; none where it passes no SmartObject. */
3794
+ static async shownBy(view) {
3795
+ const passed = view.extends?.typeArguments;
3796
+ if (passed === void 0) return void 0;
3797
+ const type = view.constructor;
3798
+ if ("list" in passed) return passed.list.length === 0 ? void 0 : new RelationList(passed, type, view).at(0);
3799
+ const first = passed[0];
3800
+ return typeof first === "object" && "relation" in first ? new Relation(first, type, view).get() : void 0;
3801
+ }
3802
+ /** The method a view's description offers under a `name`: its own, or the shown object's it passes through; none where it offers none. */
3803
+ static async offered(view, name) {
3804
+ const member = view.members.find((each) => each.name === name);
3805
+ if (member?.kind === "method") return member;
3806
+ return (await View.shownBy(view))?.methodOf(name);
3807
+ }
3808
+ /**
3809
+ * A function that calls the method `name` of whichever SmartObject is shown when the function is called, with that
3810
+ * object as `this`. A member can declare it before anything is shown: `install = this.pass('install')`. Refused,
3811
+ * naming the view's class and `name`, while nothing is shown.
3812
+ */
3813
+ pass(name) {
3814
+ return ((...args) => {
3815
+ const shown = this.#shown;
3816
+ if (shown === void 0) throw new Error(`a ${this.constructor.name} shows no SmartObject yet, so its ${String(name)} reaches none`);
3817
+ return shown[name].apply(shown, args);
3818
+ });
3819
+ }
3820
+ };
3821
+ //#endregion
3822
+ //#region dependencies/metatrom-ag/Manu/main/common/0field/json/StringMap.ts
3823
+ /**
3824
+ * Purpose: keep a JSON file of names mapped to strings, and answer by name.
3825
+ *
3826
+ * Intention: a {@link JsonObject}.
3827
+ */
3828
+ var StringMap = class extends JsonObject {
3829
+ /** Reads a file, or takes the names given; refused, naming where it came from, where a value is no string. */
3830
+ constructor(source) {
3831
+ super(source);
3832
+ if (Object.values(this.model).some((value) => typeof value !== "string")) throw new Error(`not every value a string: ${source instanceof Entry ? source.path : JSON.stringify(source)}`);
3833
+ }
3834
+ /** The string a name maps to; none where it maps none. */
3835
+ get(key) {
3836
+ return Object.hasOwn(this.model, key) ? this.model[key] : void 0;
3837
+ }
3838
+ /** Whether a name maps to a string. */
3839
+ has(key) {
3840
+ return Object.hasOwn(this.model, key);
3841
+ }
3842
+ };
3843
+ //#endregion
3844
+ //#region dependencies/metatrom-ag/Manu/main/common/file-system/File.ts
3845
+ /** Whether an {@link Entry} is a {@link File} — by the member only a `File` declares. */
3846
+ function isFile(entry) {
3847
+ return "read" in entry;
3848
+ }
3849
+ //#endregion
3850
+ //#region dependencies/metatrom-ag/Manu/main/habitats/node/file-system/ReadOnlyGitFolder.ts
3851
+ /**
3852
+ * Purpose: run git on one repository, whatever repository the environment
3853
+ * names.
3854
+ *
3855
+ * Intention: a {@link ReadOnlyNodeFolder} that runs git; names where git works as
3856
+ * the {@link GitRepository} there reads it.
3857
+ */
3858
+ var ReadOnlyGitFolder = class extends ReadOnlyNodeFolder {
3859
+ /** The environment variables that tell git where it works, valued as git would find them in this folder: a working tree, its `.git` a folder or a pointer to one. */
3860
+ gitPlaces() {
3861
+ const repository = new GitRepository(this);
3862
+ const gitDir = repository.gitDir?.path ?? `${this.path}/.git`;
3863
+ const common = repository.commonDir?.path ?? gitDir;
3864
+ return {
3865
+ GIT_DIR: gitDir,
3866
+ GIT_WORK_TREE: this.path,
3867
+ GIT_INDEX_FILE: `${gitDir}/index`,
3868
+ GIT_OBJECT_DIRECTORY: `${common}/objects`,
3869
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: "",
3870
+ GIT_COMMON_DIR: common,
3871
+ GIT_NAMESPACE: ""
3872
+ };
3873
+ }
3874
+ /** What git answers, as bytes; refused, naming the command and this folder, where git fails. */
3875
+ git(args, options = {}) {
3876
+ try {
3877
+ return process.getBuiltinModule("node:child_process").execFileSync("git", args, {
3878
+ cwd: this.path,
3879
+ stdio: [
3880
+ "pipe",
3881
+ "pipe",
3882
+ "pipe"
3883
+ ],
3884
+ env: this.here(),
3885
+ ...options
3886
+ });
3887
+ } catch (error) {
3888
+ throw new Error(`git ${args.join(" ")} failed in ${this.path}`, { cause: error });
3889
+ }
3890
+ }
3891
+ /** What git answers, as text without the line it ends on. */
3892
+ gitText(args, options = {}) {
3893
+ return this.git(args, options).toString("utf8").trim();
3894
+ }
3895
+ /** The process environment with each of those variables that is set redirected to this folder, as git would find it here. */
3896
+ here() {
3897
+ const env = { ...process.env };
3898
+ if (!elsewhere.some((name) => env[name] !== void 0)) return env;
3899
+ const places = this.gitPlaces();
3900
+ for (const name of elsewhere) if (env[name] !== void 0) env[name] = places[name];
3901
+ return env;
3902
+ }
3903
+ };
3904
+ const elsewhere = [
3905
+ "GIT_DIR",
3906
+ "GIT_WORK_TREE",
3907
+ "GIT_INDEX_FILE",
3908
+ "GIT_OBJECT_DIRECTORY",
3909
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
3910
+ "GIT_COMMON_DIR",
3911
+ "GIT_NAMESPACE"
3912
+ ];
3913
+ //#endregion
3914
+ //#region dependencies/metatrom-ag/Manu/main/0field.ts
3915
+ var __rewriteRelativeImportExtension = function(path, preserveJsx) {
3916
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
3917
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
3918
+ });
3919
+ return path;
3920
+ };
3921
+ /**
3922
+ * Purpose: the 0field — an operating system interface that works in
3923
+ * any environment.
3924
+ *
3925
+ * Intention: follows the Imago strategy — every part fits into what already
3926
+ * exists. It speaks to the {@link Manu} each habitat realizes —
3927
+ * {@link NodeKernel}, {@link DenoKernel}, {@link BunKernel}, {@link BrowserKernel} — and knows only
3928
+ * that contract; it runs each {@link Program} its realm was started with —
3929
+ * a process's file, a tab's script tags — and every program run beside
3930
+ * them, each with its own address and words, shows one that is no
3931
+ * {@link View} in the View its program names, and speaks to every
3932
+ * SmartObject that carries this file as released and takes from its
3933
+ * exports what it builds on, the realm's
3934
+ * {@link persistence} and the kernel's {@link ModuleHookChain} among them,
3935
+ * and the {@link ModuleHook} a hook written outside this tree realizes.
3936
+ */
3937
+ var OField = class OField extends TypedSmartObject {
3938
+ #programs = /* @__PURE__ */ new Set();
3939
+ /**
3940
+ * Starts the kernel of this habitat — any other environment is named as not implemented yet — then each program the
3941
+ * realm was started with, in order, as {@link OField.run} runs one, the first hearing the words {@link words}
3942
+ * resolves to, and waits until each one's start has finished; {@link words} resolves to none where the realm names
3943
+ * no program. A test is no program; its runner runs it. The started file imports {@link SmartObject} from here, and
3944
+ * so starts the 0field by being run.
3945
+ */
3946
+ async start() {
3947
+ let kernel;
3948
+ try {
3949
+ kernel = this.#kernel();
3950
+ await kernel.start();
3951
+ } catch (error) {
3952
+ loaded.reject(error);
3953
+ throw error;
3954
+ }
3955
+ loaded.resolve(kernel);
3956
+ const programs = kernel.started;
3957
+ const [first] = programs;
3958
+ if (first === void 0) return heard.resolve([]);
3959
+ if (OField.#isTest(first.model.address)) return heard.resolve(first.model.words);
3960
+ await OField.#useHooks(first.model.address, kernel.hooks);
3961
+ for (const program of programs) await this.#begin(program, program === first ? heard.resolve : () => {});
3962
+ await Promise.all(programs.map((program) => program.finished));
3963
+ }
3964
+ /**
3965
+ * Runs one more program in the running kernel, beside every other, once the kernel has started, and hands it out as
3966
+ * it begins; its {@link Program.finished} settles once its start has finished. The address is a URL, an oField IRI
3967
+ * resolved from the started file's place as its imports are, or a path read from that place; a test file, or an
3968
+ * address or a view on a data ref, is refused before anything begins, naming it. The program is the model its
3969
+ * file names by a default export that is a `URL`, restored through {@link persistence}, hearing every word; or the
3970
+ * file's default export, a {@link SmartObject} class created without arguments, or, where the first word is a
3971
+ * model's address, that model restored through {@link persistence} where it is the exported class's and refused
3972
+ * otherwise, hearing the words after it. Where the file lacks such an export, the starter's error names the file.
3973
+ * Where `attach` names a place, the habitat shows the SmartObject there before it starts, as its kernel attaches;
3974
+ * only then, where `view` names a file, read as the address is, a SmartObject that is no {@link View} is shown in that file's
3975
+ * default export, created without arguments, refused, naming the file, where it exports no View; a View shows as
3976
+ * itself. Before it imports the file, it fills the stores with what the descriptor beside that file uses, and before
3977
+ * it restores a model, with what the model names, as {@link Manu.fill} fills them — through GitHub where a
3978
+ * store lacks one.
3979
+ */
3980
+ async run(address, { words = [], attach, view } = {}) {
3981
+ const kernel = await loaded.promise;
3982
+ if (OField.#isTest(address)) throw new Error(`a test is run by its runner, not as a program: ${address}`);
3983
+ const program = new Program({
3984
+ address: kernel.hooks.locate(address, kernel.anchor()),
3985
+ words,
3986
+ ...attach === void 0 ? {} : { attach },
3987
+ ...view === void 0 ? {} : { view: kernel.hooks.locate(view, kernel.anchor()) }
3988
+ });
3989
+ await kernel.fill(program.model.address);
3990
+ await this.#begin(program, () => {});
3991
+ return program;
3992
+ }
3993
+ /** The programs it runs, in the order they began. */
3994
+ get programs() {
3995
+ return [...this.#programs];
3996
+ }
3997
+ /** The program running a SmartObject; none for a SmartObject no program runs. */
3998
+ programOf(smartObject) {
3999
+ return this.programs.find((program) => program.smartObject === smartObject);
4000
+ }
4001
+ static async #viewOf(started, address) {
4002
+ const exported = (await import(__rewriteRelativeImportExtension(address))).default;
4003
+ const isView = typeof exported === "function" && exported.prototype instanceof TypedView;
4004
+ const asked = isView ? exported.viewOf : void 0;
4005
+ if (typeof asked === "function") return asked.call(exported, started);
4006
+ if (started instanceof TypedView) return started;
4007
+ if (!isView) throw new Error(`the view it names exports no View by default: ${address}`);
4008
+ const view = new exported();
4009
+ view.show(started);
4010
+ return view;
4011
+ }
4012
+ static async #useHooks(address, chain) {
4013
+ if (!address.startsWith("file:")) return;
4014
+ const workbench = Workbench.above(ReadOnlyNodeFolder.fromUrl(address).parent);
4015
+ if (workbench === void 0) return;
4016
+ const root = `${ReadOnlyNodeFolder.urlOf(ReadOnlyNodeFolder.native(workbench.path))}/`;
4017
+ for (const hook of workbench.hooks) try {
4018
+ const { default: Hook } = await import(__rewriteRelativeImportExtension(chain.locate(hook, root)));
4019
+ chain.use(new Hook(chain));
4020
+ } catch (error) {
4021
+ console.warn(`the hook ${hook} named in ${workbench.path}/workbench.jsonld is not in use: ${error.message}`);
4022
+ }
4023
+ }
4024
+ static #isTest(address) {
4025
+ return /\.test\.[^/]+$/.test(address);
4026
+ }
4027
+ async #begin(program, hear) {
4028
+ const { address, words: said } = program.model;
4029
+ const exported = (await import(__rewriteRelativeImportExtension(address))).default;
4030
+ const lacks = (fault) => /* @__PURE__ */ new Error(`${fault}: ${address}`);
4031
+ let started;
4032
+ let heard;
4033
+ if (exported instanceof URL) {
4034
+ heard = said;
4035
+ hear(heard);
4036
+ await (await loaded.promise).fill(exported.href);
4037
+ started = await persistence.restore(exported.href);
4038
+ } else {
4039
+ const [model, ...after] = said;
4040
+ heard = after;
4041
+ hear(heard);
4042
+ if (typeof exported !== "function" || !(exported.prototype instanceof TypedSmartObject)) throw lacks("the started file exports no SmartObject by default");
4043
+ if (model === void 0 && exported.length > 0) throw lacks("the SmartObject it exports needs arguments to be created");
4044
+ if (model !== void 0) await (await loaded.promise).fill(model);
4045
+ started = model === void 0 ? new exported() : await persistence.restore(model);
4046
+ if (!(started instanceof exported)) throw lacks(`${model} restores as a ${started.constructor.name}, not the SmartObject it exports`);
4047
+ }
4048
+ const { attach, view } = program.model;
4049
+ if (attach !== void 0) {
4050
+ const shown = view === void 0 ? started : await OField.#viewOf(started, view);
4051
+ (await loaded.promise).attach(shown, attach);
4052
+ }
4053
+ if (this.#programs.size === 0) this.#listen();
4054
+ this.#programs.add(program);
4055
+ program.begin(started, heard);
4056
+ }
4057
+ #listen() {
4058
+ const process = globalThis.process;
4059
+ if (typeof process?.on !== "function") return;
4060
+ let stopping = false;
4061
+ for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]]) process.on(signal, async () => {
4062
+ if (stopping) process.exit(code);
4063
+ stopping = true;
4064
+ await Promise.all(this.programs.map(async (program) => {
4065
+ try {
4066
+ await program.stop();
4067
+ } catch (error) {
4068
+ console.error(error);
4069
+ }
4070
+ }));
4071
+ process.exit(code);
4072
+ });
4073
+ }
4074
+ #kernel() {
4075
+ const realm = globalThis;
4076
+ const running = { oField: here };
4077
+ const notImplemented = (environment) => /* @__PURE__ */ new Error(`the 0field is not implemented for this environment yet: ${environment}`);
4078
+ const serviceWorker = realm.ServiceWorkerGlobalScope;
4079
+ if (typeof serviceWorker === "function" && realm.self instanceof serviceWorker) throw notImplemented("ServiceWorker");
4080
+ const worker = realm.WorkerGlobalScope;
4081
+ if (typeof worker === "function" && realm.self instanceof worker) throw notImplemented("WebWorker");
4082
+ if (realm.window?.document !== void 0) return new BrowserKernel(running);
4083
+ if (realm.Deno !== void 0) return new DenoKernel(running);
4084
+ if (realm.Bun !== void 0) return new BunKernel(running);
4085
+ if (typeof realm.process?.versions?.node === "string") return new NodeKernel(running);
4086
+ throw new Error("the 0field did not detect its environment");
4087
+ }
4088
+ };
4089
+ const here = import.meta.url;
4090
+ const loaded = Promise.withResolvers();
4091
+ loaded.promise.catch(() => {});
4092
+ const heard = Promise.withResolvers();
4093
+ loaded.promise.catch((error) => heard.reject(error));
4094
+ /**
4095
+ * The realm's one {@link Persistence}, over the kernel once it loads; every relation restores by it. An address is
4096
+ * an oField IRI, a path or a URL — in a process a `file:` URL, in a tab one it fetches.
4097
+ */
4098
+ const persistence = new Persistence(loaded.promise);
4099
+ Relation.use(persistence);
4100
+ /**
4101
+ * The words the first program the realm was started with hears — a process's file, a tab's first tag naming one —
4102
+ * available once its file is read and before it runs, so `start()` can await them. Where its file names its model,
4103
+ * they are every word it was given; otherwise those after the model's address: `node Cli.ts cli.jsonld --help` hears
4104
+ * `['--help']`; none where the realm names no program. Await them in `start()`, never at a module's top level, which
4105
+ * the started file's import is still waiting on.
4106
+ */
4107
+ const words = heard.promise;
4108
+ words.catch(() => {});
4109
+ /**
4110
+ * The kernel's {@link ModuleHookChain}, available once the kernel has started and before the program runs, so
4111
+ * `start()` can await it where awaiting {@link started} would wait on itself.
4112
+ */
4113
+ const hooks = loaded.promise.then((kernel) => kernel.hooks);
4114
+ hooks.catch(() => {});
4115
+ /** The one {@link OField} of this realm, which runs every program; loading this file starts it. */
4116
+ const oField = new OField();
4117
+ /** The kernel, once each program the realm was started with has finished its start; never awaited here, as a service worker forbids top-level await. */
4118
+ const started = oField.start().then(() => loaded.promise);
4119
+ //#endregion
4120
+ export { Entry, GitNotes, ModuleHookChain, NodeStores, OField, OFieldIri, Persistence, Program, ReadOnlyGitFolder, ReadOnlyNodeFile, ReadOnlyNodeFolder, ReadOnlyNodeStorage, Relation, RelationList, RelationMap, RelationSet, Releases, RootedTreeNode, TypedSmartObject as SmartObject, StringMap, TypedView as View, Workbench, hooks, isFile, isFolder, oField, persistence, started, words };