@gmod/gfa-tabix 0.0.0-stage → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1607 @@
1
+ import { RegionTooLargeError, bpString, panSNHaplotypeOrSample, panSNMatchesPrefix, } from "./util.js";
2
+ import { SKIPPED } from "./walkChunk.js";
3
+ import { ATTACH_BP, attachesOwnSteps, departureStretch, } from "./walkDeparture.js";
4
+ import { GAP_KINDS, walkGaps } from "./walkGaps.js";
5
+ // Whether a step's id is a placeholder's: a run of an unloaded piece's
6
+ // steps off R, of known bp and no node identity
7
+ export const isPlaceholder = (id) => id < 0;
8
+ function integerTag(line, tag) {
9
+ const match = new RegExp(`(?:^|\\t)${tag}:i:(\\d+)`).exec(line);
10
+ return match ? +match[1] : undefined;
11
+ }
12
+ const INTEGER_TAGS = [
13
+ 'format',
14
+ 'tile',
15
+ 'revisited',
16
+ 'leftout',
17
+ ];
18
+ function stringTag(line, tag) {
19
+ var _a;
20
+ return (_a = new RegExp(`(?:^|\\t)${tag}:Z:([^\\t]+)`).exec(line)) === null || _a === void 0 ? void 0 : _a[1];
21
+ }
22
+ /**
23
+ * What a walk file's header states: a `#walks` line with the format and the
24
+ * tile size, `format:i:8\ttile:i:65536`, a `#reference\tGRCh38` line naming
25
+ * the reference sample, a `#haplotype\tHG002#1` line per other haplotype with
26
+ * rows and a `#hole` line per stretch of a reference sequence no line of the
27
+ * reference covers
28
+ */
29
+ export function walkHeader(lines) {
30
+ var _a, _b;
31
+ const header = {
32
+ references: [],
33
+ haplotypes: [],
34
+ holes: [],
35
+ };
36
+ for (const line of lines) {
37
+ const [key, value = '', start = '', end = ''] = line.split('\t');
38
+ if (key === '#reference') {
39
+ header.references.push(value);
40
+ }
41
+ else if (key === '#haplotype') {
42
+ header.haplotypes.push(value);
43
+ }
44
+ else if (key === '#hole') {
45
+ header.holes.push({ refName: value, start: +start, end: +end });
46
+ }
47
+ else if (key === '#walks') {
48
+ for (const tag of INTEGER_TAGS) {
49
+ const stated = integerTag(line, tag);
50
+ if (stated !== undefined) {
51
+ (_a = header[tag]) !== null && _a !== void 0 ? _a : (header[tag] = stated);
52
+ }
53
+ }
54
+ const graph = stringTag(line, 'graph');
55
+ if (graph !== undefined) {
56
+ (_b = header.graph) !== null && _b !== void 0 ? _b : (header.graph = graph);
57
+ }
58
+ }
59
+ }
60
+ return header;
61
+ }
62
+ // Which walks a cut decodes: the reference's, and those `wanted` names by
63
+ // PanSN prefix at sample or haplotype depth; undefined decodes every one
64
+ export function walkNameFilter(wanted, referenceHaplotype) {
65
+ return wanted === undefined || wanted.length === 0
66
+ ? undefined
67
+ : (name) => panSNMatchesPrefix(name, referenceHaplotype) ||
68
+ wanted.some(prefix => panSNMatchesPrefix(name, prefix));
69
+ }
70
+ /**
71
+ * The walks a cut on `refName` decodes: its reference's and those `wanted`
72
+ * names. A pggb P-line names a reference with no haplotype field
73
+ * (`chm13#chr1`), whose walks are its sample's.
74
+ */
75
+ export function walksKept(wanted, refName) {
76
+ return walkNameFilter(wanted, panSNHaplotypeOrSample(refName));
77
+ }
78
+ /**
79
+ * Each line's pieces in runs of consecutive piece numbers, in piece order,
80
+ * the lines in the order `pieces` first names them: a WalkRun's rows, and a
81
+ * run of walkRuns.ts's pieces
82
+ */
83
+ export function consecutivePieces(pieces) {
84
+ const byPath = new Map();
85
+ for (const row of pieces) {
86
+ const key = `${row.name}\t${row.fragStart}`;
87
+ const list = byPath.get(key);
88
+ if (list) {
89
+ list.push(row);
90
+ }
91
+ else {
92
+ byPath.set(key, [row]);
93
+ }
94
+ }
95
+ const runs = [];
96
+ for (const line of byPath.values()) {
97
+ line.sort((a, b) => a.piece - b.piece);
98
+ let from = 0;
99
+ for (let i = 1; i <= line.length; i++) {
100
+ if (i === line.length || line[i].piece !== line[i - 1].piece + 1) {
101
+ runs.push(line.slice(from, i));
102
+ from = i;
103
+ }
104
+ }
105
+ }
106
+ return runs;
107
+ }
108
+ export function joinPieces(rows) {
109
+ return consecutivePieces(rows).map(decodeRun);
110
+ }
111
+ function decodeRun(pieces) {
112
+ var _a;
113
+ const n = pieces.reduce((sum, p) => sum + p.n, 0);
114
+ const ids = new Int32Array(n);
115
+ const rev = new Uint8Array(n);
116
+ const refStarts = new Float64Array(n).fill(Number.NaN);
117
+ const against = new Uint8Array(n);
118
+ const pieceStarts = [];
119
+ const pieceChunks = [];
120
+ const bp = pieces.some(p => p.steps.bp)
121
+ ? new Int32Array(n).fill(-1)
122
+ : undefined;
123
+ const unloaded = [];
124
+ const own = [];
125
+ let at = 0;
126
+ for (const p of pieces) {
127
+ for (const steps of (_a = p.own) !== null && _a !== void 0 ? _a : []) {
128
+ own.push({ ...steps, from: at + steps.from, to: at + steps.to });
129
+ }
130
+ if (at > 0) {
131
+ pieceStarts.push(at);
132
+ }
133
+ pieceChunks.push(p.chunkStart);
134
+ if (p.steps.bp) {
135
+ bp === null || bp === void 0 ? void 0 : bp.set(p.steps.bp, at);
136
+ }
137
+ if (p.abridged) {
138
+ unloaded.push({ from: at, to: at + p.n, piece: p.abridged });
139
+ }
140
+ ids.set(p.steps.ids, at);
141
+ rev.set(p.steps.rev, at);
142
+ if (p.steps.refStarts) {
143
+ refStarts.set(p.steps.refStarts, at);
144
+ }
145
+ if (p.steps.against) {
146
+ against.set(p.steps.against, at);
147
+ }
148
+ at += p.n;
149
+ }
150
+ const first = pieces[0];
151
+ return {
152
+ name: first.name,
153
+ fragStart: first.fragStart,
154
+ hapOffset: first.hapOffset,
155
+ firstPiece: first.piece,
156
+ pieceStarts,
157
+ pieceChunks,
158
+ ids,
159
+ rev,
160
+ refStarts,
161
+ against,
162
+ ...(bp ? { bp } : {}),
163
+ ...(unloaded.length > 0 ? { unloaded } : {}),
164
+ ...(own.length > 0 ? { own } : {}),
165
+ };
166
+ }
167
+ // A direct-mapped memo of the last key seen per slot, in front of a Map or
168
+ // Set that most steps would ask the same question of again
169
+ const MEMO_SLOTS = 1 << 16;
170
+ const MEMO_MASK = MEMO_SLOTS - 1;
171
+ const memoKeys = () => new Float64Array(MEMO_SLOTS).fill(Number.NaN);
172
+ // Whether `memo` held the link, which it holds from now on
173
+ function linkHeld(memo, a, b) {
174
+ const slot = a & MEMO_MASK;
175
+ const same = memo.from[slot] === a;
176
+ const held = same && (memo.to[2 * slot] === b || memo.to[2 * slot + 1] === b);
177
+ if (!held) {
178
+ memo.to[2 * slot + 1] = same ? memo.to[2 * slot] : Number.NaN;
179
+ memo.to[2 * slot] = b;
180
+ memo.from[slot] = a;
181
+ }
182
+ return held;
183
+ }
184
+ // A number below 1e12 in absolute value as a key that sorts as its decimal
185
+ // string does: '-' sorts before every digit, and of two digit strings the
186
+ // one with the lower digits, padded right to 12, sorts first, the shorter on
187
+ // a tie
188
+ function stringOrder(x) {
189
+ const m = Math.abs(x);
190
+ let digits = 1;
191
+ let pad = 1e11;
192
+ while (m >= 10 ** digits) {
193
+ digits++;
194
+ pad /= 10;
195
+ }
196
+ return (x < 0 ? 0 : 2 ** 48) + (m * pad * 16 + digits);
197
+ }
198
+ // Each link between two kept nodes once, as its two handles, in the order
199
+ // its L line, source, strand, target and strand joined by tabs, sorts as a
200
+ // string. A tab sorts below every character of the fields, so that is the
201
+ // order of each id as a string, then of its strand, '+' first
202
+ function linkLines(links, kept) {
203
+ const distinct = new PairSet();
204
+ const chosen = [];
205
+ const sources = [];
206
+ const targets = [];
207
+ for (let i = 0; i < links.length; i += 2) {
208
+ const a = links[i];
209
+ const b = links[i + 1];
210
+ const source = Math.floor(a / 2);
211
+ const target = Math.floor(b / 2);
212
+ if (kept.has(source) && kept.has(target) && distinct.add(a, b)) {
213
+ chosen.push(i);
214
+ sources.push(2 * stringOrder(source) + (a & 1));
215
+ targets.push(2 * stringOrder(target) + (b & 1));
216
+ }
217
+ }
218
+ const order = Array.from(chosen.keys()).sort((x, y) => sources[x] - sources[y] || targets[x] - targets[y]);
219
+ const lines = [];
220
+ for (const k of order) {
221
+ lines.push(links[chosen[k]], links[chosen[k] + 1]);
222
+ }
223
+ return lines;
224
+ }
225
+ // Pairs of numbers, each exact as a double, by open addressing, so that a
226
+ // cut's millions of links are no Set apiece
227
+ class PairSet {
228
+ constructor() {
229
+ this.keys = new Float64Array(2048).fill(Number.NaN);
230
+ this.size = 0;
231
+ }
232
+ // whether the pair is new, which the set holds from now on
233
+ add(a, b) {
234
+ if (4 * (this.size + 1) > this.keys.length) {
235
+ const held = this.keys;
236
+ this.keys = new Float64Array(2 * held.length).fill(Number.NaN);
237
+ this.size = 0;
238
+ for (let k = 0; k < held.length; k += 2) {
239
+ if (!Number.isNaN(held[k])) {
240
+ this.add(held[k], held[k + 1]);
241
+ }
242
+ }
243
+ }
244
+ const { keys } = this;
245
+ const mask = keys.length / 2 - 1;
246
+ const mixed = Math.imul(a | 0, 0x9e3779b1) ^ (b | 0);
247
+ let slot = Math.imul(mixed ^ (mixed >>> 16), 0x85ebca6b) & mask;
248
+ while (!Number.isNaN(keys[2 * slot]) &&
249
+ !(keys[2 * slot] === a && keys[2 * slot + 1] === b)) {
250
+ slot = (slot + 1) & mask;
251
+ }
252
+ const fresh = Number.isNaN(keys[2 * slot]);
253
+ if (fresh) {
254
+ keys[2 * slot] = a;
255
+ keys[2 * slot + 1] = b;
256
+ this.size++;
257
+ }
258
+ return fresh;
259
+ }
260
+ }
261
+ // Links each step from `from` to `to` to the one before it, through `add`
262
+ // where `memo` has not held the link
263
+ function linkSteps(ids, rev, from, to, memo, add) {
264
+ const first = Math.max(from, 0);
265
+ const end = Math.min(to, ids.length - 1);
266
+ let before = first <= end ? ids[first] : SKIPPED;
267
+ let a = first <= end ? before * 2 + rev[first] : 0;
268
+ for (let k = first + 1; k <= end; k++) {
269
+ const id = ids[k];
270
+ const b = id * 2 + rev[k];
271
+ if (before !== SKIPPED && id !== SKIPPED && !linkHeld(memo, a, b)) {
272
+ add(a, b);
273
+ }
274
+ before = id;
275
+ a = b;
276
+ }
277
+ }
278
+ // The loops over a run's steps that a cut runs once per walk, each a
279
+ // function of its own so that it is compiled once and stays compiled
280
+ // bp of the steps before each, and after the last
281
+ function bpBefore(ids, stated, length) {
282
+ const out = new Float64Array(ids.length + 1);
283
+ for (let i = 0; i < ids.length; i++) {
284
+ const bp = stated === undefined ? -1 : stated[i];
285
+ out[i + 1] = out[i] + (bp < 0 ? length(ids[i]) : bp);
286
+ }
287
+ return out;
288
+ }
289
+ // The first and last steps whose pass lies over `start`-`end`, and the
290
+ // stretch those passes cover
291
+ function stepsOver(refStarts, bp, start, end) {
292
+ let first = -1;
293
+ let last = -1;
294
+ let lo = Infinity;
295
+ let hi = -Infinity;
296
+ for (let i = 0; i < refStarts.length; i++) {
297
+ const at = refStarts[i];
298
+ const to = at + bp[i + 1] - bp[i];
299
+ if (at < end && to > start) {
300
+ first = first < 0 ? i : first;
301
+ last = i;
302
+ lo = at < lo ? at : lo;
303
+ hi = to > hi ? to : hi;
304
+ }
305
+ }
306
+ return { first, last, lo, hi };
307
+ }
308
+ function keepSteps(ids, first, last, kept, lastKept) {
309
+ for (let i = first; i <= last; i++) {
310
+ const id = ids[i];
311
+ const slot = id & MEMO_MASK;
312
+ if (lastKept[slot] !== id) {
313
+ lastKept[slot] = id;
314
+ kept.add(id);
315
+ }
316
+ }
317
+ }
318
+ // Writes each id's index to `into` from `at`, through `indexOf` where the
319
+ // memo does not hold it
320
+ function indexSteps(ids, into, at, lastId, lastIndex, indexOf) {
321
+ for (let j = 0; j < ids.length; j++) {
322
+ const id = ids[j];
323
+ const slot = id & MEMO_MASK;
324
+ if (lastId[slot] !== id) {
325
+ lastId[slot] = id;
326
+ lastIndex[slot] = indexOf(id);
327
+ }
328
+ into[at + j] = lastIndex[slot];
329
+ }
330
+ }
331
+ function firstOnR(refStarts, from, to) {
332
+ let i = from;
333
+ while (i < to && Number.isNaN(refStarts[i])) {
334
+ i++;
335
+ }
336
+ return i < to ? i : -1;
337
+ }
338
+ function lastOnR(refStarts, from, to) {
339
+ let i = to - 1;
340
+ while (i >= from && Number.isNaN(refStarts[i])) {
341
+ i--;
342
+ }
343
+ return i >= from ? i : -1;
344
+ }
345
+ // Adds to `out` each two consecutive steps on R, from step `from` to `to`,
346
+ // that do not follow R: the one before and the one after
347
+ function departingPairs(refStarts, against, bp, from, to, squeeze, out) {
348
+ let last = -1;
349
+ for (let i = from; i < to; i++) {
350
+ const start = refStarts[i];
351
+ if (!Number.isNaN(start)) {
352
+ if (last >= 0) {
353
+ const leaveReversed = against[last] === 1;
354
+ const rejoinReversed = against[i] === 1;
355
+ const leavePos = leaveReversed
356
+ ? refStarts[last]
357
+ : refStarts[last] + bp[last + 1] - bp[last];
358
+ const rejoinPos = rejoinReversed ? start + bp[i + 1] - bp[i] : start;
359
+ const ownBp = bp[i] - bp[last + 1];
360
+ const adjacent = ownBp === 0 &&
361
+ leaveReversed === rejoinReversed &&
362
+ (leavePos === rejoinPos || squeeze(leavePos) === squeeze(rejoinPos));
363
+ if (!adjacent) {
364
+ out.push(last, i);
365
+ }
366
+ }
367
+ last = i;
368
+ }
369
+ }
370
+ }
371
+ export const edgeKey = (name, pos, reversed, hap) => `${name}\t${pos}\t${reversed ? '-' : '+'}\t${hap}`;
372
+ /**
373
+ * The cut a window draws from its walks: the reference inside the window plus
374
+ * its context, the drawn stretch, and each run from its first step on that
375
+ * stretch to its last. The drawn stretch is the window and its context,
376
+ * widened to the reference nodes over them, whole, and to every pass of a
377
+ * run's step over them. Nothing is followed past the drawn stretch and no fragment runs on
378
+ * through nodes other walks kept, so a haplotype's fragment does not depend on
379
+ * which others are cut.
380
+ *
381
+ * A contained cut splits a run wherever it steps onto the reference off the
382
+ * drawn stretch. Each piece between those steps that steps on the stretch is
383
+ * kept from its first such step to its last, so a detour that comes back is
384
+ * kept whole, and `context` bp of the walk past either end. At AMY1
385
+ * haplotypes go from a 4 kb window to the other copies and back: the cut
386
+ * above keeps 9,928 nodes there, the contained cut 182.
387
+ *
388
+ * Each departure comes back once: those inside one piece are computed from
389
+ * its steps, and kept where their stretch overlaps the drawn stretch; those
390
+ * between pieces, in different tiles or across W lines, are `records`, every
391
+ * one of which comes back, as the reader read them over the window and its
392
+ * context. A computed departure's leave and rejoin passes come from the ref
393
+ * rows the cut read, 0 for a node it places off R. A departure within
394
+ * `attachBp` of own sequence that leaves or rejoins on `drawn`, the base of
395
+ * its leave step or of its rejoin step beside the breakpoint lying there,
396
+ * gets its own steps, a 0 bp step included: a record from the leave and
397
+ * rejoin pieces of `runs` or of `attach`, which give nothing else.
398
+ * `unattached` lists those records lacking either piece, whose tiles the
399
+ * reader fetches into `attach`. Any other departure states its ends and its
400
+ * own bp alone.
401
+ */
402
+ export function walkCut(readRuns, nodes, refName, records, options = {}) {
403
+ var _a, _b;
404
+ const { squeeze = (bp) => bp, attach = [], links: linked = true, } = options;
405
+ const { windowStart, windowEnd, passesOf, before, attaches, breakpoint, runs, spans, } = walkSpans(readRuns, nodes, options);
406
+ // the links the steps returned walk, as pairs of handles, each once
407
+ const links = [];
408
+ const linkedTo = new PairSet();
409
+ const linkMemo = {
410
+ from: memoKeys(),
411
+ to: new Float64Array(2 * MEMO_SLOTS).fill(Number.NaN),
412
+ };
413
+ const link = (a, b) => {
414
+ if (linked && linkedTo.add(a, b)) {
415
+ links.push(a, b);
416
+ }
417
+ };
418
+ // links each step of `run` from `from` to `to` to the one before it
419
+ const walk = (run, from, to) => {
420
+ if (linked) {
421
+ linkSteps(run.ids, run.rev, from, to, linkMemo, link);
422
+ }
423
+ };
424
+ const kept = new Set();
425
+ for (const [id, node] of nodes) {
426
+ if (node.onWindow) {
427
+ kept.add(id);
428
+ }
429
+ }
430
+ const lastKept = memoKeys();
431
+ for (const span of spans) {
432
+ keepSteps(span.run.ids, span.first, span.last, kept, lastKept);
433
+ }
434
+ const runEnd = (run) => run.hapOffset + before(run)[run.ids.length];
435
+ // whether a fragment holds step `i` of `run`; a departure's own steps are
436
+ // linked to its leave step and to its rejoin step where one does
437
+ const spansOf = new Map();
438
+ for (const span of spans) {
439
+ const held = (_a = spansOf.get(span.run)) !== null && _a !== void 0 ? _a : [];
440
+ spansOf.set(span.run, held);
441
+ held.push(span);
442
+ }
443
+ const returned = (run, i) => {
444
+ var _a;
445
+ return ((_a = spansOf.get(run)) === null || _a === void 0 ? void 0 : _a.some(({ first, last }) => first <= i && i <= last)) ===
446
+ true;
447
+ };
448
+ const fragments = [];
449
+ for (const { run, first, last } of spans) {
450
+ const { ids, rev } = run;
451
+ const bp = before(run);
452
+ walk(run, first, last);
453
+ const hapStart = run.hapOffset + bp[first];
454
+ const hapEnd = run.hapOffset + bp[last + 1];
455
+ const held = ((_b = run.unloaded) !== null && _b !== void 0 ? _b : []).filter(({ from, to }) => from <= last && to > first);
456
+ const unloadedSteps = held.reduce((sum, { from, to }) => sum + Math.min(to, last + 1) - Math.max(from, first), 0);
457
+ fragments.push({
458
+ name: run.name,
459
+ fragStart: run.fragStart,
460
+ hapStart,
461
+ hapEnd,
462
+ ids: ids.subarray(first, last + 1),
463
+ rev: rev.subarray(first, last + 1),
464
+ refStarts: run.refStarts.subarray(first, last + 1),
465
+ against: run.against.subarray(first, last + 1),
466
+ trimmedBefore: hapStart - run.hapOffset,
467
+ trimmedAfter: runEnd(run) - hapEnd,
468
+ ...(held.length > 0
469
+ ? { abridged: held.map(u => u.piece), unloadedSteps }
470
+ : {}),
471
+ });
472
+ }
473
+ const departures = [];
474
+ const attached = new Map();
475
+ const markAttached = (run, from, to) => {
476
+ var _a;
477
+ const marks = (_a = attached.get(run)) !== null && _a !== void 0 ? _a : new Set();
478
+ attached.set(run, marks);
479
+ for (let k = from; k < to; k++) {
480
+ marks.add(k);
481
+ const id = run.ids[k];
482
+ const slot = id & MEMO_MASK;
483
+ if (lastKept[slot] !== id) {
484
+ lastKept[slot] = id;
485
+ kept.add(id);
486
+ }
487
+ }
488
+ };
489
+ const unloadedIn = (run, from, to) => {
490
+ var _a;
491
+ return ((_a = run.unloaded) !== null && _a !== void 0 ? _a : [])
492
+ .filter(u => u.from < to && u.to > from)
493
+ .map(u => u.piece);
494
+ };
495
+ const pairs = [];
496
+ for (const run of runs) {
497
+ if (run.name === refName) {
498
+ continue;
499
+ }
500
+ const { ids, rev, refStarts, against } = run;
501
+ const bp = before(run);
502
+ const bounds = pieceBounds(run);
503
+ for (let p = 0; p + 1 < bounds.length; p++) {
504
+ pairs.length = 0;
505
+ departingPairs(refStarts, against, bp, bounds[p], bounds[p + 1], squeeze, pairs);
506
+ for (let q = 0; q < pairs.length; q += 2) {
507
+ const last = pairs[q];
508
+ const i = pairs[q + 1];
509
+ const leaveReversed = against[last] === 1;
510
+ const rejoinReversed = against[i] === 1;
511
+ const ends = {
512
+ ownBp: bp[i] - bp[last + 1],
513
+ leavePos: leaveReversed
514
+ ? refStarts[last]
515
+ : refStarts[last] + bp[last + 1] - bp[last],
516
+ leaveReversed,
517
+ rejoinPos: rejoinReversed
518
+ ? refStarts[i] + bp[i + 1] - bp[i]
519
+ : refStarts[i],
520
+ rejoinReversed,
521
+ };
522
+ const [lo, hi] = departureStretch(ends);
523
+ if (lo < windowEnd && hi > windowStart) {
524
+ const d = {
525
+ name: run.name,
526
+ hapStart: run.hapOffset + bp[last + 1],
527
+ ownBp: ends.ownBp,
528
+ missingBp: 0,
529
+ leavePos: ends.leavePos,
530
+ leaveReversed,
531
+ leavePasses: passesOf(ids[last]),
532
+ rejoinPos: ends.rejoinPos,
533
+ rejoinReversed,
534
+ rejoinPasses: passesOf(ids[i]),
535
+ fromSteps: true,
536
+ };
537
+ if (i > last + 1 && attaches(ends)) {
538
+ d.steps = {
539
+ ids: ids.subarray(last + 1, i),
540
+ rev: rev.subarray(last + 1, i),
541
+ };
542
+ const held = unloadedIn(run, last + 1, i);
543
+ if (held.length > 0) {
544
+ d.abridged = held;
545
+ }
546
+ markAttached(run, last + 1, i);
547
+ walk(run, returned(run, last) ? last : last + 1, returned(run, i) ? i : i - 1);
548
+ }
549
+ departures.push(d);
550
+ }
551
+ }
552
+ }
553
+ }
554
+ const { leaves, rejoins } = recordEnds([...runs, ...attach], before, breakpoint);
555
+ const unattached = [];
556
+ for (const record of records) {
557
+ const d = { ...record };
558
+ if (attaches(d)) {
559
+ const ids = [];
560
+ const rev = [];
561
+ const held = [];
562
+ const leave = leaves.get(edgeKey(d.name, d.leavePos, d.leaveReversed, d.hapStart));
563
+ if (leave) {
564
+ const [run, i, end] = leave;
565
+ for (let k = i + 1; k < end; k++) {
566
+ ids.push(run.ids[k]);
567
+ rev.push(run.rev[k]);
568
+ }
569
+ markAttached(run, i + 1, end);
570
+ walk(run, returned(run, i) ? i : i + 1, end - 1);
571
+ for (const piece of unloadedIn(run, i + 1, end)) {
572
+ held.push(piece);
573
+ }
574
+ }
575
+ const rejoin = rejoins.get(edgeKey(d.name, d.rejoinPos, d.rejoinReversed, d.hapStart + d.ownBp));
576
+ if (rejoin) {
577
+ const [run, i, start] = rejoin;
578
+ for (let k = start; k < i; k++) {
579
+ ids.push(run.ids[k]);
580
+ rev.push(run.rev[k]);
581
+ }
582
+ markAttached(run, start, i);
583
+ walk(run, start, returned(run, i) ? i : i - 1);
584
+ for (const piece of unloadedIn(run, start, i)) {
585
+ held.push(piece);
586
+ }
587
+ }
588
+ const oneRun = leave !== undefined &&
589
+ rejoin !== undefined &&
590
+ leave[0].fragStart === rejoin[0].fragStart &&
591
+ pieceOf(leave[0], leave[1]) + 1 === pieceOf(rejoin[0], rejoin[1]) &&
592
+ (leave[2] - 1 > leave[1] || returned(leave[0], leave[1])) &&
593
+ (rejoin[2] < rejoin[1] || returned(rejoin[0], rejoin[1]));
594
+ if (leave && rejoin && oneRun && ids.length > 0) {
595
+ const [left, , end] = leave;
596
+ const [right, , start] = rejoin;
597
+ const last = left.ids[end - 1];
598
+ const next = right.ids[start];
599
+ if (last !== undefined &&
600
+ next !== undefined &&
601
+ last !== SKIPPED &&
602
+ next !== SKIPPED) {
603
+ link(last * 2 + left.rev[end - 1], next * 2 + right.rev[start]);
604
+ }
605
+ }
606
+ if (ids.length > 0) {
607
+ d.steps = { ids: Int32Array.from(ids), rev: Uint8Array.from(rev) };
608
+ if (!oneRun) {
609
+ d.breakAt = leave ? leave[2] - leave[1] - 1 : 0;
610
+ }
611
+ if (held.length > 0) {
612
+ d.abridged = held;
613
+ }
614
+ }
615
+ if (!leave || !rejoin) {
616
+ unattached.push({ departure: record });
617
+ }
618
+ }
619
+ departures.push(d);
620
+ }
621
+ sortByWalk(departures);
622
+ let gaps;
623
+ const gapsOf = () => {
624
+ gaps !== null && gaps !== void 0 ? gaps : (gaps = walkGaps({
625
+ runs,
626
+ attach,
627
+ fragments,
628
+ departures,
629
+ refName,
630
+ before,
631
+ attached,
632
+ breakpoint,
633
+ spans,
634
+ }));
635
+ return gaps;
636
+ };
637
+ return { kept, fragments, departures, unattached, gapsOf, links };
638
+ }
639
+ // The drawn stretch a cut widens the window and its context to, the runs it
640
+ // keeps, split where a contained span's context ends inside a placeholder,
641
+ // and the spans it keeps of them
642
+ function walkSpans(readRuns, nodes, { contained = false, context = 0, attachBp = ATTACH_BP, drawn, placeholder, }) {
643
+ var _a, _b;
644
+ // the drawn stretch: the window and its context, widened to the reference
645
+ // nodes on it, so a window inside a hole in the reference has one
646
+ let windowStart = (_a = drawn === null || drawn === void 0 ? void 0 : drawn.start) !== null && _a !== void 0 ? _a : Infinity;
647
+ let windowEnd = (_b = drawn === null || drawn === void 0 ? void 0 : drawn.end) !== null && _b !== void 0 ? _b : -Infinity;
648
+ for (const node of nodes.values()) {
649
+ if (node.onWindow) {
650
+ windowStart = Math.min(windowStart, node.start);
651
+ windowEnd = Math.max(windowEnd, node.end);
652
+ }
653
+ }
654
+ const length = (id) => {
655
+ const node = nodes.get(id);
656
+ return node === undefined ? 0 : node.end - node.start;
657
+ };
658
+ const passesSeen = memoKeys();
659
+ const passesHeld = new Float64Array(MEMO_SLOTS);
660
+ // each node's passes, which the cut asks of the same few nodes again and
661
+ // again; it changes no node after it first asks
662
+ const passesOf = (id) => {
663
+ var _a, _b;
664
+ const slot = id & MEMO_MASK;
665
+ if (passesSeen[slot] !== id) {
666
+ passesSeen[slot] = id;
667
+ passesHeld[slot] = (_b = (_a = nodes.get(id)) === null || _a === void 0 ? void 0 : _a.passes) !== null && _b !== void 0 ? _b : 0;
668
+ }
669
+ return passesHeld[slot];
670
+ };
671
+ const onR = (run, i) => !Number.isNaN(run.refStarts[i]);
672
+ // bp of a run's steps before each, and after its last
673
+ const prefixes = new Map();
674
+ const before = (run) => {
675
+ let out = prefixes.get(run);
676
+ if (!out) {
677
+ out = bpBefore(run.ids, run.bp, length);
678
+ prefixes.set(run, out);
679
+ }
680
+ return out;
681
+ };
682
+ // a node the reference passes twice is held at one pass, so the other
683
+ // passes come from the steps placed on them
684
+ if (drawn) {
685
+ for (const run of readRuns) {
686
+ const over = stepsOver(run.refStarts, before(run), drawn.start, drawn.end);
687
+ windowStart = Math.min(windowStart, over.lo);
688
+ windowEnd = Math.max(windowEnd, over.hi);
689
+ }
690
+ }
691
+ const attaches = (d) => attachesOwnSteps(d, drawn !== null && drawn !== void 0 ? drawn : { start: windowStart, end: windowEnd }, attachBp);
692
+ const stepOnWindow = (run, i) => {
693
+ const start = run.refStarts[i];
694
+ const bp = before(run);
695
+ return (!Number.isNaN(start) &&
696
+ start < windowEnd &&
697
+ start + bp[i + 1] - bp[i] > windowStart);
698
+ };
699
+ const spans = [];
700
+ // A contained run's spans: each stretch between steps onto the reference
701
+ // off the window that has steps on it, from its first such step to its
702
+ // last, and `context` bp of the walk past either: whole steps, but of a
703
+ // placeholder only the bp left, which is where to split it
704
+ const containedSpans = (run) => {
705
+ const { ids } = run;
706
+ const bp = before(run);
707
+ const found = [];
708
+ const splits = [];
709
+ const take = (i, left, tail) => {
710
+ const stepBp = bp[i + 1] - bp[i];
711
+ if (stepBp > left && ids[i] < 0 && ids[i] !== SKIPPED) {
712
+ splits.push({ at: i, keep: left, tail });
713
+ }
714
+ return left - stepBp;
715
+ };
716
+ let from = 0;
717
+ let first = -1;
718
+ let last = -1;
719
+ for (let i = 0; i <= ids.length; i++) {
720
+ const on = i < ids.length && stepOnWindow(run, i);
721
+ if (i === ids.length || ids[i] === SKIPPED || (onR(run, i) && !on)) {
722
+ if (first >= 0) {
723
+ for (let left = context; first > from && left > 0;) {
724
+ left = take(--first, left, true);
725
+ }
726
+ for (let left = context; last < i - 1 && left > 0;) {
727
+ left = take(++last, left, false);
728
+ }
729
+ found.push({ run, first, last });
730
+ }
731
+ from = i + 1;
732
+ first = -1;
733
+ }
734
+ else if (on) {
735
+ if (first < 0) {
736
+ first = i;
737
+ }
738
+ last = i;
739
+ }
740
+ }
741
+ return { found, splits };
742
+ };
743
+ // `run` with each split placeholder as two, the part within a span's
744
+ // context and the rest
745
+ const splitRun = (run, splits, mint) => {
746
+ var _a, _b;
747
+ const bp = before(run);
748
+ const n = run.ids.length + splits.length;
749
+ const ids = new Int32Array(n);
750
+ const rev = new Uint8Array(n);
751
+ const refStarts = new Float64Array(n).fill(Number.NaN);
752
+ const against = new Uint8Array(n);
753
+ const stepBp = new Int32Array(n);
754
+ const shifted = new Int32Array(run.ids.length + 1);
755
+ let s = 0;
756
+ let out = 0;
757
+ for (let i = 0; i < run.ids.length; i++) {
758
+ shifted[i] = out;
759
+ const split = splits[s];
760
+ const start = run.hapOffset + bp[i];
761
+ const end = run.hapOffset + bp[i + 1];
762
+ if ((split === null || split === void 0 ? void 0 : split.at) === i) {
763
+ s++;
764
+ const edge = split.tail ? end - split.keep : start + split.keep;
765
+ const part = (a, b) => {
766
+ const id = mint(run.name, a, b);
767
+ nodes.set(id, {
768
+ refName: run.name,
769
+ start: a,
770
+ end: b,
771
+ rank: 1,
772
+ passes: 0,
773
+ onWindow: false,
774
+ placeholder: true,
775
+ });
776
+ ids[out] = id;
777
+ stepBp[out++] = b - a;
778
+ };
779
+ part(start, edge);
780
+ part(edge, end);
781
+ }
782
+ else {
783
+ ids[out] = run.ids[i];
784
+ rev[out] = run.rev[i];
785
+ refStarts[out] = run.refStarts[i];
786
+ against[out] = run.against[i];
787
+ stepBp[out++] = end - start;
788
+ }
789
+ }
790
+ shifted[run.ids.length] = out;
791
+ return {
792
+ ...run,
793
+ ids,
794
+ rev,
795
+ refStarts,
796
+ against,
797
+ bp: stepBp,
798
+ pieceStarts: run.pieceStarts.map(at => shifted[at]),
799
+ unloaded: (_a = run.unloaded) === null || _a === void 0 ? void 0 : _a.map(u => ({
800
+ ...u,
801
+ from: shifted[u.from],
802
+ to: shifted[u.to],
803
+ })),
804
+ own: (_b = run.own) === null || _b === void 0 ? void 0 : _b.map(steps => ({
805
+ ...steps,
806
+ from: shifted[steps.from],
807
+ to: shifted[steps.to],
808
+ })),
809
+ };
810
+ };
811
+ const stretchSpan = (run) => {
812
+ const { first, last } = stepsOver(run.refStarts, before(run), windowStart, windowEnd);
813
+ if (first >= 0) {
814
+ spans.push({ run, first, last });
815
+ }
816
+ };
817
+ const runs = readRuns.map(run => {
818
+ const scan = contained ? containedSpans(run) : undefined;
819
+ const split = scan && placeholder && scan.splits.length > 0
820
+ ? splitRun(run, scan.splits, placeholder)
821
+ : run;
822
+ if (!scan) {
823
+ stretchSpan(run);
824
+ }
825
+ else {
826
+ for (const span of split === run
827
+ ? scan.found
828
+ : containedSpans(split).found) {
829
+ spans.push(span);
830
+ }
831
+ }
832
+ return split;
833
+ });
834
+ // A step's breakpoint on R: where the path's sequence stops following R,
835
+ // the node's end for a step along R and its start for one against it, and
836
+ // the other way round for a rejoin
837
+ const breakpoint = (run, i, leave) => {
838
+ const reversed = run.against[i] === 1;
839
+ const start = run.refStarts[i];
840
+ return {
841
+ pos: reversed === leave
842
+ ? start
843
+ : start + before(run)[i + 1] - before(run)[i],
844
+ reversed,
845
+ };
846
+ };
847
+ return {
848
+ windowStart,
849
+ windowEnd,
850
+ passesOf,
851
+ before,
852
+ attaches,
853
+ breakpoint,
854
+ runs,
855
+ spans,
856
+ };
857
+ }
858
+ // A record's own steps: those after its leave step to the end of that
859
+ // piece, then those before its rejoin step from the start of its piece. A
860
+ // leave step is the last step on R of its piece and a rejoin step the
861
+ // first of its, so the cut indexes by name, breakpoint and contig position
862
+ // each piece's last step on R and where the piece ends, and its first and
863
+ // where the piece starts
864
+ function recordEnds(runs, before, breakpoint) {
865
+ var _a;
866
+ const leaves = new Map();
867
+ const rejoins = new Map();
868
+ for (const run of runs) {
869
+ const bp = before(run);
870
+ const bounds = pieceBounds(run);
871
+ for (let p = 0; p + 1 < bounds.length; p++) {
872
+ const first = firstOnR(run.refStarts, bounds[p], bounds[p + 1]);
873
+ const last = lastOnR(run.refStarts, bounds[p], bounds[p + 1]);
874
+ if (first < 0) {
875
+ continue;
876
+ }
877
+ const leave = breakpoint(run, last, true);
878
+ leaves.set(edgeKey(run.name, leave.pos, leave.reversed, run.hapOffset + bp[last + 1]), [run, last, bounds[p + 1]]);
879
+ const rejoin = breakpoint(run, first, false);
880
+ rejoins.set(edgeKey(run.name, rejoin.pos, rejoin.reversed, run.hapOffset + bp[first]), [run, first, bounds[p]]);
881
+ }
882
+ }
883
+ for (const run of runs) {
884
+ for (const { key, leave, from, to } of (_a = run.own) !== null && _a !== void 0 ? _a : []) {
885
+ if (leave) {
886
+ leaves.set(key, [run, from - 1, to]);
887
+ }
888
+ else {
889
+ rejoins.set(key, [run, to, from]);
890
+ }
891
+ }
892
+ }
893
+ return { leaves, rejoins };
894
+ }
895
+ // The records walkCut lists as unattached, found without cutting: those it
896
+ // attaches own steps for that lack their leave piece or their rejoin piece
897
+ export function unattachedRecords(readRuns, nodes, records, options = {}) {
898
+ const { runs, before, attaches, breakpoint } = walkSpans(readRuns, nodes, options);
899
+ const { leaves, rejoins } = recordEnds(runs, before, breakpoint);
900
+ return records.filter(d => attaches(d) &&
901
+ (!leaves.has(edgeKey(d.name, d.leavePos, d.leaveReversed, d.hapStart)) ||
902
+ !rejoins.has(edgeKey(d.name, d.rejoinPos, d.rejoinReversed, d.hapStart + d.ownBp))));
903
+ }
904
+ // Sorts departures by name, then contig position, then where each leaves R,
905
+ // ties in the order given, comparing numbers: each name by its rank. Names
906
+ // come in long runs, so each is looked up once a run
907
+ function sortByWalk(departures) {
908
+ const n = departures.length;
909
+ const names = new Set();
910
+ let last;
911
+ for (const { name } of departures) {
912
+ if (name !== last) {
913
+ names.add(name);
914
+ last = name;
915
+ }
916
+ }
917
+ const rank = new Map([...names].sort().map((name, k) => [name, k]));
918
+ const ranks = new Float64Array(n);
919
+ const haps = new Float64Array(n);
920
+ const leaves = new Float64Array(n);
921
+ let lastRank = 0;
922
+ last = undefined;
923
+ departures.forEach((d, k) => {
924
+ if (d.name !== last) {
925
+ lastRank = rank.get(d.name);
926
+ last = d.name;
927
+ }
928
+ ranks[k] = lastRank;
929
+ haps[k] = d.hapStart;
930
+ leaves[k] = d.leavePos;
931
+ });
932
+ const order = Array.from(departures.keys()).sort((a, b) => ranks[a] - ranks[b] ||
933
+ haps[a] - haps[b] ||
934
+ leaves[a] - leaves[b] ||
935
+ a - b);
936
+ const sorted = order.map(k => departures[k]);
937
+ sorted.forEach((d, k) => {
938
+ departures[k] = d;
939
+ });
940
+ }
941
+ const pieceOf = (run, step) => run.firstPiece + run.pieceStarts.filter(start => start <= step).length;
942
+ // Where each of a run's pieces starts, and where the last ends
943
+ function pieceBounds(run) {
944
+ const bounds = [0];
945
+ for (const start of run.pieceStarts) {
946
+ bounds.push(start);
947
+ }
948
+ bounds.push(run.ids.length);
949
+ return bounds;
950
+ }
951
+ /**
952
+ * Adds to `into` the nodes of decoded rows that walkCut keeps whatever else
953
+ * the cut reads: those of `chunk.nodes` on the window, and those a row steps
954
+ * on between two of its steps on the window, `start`-`end` with its context,
955
+ * with no step onto the reference off the window between them in a contained
956
+ * cut. A node placed later at a reference position off the window can split a
957
+ * contained walk, so the count holds for the placements at the time. A
958
+ * placeholder is no node, and is counted in `placeholders` where a row steps
959
+ * on it between two such steps.
960
+ */
961
+ export function surelyKept(chunk, nodes, { contained, start, end }, into, placeholders) {
962
+ var _a;
963
+ for (const id of chunk.nodes.keys()) {
964
+ if (((_a = nodes.get(id)) === null || _a === void 0 ? void 0 : _a.onWindow) === true) {
965
+ into.add(id);
966
+ }
967
+ }
968
+ for (const { steps } of chunk.rows) {
969
+ const { ids, refStarts } = steps;
970
+ let last = -1;
971
+ for (let i = 0; i < ids.length; i++) {
972
+ const node = nodes.get(ids[i]);
973
+ const at = refStarts === null || refStarts === void 0 ? void 0 : refStarts[i];
974
+ const onR = at !== undefined && !Number.isNaN(at);
975
+ if ((node === null || node === void 0 ? void 0 : node.onWindow) === true &&
976
+ onR &&
977
+ at < end &&
978
+ at + node.end - node.start > start) {
979
+ if (last >= 0) {
980
+ for (let j = last + 1; j < i; j++) {
981
+ const id = ids[j];
982
+ if (!isPlaceholder(id)) {
983
+ into.add(id);
984
+ }
985
+ else if (id !== SKIPPED) {
986
+ placeholders === null || placeholders === void 0 ? void 0 : placeholders.add(id);
987
+ }
988
+ }
989
+ }
990
+ last = i;
991
+ }
992
+ else if (contained && onR) {
993
+ last = -1;
994
+ }
995
+ }
996
+ }
997
+ }
998
+ // A run of a walk's steps by its walk and its stretch of the contig, which no
999
+ // node's name is
1000
+ export const runName = (name, start, end) => `${name}:${start}-${end}`;
1001
+ // The places of a fragment's `n` steps it states: none from a host's fragment
1002
+ // without `refStarts`, and none past its steps from one whose `refStarts` runs
1003
+ // on
1004
+ const statedPlaces = (placed, n) => { var _a; return (_a = placed === null || placed === void 0 ? void 0 : placed.subarray(0, n)) !== null && _a !== void 0 ? _a : new Float64Array(); };
1005
+ // A node's name in the tables: its id, or for a placeholder its run's name
1006
+ const nodeName = (id, node) => (node === null || node === void 0 ? void 0 : node.placeholder) ? runName(node.refName, node.start, node.end) : String(id);
1007
+ // Whether placement `node` beats `held`: a pass of the reference over the
1008
+ // window beats any other, then a reference position beats one off it, and
1009
+ // among equals the path sorting first at its earliest start wins, so the order
1010
+ // a cut reads chunks in does not matter
1011
+ const outranks = (node, held) => node.onWindow !== held.onWindow
1012
+ ? node.onWindow
1013
+ : node.rank === 0 &&
1014
+ (held.rank !== 0 ||
1015
+ node.refName < held.refName ||
1016
+ (node.refName === held.refName && node.start < held.start));
1017
+ /**
1018
+ * The nodes and links of the chunks a cut reads, and the tables of the cut
1019
+ * they make with its walks. A node in two chunks is placed once.
1020
+ */
1021
+ export class WalkGraph {
1022
+ constructor(window, revisited = Number.NaN) {
1023
+ this.nodes = new Map();
1024
+ this.sequences = new Map();
1025
+ this.links = [];
1026
+ this.window = window;
1027
+ this.revisited = revisited;
1028
+ }
1029
+ // A node with its position, unless the cut already holds it at one that
1030
+ // outranks it
1031
+ placeNode(id, node) {
1032
+ const { window } = this;
1033
+ const placed = {
1034
+ ...node,
1035
+ onWindow: node.rank === 0 &&
1036
+ node.refName === window.refName &&
1037
+ node.end > window.start - window.context &&
1038
+ node.start < window.end + window.context,
1039
+ };
1040
+ const held = this.nodes.get(id);
1041
+ if (!held || outranks(placed, held)) {
1042
+ this.nodes.set(id, placed);
1043
+ }
1044
+ }
1045
+ // A link between two endpoints, each id * 2 + 1 when reversed
1046
+ addLinkEnds(source, target) {
1047
+ this.links.push(source, target);
1048
+ }
1049
+ // Bases of nodes a chunk's rows give, for a window that asks for them
1050
+ addSequences(sequences) {
1051
+ if (this.window.sequences === true) {
1052
+ for (const [id, bases] of sequences) {
1053
+ this.sequences.set(id, bases);
1054
+ }
1055
+ }
1056
+ }
1057
+ /**
1058
+ * The cut as typed arrays, which the worker transfers rather than copies:
1059
+ * nodes by reference position, each link once in the order its L line
1060
+ * sorts, then a walk per fragment, the reference's first and the rest by
1061
+ * name, and the departures with their own steps. graphTablesGFA writes
1062
+ * them as the GFA they stand for, the same bytes for the same rows.
1063
+ */
1064
+ tables(kept, fragments, departures, gaps = []) {
1065
+ this.placeOffReference(kept, fragments, departures);
1066
+ const held = [];
1067
+ for (const id of kept) {
1068
+ const node = this.nodes.get(id);
1069
+ if (node) {
1070
+ held.push({ ...node, id });
1071
+ }
1072
+ }
1073
+ held.sort((x, y) => x.refName < y.refName
1074
+ ? -1
1075
+ : x.refName > y.refName
1076
+ ? 1
1077
+ : x.start - y.start || x.id - y.id);
1078
+ const index = new Map();
1079
+ const names = [];
1080
+ const refNames = [];
1081
+ const refIndex = new Map();
1082
+ const lengths = new Int32Array(held.length);
1083
+ const refs = new Int32Array(held.length);
1084
+ const starts = new Float64Array(held.length);
1085
+ const ranks = new Int32Array(held.length);
1086
+ const passes = new Int32Array(held.length);
1087
+ const placeholders = Uint8Array.from(held, node => node.placeholder ? 1 : 0);
1088
+ const reversedOnReference = Uint8Array.from(held, node => node.reversed === true ? 1 : 0);
1089
+ held.forEach((node, i) => {
1090
+ const { id, refName, start, end, rank, passes: n } = node;
1091
+ index.set(id, i);
1092
+ names.push(nodeName(id, node));
1093
+ let ref = refIndex.get(refName);
1094
+ if (ref === undefined) {
1095
+ ref = refNames.length;
1096
+ refIndex.set(refName, ref);
1097
+ refNames.push(refName);
1098
+ }
1099
+ lengths[i] = end - start;
1100
+ refs[i] = ref;
1101
+ starts[i] = start;
1102
+ ranks[i] = rank;
1103
+ passes[i] = n;
1104
+ });
1105
+ // a kept node with no row of its own is named, and not drawn
1106
+ const lastId = memoKeys();
1107
+ const lastIndex = new Int32Array(MEMO_SLOTS);
1108
+ const indexOf = (id) => {
1109
+ let i = index.get(id);
1110
+ if (i === undefined) {
1111
+ i = names.length;
1112
+ index.set(id, i);
1113
+ names.push(nodeName(id, this.nodes.get(id)));
1114
+ }
1115
+ return i;
1116
+ };
1117
+ const nodeIndex = (id) => {
1118
+ const slot = id & MEMO_MASK;
1119
+ if (lastId[slot] !== id) {
1120
+ lastId[slot] = id;
1121
+ lastIndex[slot] = indexOf(id);
1122
+ }
1123
+ return lastIndex[slot];
1124
+ };
1125
+ const lines = linkLines(this.links, kept);
1126
+ const from = new Int32Array(lines.length / 2);
1127
+ const to = new Int32Array(lines.length / 2);
1128
+ const strands = new Uint8Array(lines.length / 2);
1129
+ for (let k = 0; k < lines.length; k += 2) {
1130
+ const a = lines[k];
1131
+ const b = lines[k + 1];
1132
+ from[k / 2] = nodeIndex(Math.floor(a / 2));
1133
+ to[k / 2] = nodeIndex(Math.floor(b / 2));
1134
+ strands[k / 2] = (a & 1) | ((b & 1) << 1);
1135
+ }
1136
+ const walks = this.referenceFirst(fragments);
1137
+ // a piece counts on the first walk holding it, else on the first
1138
+ // departure
1139
+ const counted = new Set();
1140
+ const stepsOf = (pieces) => {
1141
+ let steps = pieces ? 0 : Number.NaN;
1142
+ for (const piece of pieces !== null && pieces !== void 0 ? pieces : []) {
1143
+ if (!counted.has(piece)) {
1144
+ counted.add(piece);
1145
+ steps += piece.steps;
1146
+ }
1147
+ }
1148
+ return steps;
1149
+ };
1150
+ const abridgedSteps = Float64Array.from(walks, f => stepsOf(f.abridged));
1151
+ const offsets = new Int32Array(walks.length + 1);
1152
+ walks.forEach(({ ids }, p) => {
1153
+ offsets[p + 1] = offsets[p] + ids.length;
1154
+ });
1155
+ const steps = new Int32Array(offsets[walks.length]);
1156
+ const reversed = new Uint8Array(steps.length);
1157
+ const refStarts = new Float64Array(steps.length).fill(Number.NaN);
1158
+ walks.forEach(({ ids, rev, refStarts: placed }, p) => {
1159
+ const at = offsets[p];
1160
+ indexSteps(ids, steps, at, lastId, lastIndex, indexOf);
1161
+ reversed.set(rev, at);
1162
+ refStarts.set(statedPlaces(placed, ids.length), at);
1163
+ });
1164
+ return {
1165
+ nodes: {
1166
+ names,
1167
+ lengths,
1168
+ refs,
1169
+ starts,
1170
+ ranks,
1171
+ refNames,
1172
+ passes,
1173
+ reversed: reversedOnReference,
1174
+ placeholders,
1175
+ },
1176
+ links: { from, to, strands },
1177
+ walks: {
1178
+ names: walks.map(f => f.name),
1179
+ starts: Float64Array.from(walks, f => f.hapStart),
1180
+ ends: Float64Array.from(walks, f => f.hapEnd),
1181
+ offsets,
1182
+ steps,
1183
+ reversed,
1184
+ refStarts,
1185
+ trimmedBefore: Float64Array.from(walks, f => f.trimmedBefore),
1186
+ trimmedAfter: Float64Array.from(walks, f => f.trimmedAfter),
1187
+ abridgedSteps,
1188
+ },
1189
+ departures: departureTable(departures, nodeIndex, stepsOf),
1190
+ gaps: gapTable(gaps, new Map(walks.map((f, p) => [f, p])), nodeIndex),
1191
+ revisited: this.revisited,
1192
+ };
1193
+ }
1194
+ placeOffReference(kept, fragments, departures) {
1195
+ var _a;
1196
+ const lengthOf = (id) => {
1197
+ const node = this.nodes.get(id);
1198
+ return node ? node.end - node.start : 0;
1199
+ };
1200
+ const placed = new Map();
1201
+ // the ids no walk places, with their lengths: those on the reference,
1202
+ // placeholders, and those the cut does not keep
1203
+ const passedId = memoKeys();
1204
+ const passedLength = new Float64Array(MEMO_SLOTS);
1205
+ const visit = (name, ids, start) => {
1206
+ let at = start;
1207
+ for (const id of ids) {
1208
+ const slot = id & MEMO_MASK;
1209
+ if (passedId[slot] === id) {
1210
+ at += passedLength[slot];
1211
+ }
1212
+ else {
1213
+ const node = this.nodes.get(id);
1214
+ const length = node ? node.end - node.start : 0;
1215
+ if (node && node.rank !== 0 && !node.placeholder && kept.has(id)) {
1216
+ const held = placed.get(id);
1217
+ if (!held ||
1218
+ name < held.refName ||
1219
+ (name === held.refName && at < held.start)) {
1220
+ placed.set(id, {
1221
+ ...node,
1222
+ refName: name,
1223
+ start: at,
1224
+ end: at + length,
1225
+ });
1226
+ }
1227
+ }
1228
+ else {
1229
+ passedId[slot] = id;
1230
+ passedLength[slot] = length;
1231
+ }
1232
+ at += length;
1233
+ }
1234
+ }
1235
+ };
1236
+ for (const f of fragments) {
1237
+ visit(f.name, f.ids, f.hapStart);
1238
+ }
1239
+ for (const d of departures) {
1240
+ if (d.steps) {
1241
+ const { ids } = d.steps;
1242
+ const leaving = ids.subarray(0, (_a = d.breakAt) !== null && _a !== void 0 ? _a : ids.length);
1243
+ const rejoining = ids.subarray(leaving.length);
1244
+ const rejoiningBp = rejoining.reduce((sum, id) => sum + lengthOf(id), 0);
1245
+ visit(d.name, leaving, d.hapStart);
1246
+ visit(d.name, rejoining, d.hapStart + d.ownBp - rejoiningBp);
1247
+ }
1248
+ }
1249
+ for (const [id, node] of placed) {
1250
+ this.nodes.set(id, node);
1251
+ }
1252
+ }
1253
+ // The view anchors on the first walk when no walk names the assembly, as
1254
+ // gbz-base's cut has it; in file order that was whichever haplotype the
1255
+ // chunk listed first, CHM13 on a GRCh38 window
1256
+ referenceFirst(fragments) {
1257
+ const { refName } = this.window;
1258
+ return [...fragments].sort((a, b) => Number(b.name === refName) - Number(a.name === refName) ||
1259
+ (a.name < b.name ? -1 : a.name > b.name ? 1 : a.hapStart - b.hapStart));
1260
+ }
1261
+ }
1262
+ function gapTable(gaps, walkIndex, nodeIndex) {
1263
+ const segments = gaps.flatMap(g => g.segments);
1264
+ const segmentOffsets = new Int32Array(gaps.length + 1);
1265
+ gaps.forEach((g, k) => {
1266
+ segmentOffsets[k + 1] = segmentOffsets[k] + g.segments.length;
1267
+ });
1268
+ const stepOffsets = new Int32Array(segments.length + 1);
1269
+ segments.forEach((x, k) => {
1270
+ stepOffsets[k + 1] = stepOffsets[k] + x.ids.length;
1271
+ });
1272
+ const steps = new Int32Array(stepOffsets[segments.length]);
1273
+ const reversed = new Uint8Array(steps.length);
1274
+ segments.forEach((x, k) => {
1275
+ const at = stepOffsets[k];
1276
+ x.ids.forEach((id, j) => {
1277
+ steps[at + j] = nodeIndex(id);
1278
+ });
1279
+ reversed.set(x.rev, at);
1280
+ });
1281
+ return {
1282
+ names: gaps.map(g => g.name),
1283
+ walks: Int32Array.from(gaps, g => { var _a; return g.fragment ? ((_a = walkIndex.get(g.fragment)) !== null && _a !== void 0 ? _a : -1) : -1; }),
1284
+ edges: Uint8Array.from(gaps, g => g.edge),
1285
+ starts: Float64Array.from(gaps, g => g.start),
1286
+ ends: Float64Array.from(gaps, g => g.end),
1287
+ segmentOffsets,
1288
+ segments: {
1289
+ kinds: Uint8Array.from(segments, x => GAP_KINDS.indexOf(x.kind)),
1290
+ bp: Float64Array.from(segments, x => x.bp),
1291
+ missingBp: Float64Array.from(segments, x => x.missingBp),
1292
+ before: Float64Array.from(segments, x => x.before),
1293
+ after: Float64Array.from(segments, x => x.after),
1294
+ stepOffsets,
1295
+ steps,
1296
+ reversed,
1297
+ },
1298
+ };
1299
+ }
1300
+ function departureTable(departures, nodeIndex, stepsOf) {
1301
+ var _a;
1302
+ const n = departures.length;
1303
+ const offsets = new Int32Array(n + 1);
1304
+ departures.forEach((d, k) => {
1305
+ var _a, _b;
1306
+ offsets[k + 1] = offsets[k] + ((_b = (_a = d.steps) === null || _a === void 0 ? void 0 : _a.ids.length) !== null && _b !== void 0 ? _b : 0);
1307
+ });
1308
+ const steps = new Int32Array(offsets[n]);
1309
+ const reversed = new Uint8Array(steps.length);
1310
+ departures.forEach((d, k) => {
1311
+ if (d.steps) {
1312
+ const at = offsets[k];
1313
+ for (let j = 0; j < d.steps.ids.length; j++) {
1314
+ steps[at + j] = nodeIndex(d.steps.ids[j]);
1315
+ }
1316
+ reversed.set(d.steps.rev, at);
1317
+ }
1318
+ });
1319
+ const names = new Array(n);
1320
+ const hapStarts = new Float64Array(n);
1321
+ const ownBp = new Float64Array(n);
1322
+ const missingBp = new Float64Array(n);
1323
+ const leavePos = new Float64Array(n);
1324
+ const leaveReversed = new Uint8Array(n);
1325
+ const leavePasses = new Int32Array(n);
1326
+ const rejoinPos = new Float64Array(n);
1327
+ const rejoinReversed = new Uint8Array(n);
1328
+ const rejoinPasses = new Int32Array(n);
1329
+ const fromSteps = new Uint8Array(n);
1330
+ const breakAt = new Int32Array(n);
1331
+ const abridgedSteps = new Float64Array(n);
1332
+ for (let k = 0; k < n; k++) {
1333
+ const d = departures[k];
1334
+ names[k] = d.name;
1335
+ hapStarts[k] = d.hapStart;
1336
+ ownBp[k] = d.ownBp;
1337
+ missingBp[k] = d.missingBp;
1338
+ leavePos[k] = d.leavePos;
1339
+ leaveReversed[k] = d.leaveReversed ? 1 : 0;
1340
+ leavePasses[k] = d.leavePasses;
1341
+ rejoinPos[k] = d.rejoinPos;
1342
+ rejoinReversed[k] = d.rejoinReversed ? 1 : 0;
1343
+ rejoinPasses[k] = d.rejoinPasses;
1344
+ fromSteps[k] = d.fromSteps ? 1 : 0;
1345
+ breakAt[k] = (_a = d.breakAt) !== null && _a !== void 0 ? _a : -1;
1346
+ abridgedSteps[k] = stepsOf(d.abridged);
1347
+ }
1348
+ return {
1349
+ names,
1350
+ hapStarts,
1351
+ ownBp,
1352
+ missingBp,
1353
+ leavePos,
1354
+ leaveReversed,
1355
+ leavePasses,
1356
+ rejoinPos,
1357
+ rejoinReversed,
1358
+ rejoinPasses,
1359
+ fromSteps,
1360
+ breakAt,
1361
+ offsets,
1362
+ steps,
1363
+ reversed,
1364
+ abridgedSteps,
1365
+ };
1366
+ }
1367
+ export const BUDGET_NAMES = {
1368
+ steps: 'the step budget',
1369
+ bytes: 'a byte budget of',
1370
+ };
1371
+ // The reader decodes a step along R several times as fast as one off it, so
1372
+ // the read budget counts it as a quarter
1373
+ const ALONG_R_PER_STEP = 4;
1374
+ export const readSteps = (row) => {
1375
+ var _a;
1376
+ const interior = (_a = row.interior) !== null && _a !== void 0 ? _a : 0;
1377
+ return interior + (row.n - interior) / ALONG_R_PER_STEP;
1378
+ };
1379
+ /**
1380
+ * The zoom-in notice for a cut whose walk rows hold more steps than
1381
+ * `readPerKept` times `stepBudget`, or undefined when they fit. A window reads
1382
+ * whole tiles, so the span that fits is counted in tiles of `tile` bp from
1383
+ * the window's start; when the tiles a window there always reads are over on
1384
+ * their own, no zoom fits and the notice asks for fewer
1385
+ * haplotypes. A cut for every haplotype is also offered fewer where the
1386
+ * reference and one haplotype, at the walks' average steps, would fit the
1387
+ * whole window.
1388
+ */
1389
+ export function stepBudgetError(rows, stepBudget, readPerKept, window, tile, filtered, names = BUDGET_NAMES) {
1390
+ const budget = stepBudget * readPerKept;
1391
+ const over = readStepsOver(rows, budget, window, tile);
1392
+ const fewerFit = over !== undefined &&
1393
+ !filtered &&
1394
+ over.walks > 2 &&
1395
+ (2 * over.total) / over.walks <= budget;
1396
+ return over
1397
+ ? new RegionTooLargeError(over.fitsBp > 0
1398
+ ? `Zoom in to about ${bpString(over.fitsBp)}${fewerFit ? ', or choose fewer haplotypes,' : ''} to see the graph`
1399
+ : `Too many haplotype steps here to draw ${filtered ? 'these haplotypes' : 'every haplotype'} (${Math.round(over.read).toLocaleString()} steps read, a step along the reference counting a quarter, over ${readPerKept} × ${names.steps} of ${stepBudget.toLocaleString()}); choose fewer haplotypes`, budget, window.end - window.start, Math.max(over.fitsBp, 1))
1400
+ : undefined;
1401
+ }
1402
+ export function countStepsError(rows, stepBudget, readPerKept, window, tile, names = BUDGET_NAMES) {
1403
+ const over = readStepsOver(rows, stepBudget * readPerKept, window, tile);
1404
+ return over
1405
+ ? new RegionTooLargeError(`Too many haplotype steps in this window to count: its walk rows hold ${Math.round(over.total).toLocaleString()} steps, a step along the reference counting a quarter, over ${readPerKept} × ${names.steps} of ${stepBudget.toLocaleString()}. ${over.fitsBp > 0 ? `Count a window of about ${bpString(over.fitsBp)} or less, or leave this one uncounted` : `Its first tile alone is over, so leave this window uncounted or raise ${names.steps}`}`, stepBudget * readPerKept, window.end - window.start, Math.max(over.fitsBp, 1))
1406
+ : undefined;
1407
+ }
1408
+ function readStepsOver(rows, budget, window, tile) {
1409
+ var _a;
1410
+ let total = 0;
1411
+ const perChunk = new Map();
1412
+ const walks = new Set();
1413
+ for (const row of rows) {
1414
+ const steps = readSteps(row);
1415
+ total += steps;
1416
+ perChunk.set(row.chunkStart, ((_a = perChunk.get(row.chunkStart)) !== null && _a !== void 0 ? _a : 0) + steps);
1417
+ walks.add(row.name);
1418
+ }
1419
+ let read = 0;
1420
+ let fitsBp = 0;
1421
+ for (const cs of [...perChunk.keys()].sort((a, b) => a - b)) {
1422
+ read += perChunk.get(cs);
1423
+ if (read > budget) {
1424
+ break;
1425
+ }
1426
+ fitsBp = Math.max(fitsBp, cs + tile - window.start);
1427
+ }
1428
+ return total > budget ? { total, read, fitsBp, walks: walks.size } : undefined;
1429
+ }
1430
+ /**
1431
+ * The zoom-in notice for a cut that keeps more steps than `budget`, the
1432
+ * fragments' and the departures' attached steps together, or undefined when
1433
+ * it fits. The span that fits is the window scaled by how far over the cut
1434
+ * is. A step built for a piece the cut did not load counts as any other.
1435
+ */
1436
+ export function keptStepsError(fragments, departures, budget, window, filtered) {
1437
+ const total = fragments.reduce((sum, f) => sum + f.ids.length, 0) +
1438
+ departures.reduce((sum, d) => { var _a, _b; return sum + ((_b = (_a = d.steps) === null || _a === void 0 ? void 0 : _a.ids.length) !== null && _b !== void 0 ? _b : 0); }, 0);
1439
+ return keptOverError(total, budget, window, filtered);
1440
+ }
1441
+ // keptStepsError's notice for a cut that keeps more nodes than `limit`, which
1442
+ // it counted on the window before `readTo` when it stopped reading there
1443
+ export function keptNodesError(nodes, limit, window, filtered, readTo = window.end) {
1444
+ return keptOverError(nodes, limit, window, filtered, readTo);
1445
+ }
1446
+ function keptOverError(kept, limit, window, filtered, readTo = window.end) {
1447
+ const readBp = Math.min(readTo, window.end) - window.start;
1448
+ return kept > limit
1449
+ ? zoomInError(Math.floor((readBp * limit) / kept), limit, window, filtered)
1450
+ : undefined;
1451
+ }
1452
+ function zoomInError(fitsBp, limit, window, filtered) {
1453
+ const fits = Math.max(1, fitsBp);
1454
+ return new RegionTooLargeError(`Zoom in to about ${bpString(fits)}${filtered ? '' : ', or choose fewer haplotypes,'} to see the graph`, limit, window.end - window.start, fits);
1455
+ }
1456
+ /**
1457
+ * keptStepsError's notice given before a cut decodes its tiles, or undefined
1458
+ * where the steps it surely keeps of the tiles it counted (tileSteps in
1459
+ * walkChunk.ts, `steps` here) fit `budget`. `tiles` are the window's tiles in
1460
+ * order, those not counted with no `steps`. The span that fits is worked out
1461
+ * tile by tile from the start of the window's `context`: a counted tile holds
1462
+ * its steps evenly over its extent, a tile not counted holds the counted
1463
+ * tiles' steps per bp, and a stretch no tile covers holds none. Where those
1464
+ * steps reach the budget is where the context of the span that fits ends,
1465
+ * before the last counted tile ends and so before the window's context does:
1466
+ * the span is narrower than the window. A tile's `likely`, no fewer than its
1467
+ * `steps`, is what the cut is expected to keep of it where `steps` counts a
1468
+ * part: the span is worked out from it, and the refusal from `steps` alone.
1469
+ */
1470
+ export function surelyKeptError(tiles, budget, window, context, filtered) {
1471
+ var _a;
1472
+ let steps = 0;
1473
+ let likely = 0;
1474
+ let bp = 0;
1475
+ for (const tile of tiles) {
1476
+ if (tile.steps !== undefined) {
1477
+ steps += tile.steps;
1478
+ likely += Math.max(tile.steps, (_a = tile.likely) !== null && _a !== void 0 ? _a : 0);
1479
+ bp += tile.end - tile.start;
1480
+ }
1481
+ }
1482
+ const drawn = {
1483
+ start: Math.max(0, window.start - context),
1484
+ end: window.end + context,
1485
+ };
1486
+ return steps > budget
1487
+ ? zoomInError(budgetReach(tiles.map(tile => {
1488
+ var _a;
1489
+ return tile.steps === undefined
1490
+ ? tile
1491
+ : { ...tile, steps: Math.max(tile.steps, (_a = tile.likely) !== null && _a !== void 0 ? _a : 0) };
1492
+ }), bp > 0 ? likely / bp : 0, budget, drawn) -
1493
+ context -
1494
+ window.start, budget, window, filtered)
1495
+ : undefined;
1496
+ }
1497
+ // Where on `drawn` the steps of `tiles` from its start reach `budget`, each
1498
+ // tile's spread evenly over its extent, `perBp` a tile's with no steps of its
1499
+ // own; the end of `drawn` where they don't
1500
+ function budgetReach(tiles, perBp, budget, drawn) {
1501
+ let held = 0;
1502
+ let reach;
1503
+ for (const tile of tiles) {
1504
+ const from = Math.max(tile.start, drawn.start);
1505
+ const bp = Math.max(0, Math.min(tile.end, drawn.end) - from);
1506
+ const share = tile.steps === undefined
1507
+ ? perBp * bp
1508
+ : tile.end > tile.start
1509
+ ? (tile.steps * bp) / (tile.end - tile.start)
1510
+ : tile.steps;
1511
+ if (reach === undefined && held + share > budget) {
1512
+ reach = bp > 0 ? from + ((budget - held) * bp) / share : from;
1513
+ }
1514
+ held += share;
1515
+ }
1516
+ return Math.floor(reach !== null && reach !== void 0 ? reach : drawn.end);
1517
+ }
1518
+ /**
1519
+ * The zoom-in notice for a cut whose walk read would fetch more than
1520
+ * `budget` compressed bytes, or undefined when it fits. `bytesTo(end)` is the
1521
+ * bytes of the tiles a read from the window's first base to `end` fetches;
1522
+ * the span that fits grows a tile at a time from the tile holding the
1523
+ * window's start, and when the tiles that reaches are over on their own, no
1524
+ * zoom fits. `attaching` marks bytes the tiles fetched for records' own
1525
+ * steps take past the budget.
1526
+ */
1527
+ export function byteBudgetError(bytesTo, budget, window, tile, names = BUDGET_NAMES, attaching = false) {
1528
+ const over = bytesOver(bytesTo, budget, window, tile);
1529
+ const windowBp = window.end - window.start;
1530
+ return over === undefined
1531
+ ? undefined
1532
+ : over.fitsBp > 0
1533
+ ? new RegionTooLargeError(`Zoom in to about ${bpString(over.fitsBp)} to see the graph`, budget, windowBp, over.fitsBp, { bytes: over.bytes, zoomHelps: true })
1534
+ : new RegionTooLargeError(attaching
1535
+ ? `Too many departures here whose own steps the cut must fetch, even zoomed in (${megabytes(over.least)} against ${names.bytes} ${megabytes(budget)}); choose fewer haplotypes or a smaller attachBp`
1536
+ : `Too much graph here to fetch, even zoomed in (${megabytes(over.least)} against ${names.bytes} ${megabytes(budget)}). A satellite or rDNA array usually causes this: the graph folds the repeat into a few nodes that each haplotype loops through many times`, budget, windowBp, 1, { bytes: over.bytes });
1537
+ }
1538
+ /**
1539
+ * byteBudgetError's refusal for counts, which draw nothing and choose no
1540
+ * haplotypes: what the read would fetch, and a narrower window to count
1541
+ * instead where one fits
1542
+ */
1543
+ export function countBytesError(bytesTo, budget, window, tile, names = BUDGET_NAMES, attaching = false) {
1544
+ const over = bytesOver(bytesTo, budget, window, tile);
1545
+ const windowBp = window.end - window.start;
1546
+ const against = `against ${names.bytes} ${megabytes(budget)}`;
1547
+ const own = attaching
1548
+ ? " with the tiles holding its departures' own steps"
1549
+ : '';
1550
+ const instead = attaching
1551
+ ? '. Count with a smaller attachBp, or leave this window uncounted'
1552
+ : ', so leave this window uncounted';
1553
+ return over === undefined
1554
+ ? undefined
1555
+ : new RegionTooLargeError(`Too many bytes to read to count this window: ${over.fitsBp === 0
1556
+ ? `${megabytes(over.least)} for its first tile alone${own}, ${against}${instead}`
1557
+ : `${megabytes(over.bytes)} ${against}. Count a window of about ${bpString(over.fitsBp)} or less, or leave this one uncounted`}`, budget, windowBp, Math.max(over.fitsBp, 1), over.fitsBp > 0
1558
+ ? { bytes: over.bytes, zoomHelps: true }
1559
+ : { bytes: over.bytes });
1560
+ }
1561
+ // The widest span from the window's start, narrower than the window, whose
1562
+ // read fits `budget`, 0 where none does; `bytesTo` never falls as its end
1563
+ // grows
1564
+ function narrowerFit(bytesTo, budget, window) {
1565
+ let fits = window.start;
1566
+ let over = window.end;
1567
+ while (over - fits > 1) {
1568
+ const middle = Math.floor((fits + over) / 2);
1569
+ if (bytesTo(middle) <= budget) {
1570
+ fits = middle;
1571
+ }
1572
+ else {
1573
+ over = middle;
1574
+ }
1575
+ }
1576
+ return fits - window.start;
1577
+ }
1578
+ // What a read past `budget` would fetch: `bytes` for the window, `least` for
1579
+ // its first tile alone, and `fitsBp`, the span from the window's start whose
1580
+ // read fits, 0 where none does; undefined for a read within the budget. The
1581
+ // span grows a tile at a time, and where every tile fits and the window's
1582
+ // read is still over, as the tiles fetched to attach can make it, it is the
1583
+ // widest narrower one that fits, so it is never the window or more
1584
+ function bytesOver(bytesTo, budget, window, tile) {
1585
+ const bytes = bytesTo(window.end);
1586
+ let fitsBp = 0;
1587
+ let least;
1588
+ let more = bytes > budget;
1589
+ for (let cs = Math.floor(window.start / tile) * tile; more && cs < window.end; cs += tile) {
1590
+ const read = bytesTo(cs + 1);
1591
+ least !== null && least !== void 0 ? least : (least = read);
1592
+ more = read <= budget;
1593
+ fitsBp = more ? cs + tile - window.start : fitsBp;
1594
+ }
1595
+ const reaches = fitsBp >= window.end - window.start;
1596
+ const narrower = reaches ? narrowerFit(bytesTo, budget, window) : fitsBp;
1597
+ return bytes > budget
1598
+ ? {
1599
+ bytes,
1600
+ fitsBp: narrower,
1601
+ least: reaches && narrower === 0
1602
+ ? bytesTo(window.start + 1)
1603
+ : (least !== null && least !== void 0 ? least : bytes),
1604
+ }
1605
+ : undefined;
1606
+ }
1607
+ export const megabytes = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;