- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/graph.ts?version=120&format=json
1,238 linesFirst import 87% · codex-capacity-chair 13%Last change codex-capacity-chair in version 120, 6 versions changed it
You're reading version 120. The newest is 318, and 29 versions since then changed this file.
1// The graph: every atom ever accepted, plus labels. Sets of atoms (states of
2// the codebase) are separate values; the graph only answers questions about
3// atoms and keeps indexes so those questions are cheap.
5import {
6 atomId,
7 attrKey,
8 gapKey,
9 isAtomId,
10 isStartNode,
11 lineId,
12 lineKey,
13 parseKey,
14 posKey,
15 seqOf,
16 startNode,
17} from "./keys.ts";
18import {
19 type GraphStateStorage,
20 type StateMap,
21 storedArray,
22 storedLists,
23 storedMap,
24 storedNumbers,
25} from "./state-source.ts";
26import {
27 ATTR_NAMES,
28 type Atom,
29 type AtomId,
30 EngineError,
31 type InsertRun,
32 type Key,
33 type Label,
34 type LineId,
35 type NodeId,
36 REASON_KINDS,
37 type Reason,
38} from "./types.ts";
40/**
41 * Where a line was written and what it says. Its text never changes. A move
42 * can give it another parent in a set, even in another file: `view.parentOf`
43 * and `view.fileOf` say where it is in a set.
44 */
45export interface LineInfo {
46 readonly id: LineId;
47 readonly atom: AtomId;
48 readonly k: number;
49 /** The file it was written in. */
50 readonly file: string;
51 /** The node it was written after. */
52 readonly parent: NodeId;
53 readonly text: string;
54}
56/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
57export interface RelocationInfo {
58 readonly atom: AtomId;
59 readonly line: LineId;
60 readonly parent: NodeId;
61 readonly k: number;
62}
64/** A `together` reason seen from one end: `other` is the atom at the far end. */
65export interface TogetherLink {
66 readonly other: AtomId;
67 readonly text: string;
68 /** The atom that carries the reason. */
69 readonly from: AtomId;
70}
72export const GRAPH_FORMAT = "ai-first-vcs.graph";
74/** The saved form of a graph. Atoms are in seq order. */
75export interface GraphJSON {
76 readonly format: typeof GRAPH_FORMAT;
77 readonly version: 1;
78 readonly atoms: readonly Atom[];
79 readonly labels: readonly Label[];
80}
82/**
83 * An index entry that holds a lone value as itself, and a list only once there
84 * are two (#46): most keys name one atom, and a list for each costs more than
85 * the value.
86 */
87function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
88 const had = map.get(key);
89 if (had === undefined) map.set(key, value);
90 else if (Array.isArray(had)) {
91 had.push(value);
92 map.set(key, had);
93 } else map.set(key, [had, value]);
94}
96function listOf<V>(had: V | V[] | undefined): readonly V[] {
97 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
98}
100function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
101 const list = map.get(key);
102 if (list) {
103 list.push(value);
104 map.set(key, list);
105 } else map.set(key, [value]);
106}
108const EMPTY: readonly never[] = Object.freeze([]);
110/**
111 * A run whose lines are read when asked for (#46, text on disk): a few fields
112 * and a shared reader, where an object with its own accessor cost about 400
113 * bytes a run.
114 */
115class LazyRun implements InsertRun {
116 readonly file: string;
117 readonly parent: NodeId;
118 readonly #text: (start: number, length: number) => readonly string[];
119 readonly #start: number;
120 readonly #length: number;
121 constructor(
122 file: string,
123 parent: NodeId,
124 text: (start: number, length: number) => readonly string[],
125 start: number,
126 length: number,
127 ) {
128 this.file = file;
129 this.parent = parent;
130 this.#text = text;
131 this.#start = start;
132 this.#length = length;
133 }
134 get lines(): readonly string[] {
135 return this.#text(this.#start, this.#length);
136 }
137 toJSON(): InsertRun {
138 return { file: this.file, parent: this.parent, lines: this.lines };
139 }
140}
142/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
143const TEXT_CACHE = 4_000_000;
144/** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */
145const LIST_CACHE = 50_000;
147/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
148export interface AtomLists {
149 readonly deletes: readonly LineId[];
150 readonly writes: readonly Key[];
151 readonly reads: readonly Key[];
152 readonly holds: readonly Key[];
153}
155function listItems(l: AtomLists): number {
156 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
157}
159function frozenList<T>(xs: readonly T[]): readonly T[] {
160 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
161}
163/**
164 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
165 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
166 */
167class ListedAtom {
168 readonly #read: () => AtomLists;
169 constructor(fields: object, read: () => AtomLists) {
170 Object.assign(this, fields);
171 this.#read = read;
172 }
173 get deletes(): readonly LineId[] {
174 return this.#read().deletes;
175 }
176 get writes(): readonly Key[] {
177 return this.#read().writes;
178 }
179 get reads(): readonly Key[] {
180 return this.#read().reads;
181 }
182 get holds(): readonly Key[] {
183 return this.#read().holds;
184 }
185 toJSON(): object {
186 return { ...this, ...this.#read() };
187 }
188}
190/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
191interface NumberIndex {
192 readonly length: number;
193 push(n: number): void;
194 at(i: number): number;
195 set(i: number, n: number): void;
196}
198class Ints implements NumberIndex {
199 #buf: Int32Array | Uint8Array;
200 /** bytes: values 0-255 only, one byte each. */
201 constructor(bytes = false) {
202 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
203 }
204 length = 0;
205 push(n: number): void {
206 if (this.length === this.#buf.length) {
207 const bigger =
208 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
209 bigger.set(this.#buf);
210 this.#buf = bigger;
211 }
212 this.#buf[this.length++] = n;
213 }
214 at(i: number): number {
215 return this.#buf[i]!;
216 }
217 set(i: number, n: number): void {
218 this.#buf[i] = n;
219 }
220}
222/**
223 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
224 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
225 * zeros, and k within the lines its atom wrote.
226 */
227function parseLineId(id: string): { seq: number; k: number } | undefined {
228 if (typeof id !== "string") return undefined;
229 const n = id.length;
230 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
231 let i = 1;
232 let seq = 0;
233 const seqStart = i;
234 for (; i < n; i++) {
235 const c = id.charCodeAt(i);
236 if (c === 46 /* . */) break;
237 if (c < 48 || c > 57) return undefined;
238 seq = seq * 10 + (c - 48);
239 }
240 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
241 return undefined;
242 const kStart = ++i;
243 let k = 0;
244 for (; i < n; i++) {
245 const c = id.charCodeAt(i);
246 if (c < 48 || c > 57) return undefined;
247 k = k * 10 + (c - 48);
248 }
249 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
250 return { seq, k };
251}
253export class Graph {
254 readonly #storage?: GraphStateStorage;
255 #atoms: Atom[] = [];
256 #lamport: number[] = [];
257 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
258 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
259 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
260 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
261 #lineBase: number[] = [];
262 #lineAtom: NumberIndex = new Ints();
263 #lineFile: NumberIndex = new Ints();
264 #lineParent: NumberIndex = new Ints();
265 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
266 #lineText: string[] | undefined = [];
267 get #lineTotal(): number {
268 return this.#lineAtom.length;
269 }
270 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
271 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
272 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
273 #textCache = new Map<number, readonly string[]>();
274 #textCached = 0;
276 /**
277 * `texts`, when given, says where each atom's lines' text can be read back
278 * (#46): the graph then keeps no text, only each line's place, and reads an
279 * atom's text when a line of it is asked for, keeping the most recent.
280 */
281 constructor(
282 options: {
283 texts?: (seq: number) => readonly (readonly string[])[];
284 lists?: (seq: number) => AtomLists;
285 storage?: GraphStateStorage;
286 } = {},
287 ) {
288 if (options.texts) {
289 this.#texts = options.texts;
290 this.#lineText = undefined;
291 }
292 if (options.lists) this.#lists = options.lists;
293 this.#storage = options.storage;
294 if (options.storage) {
295 const storage = options.storage;
296 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
297 this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
298 freezeAtom(
299 atom,
300 (id) => id,
301 (author) => author,
302 ),
303 );
304 this.#lamport = storedArray(storage, "lamport");
305 this.#lineBase = storedArray(storage, "line-base");
306 this.#paths = storedArray(storage, "paths");
307 this.#movers = storedArray(storage, "movers");
308 this.#atomFiles = storedArray(storage, "atom-files");
309 this.#atomDeletes = storedArray(storage, "atom-deletes");
310 this.#lineAtom = numbers("line-atom");
311 this.#lineFile = numbers("line-file");
312 this.#lineParent = numbers("line-parent");
313 this.#deleter = numbers("deleter");
314 this.#replacing = numbers("replacing");
315 this.#lineText = storedArray(storage, "line-text");
316 this.#pathIndex = storedMap(storage, "path-index");
317 this.#moreDeleters = storedMap(storage, "more-deleters");
318 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
319 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
320 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
321 this.#dependents = storedMap(storage, "dependents");
322 this.#resolvers = storedMap(storage, "resolvers");
323 this.#together = storedMap(storage, "together");
324 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
325 this.#runStarts = storedMap(storage, "run-starts");
326 this.#relocations = storedMap(storage, "relocations");
327 this.#relocatedTo = storedMap(storage, "relocated-to");
328 this.#relocatedToCode = storedMap(storage, "relocated-to-code");
329 this.#labels = storedMap(storage, "labels");
330 }
331 }
333 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
334 #lists: ((seq: number) => AtomLists) | undefined;
335 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
336 #listCache = new Map<number, AtomLists>();
337 #listCached = 0;
339 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
340 #listsOf(seq: number): AtomLists {
341 const hit = this.#listCache.get(seq);
342 if (hit) {
343 this.#listCache.delete(seq);
344 this.#listCache.set(seq, hit);
345 return hit;
346 }
347 const got = this.#lists!(seq);
348 const lists: AtomLists = {
349 deletes: frozenList(got.deletes),
350 writes: frozenList(got.writes),
351 reads: frozenList(got.reads),
352 holds: frozenList(got.holds),
353 };
354 this.#listCache.set(seq, lists);
355 this.#listCached += listItems(lists);
356 for (const [old, kept] of this.#listCache) {
357 if (this.#listCached <= LIST_CACHE || old === seq) break;
358 this.#listCache.delete(old);
359 this.#listCached -= listItems(kept);
360 }
361 return lists;
362 }
364 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
365 #listReader(seq: number): () => AtomLists {
366 return () => this.#listsOf(seq);
367 }
369 /**
370 * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the
371 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
372 * naming a line the graph doesn't have stays a string, which nothing has claimed.
373 */
374 #code(key: Key): Key | number {
375 const t = key.charCodeAt(0);
376 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
377 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
378 if (k < 0) return key;
379 const n = this.#lineN(key.slice(2));
380 return n < 0 ? key : n * 4 + k;
381 }
383 /** An atom's lines' text, in k order. */
384 #textOf(seq: number): readonly string[] {
385 const hit = this.#textCache.get(seq);
386 if (hit) {
387 this.#textCache.delete(seq);
388 this.#textCache.set(seq, hit);
389 return hit;
390 }
391 const flat = this.#texts!(seq).flat();
392 let chars = 0;
393 for (const t of flat) chars += t.length + 1;
394 this.#textCache.set(seq, flat);
395 this.#textCached += chars;
396 for (const [old, lines] of this.#textCache) {
397 if (this.#textCached <= TEXT_CACHE || old === seq) break;
398 this.#textCache.delete(old);
399 for (const t of lines) this.#textCached -= t.length + 1;
400 }
401 return flat;
402 }
404 /**
405 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
406 * keep add()'s whole scope alive, the atom as given with all its text included.
407 */
408 #reader(seq: number): (start: number, length: number) => readonly string[] {
409 return (start, length) => this.#textOf(seq).slice(start, start + length);
410 }
412 /** Line n's text. */
413 #text(n: number): string {
414 if (this.#lineText) return this.#lineText[n]!;
415 const seq = this.#lineAtom.at(n);
416 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
417 }
418 #paths: string[] = [];
419 #pathIndex: StateMap<string, number> = new Map();
420 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
421 #deleter: NumberIndex = new Ints();
422 #moreDeleters: StateMap<number, number[]> = new Map();
423 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
424 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
425 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
426 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
427 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
428 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
429 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
430 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
431 #together: StateMap<AtomId, TogetherLink[]> = new Map();
432 #fileAtoms: StateMap<string, AtomId[]> = new Map();
433 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
434 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
435 #runStarts: StateMap<number, number | number[]> = new Map();
436 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
437 #replacing: NumberIndex = new Ints(true);
438 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
439 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
440 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
441 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
442 #movers: AtomId[] = [];
443 #atomFiles: (readonly string[])[] = [];
444 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
445 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
446 #labels: StateMap<string, Label> = new Map();
447 /** Each author's name kept once (#46). */
448 #authors = new Map<string, string>();
450 /** Number of atoms (also the seq the next atom gets). */
451 get size(): number {
452 return this.#atoms.length;
453 }
455 /** The id the next accepted atom must have. */
456 nextId(): AtomId {
457 return atomId(this.#atoms.length);
458 }
460 has(id: AtomId): boolean {
461 const seq = this.#seq(id);
462 return seq >= 0 && seq < this.#atoms.length;
463 }
465 atom(id: AtomId): Atom {
466 const seq = this.#seq(id);
467 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
468 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
469 return atom;
470 }
472 /** All atoms in seq order. */
473 atoms(): readonly Atom[] {
474 return this.#atoms;
475 }
477 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
478 lamport(id: AtomId): number {
479 this.atom(id);
480 return this.#lamport[this.#seq(id)]!;
481 }
483 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
484 comparePriority(a: AtomId, b: AtomId): number {
485 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
486 }
488 line(id: LineId): LineInfo | undefined {
489 const n = this.#lineN(id);
490 if (n < 0) return undefined;
491 const seq = this.#lineAtom.at(n);
492 return {
493 id,
494 atom: this.#atoms[seq]!.id,
495 k: n - this.#lineBase[seq]!,
496 file: this.#paths[this.#lineFile.at(n)]!,
497 parent: this.#nodeName(this.#lineParent.at(n)),
498 text: this.#text(n),
499 };
500 }
502 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
503 lineText(id: LineId): string | undefined {
504 const n = this.#lineN(id);
505 return n < 0 ? undefined : this.#text(n);
506 }
508 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
509 lineAtom(id: LineId): AtomId | undefined {
510 const n = this.#lineN(id);
511 return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id;
512 }
514 /** The file a line was written in, or undefined: line(id).file without making the record. */
515 lineFile(id: LineId): string | undefined {
516 const n = this.#lineN(id);
517 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
518 }
520 /** The node a line was written after, or undefined: line(id).parent without making the record. */
521 lineParent(id: LineId): NodeId | undefined {
522 const n = this.#lineN(id);
523 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
524 }
526 // By number, for views (#46) ------------------------------------------------------
527 // A line's n and a node's code (a line's n, or -1 - a path's index for a file's start) as the graph
528 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
530 /** A line id's n, or -1 for an unknown line. */
531 lineN(id: LineId): number {
532 return this.#lineN(id);
533 }
535 /** A line's id from its n. */
536 lineIdOf(n: number): LineId {
537 return this.#lineName(n);
538 }
540 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
541 deletedLines(id: AtomId): readonly LineId[] {
542 const ns = this.#atomDeletes[this.#seq(id)];
543 if (!ns) return EMPTY;
544 const out: LineId[] = new Array(ns.length);
545 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
546 return out;
547 }
549 /** How many lines an atom deletes, without reading its lists. */
550 deleteCount(id: AtomId): number {
551 return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
552 }
554 textOf(n: number): string {
555 return this.#text(n);
556 }
558 /** The seq of the atom that wrote line n. */
559 writerSeqOf(n: number): number {
560 return this.#lineAtom.at(n);
561 }
563 /** Line n's k: its place among its atom's lines. */
564 kOf(n: number): number {
565 return n - this.#lineBase[this.#lineAtom.at(n)]!;
566 }
568 /** The atom id with this seq, as the graph keeps it. */
569 idOfSeq(seq: number): AtomId {
570 return this.#atoms[seq]!.id;
571 }
573 lamportOfSeq(seq: number): number {
574 return this.#lamport[seq]!;
575 }
577 /** The file line n was written in. */
578 writtenIn(n: number): string {
579 return this.#paths[this.#lineFile.at(n)]!;
580 }
582 /** The code of the node line n was written after. */
583 parentCodeOf(n: number): number {
584 return this.#lineParent.at(n);
585 }
587 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
588 codeOf(node: NodeId): number | undefined {
589 return this.#nodeCode(node);
590 }
592 /** The node a code names. */
593 nodeOf(code: number): NodeId {
594 return this.#nodeName(code);
595 }
597 /** The start node's code for a path, or undefined when nothing was ever written in it. */
598 startCodeOf(path: string): number | undefined {
599 const p = this.#pathIndex.get(path);
600 return p === undefined ? undefined : -1 - p;
601 }
603 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
604 childrenN(code: number, out: number[]): void {
605 if (
606 code >= 0 &&
607 code + 1 < this.#lineTotal &&
608 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
609 this.#lineParent.at(code + 1) === code
610 )
611 out.push(code + 1);
612 const starts = this.#runStarts.get(code);
613 if (starts === undefined) return;
614 if (Array.isArray(starts)) out.push(...starts);
615 else out.push(starts);
616 }
618 replacesN(n: number): boolean {
619 return this.#replacing.at(n) === 1;
620 }
622 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
623 deleterSeqsOf(n: number): readonly number[] {
624 const first = this.#deleter.at(n);
625 if (first < 0) return EMPTY;
626 const more = this.#moreDeleters.get(n);
627 return more ? [first, ...more] : [first];
628 }
630 /** Every relocation that puts a line right after the node with this code. */
631 relocatedToCode(code: number): readonly RelocationInfo[] {
632 return this.#relocatedToCode.get(code) ?? EMPTY;
633 }
635 /** How many lines every atom together has written. */
636 get lineCount(): number {
637 return this.#lineTotal;
638 }
640 /** A line id's n, or -1 when no accepted atom wrote it. */
641 #lineN(id: LineId): number {
642 const p = parseLineId(id);
643 if (!p || p.seq >= this.#atoms.length) return -1;
644 const base = this.#lineBase[p.seq]!;
645 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
646 return p.k < end - base ? base + p.k : -1;
647 }
649 /** A line's id from its n. */
650 #lineName(n: number): LineId {
651 const seq = this.#lineAtom.at(n);
652 return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`;
653 }
655 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
656 #nodeCode(node: NodeId): number | undefined {
657 if (isStartNode(node)) {
658 const p = this.#pathIndex.get(node.slice(1));
659 return p === undefined ? undefined : -1 - p;
660 }
661 const n = this.#lineN(node);
662 return n < 0 ? undefined : n;
663 }
665 #nodeName(code: number): NodeId {
666 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
667 }
669 #pathOf(file: string): number {
670 let p = this.#pathIndex.get(file);
671 if (p === undefined) {
672 p = this.#paths.push(file) - 1;
673 this.#pathIndex.set(file, p);
674 }
675 return p;
676 }
678 /** The line ids an atom inserted, in k order. */
679 linesOf(id: AtomId): LineId[] {
680 const atom = this.atom(id);
681 const out: LineId[] = [];
682 const seq = atom.seq;
683 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
684 for (let k = 0; k < count; k++) out.push(lineId(id, k));
685 return out;
686 }
688 /** Every atom that deletes this line (across the whole graph). */
689 deletersOf(line: LineId): readonly AtomId[] {
690 const n = this.#lineN(line);
691 if (n < 0) return EMPTY;
692 const first = this.#deleter.at(n);
693 if (first < 0) return EMPTY;
694 const more = this.#moreDeleters.get(n);
695 const out = [this.#atoms[first]!.id];
696 if (more) for (const seq of more) out.push(this.#atoms[seq]!.id);
697 return out;
698 }
700 writersOf(key: Key): readonly AtomId[] {
701 return [...this.eachWriterOf(key)];
702 }
703 *eachWriterOf(key: Key): IterableIterator<AtomId> {
704 const code = this.#code(key);
705 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
706 else yield* listOf(this.#writers.get(code));
707 }
709 /** Atoms whose implicit reads include the key. */
710 readersOf(key: Key): readonly AtomId[] {
711 return [...this.eachReaderOf(key)];
712 }
713 *eachReaderOf(key: Key): IterableIterator<AtomId> {
714 const code = this.#code(key);
715 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
716 else yield* listOf(this.#readers.get(code));
717 }
719 /** Atoms whose explicit holds include the key. */
720 holdersOf(key: Key): readonly AtomId[] {
721 return [...this.eachHolderOf(key)];
722 }
723 *eachHolderOf(key: Key): IterableIterator<AtomId> {
724 const code = this.#code(key);
725 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
726 else yield* listOf(this.#holders.get(code));
727 }
729 /** Every atom that inserts or deletes a line of the file, in seq order. */
730 atomsIn(file: string): readonly AtomId[] {
731 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
732 return this.#fileAtoms.get(file) ?? EMPTY;
733 }
734 *eachAtomIn(file: string): IterableIterator<AtomId> {
735 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
736 else yield* this.#fileAtoms.get(file) ?? EMPTY;
737 }
738 hasAtomsIn(file: string): boolean {
739 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
740 }
742 /** Unique historical file paths, streamed without collecting their names. */
743 *knownFiles(): IterableIterator<string> {
744 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
745 }
747 /**
748 * The files an atom inserts, deletes or moves lines in, or sets attributes
749 * of, sorted. For lines, the file each was written in (or, for a move to a
750 * start node, that file): a set's moves can have taken them elsewhere.
751 */
752 filesOf(id: AtomId): readonly string[] {
753 this.atom(id);
754 return this.#atomFiles[this.#seq(id)]!;
755 }
757 /** Lines written right after a node (not counting moves), in seq order. */
758 childrenOf(node: NodeId): LineId[] {
759 const out: LineId[] = [];
760 const code = this.#nodeCode(node);
761 if (code === undefined) return out;
762 // The next line of the same run hangs off this one.
763 if (
764 code >= 0 &&
765 code + 1 < this.#lineTotal &&
766 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
767 this.#lineParent.at(code + 1) === code
768 ) {
769 out.push(this.#lineName(code + 1));
770 }
771 for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n));
772 return out;
773 }
775 /** Whether a line starts a run whose atom deleted the line it hangs off. */
776 replaces(line: LineId): boolean {
777 const n = this.#lineN(line);
778 return n >= 0 && this.#replacing.at(n) === 1;
779 }
781 /** Every relocation of a line, in seq order. */
782 relocationsOf(line: LineId): readonly RelocationInfo[] {
783 return this.#relocations.get(line) ?? EMPTY;
784 }
786 /** Every relocation that puts a line right after this node, in seq order. */
787 relocatedTo(node: NodeId): readonly RelocationInfo[] {
788 return this.#relocatedTo.get(node) ?? EMPTY;
789 }
791 /** Atoms that move lines, in seq order. */
792 movers(): readonly AtomId[] {
793 return this.#movers;
794 }
796 /** Atoms that list this one directly in their deps. */
797 dependentsOf(id: AtomId): readonly AtomId[] {
798 return listOf(this.#dependents.get(id));
799 }
801 /** Atoms whose `resolves` names this one. */
802 resolversOf(id: AtomId): readonly AtomId[] {
803 return listOf(this.#resolvers.get(id));
804 }
806 /** `together` reasons touching this atom, in either direction. */
807 togetherLinks(id: AtomId): readonly TogetherLink[] {
808 return this.#together.get(id) ?? EMPTY;
809 }
811 /**
812 * The atom plus everything it depends on, transitively. Computed on demand
813 * and not cached: a cached set per atom costs memory quadratic in the length
814 * of a dependency chain. Use `dependsOn` to ask about one pair.
815 */
816 closure(id: AtomId): Set<AtomId> {
817 return this.closureOf([id]);
818 }
820 /** The atoms plus everything they depend on, transitively. */
821 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
822 const out = new Set<AtomId>();
823 const stack: AtomId[] = [];
824 for (const id of ids) {
825 this.atom(id);
826 if (!out.has(id)) {
827 out.add(id);
828 stack.push(id);
829 }
830 }
831 while (stack.length > 0) {
832 for (const d of this.atom(stack.pop()!).deps) {
833 if (!out.has(d)) {
834 out.add(d);
835 stack.push(d);
836 }
837 }
838 }
839 return out;
840 }
842 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
843 dependsOn(a: AtomId, b: AtomId): boolean {
844 const atom = this.atom(a);
845 this.atom(b);
846 return a === b || this.#reaches(atom.deps, b);
847 }
849 /**
850 * Whether `target` is reachable along deps from any of `from` (themselves
851 * included). A dependency always has a lower lamport than its dependent, so
852 * the search never descends below the target's lamport.
853 */
854 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
855 const floor = this.#lamport[this.#seq(target)]!;
856 const seen = new Set<AtomId>();
857 const stack = [...from];
858 while (stack.length > 0) {
859 const cur = stack.pop()!;
860 if (cur === target) return true;
861 if (seen.has(cur)) continue;
862 seen.add(cur);
863 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
864 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
865 }
866 return false;
867 }
869 /**
870 * Accept an atom into the graph. It must carry the next id and seq, and
871 * everything it touches must come from atoms in its dependency closure.
872 * The atom is frozen. Adding to the graph does not add it to any set.
873 */
874 add(atom: Atom): void {
875 if (this.#storage) this.#storage.transaction(() => this.#add(atom));
876 else this.#add(atom);
877 }
879 #add(atom: Atom): void {
880 validateShape(atom);
881 const seq = this.#atoms.length;
882 const bad = (why: string): never => {
883 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
884 };
885 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
887 const deps = new Set<AtomId>();
888 for (const d of atom.deps) {
889 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
890 if (deps.has(d)) bad(`dependency ${d} listed twice`);
891 deps.add(d);
892 }
893 for (const d of [...atom.needs, ...atom.resolves]) {
894 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
895 }
896 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
898 // Everything it touches must come from its closure. Derived deps name the
899 // writers directly, so this is usually one lookup per writer.
900 const below = new Map<AtomId, boolean>();
901 const inClosure = (writer: AtomId): boolean => {
902 let hit = below.get(writer);
903 if (hit === undefined) {
904 hit = deps.has(writer) || this.#reaches(deps, writer);
905 below.set(writer, hit);
906 }
907 return hit;
908 };
909 const checkLine = (line: LineId, what: string): void => {
910 const writer = this.lineAtom(line);
911 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
912 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
913 };
915 for (const run of atom.inserts) {
916 if (isStartNode(run.parent)) {
917 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
918 } else {
919 // The parent may have been moved into run.file, so its own file can differ.
920 checkLine(run.parent, "an insert");
921 }
922 }
923 const moved = new Set<LineId>();
924 for (const m of atom.moves ?? []) {
925 checkLine(m.line, "a move");
926 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
927 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
928 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
929 moved.add(m.line);
930 if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
931 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
932 }
933 }
934 const deleted = new Set<LineId>();
935 for (const line of atom.deletes) {
936 checkLine(line, "a delete");
937 if (deleted.has(line)) bad(`deletes ${line} twice`);
938 deleted.add(line);
939 }
940 const writes = new Set(atom.writes);
941 for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
942 for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
943 const parsed = parseKey(key);
944 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
945 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
946 checkLine(parsed.node, `key ${key}`);
947 }
949 // Accept.
950 const frozen = freezeAtom(
951 atom,
952 (id) => this.#atoms[seqOf(id)]!.id,
953 (author) => {
954 if (this.#storage) return author;
955 let a = this.#authors.get(author);
956 if (a === undefined) this.#authors.set(author, (a = author));
957 return a;
958 },
959 this.#texts ? this.#reader(seq) : undefined,
960 this.#lists ? this.#listReader(seq) : undefined,
961 );
962 this.#atoms.push(this.#storage ? atom : frozen);
963 let lam = 0;
964 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
965 this.#lamport.push(lam);
967 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
968 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
969 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
970 const deletedN = atom.deletes.map((line) => this.#lineN(line));
971 this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
972 this.#lineBase.push(this.#lineTotal);
973 for (const run of atom.inserts) {
974 const file = this.#pathOf(run.file);
975 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
976 const first = this.#lineTotal;
977 pushOne(this.#runStarts, parent, first);
978 for (let i = 0; i < run.lines.length; i++) {
979 const n = this.#lineTotal;
980 this.#lineAtom.push(seq);
981 this.#lineFile.push(file);
982 this.#lineParent.push(parent);
983 this.#lineText?.push(run.lines[i]!);
984 this.#deleter.push(-1);
985 this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
986 parent = n;
987 }
988 }
989 (frozen.moves ?? []).forEach((m, i) => {
990 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
991 pushIndex(this.#relocations, m.line, info);
992 pushIndex(this.#relocatedTo, m.parent, info);
993 pushIndex(
994 this.#relocatedToCode,
995 isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent),
996 info,
997 );
998 });
999 if (frozen.moves) this.#movers.push(frozen.id);
1000 for (const n of deletedN) {
1001 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1002 else pushIndex(this.#moreDeleters, n, seq);
1003 }
1004 for (const key of new Set(atom.writes)) {
1005 const code = this.#code(key);
1006 if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1007 else pushOne(this.#writers, code, frozen.id);
1008 }
1009 for (const key of new Set(atom.reads)) {
1010 const code = this.#code(key);
1011 if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1012 else pushOne(this.#readers, code, frozen.id);
1013 }
1014 for (const key of new Set(atom.holds)) {
1015 const code = this.#code(key);
1016 if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1017 else pushOne(this.#holders, code, frozen.id);
1018 }
1019 for (const d of deps) pushOne(this.#dependents, d, frozen.id);
1020 for (const r of new Set(frozen.resolves)) pushOne(this.#resolvers, r, frozen.id);
1021 const files = new Set<string>();
1022 for (const run of atom.inserts) files.add(run.file);
1023 for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1024 for (const a of frozen.attrs ?? []) files.add(a.file);
1025 for (const m of frozen.moves ?? []) {
1026 files.add(this.lineFile(m.line)!);
1027 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1028 }
1029 this.#atomFiles.push(Object.freeze([...files].sort()));
1030 for (const file of files) {
1031 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1032 else pushIndex(this.#fileAtoms, file, frozen.id);
1033 }
1034 for (const r of frozen.reasons) {
1035 if (r.kind !== "together" || r.to === frozen.id) continue;
1036 pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id });
1037 pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id });
1038 }
1039 }
1041 // Labels -----------------------------------------------------------------
1043 /**
1044 * Add or replace a label. Label names may not look like atom ids. A base is
1045 * resolved to its head only when it is used, never followed further, so
1046 * bases may name each other in any shape.
1047 */
1048 setLabel(label: Label): void {
1049 this.#putLabel(label, (name) => this.#labels.has(name));
1050 }
1052 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1053 const bad = (why: string): never => {
1054 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1055 };
1056 if (typeof label !== "object" || label === null) bad("not an object");
1057 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1058 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1059 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1060 if (
1061 label.base !== undefined &&
1062 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1063 ) {
1064 bad(`base ${label.base} is neither a label nor an atom`);
1065 }
1066 if (label.base === label.name) bad("a label cannot be its own base");
1067 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1068 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1069 const copy: Label = {
1070 name: label.name,
1071 head: label.head,
1072 ...(label.base !== undefined ? { base: label.base } : {}),
1073 title: label.title,
1074 message: label.message,
1075 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1076 };
1077 this.#labels.set(label.name, Object.freeze(copy));
1078 }
1080 label(name: string): Label | undefined {
1081 return this.#labels.get(name);
1082 }
1084 /** Labels sorted by name. */
1085 labels(): Label[] {
1086 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1087 }
1089 /**
1090 * Remove a label. Labels that used it as their base get its head atom as
1091 * their base instead, so their contents don't change.
1092 */
1093 removeLabel(name: string): boolean {
1094 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1095 }
1097 #removeLabel(name: string): boolean {
1098 const gone = this.#labels.get(name);
1099 if (!gone) return false;
1100 this.#labels.delete(name);
1101 for (const label of [...this.#labels.values()]) {
1102 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1103 }
1104 return true;
1105 }
1107 // JSON -------------------------------------------------------------------
1109 toJSON(): GraphJSON {
1110 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1111 }
1113 /** Load a saved graph. Every atom is re-validated as it is added. */
1114 static fromJSON(data: unknown): Graph {
1115 const bad = (why: string): never => {
1116 throw new EngineError("bad-json", why);
1117 };
1118 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1119 const obj = data as Partial<GraphJSON>;
1120 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1121 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1122 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1123 const graph = new Graph();
1124 for (const atom of obj.atoms!) graph.add(atom);
1125 // Labels may name each other as bases, in any order and any shape.
1126 const names = new Set<string>();
1127 for (const label of obj.labels!) {
1128 const name: unknown = (label as Partial<Label> | null)?.name;
1129 if (typeof name !== "string") return bad("every label needs a name");
1130 if (names.has(name)) bad(`label ${name} appears twice`);
1131 names.add(name);
1132 }
1133 for (const label of obj.labels!) {
1134 try {
1135 graph.#putLabel(label, (name) => names.has(name));
1136 } catch (err) {
1137 if (err instanceof EngineError) bad(err.message);
1138 throw err;
1139 }
1140 }
1141 return graph;
1142 }
1144 #seq(id: AtomId): number {
1145 return typeof id === "string" ? seqOf(id) : -1;
1146 }
1147}
1149function validateShape(atom: Atom): void {
1150 const bad = (why: string): never => {
1151 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1152 };
1153 if (typeof atom !== "object" || atom === null) bad("not an object");
1154 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1155 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1156 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1157 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1158 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1159 for (const run of atom.inserts as readonly InsertRun[]) {
1160 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1161 if (typeof run.parent !== "string") bad("a run needs a parent");
1162 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1163 for (const text of run.lines) {
1164 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1165 bad("run lines must be strings without line breaks");
1166 }
1167 }
1168 if (atom.attrs !== undefined) {
1169 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1170 for (const a of atom.attrs) {
1171 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1172 bad("an attr needs a file and a name");
1173 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1174 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1175 }
1176 }
1177 if (atom.moves !== undefined) {
1178 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1179 for (const m of atom.moves) {
1180 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1181 }
1182 }
1183 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1184 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1185 }
1186 for (const r of atom.reasons as readonly Reason[]) {
1187 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1188 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1189 }
1190 }
1191}
1193/**
1194 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1195 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1196 * kept once however often it's named (#46).
1197 */
1198function freezeAtom(
1199 atom: Atom,
1200 canon: (id: AtomId) => AtomId,
1201 author: (name: string) => string,
1202 text?: (start: number, length: number) => readonly string[],
1203 lists?: () => AtomLists,
1204): Atom {
1205 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1206 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1207 // With text kept elsewhere (#46), a run's lines are read when asked for.
1208 let k = 0;
1209 const run = (r: InsertRun): InsertRun => {
1210 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1211 const start = k;
1212 const length = r.lines.length;
1213 k += length;
1214 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1215 };
1216 const copy: Atom = {
1217 id: atom.id,
1218 seq: atom.seq,
1219 author: author(atom.author),
1220 message: atom.message,
1221 time: atom.time,
1222 inserts: Object.freeze(atom.inserts.map(run)),
1223 ...(lists
1224 ? {}
1225 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1226 needs: list(atom.needs, canon),
1227 resolves: list(atom.resolves, canon),
1228 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1229 deps: list(atom.deps, canon),
1230 ...(atom.attrs && atom.attrs.length > 0
1231 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1232 : {}),
1233 ...(atom.moves
1234 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1235 : {}),
1236 } as Atom;
1237 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
1238}