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