Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/view.ts?version=245&format=json
1,194 linescapacity 46% · First import 31% · codex-capacity-chair 20% · codex-capacity-policy 3%Last change capacity in version 245, 36 versions changed it

You're reading version 245. The newest is 318, and 9 versions since then changed this file. Go to the newestCompare with 318

1// Projection: the files a closed set of atoms produces. A pure function of the
2// set. Each file is a tree of lines hanging off its start node; linearizing it
3// depth-first, children in descending priority, gives the file's sequence. A
4// line hangs off the node it was written after, unless a move in the set gave
5// it another parent (#28): then the newest such move decides.
6//
7// A laid-out file is kept as arrays of line numbers (the graph's n), not as a
8// record per line (#46): a record, its id and two index entries cost about
9// 370 bytes a line, and the view cache holds up to 200,000 lines. Records are
10// made when a caller asks for them, and the latest asked for is kept.
12import type { Graph, RelocationInfo } from "./graph.ts";
13import { isStartNode, lineId, seqOf } from "./keys.ts";
14import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts";
15import { isClosedSet, StableSet } from "./state-source.ts";
16import { joinLines } from "./text.ts";
17import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts";
19/** A line in a file's full sequence, tombstones included. */
20export interface SeqLine {
21 readonly id: LineId;
22 readonly text: string;
23 /** The atom that wrote it. */
24 readonly atom: AtomId;
25 /** Atoms in the set that delete it, by seq. Empty when it is visible. */
26 readonly deletedBy: readonly AtomId[];
27 readonly visible: boolean;
30/** A visible line of a projected file. */
31export interface VisibleLine {
32 readonly textChunks?: () => Iterable<string>;
33 readonly id: LineId;
34 readonly text: string;
35 readonly atom: AtomId;
38/** A file's attributes in a view. */
39export interface FileAttrs {
40 /** Kept with no lines (an empty file). */
41 readonly exists: boolean;
42 readonly exec: boolean;
43 /** The target, when the file is a symbolic link. */
44 readonly link: string | null;
45 /** The SHA-256 of its bytes, when the file is binary. */
46 readonly blob: string | null;
49/** Structural read boundary shared by historical and transaction-bound projections. */
50export type ReadView = Omit<
51 Pick<View, keyof View>,
52 | "sameText"
53 | "visibleCount"
54 | "shareMoves"
55 | "shareFiles"
56 | "knowPaths"
57 | "fileOfNumber"
58 | "lineNumberOf"
59 | "visibleWriters"
60> & {
61 sameText(path: string, other: ReadView): boolean;
62};
64const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
66/**
67 * A file layout's bytes, less its lookup indexes, worked out once per layout (abso Capacity): a layout never changes
68 * once made, and the view cache weighs every view it holds on every lookup, which summed every line's text again.
69 */
70const layoutSizes = new WeakMap<FileState, number>();
71function layoutBytes(f: FileState): number {
72 let n = layoutSizes.get(f);
73 if (n !== undefined) return n;
74 // FileState and FileAttrs are per laid-out file; typed-array headers are separate from their payload byte lengths.
75 n = OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
76 n += f.seq.byteLength + f.vis.byteLength;
77 if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0);
78 if (f.visWriter) n += 4 * f.visWriter.length;
79 if (f.visK) n += 4 * f.visK.length;
80 if (f.seqWriter) n += 4 * f.seqWriter.length;
81 if (f.seqK) n += 4 * f.seqK.length;
82 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
83 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
84 layoutSizes.set(f, n);
85 return n;
87const NONE: readonly never[] = Object.freeze([]);
89interface FileState {
90 readonly attrs: FileAttrs;
91 /** Full history is retained only when a sequence caller explicitly requests it. */
92 readonly complete: boolean;
93 /** The file's sequence, tombstones included: each line's n. */
94 readonly seq: Int32Array;
95 /** Its visible lines' n, in order. */
96 readonly vis: Int32Array;
97 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
98 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
99 /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */
100 readonly visText?: readonly (string | null)[];
101 /** Its visible lines' writers' seqs, when laid out from the file's packed history. */
102 readonly visWriter?: Int32Array;
103 /** Its visible lines' places in their writers (a line id's k), when laid out from packed history. */
104 readonly visK?: Int32Array;
105 /** The same for every line of seq, when complete and laid out from packed history. */
106 readonly seqWriter?: Int32Array;
107 readonly seqK?: Int32Array;
108 /** Positions by n, built the first time they're asked for. */
109 seqIndex?: Map<number, number>;
110 visIndex?: Map<number, number>;
113interface Child {
114 readonly n: number;
115 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
116 readonly replaces: number;
117 readonly lamport: number;
118 readonly seq: number;
119 readonly k: number;
122const EMPTY_INTS = new Int32Array(0);
123const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
125// Approximate retained-container costs for View.weight(): reference slots,
126// object headers, and map/set entries. These are cache-budget units, not V8
127// heap measurements. Referenced Graph strings and records are not charged.
128const ARRAY_HEADER_BYTES = 24;
129const OBJECT_BYTES = 32;
130const MAP_HEADER_BYTES = 32;
131const MAP_ENTRY_BYTES = 40;
132const SET_ENTRY_BYTES = 32;
133const REFERENCE_BYTES = 8;
134/**
135 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
136 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
137 */
138export const MOVED_LINES_KEPT = 20_000;
139class TooManyMoves extends Error {}
140const NO_LINES: readonly number[] = Object.freeze([]);
141/** Nodes whose nearest moved line above a graph remembers, at most: about 40 bytes each. */
142const CLIMB_MEMO = 200_000;
144/** One relocation of a moved line, with its line's number and its new parent's code. */
145interface MoveEntry {
146 readonly n: number;
147 readonly r: RelocationInfo;
148 readonly parent: number;
151/**
152 * A graph's moves, whatever the set (abso Capacity): each mover's moved lines, each moved line's relocations in seq
153 * order, and for any node the nearest node at or above it, by where lines were written, that a move ever relocated,
154 * or its file's start. Worked out once per graph and extended as it grows. A view's moves then resolve over the moved
155 * lines alone: before, every view walked each moved line's file up to its start, a read per line.
156 */
157class MoveSkeleton {
158 readonly #graph: Graph;
159 #seen = 0;
160 /** Movers in seq order, with the numbers of the lines each moves, in its moves' order. */
161 readonly movers: { readonly seq: number; readonly lines: readonly number[] }[] = [];
162 /** Every relocation of each moved line, by the line's number, in seq order. */
163 readonly byLine = new Map<number, MoveEntry[]>();
164 readonly #climbed = new Map<number, number>();
166 constructor(graph: Graph) {
167 this.#graph = graph;
168 }
170 /** The graph's accepted count when movers were last taken in: nothing to read while it's the same. */
171 #stamp = -1;
173 /** Take in movers the graph gained since. */
174 update(): this {
175 const graph = this.#graph;
176 if (this.#stamp === graph.accepted) return this;
177 this.#stamp = graph.accepted;
178 const all = graph.movers();
179 if (this.#seen === all.length) return this;
180 for (; this.#seen < all.length; this.#seen++) {
181 const id = all[this.#seen]!;
182 const lines: number[] = [];
183 graph.atom(id).moves!.forEach((m, k) => {
184 const n = graph.lineN(m.line);
185 const r: RelocationInfo = Object.freeze({ atom: id, line: m.line, parent: m.parent, k });
186 const entry: MoveEntry = { n, r, parent: graph.codeOf(m.parent)! };
187 const list = this.byLine.get(n);
188 if (list) list.push(entry);
189 else this.byLine.set(n, [entry]);
190 lines.push(n);
191 });
192 this.movers.push({ seq: seqOf(id), lines });
193 }
194 // A new moved line can sit between a node and the one it climbed to.
195 this.#climbed.clear();
196 return this;
197 }
199 /** The nearest node at or above this one, by where lines were written, that a move ever relocated; or its file's start. */
200 climb(code: number): number {
201 const walked: number[] = [];
202 let c = code;
203 while (c >= 0 && !this.byLine.has(c)) {
204 const known = this.#climbed.get(c);
205 if (known !== undefined) {
206 c = known;
207 break;
208 }
209 walked.push(c);
210 c = this.#graph.parentCodeOf(c);
211 }
212 if (this.#climbed.size + walked.length > CLIMB_MEMO) this.#climbed.clear();
213 for (const w of walked) this.#climbed.set(w, c);
214 return c;
215 }
218const skeletons = new WeakMap<Graph, MoveSkeleton>();
219function skeletonOf(graph: Graph): MoveSkeleton {
220 let skeleton = skeletons.get(graph);
221 if (!skeleton) skeletons.set(graph, (skeleton = new MoveSkeleton(graph)));
222 return skeleton.update();
225/**
226 * The projection of a closed set. Construct once, then ask for files, lines
227 * and sequences. Throws `not-closed` if some atom's dependency is missing.
228 * Each file is laid out the first time it is asked for, so a view of a large
229 * set costs little until files are read.
230 */
231export class View {
232 readonly graph: Graph;
233 /** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */
234 #set: AtomSet | undefined;
235 readonly #stable: StableSet<AtomId> | undefined;
236 /** Fixed-size memo for immutable indexed membership, independent of history size. */
237 #membershipSeq = new Float64Array(256).fill(-1);
238 #membershipValue = new Uint8Array(256);
239 #files = new Map<string, FileState>();
240 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
241 #knownList: string[] | undefined;
242 /** 1 for each atom (by seq) in the set. */
243 #in: Uint8Array;
244 /** Atoms in the set that move lines. */
245 #movers: AtomId[] | undefined;
246 #hasMoves = false;
247 /** Each moved line's relocation that counts in this set; built on first use. */
248 #relocs: Map<LineId, RelocationInfo> | undefined;
249 /** The same, by n, with the new parent's code. */
250 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
251 /** The moved lines under each node, by its code, made from the relocations on first use. */
252 #movedInto: Map<number, number[]> | undefined;
253 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
254 #movesOnDisk: boolean | undefined;
255 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
256 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
257 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
258 #textCache: { path: string; text: string } | undefined;
260 constructor(graph: Graph, set: Iterable<AtomId>) {
261 this.graph = graph;
262 if (set instanceof StableSet) {
263 this.#stable = set;
264 this.#set = set;
265 this.#in = new Uint8Array(0);
266 // A set kept closed when it was written needs no proof here (abso Capacity).
267 for (const id of isClosedSet(set) ? [] : set) {
268 const atom = graph.atom(id);
269 for (const dependency of atom.deps) {
270 graph.atom(dependency);
271 if (!set.has(dependency))
272 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
273 }
274 }
275 for (const id of graph.movers()) {
276 if (set.has(id)) {
277 this.#hasMoves = true;
278 break;
279 }
280 }
281 this.#relocs = this.#hasMoves ? undefined : new Map();
282 this.#relocsN = this.#hasMoves ? undefined : new Map();
283 return;
284 }
285 const inSet = new Uint8Array(graph.size);
286 // An atom's number is in its id (abso Capacity): reading the atom for it read the whole history on a stored graph.
287 const seqIn = (id: AtomId): number => {
288 const seq = seqOf(id);
289 return seq >= 0 && seq < inSet.length && graph.idOfSeq(seq) === id ? seq : graph.atom(id).seq;
290 };
291 for (const id of set) inSet[seqIn(id)] = 1;
292 // Validate one atom at a time. Keeping all decoded atoms here defeats
293 // storage-backed Graph reads even though the view only needs membership.
294 for (let seq = 0; seq < inSet.length; seq++) {
295 if (inSet[seq] !== 1) continue;
296 const atom = graph.atom(graph.idOfSeq(seq));
297 for (const d of atom.deps) {
298 if (inSet[seqIn(d)] !== 1) throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
299 }
300 }
301 this.graph = graph;
302 this.#in = inSet;
303 this.#movers = graph.movers().filter((id) => inSet[seqOf(id)] === 1);
304 this.#hasMoves = this.#movers.length > 0;
305 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
306 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
307 }
309 /** The set of atoms this view projects. */
310 get set(): AtomSet {
311 if (!this.#set) {
312 const out = new Set<AtomId>();
313 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
314 this.#set = out;
315 }
316 return this.#set;
317 }
319 /** Whether the atom with this seq is in the set. */
320 #has(seq: number): boolean {
321 if (this.#stable) {
322 const slot = seq % this.#membershipSeq.length;
323 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
324 const present = this.#stable.has(this.graph.idOfSeq(seq));
325 this.#membershipSeq[slot] = seq;
326 this.#membershipValue[slot] = present ? 1 : 0;
327 return present;
328 }
329 return seq < this.#in.length && this.#in[seq] === 1;
330 }
332 /**
333 * The relocation that counts for each moved line: the newest (by priority)
334 * in the set. Two moves made apart can loop lines into each other, so no
335 * start node reaches them; then the oldest relocation on the loop is
336 * ignored, and the next newest of that line counts, until none loop.
337 */
338 #relocations(): Map<LineId, RelocationInfo> {
339 if (this.#relocs) return this.#relocs;
340 this.#takeShared();
341 if (this.#relocs) return this.#relocs;
342 const graph = this.graph;
343 const skeleton = skeletonOf(graph);
344 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
345 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
346 const ignored = new Set<string>();
347 const pick = (n: number): MoveEntry | undefined => {
348 let best: MoveEntry | undefined;
349 for (const e of skeleton.byLine.get(n) ?? []) {
350 if (this.#has(seqOf(e.r.atom)) && !ignored.has(identity(e.r)) && (!best || stronger(e.r, best.r))) best = e;
351 }
352 return best;
353 };
354 // By the moved line's number, in the order its movers come (seq order, then each mover's moves).
355 const relocs = new Map<number, MoveEntry>();
356 for (const mover of skeleton.movers) {
357 if (!this.#has(mover.seq)) continue;
358 for (const n of mover.lines) {
359 if (!relocs.has(n)) relocs.set(n, pick(n)!);
360 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
361 }
362 }
363 // From a node, the next node that matters for loops: a line moved in this set, or a file's start.
364 const hop = (code: number): number => {
365 let c = skeleton.climb(code);
366 while (c >= 0 && !relocs.has(c)) c = skeleton.climb(graph.parentCodeOf(c));
367 return c;
368 };
369 const step = (n: number): number => {
370 const e = relocs.get(n);
371 return hop(e ? e.parent : graph.parentCodeOf(n));
372 };
373 // Two moves made apart can loop lines into each other, so no start node reaches them; then the oldest
374 // relocation on the loop is ignored, and the next newest of that line counts, until none loop.
375 const reaches = new Set<number>();
376 for (const line of [...relocs.keys()]) {
377 for (;;) {
378 const path: number[] = [];
379 const onPath = new Map<number, number>();
380 let cur = line;
381 let loopAt = -1;
382 while (cur >= 0 && !reaches.has(cur)) {
383 const at = onPath.get(cur);
384 if (at !== undefined) {
385 loopAt = at;
386 break;
387 }
388 onPath.set(cur, path.length);
389 path.push(cur);
390 cur = step(cur);
391 }
392 if (loopAt < 0) {
393 for (const l of path) reaches.add(l);
394 break;
395 }
396 let weakest: MoveEntry | undefined;
397 for (const l of path.slice(loopAt)) {
398 const e = relocs.get(l);
399 if (e && (!weakest || stronger(weakest.r, e.r))) weakest = e;
400 }
401 ignored.add(identity(weakest!.r));
402 const next = pick(weakest!.n);
403 if (next) relocs.set(weakest!.n, next);
404 else relocs.delete(weakest!.n);
405 }
406 }
407 this.#relocsN = new Map([...relocs].map(([n, e]) => [n, { r: e.r, parent: e.parent }]));
408 this.#relocs = new Map([...relocs.values()].map((e) => [e.r.line, e.r]));
409 return this.#relocs;
410 }
412 /** The view whose moves this one may take, until it needs them all; then the view it took them from. */
413 #movesFrom: View | undefined;
414 #movesTaken: View | undefined;
416 /**
417 * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the
418 * moves then resolve the same, and every line sits where it sits there. Checked when this view first needs all its
419 * moves, so any caller may ask, and a view that only finds a few lines' files never resolves them.
420 */
421 shareMoves(from: View): void {
422 if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves || this.#relocs) return;
423 this.#movesFrom = from;
424 }
426 /**
427 * Files laid out as another view lays them out (abso Capacity): a draft's view over its base's, for every file the
428 * draft doesn't touch. The caller knows what the draft is; `except` is asked once, when a file is first needed, for
429 * the files the draft touches, or undefined when nothing can be shared (a draft that moves lines). Without it, an
430 * agent's tree, files and blame laid out every file of the project again for each agent.
431 */
432 shareFiles(from: View, except: () => ReadonlySet<string> | undefined): void {
433 if (from.graph !== this.graph || from === this || this.#filesFrom !== undefined) return;
434 this.#filesFrom = { from, except };
435 }
436 #filesFrom: { from: View; except: () => ReadonlySet<string> | undefined } | null | undefined;
438 /**
439 * The files this view's set has, from what the project keeps for a published version (abso Capacity): hasFile
440 * answers from it, not a layout of the file. Collisions resolving an import tried up to seven names, and each one
441 * laid its file out. `paths` is asked once, when first needed; undefined lays files out as before.
442 */
443 knowPaths(paths: () => ReadonlySet<string> | undefined): void {
444 if (this.#pathsFrom === undefined) this.#pathsFrom = paths;
445 }
446 #pathsFrom: (() => ReadonlySet<string> | undefined) | undefined;
447 #knownPaths: ReadonlySet<string> | null | undefined;
448 #filesShared: { from: View; except: ReadonlySet<string> } | null | undefined;
449 #sharedFiles(): { from: View; except: ReadonlySet<string> } | null {
450 if (this.#filesShared === undefined) {
451 const share = this.#filesFrom;
452 const except = share ? share.except() : undefined;
453 this.#filesShared = share && except ? { from: share.from, except } : null;
454 }
455 return this.#filesShared;
456 }
458 #takeShared(): void {
459 const from = this.#movesFrom;
460 if (!from) return;
461 this.#movesFrom = undefined;
462 if (from.#scratchMoves()) return;
463 for (const id of this.graph.movers()) {
464 const seq = seqOf(id);
465 if (this.#has(seq) !== from.#has(seq)) return;
466 }
467 this.#relocs = from.#relocations();
468 this.#relocsN = from.#relocationsN();
469 this.#movesOnDisk = false;
470 this.#movesTaken = from;
471 }
473 /** Moved lines' relocations picked one at a time, before the view resolves them all (null: not moved here). */
474 readonly #picked = new Map<number, MoveEntry | null>();
476 /**
477 * The relocation of moved line n that counts here, as #relocations picks it before any loop: right whenever the
478 * walk that reached n goes on to a file's start, since only lines on a loop have their relocation set aside.
479 */
480 #pickOne(n: number): MoveEntry | undefined {
481 let picked = this.#picked.get(n);
482 if (picked === undefined) {
483 const graph = this.graph;
484 let best: MoveEntry | undefined;
485 for (const e of skeletonOf(graph).byLine.get(n) ?? []) {
486 if (this.#has(seqOf(e.r.atom)) && (!best || graph.comparePriority(e.r.atom, best.r.atom) > 0)) best = e;
487 }
488 this.#picked.set(n, (picked = best ?? null));
489 }
490 return picked ?? undefined;
491 }
493 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
494 #scratchMoves(): boolean {
495 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
496 if (this.#movesOnDisk === undefined) {
497 try {
498 this.#relocations();
499 this.#movesOnDisk = false;
500 } catch (error) {
501 if (!(error instanceof TooManyMoves)) throw error;
502 this.#movesOnDisk = true;
503 }
504 }
505 return this.#movesOnDisk;
506 }
508 /** The relocations by n, with each new parent's code. */
509 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
510 if (this.#relocsN) return this.#relocsN;
511 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
512 for (const [line, r] of this.#relocations())
513 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
514 this.#relocsN = out;
515 return out;
516 }
518 /** The node a line hangs off in this set: where it was written, or where a move put it. */
519 parentOf(line: LineId): NodeId {
520 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
521 if (this.#scratchMoves())
522 return this.graph.withProjectionScratch((scratch) =>
523 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
524 );
525 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
526 if (r) return r.parent;
527 const parent = this.graph.lineParent(line);
528 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
529 return parent;
530 }
532 /** Whether any atom in the set moves lines. */
533 hasMoves(): boolean {
534 return this.#hasMoves;
535 }
537 /** The file a line is in, in this set: the one its chain of parents reaches. */
538 fileOf(line: LineId): string {
539 const n = this.graph.lineN(line);
540 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
541 return this.#fileOfN(n);
542 }
544 #fileOfN(n: number): string {
545 const graph = this.graph;
546 if (!this.#hasMoves) return graph.writtenIn(n);
547 if (this.#scratchMoves())
548 return graph.withProjectionScratch((scratch) => {
549 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
550 let current = graph.nodeOf(n);
551 while (!isStartNode(current)) current = moves.parent(current);
552 return current.slice(1);
553 });
554 return this.#fileOfCode(n);
555 }
557 /** The file a node sits in, in this set: up by where lines were written, through the moves that count here. */
558 #fileOfCode(code: number): string {
559 const graph = this.graph;
560 const skeleton = skeletonOf(graph);
561 if (!this.#relocsN) {
562 // One moved line at a time, until a walk comes back to a line it passed: then moves loop, and are resolved whole.
563 const passed = new Set<number>();
564 let c = code;
565 for (;;) {
566 c = skeleton.climb(c);
567 if (c < 0) return graph.nodeOf(c).slice(1);
568 if (passed.has(c)) break;
569 passed.add(c);
570 const e = this.#pickOne(c);
571 c = e ? e.parent : graph.parentCodeOf(c);
572 }
573 }
574 const relocs = this.#relocationsN();
575 let c = code;
576 for (;;) {
577 c = skeleton.climb(c);
578 if (c < 0) return graph.nodeOf(c).slice(1);
579 const e = relocs.get(c);
580 c = e ? e.parent : graph.parentCodeOf(c);
581 }
582 }
584 /** The lines hanging off a node in this set, in layout order. */
585 #children(code: number): Child[] {
586 const graph = this.graph;
587 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
588 const out: Child[] = [];
589 for (const n of graph.eachChildN(code)) {
590 const seq = graph.writerSeqOf(n);
591 if (!this.#has(seq) || relocs?.has(n)) continue;
592 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
593 }
594 if (relocs) {
595 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
596 // (abso Capacity).
597 if (!this.#movedInto) {
598 this.#movedInto = new Map();
599 for (const [n, { parent }] of relocs) {
600 const into = this.#movedInto.get(parent);
601 if (into) into.push(n);
602 else this.#movedInto.set(parent, [n]);
603 }
604 }
605 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
606 const r = relocs.get(n)!.r;
607 const seq = graph.atom(r.atom).seq;
608 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
609 }
610 }
611 // A line's replacements (runs of atoms that deleted it) first, then the
612 // rest; each group in descending priority (lamport, then seq); lines of
613 // one atom keep k order. A replacement already outranks every insertion
614 // after the line that reads it (it depends on them, or conflicts with
615 // them); the grouping also puts it above a `before` insertion, which
616 // doesn't read the line above, so the new text lands in the replaced
617 // line's place. A moved line ranks like an insertion by the moving atom.
618 if (out.length > 1)
619 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
620 return out;
621 }
623 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
624 *#layoutNodes(start: number): IterableIterator<number> {
625 const graph = this.graph;
626 if (graph.hasOrderedChildren && !this.#hasMoves) {
627 const first = (parent: number, after?: number): number | undefined => {
628 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
629 return undefined;
630 };
631 let n = first(start);
632 while (n !== undefined) {
633 yield n;
634 const child = first(n);
635 if (child !== undefined) {
636 n = child;
637 continue;
638 }
639 let previous = n;
640 for (;;) {
641 const parent = graph.parentCodeOf(previous);
642 const sibling = first(parent, previous);
643 if (sibling !== undefined) {
644 n = sibling;
645 break;
646 }
647 if (parent === start) {
648 n = undefined;
649 break;
650 }
651 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
652 previous = parent;
653 }
654 }
655 return;
656 }
657 const stack: number[] = [];
658 const push = (parent: number): void => {
659 const children = this.#children(parent);
660 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
661 };
662 push(start);
663 while (stack.length) {
664 const n = stack.pop()!;
665 yield n;
666 push(n);
667 }
668 }
670 /** Lay out one file: its line tree from the set's atoms, linearized. */
671 #layout(path: string, complete: boolean): FileState {
672 const graph = this.graph;
673 if (graph.packedLayout && !this.#scratchMoves()) return this.#layoutPacked(path, complete);
674 if (this.#scratchMoves())
675 return graph.withProjectionScratch((scratch) =>
676 this.#layoutResolved(
677 path,
678 complete,
679 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
680 ),
681 );
682 return this.#layoutResolved(path, complete);
683 }
685 /** For each path, the files that lines moved into it were written in: worked out once per view. */
686 #movedFrom: Map<string, Set<number>> | undefined;
687 #movedInFrom(): Map<string, Set<number>> {
688 if (this.#movedFrom) return this.#movedFrom;
689 this.#relocations();
690 if (this.#movesTaken) return (this.#movedFrom = this.#movesTaken.#movedInFrom());
691 const graph = this.graph;
692 const out = new Map<string, Set<number>>();
693 if (this.#hasMoves) {
694 const relocs = this.#relocationsN();
695 const fileOf = (code: number): string => this.#fileOfCode(code);
696 for (const [n, { parent }] of relocs) {
697 const into = fileOf(parent);
698 let from = out.get(into);
699 if (!from) out.set(into, (from = new Set()));
700 from.add(graph.writtenInIndex(n));
701 }
702 }
703 this.#movedFrom = out;
704 return out;
705 }
707 /**
708 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, in the files
709 * its moved-in lines came from, and in the files runs under any of those lines were written in, read a page at a
710 * time; the same tree and order as #layoutResolved, built in memory with no read per line.
711 */
712 #layoutPacked(path: string, complete: boolean): FileState {
713 const graph = this.graph;
714 const attrs = this.#attributes(path);
715 const start = graph.startCodeOf(path);
716 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
717 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
718 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
719 const children = new Map<number, Child[]>();
720 const texts = new Map<number, string | null>();
721 const writers = new Map<number, number>();
722 const places = new Map<number, number>();
723 const deleters = new Map<number, number[]>();
724 // Each atom's lamport once per layout: most lines share a few atoms, and a stored graph reads it from a page.
725 const lamports = new Map<number, number>();
726 const lamportOf = (seq: number): number => {
727 let lamport = lamports.get(seq);
728 if (lamport === undefined) {
729 lamport = graph.lamportOfSeq(seq);
730 lamports.set(seq, lamport);
731 }
732 return lamport;
733 };
734 for (const file of files) {
735 const lineTexts = graph.packedTexts(file);
736 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
737 const text = lineTexts.next().value as string | null;
738 if (!this.#has(seq)) continue;
739 const moved = relocs?.get(n);
740 let at = parent;
741 let child: Child = { n, replaces, lamport: lamportOf(seq), seq, k };
742 if (moved) {
743 const mover = graph.atom(moved.r.atom).seq;
744 child = { n, replaces: 0, lamport: lamportOf(mover), seq: mover, k: moved.r.k };
745 at = moved.parent;
746 }
747 const list = children.get(at);
748 if (list) list.push(child);
749 else children.set(at, [child]);
750 texts.set(n, text);
751 writers.set(n, seq);
752 places.set(n, k);
753 }
754 for (const [n, deleter] of graph.packedDeletes(file)) {
755 if (!this.#has(deleter)) continue;
756 const by = deleters.get(n);
757 if (by) by.push(deleter);
758 else deleters.set(n, [deleter]);
759 }
760 // Runs written elsewhere under this file's lines follow them; the loop reads their files too.
761 for (const [parent, into] of graph.packedCrossings(file)) if (texts.has(parent)) files.add(into);
762 }
763 const order = (a: Child, b: Child) =>
764 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
765 const priority = (a: number, b: number) => lamportOf(a) - lamportOf(b) || a - b;
766 const seq: number[] = [];
767 const vis: number[] = [];
768 const visText: (string | null)[] = [];
769 const visWriter: number[] = [];
770 const visK: number[] = [];
771 const seqWriter: number[] = [];
772 const seqK: number[] = [];
773 const deletedBy = new Map<number, readonly number[]>();
774 const stack: number[] = [];
775 const push = (code: number) => {
776 const list = children.get(code);
777 if (!list) return;
778 if (list.length > 1) list.sort(order);
779 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
780 };
781 push(start);
782 while (stack.length) {
783 const n = stack.pop()!;
784 const by = deleters.get(n);
785 if (by) {
786 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
787 } else {
788 vis.push(n);
789 visText.push(texts.get(n) ?? null);
790 visWriter.push(writers.get(n)!);
791 visK.push(places.get(n)!);
792 }
793 if (complete) {
794 seq.push(n);
795 seqWriter.push(writers.get(n)!);
796 seqK.push(places.get(n)!);
797 }
798 push(n);
799 }
800 return {
801 attrs,
802 complete,
803 seq: Int32Array.from(seq),
804 vis: Int32Array.from(vis),
805 deletedBy,
806 visText,
807 visWriter: Int32Array.from(visWriter),
808 visK: Int32Array.from(visK),
809 ...(complete ? { seqWriter: Int32Array.from(seqWriter), seqK: Int32Array.from(seqK) } : {}),
810 };
811 }
813 #attributes(path: string): FileAttrs {
814 const graph = this.graph;
815 // For each attribute, the highest-priority setter in the set wins.
816 const setters = new Map<string, { id: AtomId; value: string | null }>();
817 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
818 if (graph.packedFiles) {
819 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
820 if (!this.#has(seq)) continue;
821 const id = graph.idOfSeq(seq);
822 const best = setters.get(name);
823 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
824 }
825 return {
826 exists: setters.get("exists")?.value === "1",
827 exec: setters.get("exec")?.value === "1",
828 link: setters.get("link")?.value ?? null,
829 blob: setters.get("blob")?.value ?? null,
830 };
831 }
832 for (const id of graph.eachAtomIn(path)) {
833 if (!this.#has(graph.atom(id).seq)) continue;
834 for (const a of graph.atom(id).attrs ?? []) {
835 if (a.file !== path) continue;
836 const best = setters.get(a.name);
837 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
838 }
839 }
841 return {
842 exists: setters.get("exists")?.value === "1",
843 exec: setters.get("exec")?.value === "1",
844 link: setters.get("link")?.value ?? null,
845 blob: setters.get("blob")?.value ?? null,
846 };
847 }
849 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
850 const graph = this.graph;
851 const attrs = this.#attributes(path);
852 const seq: number[] = [];
853 const vis: number[] = [];
854 const deletedBy = new Map<number, readonly number[]>();
856 const start = graph.startCodeOf(path);
857 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
858 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
859 let deleted = false;
860 const by: number[] = [];
861 for (const deleter of graph.eachDeleterSeqOf(n)) {
862 if (!this.#has(deleter)) continue;
863 deleted = true;
864 if (!complete) break;
865 by.push(deleter);
866 }
867 if (deleted) {
868 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
869 } else vis.push(n);
870 if (complete) seq.push(n);
871 }
873 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
874 }
876 get #known(): string[] {
877 if (!this.#knownList) {
878 const known = new Set<string>();
879 if (this.#stable) {
880 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
881 } else {
882 for (let seq = 0; seq < this.#in.length; seq++)
883 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
884 }
885 this.#knownList = [...known].sort();
886 }
887 return this.#knownList;
888 }
890 /** Files with at least one visible line, sorted. */
891 paths(): string[] {
892 if (this.#stable) {
893 const paths: string[] = [];
894 for (const path of this.graph.knownFiles()) {
895 if (this.hasFile(path)) paths.push(path);
896 else this.#files.delete(path);
897 }
898 return paths.sort();
899 }
900 return this.#known.filter((p) => this.hasFile(p));
901 }
903 /** Every file the set has ever written a line in, including fully deleted ones. */
904 knownPaths(): string[] {
905 return [...this.#known];
906 }
908 /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */
909 fileOfNumber(n: number): string {
910 return this.#fileOfN(n);
911 }
913 /** How many visible lines a file has. */
914 visibleCount(path: string): number {
915 return this.#file(path).vis.length;
916 }
918 /** Whether the file exists in this projection (has a visible line). */
919 hasFile(path: string): boolean {
920 if (!this.#files.has(path)) {
921 // A file the draft doesn't touch exists as it does in the base; a published version's files are kept.
922 const shared = this.#filesFrom === undefined ? null : this.#sharedFiles();
923 if (shared && !shared.except.has(path)) return shared.from.hasFile(path);
924 if (this.#pathsFrom !== undefined) {
925 if (this.#knownPaths === undefined) this.#knownPaths = this.#pathsFrom() ?? null;
926 if (this.#knownPaths) return this.#knownPaths.has(path);
927 }
928 }
929 const attrs = this.attrs(path);
930 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
931 }
933 /** A file's attributes: kept while empty, executable, a link's target. */
934 attrs(path: string): FileAttrs {
935 return this.#files.get(path)?.attrs ?? this.#attributes(path);
936 }
938 /** The projected text of a file ("" if it has no visible lines). */
939 text(path: string): string {
940 if (this.#textCache?.path === path) return this.#textCache.text;
941 const { vis, visText } = this.#file(path);
942 const lines: string[] = new Array(vis.length);
943 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
944 const text = joinLines(lines);
945 this.#textCache = { path, text };
946 return text;
947 }
949 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
950 sameText(path: string, other: ReadView): boolean {
951 if (!(other instanceof View)) {
952 const a = this.lines(path),
953 b = other.lines(path);
954 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
955 }
956 const a = this.#file(path).vis;
957 const b = other.#file(path).vis;
958 if (a.length !== b.length) return false;
959 for (let i = 0; i < a.length; i++)
960 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
961 return true;
962 }
964 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
965 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
966 }
968 /** Visible lines without retaining their text in the view cache. */
969 *visibleLines(path: string): IterableIterator<VisibleLine> {
970 const graph = this.graph;
971 for (const n of this.#file(path).vis)
972 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
973 }
975 /** Atom-building line handles; text is loaded only when requested. */
976 buildLines(path: string): readonly VisibleLine[] {
977 const graph = this.graph;
978 // Texts and writers the packed layout already holds are not read again (abso Capacity).
979 const { vis, visText, visWriter, visK } = this.#file(path);
980 const lines: VisibleLine[] = new Array(vis.length);
981 for (let i = 0; i < vis.length; i++) {
982 const n = vis[i]!;
983 const packed = visText?.[i];
984 lines[i] = {
985 id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
986 textChunks: () => graph.textChunks(n),
987 get text() {
988 return packed ?? graph.textOf(n);
989 },
990 atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
991 };
992 }
993 return lines;
994 }
996 /** Visible lines with their ids. */
997 lines(path: string): readonly VisibleLine[] {
998 if (this.#linesCache?.path === path) return this.#linesCache.lines;
999 const graph = this.graph;
1000 const { vis, visText, visWriter, visK } = this.#file(path);
1001 const lines: VisibleLine[] = new Array(vis.length);
1002 for (let i = 0; i < vis.length; i++) {
1003 const n = vis[i]!;
1004 lines[i] = {
1005 id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
1006 text: visText?.[i] ?? graph.textOf(n),
1007 atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
1008 };
1010 this.#linesCache = { path, lines };
1011 return lines;
1014 /** The full linearized sequence of a file, tombstones included. */
1015 sequence(path: string): readonly SeqLine[] {
1016 if (this.#seqCache?.path === path) return this.#seqCache.seq;
1017 const graph = this.graph;
1018 const f = this.#file(path, true);
1019 const out: SeqLine[] = new Array(f.seq.length);
1020 // Ids and writers from the packed layout, and each text read only when asked (abso Capacity): callers walk a few
1021 // lines of a file's history, and reading every line's text was a row each on a stored graph.
1022 const { seqWriter, seqK } = f;
1023 for (let i = 0; i < f.seq.length; i++) {
1024 const n = f.seq[i]!;
1025 const by = f.deletedBy.get(i);
1026 const writer = seqWriter ? seqWriter[i]! : graph.writerSeqOf(n);
1027 let text: string | undefined;
1028 out[i] = {
1029 id: seqWriter && seqK ? lineId(graph.idOfSeq(writer), seqK[i]!) : graph.lineIdOf(n),
1030 get text() {
1031 text ??= graph.textOf(n);
1032 return text;
1033 },
1034 atom: graph.idOfSeq(writer),
1035 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
1036 visible: by === undefined,
1037 };
1039 this.#seqCache = { path, seq: out };
1040 return out;
1043 /** Two visible neighbours without retaining the file's historical sequence. */
1044 visibleNeighbours(path: string, line: LineId): LineId[] {
1045 const graph = this.graph;
1046 const target = graph.lineN(line);
1047 const start = graph.startCodeOf(path);
1048 if (target < 0 || start === undefined) return [];
1049 const scan = (nodes: Iterable<number>): LineId[] => {
1050 let previous: LineId | undefined;
1051 let found = false;
1052 for (const n of nodes) {
1053 if (n === target) {
1054 found = true;
1055 continue;
1057 let deleted = false;
1058 for (const seq of graph.eachDeleterSeqOf(n))
1059 if (this.#has(seq)) {
1060 deleted = true;
1061 break;
1063 if (deleted) continue;
1064 const id = graph.lineIdOf(n);
1065 if (found) return previous === undefined ? [id] : [previous, id];
1066 previous = id;
1068 return found && previous !== undefined ? [previous] : [];
1069 };
1070 if (this.#scratchMoves())
1071 return graph.withProjectionScratch((scratch) =>
1072 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
1073 );
1074 return scan(this.#layoutNodes(start));
1077 /** Index of a line in `sequence(path)`, or -1. */
1078 sequenceIndex(path: string, line: LineId): number {
1079 const f = this.#file(path, true);
1080 if (!f.seqIndex) {
1081 f.seqIndex = new Map();
1082 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
1084 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
1087 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
1088 lineNumber(path: string, line: LineId): number {
1089 return this.lineNumberOf(path, this.graph.lineN(line));
1092 /** lineNumber by the line's number, with no lookup of its id. */
1093 lineNumberOf(path: string, n: number): number {
1094 const f = this.#file(path);
1095 if (!f.visIndex) {
1096 f.visIndex = new Map();
1097 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
1099 return f.visIndex.get(n) ?? -1;
1102 /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */
1103 visibleWriters(path: string): number[] {
1104 const graph = this.graph;
1105 const { vis, visWriter } = this.#file(path);
1106 // The packed layout keeps them (abso Capacity): looking each up again read a page per few lines on a stored graph.
1107 if (visWriter) return Array.from(visWriter);
1108 return Array.from(vis, (n) => graph.writerSeqOf(n));
1111 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
1112 files(): Record<string, string> {
1113 const out: Record<string, string> = {};
1114 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
1115 return out;
1118 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
1119 blobs(): Record<string, string> {
1120 // From attributes alone (abso Capacity): a file with a blob exists, so no file is laid out to find them. Going
1121 // through paths() laid out every file in the set, and shared() asks for blobs on every call.
1122 const out: Record<string, string> = {};
1123 const candidates = this.#stable ? [...this.graph.knownFiles()].sort() : this.#known;
1124 for (const path of candidates) {
1125 const blob = this.attrs(path).blob;
1126 if (blob !== null) out[path] = blob;
1128 return out;
1131 /**
1132 * About how many bytes of retained state this view costs (#46). This uses
1133 * approximate ownership costs for containers and wrappers, not V8 heap
1134 * measurements. Graph-owned strings and records count only as references.
1135 * This method only inspects already-created state: it does not lay out files,
1136 * populate lazy caches, enumerate the graph, or count temporary traversal
1137 * containers and shared empty singleton payloads as retained view state.
1138 */
1139 weight(seen?: Set<object>): number {
1140 let n = this.#in.byteLength;
1141 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
1142 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
1143 n += MAP_HEADER_BYTES; // #files exists from construction.
1144 if (this.#stable) n += this.#stable.retainedBytes;
1145 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
1146 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
1147 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
1148 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
1149 n += MAP_ENTRY_BYTES * this.#picked.size;
1150 for (const f of this.#files.values()) {
1151 n += MAP_ENTRY_BYTES;
1152 if (f !== NO_FILE) {
1153 // A layout another view counted already (`seen`, across a cache's views) isn't counted again.
1154 if (!seen?.has(f)) n += layoutBytes(f);
1155 seen?.add(f);
1156 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
1157 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
1160 if (this.#linesCache)
1161 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
1162 if (this.#seqCache) {
1163 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
1164 for (const line of this.#seqCache.seq)
1165 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
1167 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
1168 return n;
1171 #file(path: string, complete = false): FileState {
1172 let state = this.#files.get(path);
1173 if (!state || (complete && !state.complete)) {
1174 const shared = this.#filesFrom === undefined ? null : this.#sharedFiles();
1175 if (shared && !shared.except.has(path)) state = shared.from.#file(path, complete);
1176 else state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
1177 this.#files.set(path, state);
1179 return state;
1183/** The files of a closed set, path -> text. */
1184export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
1185 return new View(graph, set).files();
1188/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
1189export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
1190 if (isStartNode(node)) return 0;
1191 const i = view.sequenceIndex(path, node);
1192 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
1193 return i + 1;