@ontology-kit/reader 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/model.js ADDED
@@ -0,0 +1,648 @@
1
+ /** Loading, saving and navigating an ontology folder (okb.json + nodes.jsonl + edges.jsonl; see layout.ts). Part of @ontology-kit/reader. */
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { OkbError } from "./errors.js";
6
+ import { compareNatural, readGraph, writeGraph } from "./layout.js";
7
+ import { acquireLock, isLocked, waitUnlocked } from "./lock.js";
8
+ import { FORMAT_VERSION } from "./registry.js";
9
+ import * as naming from "./naming.js";
10
+ import { Relationships, edgeProps, isRelationship } from "./relationships.js";
11
+ import { DISPOSITIONS, VALUE_TYPES, } from "./types.js";
12
+ export { DISPOSITIONS, VALUE_TYPES };
13
+ export const FORMAT = FORMAT_VERSION;
14
+ export const MANIFEST = "okb.json";
15
+ const ID_PREFIX = {
16
+ CompetencyQuestion: "cq", DesignDecision: "d", Class: "c", Slot: "s", Instance: "i", Term: "t", ReusedOntology: "r", Source: "src", SourceLocation: "loc", Rule: "rule",
17
+ };
18
+ /** Nodes whose ids always carry a tag: different people can add different ones with the same name (or none). */
19
+ const TAGGED_TYPES = new Set(["CompetencyQuestion", "DesignDecision", "Instance", "SourceLocation"]);
20
+ const TAG_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"; // Crockford base32: lowercase, no i l o u
21
+ /**
22
+ * Six characters (30 bits) that two branches won't pick twice. Random, except when
23
+ * SOURCE_DATE_EPOCH is set (a reproducible build): then a hash of the epoch, the type,
24
+ * the name and the attempt number, so generated output like examples/wine is identical
25
+ * on every run.
26
+ */
27
+ function idTag(type, name, attempt) {
28
+ const epoch = process.env.SOURCE_DATE_EPOCH;
29
+ const bytes = epoch
30
+ ? createHash("sha256").update(`${epoch}\0${type}\0${name ?? ""}\0${attempt}`).digest()
31
+ : randomBytes(6);
32
+ let tag = "";
33
+ for (let i = 0; i < 6; i++)
34
+ tag += TAG_ALPHABET[bytes[i] % 32];
35
+ return tag;
36
+ }
37
+ /** Now as `2026-11-21T14:03:22Z`. SOURCE_DATE_EPOCH pins it, like the id tags, so generated output is the same on every run. */
38
+ function timestamp() {
39
+ const epoch = process.env.SOURCE_DATE_EPOCH;
40
+ if (epoch !== undefined && epoch !== "" && !/^\d+$/.test(epoch))
41
+ throw new OkbError(`SOURCE_DATE_EPOCH must be whole seconds since 1970; got '${epoch}'.`);
42
+ const ms = epoch ? Number(epoch) * 1000 : Date.now();
43
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
44
+ }
45
+ /** `okb show class:Genre` etc.: prefixes that say which kind of node a name refers to. */
46
+ const REF_PREFIX = {
47
+ class: "Class", slot: "Slot", instance: "Instance", term: "Term", cq: "CompetencyQuestion", question: "CompetencyQuestion", decision: "DesignDecision",
48
+ };
49
+ export { OkbError };
50
+ /** What a node is called: its name, or a question's/term's text, or a decision's title. */
51
+ export function nodeLabel(n) {
52
+ if ("name" in n)
53
+ return n.name;
54
+ if ("text" in n)
55
+ return n.text;
56
+ if ("title" in n)
57
+ return n.title;
58
+ return n.id;
59
+ }
60
+ /** Every name-like field a node can be looked up by (a quote's text counts: its id has a random tag). */
61
+ function lookupNames(n) {
62
+ return [("name" in n && n.name) || "", ("text" in n && n.text) || "", ("title" in n && n.title) || "", ("quote" in n && typeof n.quote === "string" && n.quote) || ""];
63
+ }
64
+ export { isRelationship };
65
+ export function findRoot(start) {
66
+ let d = resolve(start);
67
+ for (;;) {
68
+ if (existsSync(join(d, MANIFEST)))
69
+ return d;
70
+ const parent = dirname(d);
71
+ if (parent === d)
72
+ return null;
73
+ d = parent;
74
+ }
75
+ }
76
+ function readJson(path, fallback) {
77
+ return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : fallback;
78
+ }
79
+ export class Ontology {
80
+ root;
81
+ manifest;
82
+ // Changed only through addNode/addEdge/remove*, which keep the indexes current.
83
+ _nodes;
84
+ _edges;
85
+ byId = new Map();
86
+ /** Relationship values and the edges that store them (see relationships.ts). */
87
+ rel = new Relationships(this);
88
+ outIdx = new Map();
89
+ incIdx = new Map();
90
+ constructor(root, manifest, nodes, edges) {
91
+ this.root = root;
92
+ this.manifest = manifest;
93
+ this._nodes = [...nodes];
94
+ this._edges = [...edges];
95
+ this.reindex();
96
+ }
97
+ get nodes() {
98
+ return this._nodes;
99
+ }
100
+ get edges() {
101
+ return this._edges;
102
+ }
103
+ static load(start) {
104
+ const root = Ontology.rootOf(start);
105
+ // A command that is saving writes several files: don't read in the middle. If one took the lock while
106
+ // this was reading, the files may be a mix of old and new, so read again.
107
+ for (let attempt = 0;; attempt++) {
108
+ waitUnlocked(root);
109
+ const ont = Ontology.read(root);
110
+ if (attempt >= 3 || !isLocked(root))
111
+ return ont;
112
+ }
113
+ }
114
+ /**
115
+ * Load, change and save one folder with its lock held, so a second command running at the same time
116
+ * waits instead of overwriting this one's work. `fn` may be async; it should call `save()` itself.
117
+ * @internal
118
+ */
119
+ static edit(start, fn) {
120
+ const root = Ontology.rootOf(start);
121
+ const release = acquireLock(root);
122
+ let result;
123
+ try {
124
+ result = fn(Ontology.read(root));
125
+ }
126
+ catch (e) {
127
+ release();
128
+ throw e;
129
+ }
130
+ if (result instanceof Promise)
131
+ return result.finally(release);
132
+ release();
133
+ return result;
134
+ }
135
+ static rootOf(start) {
136
+ const root = findRoot(start);
137
+ if (!root) {
138
+ throw new OkbError(`No ontology found in ${resolve(start)} or its parents. Create one with: okb init <folder> --name "My Ontology"`);
139
+ }
140
+ return root;
141
+ }
142
+ static read(root) {
143
+ // Trusted as typed; struct-well-formed reports what a hand edit got wrong.
144
+ const { nodes, edges } = readGraph(root);
145
+ const ont = new Ontology(root, readJson(join(root, MANIFEST), { format: FORMAT, currentStep: 1 }), nodes, edges);
146
+ if (ont.manifest.format === "okb-lpg/1")
147
+ ont.migrateFromV1();
148
+ // okb-lpg/2 -> /3 changes how new ids are made, not any existing id, so only the version moves.
149
+ if (ont.manifest.format === "okb-lpg/2")
150
+ ont.manifest.format = FORMAT;
151
+ return ont;
152
+ }
153
+ /** okb-lpg/1 stored relationship values as HAS_VALUE edges with a `slot` property. */
154
+ /** @internal */
155
+ migrateFromV1() {
156
+ for (const s of this.ofType("Slot")) {
157
+ if (s.valueType === "Instance" && !s.relType)
158
+ s.relType = naming.relType(s.name);
159
+ }
160
+ this.reindex();
161
+ const old = this.edges.filter((e) => e.type === "HAS_VALUE");
162
+ this._edges = this._edges.filter((e) => e.type !== "HAS_VALUE");
163
+ this.reindex();
164
+ for (const e of old)
165
+ if (typeof e.slot === "string")
166
+ this.rel.link(e.from, e.slot, e.to);
167
+ this.manifest.format = FORMAT;
168
+ }
169
+ static fromData(nodes, edges, manifest) {
170
+ return new Ontology(".", { format: FORMAT, currentStep: 8, ...manifest }, nodes, edges);
171
+ }
172
+ /** @internal */
173
+ save() {
174
+ writeGraph(this.root, this.manifest, this.nodes, this.edges);
175
+ }
176
+ // addNode/addEdge update the indexes in place; everything else that changes
177
+ // nodes or edges (load, removal, retyping edges) calls reindex().
178
+ /** Rebuild every index from scratch. The first node with a given id wins. */
179
+ /** @internal */
180
+ reindex() {
181
+ this.byId = new Map();
182
+ for (const n of this.nodes)
183
+ if (!this.byId.has(n.id))
184
+ this.byId.set(n.id, n);
185
+ this.outIdx = new Map();
186
+ this.incIdx = new Map();
187
+ for (const e of this.edges)
188
+ this.indexEdge(e);
189
+ }
190
+ indexEdge(e) {
191
+ const ko = `${e.from}\u0000${e.type}`;
192
+ const ki = `${e.to}\u0000${e.type}`;
193
+ let out = this.outIdx.get(ko);
194
+ if (!out)
195
+ this.outIdx.set(ko, (out = []));
196
+ out.push(e);
197
+ let inc = this.incIdx.get(ki);
198
+ if (!inc)
199
+ this.incIdx.set(ki, (inc = []));
200
+ inc.push(e);
201
+ }
202
+ /** The Ontology node (scope, conventions). A stand-in if the file lacks one; struct-well-formed reports that. */
203
+ get meta() {
204
+ const n = this.byId.get("ontology");
205
+ return n?.type === "Ontology"
206
+ ? n
207
+ : { type: "Ontology", id: "ontology", name: "", domain: "", purpose: "", users: [], maintainers: [], outOfScope: [], kind: "application", reuseReviewed: false };
208
+ }
209
+ get conventions() {
210
+ return this.meta.conventions;
211
+ }
212
+ get step() {
213
+ return Number(this.manifest.currentStep ?? 1);
214
+ }
215
+ get(id) {
216
+ return this.byId.get(id);
217
+ }
218
+ require(id, type) {
219
+ const n = this.byId.get(id);
220
+ if (!n)
221
+ throw new OkbError(`'${id}' is referenced but doesn't exist. Was a file edited by hand? okb validate shows what's broken.`);
222
+ if (type && n.type !== type)
223
+ throw new OkbError(`'${id}' is ${n.type === "Instance" ? "an" : "a"} ${n.type}, not a ${type}.`);
224
+ return n;
225
+ }
226
+ ofType(type) {
227
+ return this.nodes.filter((n) => n.type === type);
228
+ }
229
+ outEdges(id, type) {
230
+ return this.outIdx.get(`${id}\u0000${type}`) ?? [];
231
+ }
232
+ inEdges(id, type) {
233
+ return this.incIdx.get(`${id}\u0000${type}`) ?? [];
234
+ }
235
+ targets(id, type) {
236
+ return this.outEdges(id, type).map((e) => e.to);
237
+ }
238
+ sources(id, type) {
239
+ return this.inEdges(id, type).map((e) => e.from);
240
+ }
241
+ edgesOf(type) {
242
+ return this.edges.filter((e) => e.type === type);
243
+ }
244
+ label(id) {
245
+ const n = this.byId.get(id);
246
+ return n ? nodeLabel(n) : id;
247
+ }
248
+ find(ref, types, required = true) {
249
+ let ts = typeof types === "string" ? [types] : types;
250
+ const prefixed = ref.match(/^(class|slot|instance|term|cq|question|decision):(.+)$/i);
251
+ if (prefixed) {
252
+ ts = [REF_PREFIX[prefixed[1].toLowerCase()]];
253
+ ref = prefixed[2].trim();
254
+ }
255
+ const ok = (n) => !ts || ts.includes(n.type);
256
+ const direct = this.byId.get(ref);
257
+ if (direct && ok(direct))
258
+ return direct;
259
+ const k = naming.key(ref);
260
+ let hits = this.nodes.filter((n) => ok(n) && k && lookupNames(n).some((x) => naming.key(x) === k));
261
+ if (hits.length === 0 && /^\d+$/.test(ref) && ts) {
262
+ // A bare number is a position in `okb cq list` / `okb decision list` (display order; ids carry no number),
263
+ // or, for ids made before okb-lpg/3, the number inside `cq.3` / `d.3`.
264
+ for (const [t, p] of [["CompetencyQuestion", "cq"], ["DesignDecision", "d"]]) {
265
+ if (!ts.includes(t))
266
+ continue;
267
+ const legacy = this.byId.get(`${p}.${ref}`);
268
+ const nth = this.numbered(t)[Number(ref) - 1];
269
+ hits = hits.concat(legacy?.type === t ? [legacy] : nth ? [nth] : []);
270
+ }
271
+ }
272
+ if (hits.length > 1 && !ts) {
273
+ // Untyped lookups prefer the modeling elements over brainstorm terms, questions, etc.
274
+ for (const pref of ["Class", "Slot", "Instance"]) {
275
+ const h = hits.filter((n) => n.type === pref);
276
+ if (h.length === 1)
277
+ return h[0];
278
+ if (h.length > 1)
279
+ break;
280
+ }
281
+ }
282
+ if (hits.length === 1)
283
+ return hits[0];
284
+ if (hits.length > 1) {
285
+ const hint = hits.map((h) => `${h.type.toLowerCase()}:${nameOrText(h) ?? h.id}`).join(" or ");
286
+ throw new OkbError(`'${ref}' matches more than one thing (${hits.map((h) => `${h.type} ${nameOrText(h)}`).join(", ")}). Say which one: ${hint}`);
287
+ }
288
+ if (!required)
289
+ return undefined;
290
+ const what = ts ? ts.join(" or ") : "node";
291
+ if (ts) {
292
+ const wanted = ts;
293
+ const other = this.nodes.find((n) => !wanted.includes(n.type) && k && lookupNames(n).slice(0, 2).some((x) => naming.key(x) === k));
294
+ if (other) {
295
+ const extra = other.type === "Instance" && ts.includes("Class")
296
+ ? " Instances can't have subclasses or be used as a class (rule inst-are-leaves); if you need that, make it a class."
297
+ : "";
298
+ throw new OkbError(`'${ref}' is ${naming.an(other.type)}, not ${naming.an(what)}.${extra}`);
299
+ }
300
+ }
301
+ const sugg = this.suggest(ref, ts);
302
+ throw new OkbError(`No ${what} named '${ref}'.${sugg.length ? ` Did you mean: ${sugg.join(", ")}?` : ""}`);
303
+ }
304
+ /** @internal */
305
+ suggest(ref, types, limit = 3) {
306
+ const k = naming.key(ref);
307
+ const scored = this.nodes
308
+ .flatMap((n) => ("name" in n && n.name && (!types || types.includes(n.type)) ? [n.name] : []))
309
+ .map((name) => ({ name, d: editDistance(k, naming.key(name)) }))
310
+ .filter((x) => x.d <= Math.max(2, Math.floor(k.length / 3)))
311
+ .sort((a, b) => a.d - b.d);
312
+ return scored.slice(0, limit).map((x) => x.name);
313
+ }
314
+ /** @internal */
315
+ newId(type, name) {
316
+ const prefix = ID_PREFIX[type] ?? type.toLowerCase();
317
+ const slug = naming.slug(name ?? type);
318
+ // Where two branches could each create a different node with the same id, the id carries a
319
+ // tag. Elsewhere a slug id is the first free one, and a clash with an existing id gets a tag too.
320
+ const base = type === "CompetencyQuestion" || type === "DesignDecision" ? prefix : `${prefix}.${slug}`;
321
+ const plain = TAGGED_TYPES.has(type) ? undefined : base;
322
+ if (plain && !this.byId.has(plain))
323
+ return plain;
324
+ for (let attempt = 0;; attempt++) {
325
+ const tag = idTag(type, name, attempt);
326
+ const id = type === "CompetencyQuestion" || type === "DesignDecision" ? `${base}.${tag}` : `${base}-${tag}`;
327
+ if (!this.byId.has(id))
328
+ return id;
329
+ }
330
+ }
331
+ /**
332
+ * Competency questions or design decisions in display order, the order their numbers follow:
333
+ * oldest first by `createdAt`, nodes with no `createdAt` (made before timestamps) before those that
334
+ * have one, in id order with numbers compared as numbers (`cq.2` before `cq.10`), and ties by id.
335
+ * File order is sorted by id and says nothing about age.
336
+ * @internal
337
+ */
338
+ numbered(type) {
339
+ return this.nodes.filter((n) => n.type === type).sort((a, b) => {
340
+ const ca = a.createdAt ?? "";
341
+ const cb = b.createdAt ?? "";
342
+ return (ca < cb ? -1 : ca > cb ? 1 : 0) || compareNatural(a.id, b.id);
343
+ });
344
+ }
345
+ /**
346
+ * The number a person types for a competency question or design decision (`okb cq link 2 ...`):
347
+ * its position in display order (see `numbered`), counting from 1. Ids carry no number.
348
+ * @internal
349
+ */
350
+ displayNumber(n) {
351
+ return this.numbered(n.type).indexOf(n) + 1;
352
+ }
353
+ opTime = null;
354
+ /**
355
+ * Run one command with a single clock read: every stamp it writes (createdAt, updatedAt) is
356
+ * the same value, so a command that creates a node and edits it afterwards leaves the two
357
+ * equal. The CLI wraps each command in this; nesting reuses the outer read. A library caller
358
+ * that calls ops directly without it still gets a fresh read per addNode/touch, which is fine.
359
+ * @internal
360
+ */
361
+ tick(fn) {
362
+ if (this.opTime !== null)
363
+ return fn();
364
+ this.opTime = timestamp();
365
+ try {
366
+ return fn();
367
+ }
368
+ finally {
369
+ this.opTime = null;
370
+ }
371
+ }
372
+ /**
373
+ * Record that something stored ON the node changed (its own fields, property values or
374
+ * facets). Every op that changes a node's content calls this; ops that only add or remove
375
+ * edges don't.
376
+ * @internal
377
+ */
378
+ touch(node) {
379
+ // Never before createdAt: a question or decision added in the same second as another was stamped a second later.
380
+ const now = this.opTime ?? timestamp();
381
+ node.updatedAt = node.createdAt && node.createdAt > now ? node.createdAt : now;
382
+ }
383
+ /** @internal */
384
+ addNode(node) {
385
+ if (this.byId.has(node.id))
386
+ throw new OkbError(`A node with id ${node.id} already exists.`);
387
+ let now = this.opTime ?? timestamp();
388
+ if (node.type === "CompetencyQuestion" || node.type === "DesignDecision") {
389
+ // These are numbered by age (see `numbered`), and stamps have one-second resolution: a new one
390
+ // always sorts after the existing ones, even when two are added in the same second.
391
+ const newest = this.nodes.reduce((m, n) => (n.type === node.type && n.createdAt && n.createdAt > m ? n.createdAt : m), "");
392
+ if (newest >= now)
393
+ now = new Date(Date.parse(newest) + 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
394
+ }
395
+ node.createdAt = now;
396
+ node.updatedAt = now;
397
+ this._nodes.push(node);
398
+ this.byId.set(node.id, node);
399
+ return node;
400
+ }
401
+ /** @internal */
402
+ addEdge(from, type, to, props = {}) {
403
+ const existing = this.outEdges(from, type).find((e) => e.to === to && Object.entries(props).every(([k, v]) => e[k] === v));
404
+ if (existing)
405
+ return existing;
406
+ const e = { from, type, to, ...props };
407
+ this._edges.push(e);
408
+ this.indexEdge(e);
409
+ return e;
410
+ }
411
+ /** @internal */
412
+ removeEdges(pred) {
413
+ const before = this.edges.length;
414
+ this._edges = this._edges.filter((e) => !pred(e));
415
+ this.reindex();
416
+ return before - this.edges.length;
417
+ }
418
+ /** Change every edge of one type to another (a relationship's edge type was renamed). */
419
+ /** @internal */
420
+ retypeEdges(from, to) {
421
+ for (const e of this._edges)
422
+ if (e.type === from)
423
+ e.type = to;
424
+ this.reindex();
425
+ }
426
+ /** Remove a node, every edge touching it, and every value stored under its id. For a relationship slot, call rel.drop() first. */
427
+ /** @internal */
428
+ removeNode(id) {
429
+ this._nodes = this._nodes.filter((x) => x.id !== id);
430
+ this._edges = this._edges.filter((e) => e.from !== id && e.to !== id);
431
+ // Values and facets stored under the removed id are content of the nodes that hold them.
432
+ const drop = (x, map) => {
433
+ if (map && id in map) {
434
+ delete map[id];
435
+ this.touch(x);
436
+ }
437
+ };
438
+ for (const x of this.nodes) {
439
+ if (x.type === "Instance" || x.type === "Rule")
440
+ drop(x, x.values);
441
+ else if (x.type === "Class") {
442
+ drop(x, x.fixedValues);
443
+ drop(x, x.defaults);
444
+ drop(x, x.facetOverrides);
445
+ }
446
+ }
447
+ this.reindex();
448
+ }
449
+ parents(id) {
450
+ return this.targets(id, "IS_A");
451
+ }
452
+ children(id) {
453
+ return this.sources(id, "IS_A");
454
+ }
455
+ /** All classes above id (not including id). Cycle-safe. */
456
+ ancestors(id) {
457
+ return this.walk(id, (x) => this.parents(x));
458
+ }
459
+ descendants(id) {
460
+ return this.walk(id, (x) => this.children(x));
461
+ }
462
+ /**
463
+ * Everything reachable with `next`, nearest first (a parent before its own parents), and among classes
464
+ * the same distance away in id order, so the order is the same in memory and after a save and reload.
465
+ * Cycle-safe.
466
+ */
467
+ walk(id, next) {
468
+ const seen = new Set();
469
+ const queue = [id];
470
+ for (let i = 0; i < queue.length; i++) {
471
+ for (const c of [...next(queue[i])].sort(compareNatural)) {
472
+ if (seen.has(c) || c === id)
473
+ continue;
474
+ seen.add(c);
475
+ queue.push(c);
476
+ }
477
+ }
478
+ return seen;
479
+ }
480
+ /** id plus all its ancestors. */
481
+ up(id) {
482
+ return new Set([id, ...this.ancestors(id)]);
483
+ }
484
+ /** a is b, or a (transitively) IS_A b. */
485
+ isSub(a, b) {
486
+ return a === b || this.ancestors(a).has(b);
487
+ }
488
+ /** a and b can never share members: a declared DISJOINT_WITH pair covers them (directly or via ancestors). */
489
+ disjointImplied(a, b) {
490
+ const ua = this.up(a);
491
+ const ub = this.up(b);
492
+ return this.edgesOf("DISJOINT_WITH").some((e) => (ua.has(e.from) && ub.has(e.to)) || (ua.has(e.to) && ub.has(e.from)));
493
+ }
494
+ roots() {
495
+ return this.ofType("Class").filter((c) => this.parents(c.id).length === 0).map((c) => c.id);
496
+ }
497
+ /** Every class an instance belongs to, including inherited ones. */
498
+ instanceClasses(id) {
499
+ const out = new Set();
500
+ for (const c of this.targets(id, "INSTANCE_OF"))
501
+ for (const x of this.up(c))
502
+ out.add(x);
503
+ return out;
504
+ }
505
+ /** Classes a node belongs to for slot purposes: an instance's classes, or a class and its ancestors. */
506
+ classContext(id) {
507
+ const n = this.byId.get(id);
508
+ if (n?.type === "Rule")
509
+ return [];
510
+ return [...(n?.type === "Instance" ? this.instanceClasses(id) : this.up(id))];
511
+ }
512
+ /** Whether following `type` edges from `from` ever reaches `to`. */
513
+ reaches(from, to, type) {
514
+ const seen = new Set();
515
+ const stack = [from];
516
+ for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
517
+ if (id === to)
518
+ return true;
519
+ if (seen.has(id))
520
+ continue;
521
+ seen.add(id);
522
+ stack.push(...this.targets(id, type));
523
+ }
524
+ return false;
525
+ }
526
+ ownSlots(id) {
527
+ return this.targets(id, "HAS_SLOT");
528
+ }
529
+ slotsOfClasses(classes) {
530
+ const out = [];
531
+ for (const c of classes)
532
+ for (const s of this.ownSlots(c))
533
+ if (!out.includes(s))
534
+ out.push(s);
535
+ return out;
536
+ }
537
+ /** Own + inherited slots of a class, all slots of an instance, or the slots declared to apply to Rules. */
538
+ applicableSlots(id) {
539
+ const n = this.byId.get(id);
540
+ if (n?.type === "Instance")
541
+ return this.slotsOfClasses(this.instanceClasses(id));
542
+ if (n?.type === "Rule")
543
+ return this.ofType("Slot").filter((s) => s.appliesToRules).map((s) => s.id);
544
+ return this.slotsOfClasses([id, ...this.ancestors(id)]);
545
+ }
546
+ domain(slotId) {
547
+ return this.sources(slotId, "HAS_SLOT");
548
+ }
549
+ /** Whether a slot belongs to anything: a class, or every Rule. */
550
+ isAttached(slotId) {
551
+ const s = this.byId.get(slotId);
552
+ return this.domain(slotId).length > 0 || (s?.type === "Slot" && s.appliesToRules === true);
553
+ }
554
+ range(slotId) {
555
+ return this.targets(slotId, "RANGE");
556
+ }
557
+ inverses(slotId) {
558
+ return [...this.targets(slotId, "INVERSE_OF"), ...this.sources(slotId, "INVERSE_OF")];
559
+ }
560
+ /** Slot facets with overrides from any of `classes` applied (most restrictive wins). */
561
+ effectiveFacets(slotId, classes) {
562
+ // A HAS_SLOT edge to something that isn't a slot (a hand edit) gets no facets; struct-well-formed reports it.
563
+ const n = this.byId.get(slotId);
564
+ const s = n?.type === "Slot" ? n : {};
565
+ const single = s.cardinality === "single";
566
+ let max = s.maxCardinality ?? (single ? 1 : null);
567
+ if (single && max !== null)
568
+ max = Math.min(max, 1);
569
+ const f = {
570
+ valueType: s.valueType,
571
+ allowedValues: Array.isArray(s.allowedValues) ? [...s.allowedValues] : null,
572
+ min: s.minCardinality ?? 0,
573
+ max,
574
+ range: this.range(slotId),
575
+ overriddenBy: [],
576
+ };
577
+ for (const c of classes) {
578
+ const cn = this.byId.get(c);
579
+ const ov = cn?.type === "Class" ? cn.facetOverrides?.[slotId] : undefined;
580
+ if (!ov)
581
+ continue;
582
+ f.overriddenBy.push(c);
583
+ const allowed = ov.allowedValues;
584
+ if (Array.isArray(allowed)) {
585
+ const base = f.allowedValues ?? allowed;
586
+ f.allowedValues = base.filter((v) => allowed.includes(v));
587
+ }
588
+ if (typeof ov.minCardinality === "number")
589
+ f.min = Math.max(f.min, ov.minCardinality);
590
+ if (typeof ov.maxCardinality === "number")
591
+ f.max = f.max === null ? ov.maxCardinality : Math.min(f.max, ov.maxCardinality);
592
+ if (Array.isArray(ov.range) && ov.range.length)
593
+ f.range = [...ov.range];
594
+ }
595
+ return f;
596
+ }
597
+ /** Values a node states for a slot: literals (values / fixedValues) plus relationship targets. */
598
+ statedValues(id, slotId) {
599
+ const n = this.byId.get(id);
600
+ if (!n)
601
+ return [];
602
+ const out = [];
603
+ const lit = literalValue(n, slotId);
604
+ if (lit !== undefined)
605
+ out.push(...(Array.isArray(lit) ? lit : [lit]));
606
+ out.push(...this.rel.values(id, slotId));
607
+ return out;
608
+ }
609
+ /** The fixed (class-level) values for a slot inherited from any of `classes`, with the class that set them. */
610
+ inheritedFixed(slotId, classes, exclude) {
611
+ for (const c of classes) {
612
+ if (c === exclude)
613
+ continue;
614
+ const vals = this.statedValues(c, slotId);
615
+ if (vals.length)
616
+ return { cls: c, values: vals };
617
+ }
618
+ return null;
619
+ }
620
+ }
621
+ /** A node's own literal value for a slot: an instance's value, or a class's fixed value. */
622
+ export function literalValue(n, slotId) {
623
+ if (n.type === "Instance" || n.type === "Rule")
624
+ return n.values?.[slotId];
625
+ if (n.type === "Class")
626
+ return n.fixedValues?.[slotId];
627
+ return undefined;
628
+ }
629
+ /** Where a node keeps its own literal values: instances and rules in `values`, classes in `fixedValues`. */
630
+ export function literalValues(n) {
631
+ return n.type === "Class" ? (n.fixedValues ??= {}) : (n.values ??= {});
632
+ }
633
+ /** A node's name, or a question's/term's text (undefined for anything else). */
634
+ export function nameOrText(n) {
635
+ return "name" in n ? n.name : "text" in n ? n.text : undefined;
636
+ }
637
+ export { edgeProps };
638
+ export function editDistance(a, b) {
639
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
640
+ for (let j = 1; j <= b.length; j++)
641
+ dp[0][j] = j;
642
+ for (let i = 1; i <= a.length; i++) {
643
+ for (let j = 1; j <= b.length; j++) {
644
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
645
+ }
646
+ }
647
+ return dp[a.length][b.length];
648
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * How names turn into identities: the folding that makes lookups case- and delimiter-insensitive,
3
+ * the slug an id is built from, and the edge type a relationship slot's name becomes. These are the
4
+ * parts of naming the file format itself depends on. okb keeps the style rules (PascalCase, plurals).
5
+ */
6
+ /** 'Rosé' -> 'Rose': decompose, then drop the combining marks. */
7
+ export declare function stripAccents(s: string): string;
8
+ /** 'RedWine' / 'red_wine' / 'Red wine' -> ['red', 'wine'] */
9
+ export declare function tokens(name: string): string[];
10
+ /** Words with original capitalization (and trailing dots kept, for abbreviation checks). */
11
+ export declare function rawTokens(name: string): string[];
12
+ /** Lowercase letters and digits only, without accents: 'Rosé Wine!' -> 'rosewine'. */
13
+ export declare function fold(text: string): string;
14
+ /**
15
+ * Case- and delimiter-insensitive identity for uniqueness checks (the fold of a
16
+ * name). Memoized: name lookups compare against every node's name, so the same
17
+ * short strings recur constantly.
18
+ */
19
+ export declare function key(name: string): string;
20
+ /** The part of an id built from a name: 'Red Wine' -> 'red-wine'. */
21
+ export declare function slug(name: string): string;
22
+ /** "a Winery" / "an Author" */
23
+ export declare const an: (w: string) => string;
24
+ /** Relationship (edge) type for a slot name: 'goesWellWith' -> 'GOES_WELL_WITH' (the openCypher convention). */
25
+ export declare function relType(slotName: string): string;