jbrowse-plugin-graphgenomeviewer 4.0.30 → 4.1.1

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.
Files changed (35) hide show
  1. package/dist/chunks/GbzBaseSyntenyAdapter-3BCUI2JI.js +8 -0
  2. package/dist/chunks/GbzBaseSyntenyAdapter-3BCUI2JI.js.map +7 -0
  3. package/dist/chunks/{GraphGenomeView-RNS6NHJR.js → GraphGenomeView-QOBHGMLE.js} +2 -2
  4. package/dist/chunks/{LinearGraphDisplay-3VVMBJ7R.js → LinearGraphDisplay-TPXW6POY.js} +2 -2
  5. package/dist/chunks/chunk-HW55QCJG.js +3 -0
  6. package/dist/chunks/chunk-HW55QCJG.js.map +7 -0
  7. package/dist/chunks/chunk-LGFKHSVJ.js +5 -0
  8. package/dist/chunks/{chunk-55NBPT36.js.map → chunk-LGFKHSVJ.js.map} +3 -3
  9. package/dist/chunks/chunk-SIP5IHWK.js +2 -0
  10. package/dist/chunks/{chunk-UCSUECJN.js.map → chunk-SIP5IHWK.js.map} +4 -4
  11. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +5 -5
  12. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
  13. package/package.json +3 -3
  14. package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.test.ts +13 -11
  15. package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.ts +23 -34
  16. package/src/GraphGenomeView/components/ElTree.test.tsx +24 -0
  17. package/src/GraphGenomeView/components/ElTree.tsx +33 -0
  18. package/src/GraphGenomeView/components/GraphCanvas.tsx +66 -2
  19. package/src/GraphGenomeView/components/WalkRowsOverlay.tsx +86 -255
  20. package/src/GraphGenomeView/components/usePaneGestures.ts +14 -0
  21. package/src/GraphGenomeView/genes/geneFeatures.ts +25 -5
  22. package/src/GraphGenomeView/genes/genes.test.ts +47 -0
  23. package/src/GraphGenomeView/model.test.ts +6 -3
  24. package/src/GraphGenomeView/model.ts +237 -2
  25. package/src/version.ts +1 -1
  26. package/dist/chunks/GbzBaseSyntenyAdapter-VXDXFND3.js +0 -8
  27. package/dist/chunks/GbzBaseSyntenyAdapter-VXDXFND3.js.map +0 -7
  28. package/dist/chunks/chunk-55NBPT36.js +0 -5
  29. package/dist/chunks/chunk-PFRZ4MRS.js +0 -3
  30. package/dist/chunks/chunk-PFRZ4MRS.js.map +0 -7
  31. package/dist/chunks/chunk-UCSUECJN.js +0 -2
  32. package/src/GraphGenomeView/components/referenceRampCss.test.ts +0 -27
  33. package/src/GraphGenomeView/components/referenceRampCss.ts +0 -39
  34. /package/dist/chunks/{GraphGenomeView-RNS6NHJR.js.map → GraphGenomeView-QOBHGMLE.js.map} +0 -0
  35. /package/dist/chunks/{LinearGraphDisplay-3VVMBJ7R.js.map → LinearGraphDisplay-TPXW6POY.js.map} +0 -0
@@ -0,0 +1,8 @@
1
+ import{a as Mn,b as Ps,c as kr,d as Nr}from"./chunk-KDIBFGZM.js";import{e as Rs,f as _s,g as Ae,h as vn,i as En,j as gt,k as An,l as wt,n as Cn}from"./chunk-LGFKHSVJ.js";import{a as Mr}from"./chunk-KWAXLUPQ.js";import"./chunk-LGKM2PZH.js";import{a as ks,d as Rr,e as _r,f as Pr}from"./chunk-4T7DPQTR.js";import{a as nt}from"./chunk-J4OLMLS5.js";import{a as Or,b as Tr}from"./chunk-SCMIJAAX.js";import"./chunk-7BKUWQE5.js";import{e as mt,f as ze,g as In}from"./chunk-KULNKXPT.js";import{a as Ms,b as de}from"./chunk-FY3BTKY4.js";var gs=Ms((Sd,ms)=>{ms.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function be(n,e){return 2*n+(e==="reverse"?1:0)}function R(n){return Math.floor(n/2)}function je(n){return n%2===0?"forward":"reverse"}function U(n){return n%2===1}function oe(n){return n%2===0?n+1:n-1}function Lr(n){return n==="left"?"right":"left"}function yt(n){return n==="forward"?"left":"right"}function xt(n){return n==="forward"?"right":"left"}function Fr(n){return n==="left"?"forward":"reverse"}function Hr(n){return n==="right"?"forward":"reverse"}function Ue(n,e){let t=R(n),r=R(e);return U(n)?r>t||r===t&&!U(e):r>=t}function bt(n){return Fe(n[0],n[n.length-1])}function Fe(n,e){return n===void 0||e===void 0?!0:U(n)===U(e)?!U(n):Ue(n,e)}var rt=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},$r=255,Os=256,St=class{source;sigma;threshold;constructor(e,t){this.source=new rt(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<$r?Math.floor(Os/this.sigma):0}next(){if(this.sigma>=$r){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let o=this.source.int();if(o===void 0)return;r+=o}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function qr(n){let e=new rt(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var It=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new St(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:oe(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];R(s.node)===R(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var Ts=["","A","C","G","T","N"];function Br(n){let e=n[n.length-1];if(e===void 0)return 0;let t=e,r=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),r+=1;return 3*(n.length-1)+r}function Gr(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=Ts[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var Ns={A:"T",C:"G",G:"C",T:"A",N:"N"};function vt(n){let e="";for(let t=n.length-1;t>=0;t--)e+=Ns[n[t]]??"N";return e}function Dr(n,e){let t=new Map;if(n!==void 0)for(let r of n.split(";")){let o=r.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function Ur(n){return{name:n.get("pggname"),subgraph:Dr(n.get("subgraph"),"subgraph"),translation:Dr(n.get("translation"),"translation")}}function zr(n,e){for(let[t,r]of e){let o=n.get(t);o||(o=new Set,n.set(t,o));for(let s of r)o.add(s)}}function Wr(n,e){let t={name:n,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(n,new Set([e.name])),zr(t.subgraph,e.subgraph),zr(t.translation,e.translation)),t}function jr(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function Qr(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of jr(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of jr(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function Yr(n){let e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;let o=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(o)].map(s=>s.toString(16).padStart(2,"0")).join("")}var Ls="_gbwt_ref";function ge(n){let e=`${n.sample}#${n.haplotype}#${n.contig}`;return n.end===void 0?e:`${e}[${n.fragment}-${n.end}]`}var Fs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Hs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function $s(n){let e=Fs.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Hs.exec(n);if(t)return{contig:t[1]};throw new Error(`"${n}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function We(n){return typeof n=="string"?$s(n):n}function Qe(n,e){return{sample:n.sample??Ls,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var qs=4096;function _n(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=qs?r[1]=t:e.push([t,t])}return e}var Bs=32768,Vr={mostChosenPaths:32},Rn=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let r=this.byNode.get(e.node);r||(r=new Map,this.byNode.set(e.node,r)),r.set(e.offset,t)}},fe=class extends Error{};function Et(n,e,t,r){return n==="forward"?e+t:e-r}function Xr(n,e,t,r){return n==="forward"?e-r:e+t}function Kr(n){return Fe(oe(n.handles[n.handles.length-1]),oe(n.handles[0]))}function ot(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function Zr(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let v=performance.now(),C=v-o;return o=v,C},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},a=(v,C)=>{let P=`${v}: ${C}`;i.walks[P]=(i.walks[P]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async v=>{let C=t.get(v)??c.get(v);if(C)return C;let P=await e.getRecord(v);if(i.graphFetches+=1,!P)throw new Error(`Node record ${v} is missing from the database`);return c.set(v,P),P},d=v=>t.get(v).sequenceLen,h=await e.pathsByHandle(),u=v=>{let C=h.get(v);return C!==void 0&&n.keep(C.name)},p=[],m=new Rn,w=new Map,x=new Set,S=new Set,g=async v=>{let C=(await l(v.node)).gbwt().lf(v.offset);return C===void 0||C.node===0?void 0:C},I=async(v,C)=>{let P=(await l(oe(v.node))).gbwt().predecessorAt(v.offset);if(P===void 0||C!==void 0&&!C.has(P))return;let N=(await l(P)).gbwt().offsetTo(v);if(N===void 0)throw new Error(`No offset in ${P} leads to ${v.node}:${v.offset}`);return{node:P,offset:N}},y=(v,C,P,N)=>{let B=P.map(te=>te.pos.node),W=P.map(te=>te.pos.offset),K=0;for(let te of B)K+=d(te);let H=C==="forward"?P[0].left:P[P.length-1].left,L=p.length;p.push({pathHandle:v,orientation:C,handles:B,offsets:W,len:K,hapStart:H,hapEnd:H+K,canonical:Fe(B[0],B[B.length-1]),source:N});for(let te of P)m.set(te.pos,L);let Y=w.get(v);return Y?Y.push(L):w.set(v,[L]),L},E=async(v,C,P,N)=>{let B=[],W=v;for(;;){r?.throwIfAborted();let H=await I(W.pos,t);if(!H)break;W={pos:H,left:Xr(P,W.left,d(W.pos.node),d(H.node))},B.push(W)}B.reverse();let K=[v];for(W=v;;){r?.throwIfAborted();let H=await g(W.pos);if(!H||!t.has(H.node))break;W={pos:H,left:Et(P,W.left,d(W.pos.node),d(H.node))},K.push(W)}return y(C,P,[...B,...K],N)},A=async(v,C,P,N)=>p[m.get(v.pos)??await E(v,C,P,N)],T=v=>{let C=v.handles[v.handles.length-1];return{pos:{node:C,offset:v.offsets[v.offsets.length-1]},left:v.orientation==="forward"?v.hapEnd-d(C):v.hapStart}},O=v=>{let C=v.handles[0];return{pos:{node:C,offset:v.offsets[0]},left:v.orientation==="forward"?v.hapStart:v.hapEnd-d(C)}},F=await E({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),M=p[F],z=()=>{if(i.fallback!==void 0)return{reference:M,pieces:[],stats:i};let v=new Map;p.forEach((P,N)=>{N!==F&&v.set(ot(P),[...v.get(ot(P))??[],P])});let C=[];for(let P of v.values()){let N=new Set;for(let B of P)B.canonical&&!N.has(B.orientation)&&(N.add(B.orientation),C.push(B),i.sources[B.source]+=1)}return i.sources.reference=1,i.pieces=C.length,{reference:M,pieces:C,stats:i}},_=v=>{let C=v-v%2;return e.haplotypeSamplesInRange(C,C+1)},j=async(v,C)=>{let P=C?x:S,N=C?S:x,B=v;for(;;){if(P.has(B))return;P.add(B);let W=p[B],K=C?T(W):O(W),H=0,L;for(;L===void 0;){r?.throwIfAborted();let Y=C?await g(K.pos):await I(K.pos);if(!Y){L="endmarker";break}let te=(await l(K.pos.node)).sequenceLen,ie=(await l(Y.node)).sequenceLen,le=C?Et(W.orientation,K.left,te,ie):Xr(W.orientation,K.left,te,ie);if(t.has(Y.node)){let ee=m.get(Y);ee===void 0?(B=await E({pos:Y,left:le},W.pathHandle,W.orientation,"chain"),N.add(B),L="landed"):(N.add(ee),L="merge")}else H>Bs?L="bound":(H+=ie,K={pos:Y,left:le})}if(a("chain",L),L!=="landed")return}},V=async v=>{if(n.context>v.context)throw new fe(`the context of ${n.context} bp exceeds the ${v.context} bp the haplotype index's stray rows cover`);let C=i.spacing;if(C===void 0)throw new fe("the haplotype index has no anchors");let{bin:P,bound:N}=v,{fills:B,inserted:W}=n.snarls;if(n.snarls.mode==="overlapping"&&B.length>0)throw new fe("the haplotype index's stray rows cover contained snarls only");for(let b of B){if(b.inserted>0&&b.low===b.high)throw new fe(`the haplotype index's stray rows leave out the snarl bounded by node ${b.low} at both ends`);if(b.inserted>0&&(v.snarlNodes===void 0||b.nodes>v.snarlNodes))throw new fe(v.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${b.nodes} nodes exceeds the ${v.snarlNodes} the haplotype index's stray rows cover`)}let K=Math.floor(n.window.start/P),H=Math.floor((n.window.end-1)/P),L=K*P,Y=(H+1)*P,te=await e.haplotypeBinNodes(n.referenceHandle,K,H);for(let b of t.keys()){let k=R(b);if(!U(b)&&!te(k)&&!W.has(k))throw new fe(`the haplotype index lists node ${k} of the subgraph in no bin that the window touches`)}let ie=new Map,le=async b=>{let k=await e.haplotypeAnchor(n.referenceHandle,b*C);return k&&ie.set(b,k),k},ee=Math.max(0,Math.floor((L-N)/C)-1),_e=Math.ceil((Y+N)/C)+1;for(await Promise.all(Array.from({length:_e-ee+1},(b,k)=>le(ee+k)));ee>0&&(ie.get(ee)?.pathOffset??Number.POSITIVE_INFINITY)>=L-N;)ee-=1,await le(ee);for(;ie.has(_e)&&ie.get(_e).pathOffset<=Y+N;)_e+=1,await le(_e);let J=[...ie.keys()].sort((b,k)=>b-k),ae=ie.get(J[0]??-1);if(!ae)throw new fe("the haplotype index has no anchors on this path");let xe=b=>ie.get(b).pathOffset,Te=new Map;for(let b of J){let k=R(ie.get(b).node);Te.set(k,[...Te.get(k)??[],b])}let Ne=[...Te.keys()],mr=await Promise.all(Ne.map(b=>_(2*b)));if(!mr[Ne.indexOf(R(ae.node))].some(b=>b.pathHandle===n.referenceHandle&&b.orientation==="forward"&&b.pathOffset===ae.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${ae.pathOffset} (node ${R(ae.node)}); it does not match this graph`);let gr=J.filter(b=>xe(b)<=n.window.start),vs=J.filter(b=>xe(b)>=n.window.end);i.anchors=[xe(gr[gr.length-1]??J[0]),xe(vs[0]??J[J.length-1])],i.anchorsRead=J.length;let bn=new Map,wr=new Set;if(Ne.forEach((b,k)=>{let $=Te.get(b),Q=$.length===1?$[0]:void 0;for(let G of mr[k])wr.add(G.pathHandle),G.orientation==="forward"&&u(G.pathHandle)&&bn.set(G.pathHandle,[...bn.get(G.pathHandle)??[],{k:Q,row:G}])}),i.chosenPaths=[...wr].filter(u).length,i.chosenPaths>Vr.mostChosenPaths)throw new fe(`${i.chosenPaths} chosen paths pass the anchors, more than ${Vr.mostChosenPaths}`);let ut=[],Le=Number.POSITIVE_INFINITY,Pe=0;for(let[b,k]of bn){k.sort(($,Q)=>$.row.pathOffset-Q.row.pathOffset);for(let $=0;$+1<k.length;$++){let Q=k[$],G=k[$+1];if(Q.k===void 0||G.k===void 0||Math.abs(Q.k-G.k)!==1)continue;let[Z,ne]=xe(Q.k)<=xe(G.k)?[Q,G]:[G,Q],re=xe(Z.k),se=xe(ne.k);re<Y&&se>=L?(ut.push({pathHandle:b,from:Q.row,to:G.row}),Le=Math.min(Le,re-N),Pe=Math.max(Pe,se+N)):re>=Y&&re-Y<=N?(ut.push({pathHandle:b,from:Z.row,to:void 0}),Le=Math.min(Le,re-N),Pe=Math.max(Pe,re+N)):se<L&&L-se<=N&&(ut.push({pathHandle:b,from:ne.row,to:void 0}),Le=Math.min(Le,se-N),Pe=Math.max(Pe,se+N))}}let Es=new Set(B.map(b=>`${b.low}:${b.high}`)),yr=await e.haplotypeStraysInBins(n.referenceHandle,K,H),As=yr.filter(b=>u(b.pathHandle)&&(b.snarl===void 0||Es.has(`${b.snarl[0]}:${b.snarl[1]}`))).sort((b,k)=>b.pathHandle-k.pathHandle||b.pathStart-k.pathStart);i.strays={bins:H-K+1,rows:yr.length,walked:0,outsideBp:0},Pe>0&&await n.prefetchReferenceRange(n.referenceHandle,Math.max(0,Le),Pe+1),i.ms.scan=s();let xr=8*C+2*(n.window.end-n.window.start),br=i.strays,et=0,Sr=b=>{if(br.outsideBp+=b,et+=b,et>xr)throw new fe(`a walk of a chosen path near the window went past its cap of ${xr} bp`)},Sn=new Map,Ir=(b,k,$)=>(Sn.get(b)??[]).some(([Q,G])=>Q<=k&&$<G),vr=(b,k,$)=>{Sn.set(b,[...Sn.get(b)??[],[k,$]])},Er=async(b,k,$,Q,G)=>{let Z=k,ne=$,re=ne;for(;Z&&ne<=Q;){r?.throwIfAborted();let se;if(t.has(Z.node)){let tt=await A({pos:Z,left:ne},b,"forward",G),Cr=T(tt);Z=Cr.pos,ne=Cr.left,se=d(Z.node),re=Math.max(re,tt.hapEnd)}else se=(await l(Z.node)).sequenceLen,Sr(se),re=Math.max(re,ne+se);Z=await g(Z),ne+=se}return re},Cs=async(b,k,$,Q)=>{let G={pos:k,left:$},Z=$;for(;G.left>Q;){r?.throwIfAborted();let ne=await I(G.pos);if(!ne)break;let re=(await l(ne.node)).sequenceLen,se=G.left-re;if(t.has(ne.node)){let tt=await A({pos:ne,left:se},b,"forward","section");G=O(tt),Z=Math.min(Z,tt.hapStart)}else Sr(re),G={pos:ne,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:b,from:k,to:$}of ut){let Q=k.pathOffset,G=($??k).pathOffset+N;if(Ir(b,Q-N,G))continue;let Z={node:k.node,offset:k.offset};et=0;let ne=await Er(b,Z,Q,G,"section");et=0;let re=await Cs(b,Z,Q,Q-N);vr(b,Math.min(re,Q-N),Math.max(ne,G+1)),a($?"section":"visit",$?"past the far anchor":"bound")}for(let b of As){if(Ir(b.pathHandle,b.pathStart,b.pathEnd))continue;et=0;let k=await Er(b.pathHandle,{node:b.node,offset:b.offset},b.pathStart,b.pathEnd,"stray");vr(b.pathHandle,b.pathStart,Math.max(k,b.pathEnd+1)),br.walked+=1}i.ms.walks=s();let Ar=[];i.scans=_n([...t.keys()].sort((b,k)=>b-k));for(let[b,k]of i.scans)for(let $ of await e.haplotypeSamplesInRange(b,k))if(i.scanRows+=1,t.has($.node)&&u($.pathHandle)){if(!(w.get($.pathHandle)??[]).some(Q=>{let G=p[Q];return G.hapStart<=$.pathOffset&&$.pathOffset<G.hapEnd}))throw new fe(`chosen path ${$.pathHandle} has a sample at ${$.pathOffset} on the window's nodes that no walk reached`);$.orientation==="reverse"&&Ar.push($)}for(let b of Ar)await A({pos:{node:b.node,offset:b.offset},left:b.pathOffset},b.pathHandle,"reverse","twin");i.ms.check=s()},ue=async()=>{let v=new Map,C=H=>{let L=ot(H),Y=v.get(L);Y?Y.add(H.orientation):v.set(L,new Set([H.orientation]))},P=0,N=()=>{for(;P<p.length;P++)C(p[P])};N();let B=H=>(v.get(ot(H))?.size??0)>1,W=2*f,K=(H,L)=>L===F?u(n.referenceHandle)&&Kr(H):!H.canonical||Kr(H);for(let H=0;H<p.length;H++){let L=p[H];if(B(L)||!K(L,H))continue;i.twins.tried+=1;let Y=L.orientation==="forward"?"reverse":"forward",te=T(L),ie=0,le;for(;!le&&ie<=W;){r?.throwIfAborted();let J=await g(te.pos);if(!J)break;let ae=(await l(J.node)).sequenceLen,xe=Et(L.orientation,te.left,(await l(te.pos.node)).sequenceLen,ae),Te=oe(J.node);le=(await e.haplotypeSamplesInRange(Te,Te)).find(Ne=>Ne.pathHandle===L.pathHandle&&Ne.orientation===Y&&Ne.pathOffset===xe),ie+=ae,te={pos:J,left:xe}}let ee=le&&{pos:{node:le.node,offset:le.offset},left:le.pathOffset},_e=0;for(;ee&&!B(L)&&_e<=W+L.len;){if(r?.throwIfAborted(),t.has(ee.pos.node)){let J=await A(ee,L.pathHandle,Y,"twin"),ae=p.indexOf(J);await j(ae,!0),await j(ae,!1),N(),ee=T(J)}if(!B(L)){let J=(await l(ee.pos.node)).sequenceLen;_e+=J;let ae=await g(ee.pos);ee=ae?{pos:ae,left:Et(Y,ee.left,J,(await l(ae.node)).sequenceLen)}:void 0}}if(N(),!B(L))throw new fe(`piece ${ot(L)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()};try{let v=await e.haplotypeStrayOptions();if(v===void 0)throw new fe("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await V(v),await ue()}catch(v){if(!(v instanceof fe))throw v;i.fallback=v.message}return z()}function Jr(n,e){return n.handles[0]-e.handles[0]||n.offsets[0]-e.offsets[0]}function At(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var Ct=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},Pn=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=At(a,o)-At(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),d=At(c,o),h=At(c,s);for(let u=0;u<h-d;u++){let p=r===1?c[h-1-u]-o:s-1-c[d+u],m=i.bestBefore(p),w=(m===-1?0:i.ending[m])+l;if(w>i.ending[p]&&(i.raise(p,w),a)){let x=a.count++;a.row[x]=f,a.column[x]=p,a.previous[x]=m===-1?-1:a.endingMatch[m],a.endingMatch[p]=x}}}}chain(e,t,r,o,s){let i=new Ct(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let f=i.bestBefore(o-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,o,s){let i=new Ct(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let f=0;f<s-o;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(r-1,t-1,-1,o,s),c=0,l=-1;for(let d=0;d<=i;d++){let h=a[d]+f[i-d];h>l&&(l=h,c=d)}return o+c}};function eo(n,e,t){let r=new Pn(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Gs=100,Tn=4e6,Ds=5e3,he=15,zs=64,js=8,ao=1,Nn=-4,ce=-6,Ce=-1,Ye=-(2**30),Rt=0,kn=1,fo=2;function He(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function Mt(n,e,t){return n>=t&&n>=e?Rt:t>=e?fo:kn}function co(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Ye),f=new Int32Array(s).fill(Ye),c=new Int32Array(s).fill(Ye);a[0]=0;for(let p=1;p<=o;p++)c[p]=ce+(p-1)*Ce,i[p]=(p===1?Rt:fo)<<4;for(let p=1;p<=r;p++){let m=new Int32Array(s).fill(Ye),w=new Int32Array(s).fill(Ye),x=new Int32Array(s).fill(Ye);w[0]=ce+(p-1)*Ce,i[p*s]=(p===1?Rt:kn)<<2;let S=n.charCodeAt(p-1);for(let g=1;g<=o;g++){let I=Mt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(S===e.charCodeAt(g-1)?ao:Nn);let y=Mt(a[g]+ce,f[g]+Ce,c[g]+ce);w[g]=Math.max(a[g]+ce,f[g]+Ce,c[g]+ce);let E=Mt(m[g-1]+ce,w[g-1]+ce,x[g-1]+Ce);x[g]=Math.max(m[g-1]+ce,w[g-1]+ce,x[g-1]+Ce),i[p*s+g]=I|y<<2|E<<4}a=m,f=w,c=x}let l=[],d=r,h=o,u=Mt(a[o],f[o],c[o]);for(;d>0||h>0;){let p=i[d*s+h]>>2*u&3;u===Rt?(l.push(n[d-1]===e[h-1]?"=":"X"),d-=1,h-=1):u===kn?(l.push("I"),d-=1):(l.push("D"),h-=1),u=p}for(let p of l.reverse())He(t,p,1)}function Us(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-ce-(t-1)*Ce,-ce+10*Math.log2(t)))+(Math.min(n,e)>0?-Nn:0)}function lo(n,e){let t=Math.abs(n-e);return t===0?0:.01*he*t+.5*Math.log2(t)}function to(n,e,t){return{qs:n.qs+e,qe:n.qs+t,ts:n.flipped?n.te-t:n.ts+e,te:n.flipped?n.te-e:n.ts+t,flipped:n.flipped}}function Ws(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-n.qs),l=Math.min(r,f-n.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,n.flipped?n.te-f:a-n.ts),l=Math.min(r,n.flipped?n.te-a:f-n.ts);c<l&&o.push([c,l])}if(o.length===0)return[n];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=he&&s.push(to(n,i,a)),i=Math.max(i,f);return r-i>=he&&s.push(to(n,i,r)),s}function Ln(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...n].sort((c,l)=>c.qs-l.qs||c.ts-l.ts);for(;f.length>0&&s.length<o;){let c=f.map(g=>g.qe-g.qs),l=new Int32Array(f.length).fill(-1),d=new Int32Array(f.length);for(let g=0;g<f.length;g++){let I=f[g],y=I.qe-I.qs;for(let E=g-1;E>=Math.max(0,g-Ds);E--){if(c[E]+y<=c[g])continue;let A=f[E];if(A.flipped===I.flipped&&A.qs<I.qs&&(I.flipped?I.te<A.te:A.ts<I.ts)){let O=Math.max(0,A.qe-I.qs,I.flipped?I.te-A.ts:A.te-I.ts),F=I.qs+O-A.qe,M=I.flipped?A.ts-(I.te-O):I.ts+O-A.te;if(O<y&&F<=e&&M<=e){let z=c[E]+y-O-r(F,M);z>c[g]&&(c[g]=z,l[g]=E,d[g]=O)}}}}let h=0;for(let g=1;g<f.length;g++)c[g]>c[h]&&(h=g);let u=[];for(let g=h;g>=0;g=l[g])u.push({run:f[g],trim:d[g]});if(u.reverse(),u.reduce((g,{run:I,trim:y})=>g+I.qe-I.qs-y,0)<t)break;s.push(u);let m=u[0],w=u.at(-1),{flipped:x}=m.run,S=x?a.flipped:a.forward;S.query.push([m.run.qs+m.trim,w.run.qe]),S.target.push(x?[w.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,w.run.te]);for(let{run:g,trim:I}of u)i.query.push([g.qs+I,g.qe]),i.target.push(g.flipped?[g.ts,g.te-I]:[g.ts+I,g.te]);f=f.flatMap(g=>{let I=g.flipped?a.flipped:a.forward;return Ws(g,[...i.query,...I.query],[...i.target,...I.target])}).sort((g,I)=>g.qs-I.qs||g.ts-I.ts)}return s}function On(n,e){let t=new Map;for(let s=0;s+he<=e.length;s++){let i=e.slice(s,s+he),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+he<=n.length;s++){let i=t.get(n.slice(s,s+he));if(i&&i.length<=zs)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+he,c.te=a+he;else{let l={qs:s,qe:s+he,ts:a,te:a+he,flipped:!1};o.set(f,l),r.push(l)}}}return r}function Qs(n,e){return[...On(n,e),...On(n,vt(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function _t(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,d=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?vt(d):d,r,s.qe,c)}He(r,"=",i.qe-f),s=i}}function Fn(n,e,t){He(t,"I",n.length),He(t,"D",e.length)}function ho(n,e,t){n.length*e.length<=Tn?co(n,e,t):Fn(n,e,t)}function Hn(n,e,t,r=0){let[o]=n.length*e.length>Tn&&r<js?Ln(On(n,e),1/0,he,lo,1):[];if(!o){ho(n,e,t);return}let s=(f,c,l)=>{Hn(f,c,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),_t(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function Ys(n,e,t){Hn(n,e,t)}function Vs(n,e,t){let r=[];_t(n,e,t,r,Ys);let o=n[0],s=n.at(-1),{flipped:i}=o.run;return{queryStart:o.run.qs+o.trim,queryEnd:s.run.qe,targetStart:i?s.run.ts:o.run.ts+o.trim,targetEnd:i?o.run.te-o.trim:s.run.te,strand:i?"-":"+",edits:i?r.reverse():r,sharedBases:0}}function Xs(n,e,t,r){let o=[];if(n.length*e.length<=Tn)co(n,e,t);else{let s=Ln(Qs(n,e),1/0,Math.max(r,he),lo),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>Vs(a,n,e)),i){let a=(l,d,h,u,p)=>{o.some(w=>u<w.queryEnd&&w.queryStart<u+l.length||p<w.targetEnd&&w.targetStart<p+d.length)?ho(l,d,h):Hn(l,d,h)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),_t(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else Fn(n,e,t)}return o}function $n(n,e){let t=n.strand==="-",r=0,o=0;for(let[s,i]of n.edits)e(s,i,t?n.queryEnd-1-r:n.queryStart+r,n.targetStart+o),s!=="D"&&(r+=i),s!=="I"&&(o+=i)}function no(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return $n(n,(i,a,f,c)=>{let l=e==="query"?f:c,d=h=>{let u=l+o*h;return u>=t&&u<r};if(i==="="||i==="X")for(let h=0;h<a;h++)d(h)&&(s+=i==="="?ao:Nn);else if(i==="I"==(e==="query"))for(let h=0;h<a;h++)d(h)&&(s+=h===0?ce:Ce);else d(0)&&(s+=ce+(a-1)*Ce)}),s}function ro(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function Ks(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,f=new Uint8Array(n.queryEnd-n.queryStart);for(let[u,p]of n.shared)f.fill(1,u-n.queryStart,p-n.queryStart);let c=u=>f[u-n.queryStart]===1,l=()=>{He(r,"I",o),He(r,"D",s),o=0,s=0};$n(n,(u,p,m)=>{if(u==="I")o+=p;else if(u==="D")s+=p;else{for(let w=0;w<p;w++)e[i+w]?(o+=1,s+=1,c(t?m-w:m+w)&&(a+=1)):((o>0||s>0)&&l(),He(r,u,1));i+=p}}),l();let d={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[u,p]=r.shift();d[u]+=p}let h={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[u,p]=r.pop();h[u]+=p}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?h.I:d.I),queryEnd:n.queryEnd-(t?d.I:h.I),targetStart:n.targetStart+d.D,targetEnd:n.targetEnd-h.D,edits:r,sharedBases:n.sharedBases-a}}function Zs(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];$n(c,(d,h,u,p)=>{if(d==="="||d==="X")for(let m=0;m<h;m++)l.push([c.strand==="-"?u-m:u+m,p+m])});for(let[d,h]of l)o.query[d]=Math.min(255,o.query[d]+1),o.target[h]=Math.min(255,o.target[h]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[d,h]of c)for(let[u,p]of[["query",d],["target",h]])if(o[u][p]>1){let m=i[u].get(p);m?m.at(-1)!==l&&m.push(l):i[u].set(p,[l])}});let a=new Map,f=(c,l,d)=>{let h=`${d}:${c}:${l}`,u=a.get(h);if(u===void 0){let[p,m]=ro(n[c],d),[w,x]=ro(n[l],d),S=Math.max(p,w),g=Math.min(m,x),[I,y]=[n[c],n[l]];u=[no(y,d,S,g)-no(I,d,S,g),y.sharedBases-I.sharedBases,c-l].find(A=>A!==0)>0,a.set(h,u)}return u};return n.flatMap((c,l)=>{let d=s[l],h=new Uint8Array(d.length);if(d.forEach(([m,w],x)=>{for(let[S,g]of[["query",m],["target",w]])!h[x]&&i[S].get(g)?.some(I=>I!==l&&f(l,I,S))&&(h[x]=1)}),!h.includes(1))return[c];let u=Ks(c,h),p=u?.edits.reduce((m,[w,x])=>m+(w==="="?x:0),0)??0;return u&&p>=r?[u]:[]})}function oo(n,e){return n.map(t=>{let r=e(R(t));return U(t)?vt(r):r}).join("")}function so(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(R(r)).length);return t}function io(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=R(i);e.has(f)?t.set(f,a):e.set(f,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function Js(n,e,t,r){let o=io(n),s=io(e),i=new Map;e.forEach((d,h)=>{s[h]||i.set(R(d),[h])});let a=2*e.length,f=(d,h,u)=>d*a+2*h+(u?1:0),c=new Set;n.forEach((d,h)=>{for(let u of o[h]?[]:i.get(R(d))??[])c.add(f(h,u,U(d)!==U(e[u])))});let l=[];return n.forEach((d,h)=>{for(let u of o[h]?[]:i.get(R(d))??[]){let p=U(d)!==U(e[u]),m=p?-1:1;if(!c.has(f(h-1,u-m,p))){let w=h,x=u;for(;w<n.length&&x>=0&&x<e.length&&c.has(f(w,x,p));)w+=1,x+=m;let S=x-m;l.push({qs:t[h],qe:t[w],ts:r[Math.min(u,S)],te:r[Math.max(u,S)+1],flipped:p})}}}),l}function po(n){let{query:e,target:t,sequenceOf:r}=n,o=oo(e,r),s=oo(t,r),i=Js(e,t,so(e,r),so(t,r)),a=n.minMatch??Gs,f=n.bases??!0,c=[];for(let l of Ln(i,n.maxGap??1/0,a,Us)){let d=[],h=l[0],u=l.at(-1),{flipped:p}=h.run;_t(l,o,s,d,f?(w,x,S,g,I)=>{for(let y of Xs(w,x,S,a)){let E=I+x.length;c.push({...y,queryStart:g+y.queryStart,queryEnd:g+y.queryEnd,targetStart:p?E-y.targetEnd:I+y.targetStart,targetEnd:p?E-y.targetStart:I+y.targetEnd,strand:p?"+":"-",edits:p?y.edits.reverse():y.edits,shared:[]})}}:Fn),c.push({queryStart:h.run.qs+h.trim,queryEnd:u.run.qe,targetStart:p?u.run.ts:h.run.ts+h.trim,targetEnd:p?h.run.te-h.trim:u.run.te,strand:p?"-":"+",edits:p?d.reverse():d,sharedBases:l.reduce((w,{run:x,trim:S})=>w+x.qe-x.qs-S,0),shared:l.map(({run:w,trim:x})=>[w.qs+x,w.qe])})}return Zs(c,o.length,s.length,a).map(({shared:l,...d})=>d).sort((l,d)=>l.queryStart-d.queryStart)}function uo(n){return n.map(([e,t])=>`${t}${e}`).join("")}var Se=class extends Error{name="SubgraphLimitError";limit;windowBp;walkedBp;constructor(e,t){super(t===void 0?`Subgraph size limit of ${e} nodes exceeded`:`Subgraph size limit of ${e} nodes exceeded ${t.walkedBp} bp into a ${t.windowBp} bp window`),this.limit=e,this.windowBp=t?.windowBp,this.walkedBp=t?.walkedBp}};function qn(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var it=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(qn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&qn(e[s],e[a])&&(a=s),i<e.length&&qn(e[i],e[a])&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}}return t}get size(){return this.heap.length}};function ei(n){let e=new Int32Array(n.length),t=new Int32Array(n.length);return n.forEach(([r,o],s)=>{e[s]=r,t[s]=o}),{pathAt:e,refAt:t,count:n.length}}function ti(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function $e(n){return`${n.node}:${n.offset}`}function st(n){return n.map(e=>oe(e)).reverse()}function ni(n,e){let t=e.identity.hapStart-n.identity.hapEnd,r=n.strand==="+"?e.refStart-n.refEnd:n.refStart-e.refEnd;return n.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function ri(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);go(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=n.identity.walkForward,[a,f]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,pieces:[...a.pieces,...f.pieces],soloAligned:[...a.soloAligned,...f.soloAligned],identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function oi(n,e,t){if(n.some(i=>i.weight!==void 0))return n;let r=new Map;n.forEach((i,a)=>{if(i.identity){let f=r.get(i.identity.pathHandle);f?f.push(a):r.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of r.values()){i.sort((l,d)=>n[l].identity.hapStart-n[d].identity.hapStart);let a=i[0],f=n[a],c=[];for(let l of i.slice(1)){let d=n[l],h=c.length===0?ni(f,d):void 0;if(h){f=ri(f,d,h),s.add(l);continue}if(!e(d)){c.push(l);continue}let u=e(f)?t([f,...c.map(p=>n[p]),d]):void 0;if(u){f=u;for(let p of[...c,l])s.add(p)}else o.set(a,f),a=l,f=d;c=[]}o.set(a,f)}return n.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function Pt(n,e){return{node:n.path[e],offset:n.offsets[e]}}var si=32768;function ii(n){let e=[...n].sort((r,o)=>r-o),t=[];for(let r of e){let o=t[t.length-1];o&&r-o[1]<=si?o[1]=r:t.push([r,r])}return t}var qe=class n{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new n(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(be(e,"forward"))}hasHandle(e){return this.records.has(e)}record(e){let t=this.records.get(e);if(!t)throw new Error(`Subgraph has no record for handle ${e}`);return t}sortedHandles(){return[...this.records.keys()].sort((e,t)=>e-t)}async addNode(e){if(this.signal?.throwIfAborted(),this.limit!==void 0&&this.nodeCount>=this.limit)throw new Se(this.limit);let t=await this.db.getRecord(be(e,"forward")),r=await this.db.getRecord(be(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${ge(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${ge(t.name)} at ${t.name.fragment} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`The fragment of ${ge(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(R(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`The fragment of ${ge(e.name)} at ${e.name.fragment} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=R(e);await this.ensureNode(o);let s=this.record(e),i=je(e),a=new it;return a.push(t,o,yt(i)),a.push(s.sequenceLen-t-1,o,xt(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords(Math.min(i,a),Math.max(i,a)+1)){let c=await this.db.indexedPositionsBetween(e,t,r),l=ii(c.map(d=>d.pos.node));await Promise.all(l.map(([d,h])=>this.db.prefetchRecords(d,h+2)))}}return o}async aroundInterval(e,t,r){if(t===0)throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof Se&&o.windowBp===void 0?new Se(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new it;for(;;){let f=R(o.node),c=je(o.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,yt(c));let d=l.sequenceLen-s;if(i<=d){a.push(i===d?0:d-i-1,f,xt(c));break}a.push(0,f,xt(c));let h=l.gbwt().lf(o.offset);if(!h)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=h,s=0,i-=d}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new it;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let r=new Set,o=new Set;for(let i of this.records.keys())o.add(R(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=Lr(f);if(!r.has(`${a}:${l}`)){let u=this.record(be(a,Fr(f))),p=i+u.sequenceLen-1;p<=t&&e.push(p,a,l)}let d=this.record(be(a,Hr(f))),h=i+1;if(h<=t)for(let u of d.successors()){let p=R(u),m=yt(je(u));r.has(`${p}:${m}`)||e.push(h,p,m)}}for(let i of o)this.records.delete(be(i,"forward")),this.records.delete(be(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let r=[e,oe(t)],o=new Set([R(e),R(t)]),s=[];for(;r.length>0;){let i=r.pop(),a=R(i);this.hasNode(a)||(await this.addNode(a),s.push(a));for(let f of this.record(i).successors()){let c=R(f);o.has(c)||(r.push(f,oe(f)),o.add(c))}}return{inserted:s,nodes:o.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[r,o]of await this.overlappingSnarls(e)){let{inserted:s,nodes:i}=await this.fillBetween(r,o),a=R(r),f=R(o);this.snarlFills.push({low:Math.min(a,f),high:Math.max(a,f),nodes:i,inserted:s.length});for(let c of s)this.snarlNodes.add(c);t+=s.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?Ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(o=>this.hasHandle(o));return r===void 0?!1:t.length>1||this.record(oe(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(oe(l))).successors().length>1},r=async f=>{let c=await e(oe(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[oe(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=R(f);if(!this.hasHandle(f)&&!o.has(c)){o.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let d of["forward","reverse"])s.push(...(await e(be(c,d))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((y,E)=>i.set(y,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let y=0;y<s;y++){let E=this.record(o[y]),A=E.gbwt().decompressArrays();f[y]=E.sequenceLen,c.push(A),a[y+1]=a[y]+A.nodes.length}let l=a[s],d=new Int32Array(l),h=new Int32Array(l),u=new Uint8Array(l);for(let y=0;y<s;y++){let E=c[y];d.set(E.nodes,a[y]),h.set(E.offsets,a[y])}c.length=0;for(let y=0;y<l;y++){let E=i.get(d[y]);E===void 0?d[y]=-1:(d[y]=E,u[a[E]+h[y]]=1)}let p=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,w,x=(y,E,A)=>{let T=[],O=0,F=0,M=-1,z=y,_=E;for(;;){z===p&&_===m&&(M=O),A&&(A.push(o[z]),T.push(_)),O+=1,F+=f[z];let j=a[z]+_,V=d[j];if(V<0)break;_=h[j],z=V}return{offsets:T,len:F,refAt:M,last:z}},S=(y,E,A,T)=>{T>=0&&(this.refId=this.paths.length,w=T),this.paths.push({path:y,offsets:E,len:A,weight:void 0,identity:void 0})},g=new Int32Array(s);for(let y=0;y<s;y++){let E=o[y];if(!U(E)){let A=a[y],T=a[y+1]-A;for(let O=0;O<T;O++)if(u[A+O]===0){let F=[],{offsets:M,len:z,refAt:_,last:j}=x(y,O,F),V=o[j];if(_>=0||Fe(E,V)){if(S(F,M,z,_),!U(V)){let ue=i.get(oe(V));g[ue]=g[ue]+1}}else this.twinStarts.add($e({node:E,offset:O}))}}}for(let y=0;y<s;y++){let E=o[y];if(U(E)){let A=a[y],T=a[y+1]-A,O=0;for(let M=0;M<T;M++)u[A+M]===0&&(O+=1);let F=(p===void 0||w!==void 0)&&O===g[y];for(let M=0;M<T;M++)if(u[A+M]===0){let z=F?void 0:x(y,M,void 0);if(z&&(z.refAt>=0||Fe(E,o[z.last]))){let _=[],{offsets:j,len:V,refAt:ue}=x(y,M,_);S(_,j,V,ue)}else this.twinStarts.add($e({node:E,offset:M}))}}}let I=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),I&&(this.refId=this.paths.indexOf(I)),r){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=r.nodeOffset;for(let T of y.path.slice(0,w))E+=this.record(T).sequenceLen;let A=r.seqOffset-E;this.refInterval=[A,A+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:A,hapEnd:A+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=t?.path,o=r&&!bt(r)?st(r):void 0,s=c=>o!==void 0&&kt(c,o)===0||kt(c,st(c))===0,i=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,l)=>kt(c.path,l.path)||c.len-l.len||(c===t?-1:l===t?1:0));let a=[],f;for(let c of this.paths){let l=a[a.length-1],d=i&&c!==t&&s(c.path);this.twinDeferred||=d,l&&kt(l.path,c.path)===0&&!d?l.weight=(l.weight??1)+(c.weight??1):(c===t&&(f=a.length),a.push({...c,weight:c.weight??1}))}this.paths=a,this.refId=f}mergeDistinct(){this.distinctPaths(!1)}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,r=i=>`${i.pathHandle}:${i.hapStart}-${i.hapEnd}`,o=new Set;e?.identity&&t&&o.add(r({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let i of this.paths)i!==e&&i.identity?.orientation==="forward"&&o.add(r(i.identity));let s=this.paths.filter(i=>i===e||i.identity?.orientation!=="reverse"||!o.has(r(i.identity)));s.length<this.paths.length&&(this.paths=s,this.refId=e===void 0?void 0:s.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(i=>i.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((i,a)=>a!==this.refId&&i.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let r=this.refId===void 0?void 0:this.paths[this.refId],o=this.paths.filter((i,a)=>a===this.refId||i.identity!==void 0&&e(i.identity.name)),s=new Set;for(let i of o)for(let a of i.path)s.add(R(a));for(let i of[...this.records.keys()])s.has(R(i))||this.records.delete(i);this.paths=o,this.refId=r===void 0?void 0:o.indexOf(r)}async extractChosenPaths(e,t,r,o){this.clearPaths();let s=e.position.seqOffset,i=await Zr({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:s-e.position.nodeOffset,window:{start:s,end:s+t},context:o,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:r,signal:this.signal,prefetchReferenceRange:(l,d,h)=>this.prefetchReferenceRange(l,d,h)});if(this.stats.keep=i.stats,i.stats.fallback!==void 0)return!1;let a=await this.db.pathsByHandle(),f=l=>({path:l.handles,offsets:l.offsets,len:l.len,weight:void 0,identity:{pathHandle:l.pathHandle,name:l===i.reference?e.name:a.get(l.pathHandle).name,orientation:l.orientation,hapStart:l.hapStart,hapEnd:l.hapEnd}}),c=[i.reference,...i.pieces].sort(Jr);return this.paths=c.map(f),this.refId=c.indexOf(i.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[i.reference.hapStart,i.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");let e=await this.db.haplotypeSampleGap()??4096,t=_n(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[p,m]of t)for(let w of await this.db.haplotypeSamplesInRange(p,m))r.set($e(w),w);let o=p=>{let m=0,w=t.length-1;for(;m<w;){let S=m+w+1>>1;t[S][0]<=p?m=S:w=S-1}let x=t[m];return x[0]<=p&&p<=x[1]},s=new Map;this.paths.forEach((p,m)=>{p.path.length>0&&m!==this.refId&&s.set($e(Pt(p,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((p,m)=>{m!==this.refId&&i.fragmentLengths.push(p.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),f=p=>(i.graphLookups+=1,a(p)),c=async(p,m)=>{if(o(p.node))return r.get($e(p));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let w=await this.db.haplotypeSampleAt(p.node,p.offset);return w||(i.companionMisses+=1),w},l=new Map,d=async p=>{let m=l.get(p);if(!m){let w=await this.db.getPath(p);if(!w)throw new Error(`Path ${p} is missing from the database`);m=w.name,l.set(p,m)}return m},h=(p,m,w)=>p.orientation==="forward"?{pathHandle:p.pathHandle,orientation:"forward",base:p.pathOffset-m}:{pathHandle:p.pathHandle,orientation:"reverse",base:p.pathOffset+m+w},u=(p,m)=>p.orientation==="forward"?{pathHandle:p.pathHandle,orientation:"forward",base:p.hapStart-m}:{pathHandle:p.pathHandle,orientation:"reverse",base:p.hapEnd+m};for(let p=0;p<this.paths.length;p++){let m=this.paths[p];if(p===this.refId||m.identity)continue;let w=[],x=new Set,S={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(S);let g,I=0,y=p,E;for(;g===void 0;){if(this.signal?.throwIfAborted(),y!==void 0){if(x.has(y)){S.end="cycle";break}x.add(y);let M=this.paths[y];w.push({index:y,startBp:I}),S.fragments+=1;let z=I;for(let j=0;j<M.path.length;j++){let V=Pt(M,j),ue=r.get($e(V)),v=this.record(V.node).sequenceLen;if(ue){g=h(ue,z,v);break}z+=v}if(I+=M.len,g){S.end="in-fragment sample";break}let _=Pt(M,M.path.length-1);E=this.record(_.node).gbwt().lf(_.offset),y=void 0}if(E===void 0||E.node===0){S.end="endmarker";break}let A=$e(E),T=s.get(A);if(T!==void 0){let M=this.paths[T].identity;if(M){g=u(M,I),S.end="identified sibling";break}y=T;continue}this.records.has(E.node)&&(S.reentries+=1),this.twinStarts.has(A)&&(S.twinLandings+=1);let O=await c(E,S),F=await f(E.node);if(O){g=h(O,I,F.sequenceLen),S.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,S.steps+=1,I-w[w.length-1].startBp>4*e+4*F.sequenceLen){S.end="bound";break}I+=F.sequenceLen,E=F.gbwt().lf(E.offset)}if(g){S.pathHandle=g.pathHandle;let A=await d(g.pathHandle);for(let{index:T,startBp:O}of w){let F=this.paths[T];F.identity=g.orientation==="forward"?{pathHandle:g.pathHandle,name:A,orientation:"forward",hapStart:g.base+O,hapEnd:g.base+O+F.len}:{pathHandle:g.pathHandle,name:A,orientation:"reverse",hapStart:g.base-O-F.len,hapEnd:g.base-O}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=ti(c,a);if(l===void 0)return;o[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[o]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[e.length-o-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),X(r,"M",i),go(r,o-i-a,s-i-a),X(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??ei(eo(e,t,d=>this.record(d).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(d,h,u,p)=>{d===h?X(s,"D",i[p]-i[u]):u===p?X(s,"I",this.pathLen(e.slice(d,h))):this.align(e.slice(d,h),t.slice(u,p),s)},f=0,c=0,l=0;for(let d=0;d<o.count;d++){let h=o.pathAt[d],u=o.refAt[d];(c!==h||l!==u)&&a(c,h,l,u);let p=this.record(e[h]).sequenceLen;X(s,"M",p),f+=p,c=h+1,l=u+1}return a(c,e.length,l,t.length),{edits:s,matched:f,matches:o}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(bt(r)&&(t.identity===void 0||!bt(st(t.path))))o={...this.editsAgainst(t.path,r),flipped:!1};else{let s=st(t.path),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={...this.editsAgainst(t.path,r),flipped:!1};else if(i===0)o={...this.editsAgainst(s,r),flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.alignment(e)?.edits.map(([t,r])=>`${r}${t}`).join("")}alignments(){let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,r=this.refPrefix(t)[t.length],o=(l,d,h,u)=>{let p=fi(l),m=this.paths[h[0]],w=this.paths[h[h.length-1]],x=m.identity,S=x?.orientation==="forward",[g,I]=S?[m,w]:[w,m];return{strand:d,refStart:e.start+p.leading,refEnd:e.start+r-p.trailing,edits:p.edits,weight:m.weight,path:h.flatMap(y=>this.paths[y].path),start:Pt(m,0),pieces:h,soloAligned:u,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+g.identity.hapStart,hapEnd:x.name.fragment+I.identity.hapEnd,walkForward:S}}},s=l=>l.soloAligned.reduce((d,h)=>d+h,0),i=l=>l.pieces.reduce((d,h)=>d+this.paths[h].len,0),a=l=>2*s(l)>=i(l),f=l=>{let d=l[0],h=l[l.length-1],u=d.identity.walkForward;if(l.some((_,j)=>_.strand!==d.strand||_.identity.walkForward!==u||j>0&&_.identity.hapStart<l[j-1].identity.hapEnd))return;let p=u?l:[...l].reverse(),m=p.flatMap(_=>_.pieces),w=p.flatMap(_=>_.soloAligned),x=d.strand==="+"!==u,S=m.map(_=>this.paths[_]),g=S.slice(1).map((_,j)=>{let V=S[j].identity;return u?_.identity.hapStart-V.hapEnd:V.hapStart-_.identity.hapEnd}),I=x?[...S].reverse():S,y=x?[...g].reverse():g,E=I.flatMap(_=>x?st(_.path):_.path),{edits:A}=this.editsAgainst(E,t),T=mo(A,I.map(_=>_.len)),O=new Map((x?[...m].reverse():m).map((_,j)=>[_,T[j]])),F=_=>2*_.pieces.reduce((j,V)=>j+O.get(V),0)>=s(_);if(!F(d)||!F(h))return;let M=[],z=0;return I.slice(0,-1).forEach((_,j)=>{z+=_.len,M.push([z,y[j]])}),o(ci(A,M),d.strand,m,w)},c=[];return this.paths.forEach((l,d)=>{if(d===this.refId)return;let{edits:h,flipped:u}=this.alignment(d),p=l.identity,m=p?p.orientation==="forward"!==u:!u;c.push(o(h,m?"+":"-",[d],mo(h,[l.len])))}),oi(c,a,f).map(l=>{let{edits:d,identity:h,pieces:u,soloAligned:p,...m}=l,w={...m,cigar:li(d)};return h?{...w,resolved:!0,name:h.name,label:ge({...h.name,fragment:h.hapStart,end:h.hapEnd}),pathHandle:h.pathHandle,hapStart:h.hapStart,hapEnd:h.hapEnd}:{...w,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:d}=l;return d?[{name:d.name,start:d.name.fragment+d.hapStart,steps:Tt(l,d)}]:[]}),i=l=>d=>d.sample===l.sample&&d.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(be(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(d=>f(d.name)).flatMap(d=>po({...o,query:d.steps,target:l.steps,sequenceOf:c}).map(h=>({query:d.name,queryStart:d.start+h.queryStart,queryEnd:d.start+h.queryEnd,strand:h.strand,target:l.name,targetStart:l.start+h.targetStart,targetEnd:l.start+h.targetEnd,cigar:uo(h.edits),matches:h.edits.reduce((u,[p,m])=>u+(p==="="?m:0),0),columns:h.edits.reduce((u,[,p])=>u+p,0),sharedBases:h.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=be(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&Ue(o,s)&&t.push([r==="reverse"?1:0,R(s),U(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!U(r)){let o=R(r),s=`S ${o} ${this.record(r).sequence}
2
+ `;for(let[i,a,f]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${f?"-":"+"}
3
+ `;t.push(e.encode(s))}return Yr(t)}async toGFA(e={}){let t=e.cigar??!1,r=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...Qr(Wr(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)U(c)||r.push(`S ${R(c)} ${this.record(c).sequence}`);let s=c=>U(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&Ue(c,l)&&r.push(`L ${R(c)} ${s(c)} ${R(l)} ${s(l)} 0M`);let i=(c,l,d,h,u)=>{let p=Tt(c,l).map(x=>`${U(x)?"<":">"}${R(x)}`).join(""),m=c.weight===void 0?"":` WT:i:${c.weight}`,w=u===void 0?"":` CG:Z:${u}`;return`W ${d.sample} ${d.haplotype} ${d.contig} ${d.fragment} ${h} ${p}${m}${w}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&r.push(i(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let f=1;return this.paths.forEach((c,l)=>{if(l!==this.refId){let d=e.names!=="anonymous"?c.identity:void 0,h=t?this.alignToRef(l):void 0;r.push(d?i(c,d,{...d.name,fragment:d.name.fragment+d.hapStart},d.name.fragment+d.hapEnd,h):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,h)),f+=1}}),`${r.join(`
4
+ `)}
5
+ `}outputPaths(e){let t=e.cigar??!1,r=[],o=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let i={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};r.push({info:this.paths[this.refId],identity:void 0,name:ge({...i,end:this.refPath.fragment+this.refInterval[1]}),cigar:void 0})}let s=1;return this.paths.forEach((i,a)=>{if(a===this.refId)return;let f=e.names!=="anonymous"?i.identity:void 0;r.push({info:i,identity:f,name:f?ge({...f.name,fragment:f.name.fragment+f.hapStart,end:f.name.fragment+f.hapEnd}):ge({sample:"unknown",contig:o,haplotype:s,fragment:0,end:i.len}),cigar:t?this.alignToRef(a):void 0}),s+=1}),r}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Ue(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!U(s)).map(s=>({id:String(R(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(R(s)),from_is_reverse:U(s),to:String(R(i)),to_is_reverse:U(i)});let o=this.outputPaths(e).map(s=>ai(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!U(i)),r=new Int32Array(t.length),o=[];t.forEach((i,a)=>{r[a]=R(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:r,nodeSequences:o,edges:Int32Array.from(s),paths:this.outputPaths(e).map(i=>({name:i.name,weight:i.info.weight,cigar:i.cigar,steps:Int32Array.from(Tt(i.info,i.identity))}))}}};function Tt(n,e){return e?.orientation==="reverse"?n.path.map(t=>oe(t)).reverse():n.path}function ai(n,e,t,r){return{name:t,...n.weight===void 0?{}:{weight:n.weight},...r===void 0?{}:{cigar:r},path:Tt(n,e).map(o=>({id:String(R(o)),is_reverse:U(o)}))}}function kt(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n[r],s=e[r];if(o!==s)return o<s?-1:1}return n.length-e.length}function X(n,e,t){if(t===0)return;let r=n[n.length-1];r?.[0]===e?r[1]+=t:n.push([e,t])}function Ot(n){return n===0?0:6+(n-1)}function go(n,e,t){if(e===0)X(n,"D",t);else if(t===0)X(n,"I",e);else{let r=Math.min(e,t),o=4*r+Ot(e-r)+Ot(t-r),s=Ot(e)+Ot(t);o<=s?(X(n,"M",r),X(n,"I",e-r),X(n,"D",t-r)):(X(n,"I",e),X(n,"D",t))}}function fi(n){let e=0;for(;e<n.length&&n[e][0]!=="M";)e+=1;if(e===n.length){let a=n.filter(([c])=>c==="I"),f=n.filter(([c])=>c==="D").reduce((c,[,l])=>c+l,0);return{edits:a.map(([c,l])=>[c,l]),leading:0,trailing:f}}let t=n.length;for(;n[t-1][0]!=="M";)t-=1;let r=a=>({inserted:a.reduce((f,[c,l])=>f+(c==="I"?l:0),0),deleted:a.reduce((f,[c,l])=>f+(c==="D"?l:0),0)}),o=r(n.slice(0,e)),s=r(n.slice(t)),i=[];X(i,"I",o.inserted);for(let[a,f]of n.slice(e,t))X(i,a,f);return X(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function mo(n,e){let t=e.map(()=>0),r=e.length-1,o=0,s=e[0],i=0;for(let[a,f]of n){if(a==="D")continue;let c=f;for(;c>0;){for(;o<r&&i>=s;)o+=1,s+=e[o];let l=o<r?Math.min(c,s-i):c;a==="M"&&(t[o]+=l),i+=l,c-=l}}return t}function ci(n,e){let t=[],r=0,o=0;for(let[s,i]of n){if(s==="D"){X(t,s,i);continue}let a=r;for(;o<e.length&&e[o][0]<r+i;){let[f,c]=e[o];X(t,s,f-a),X(t,"I",c),a=f,o+=1}X(t,s,r+i-a),r+=i}for(;o<e.length;o++)X(t,"I",e[o][1]);return t}function li(n){return n.map(([e,t])=>`${t}${e}`).join("")}async function wo(n,e){let t=qe.create(n,e),r=await t.pathPosition(Qe(We(e.path),e.offset));return await t.aroundPosition(r.position.handle,r.position.nodeOffset,e.context??100),await t.extractSnarls(e.snarls??"none"),t.extractPaths(r,e.haplotypes??"all"),t}async function di(n,e){let{start:t,end:r}=e,o=qe.create(n,e);try{let s=await o.pathPosition(Qe(We(e.path),t));return await o.prefetchReferenceWalk(s,r-t),await o.aroundInterval(s.position,r-t,e.context??100),await o.extractSnarls(e.snarls??"none"),{subgraph:o,reference:s}}catch(s){throw s instanceof Se&&s.windowBp===void 0?new Se(s.limit,{windowBp:r-t,walkedBp:o.referenceWalkedBp??0}):s}}async function Bn(n,e){let{keep:t}=e,r=e.haplotypes??"all",o=r==="all"||r==="distinct";if(t!==void 0&&o&&!n.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await di(n,e);return t===void 0||!o?(s.extractPaths(i,r),s):(await s.extractChosenPaths(i,e.end-e.start,t,e.context??100)||(s.extractPaths(i,"all"),await s.identifyPaths()),s.keepHaplotypes(t),r==="distinct"&&s.mergeDistinct(),s)}async function yo(n,e){let t=e.haplotypes??"all",r=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(r==="overlapping"&&e.nodeIds.length>1)throw new Error("Overlapping snarls cannot be extracted for a node-based query with multiple nodes");let o=qe.create(n,e);return await o.aroundNodes(e.nodeIds,e.context??100),await o.extractSnarls(r),o.extractPaths(void 0,t),o}async function xo(n,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let r=qe.create(n,e);return await r.betweenNodes(e.startHandle,e.endHandle),r.extractPaths(void 0,t),r}function ve(n,e){let t=0;for(let o=0;o<8;o++){let s=n[e+o];if(s===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(s&127),(s&128)===0)return[t,e+o+1]}let r=n[e+8];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+r,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function hi(n,e,t){switch(t){case 1:return n.getInt8(e);case 2:return n.getInt16(e);case 3:return n.getInt8(e)<<16|n.getUint16(e+1);case 4:return n.getInt32(e);case 6:return n.getInt16(e)*4294967296+n.getUint32(e+2);default:{let r=n.getBigInt64(e);if(r>BigInt(Number.MAX_SAFE_INTEGER)||r<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${r} exceeds the safe integer range`);return Number(r)}}}var pi=new TextDecoder;function Nt(n){let[e,t]=ve(n,0),r=[],o=t;for(;o<e;){let[a,f]=ve(n,o);r.push(a),o=f}let s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=e;return r.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=hi(s,i,f);return i+=f,c}if(a===7){let f=s.getFloat64(i);return i+=8,f}if(a===8)return 0;if(a===9)return 1;if(a>=12){let f=a-12>>1,c=n.subarray(i,i+f);return i+=f,a%2===0?c:pi.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var at=2,Ft=5,So=10,Lt=13;function Io(n,e){return n[e]*256+n[e+1]}function ke(n,e){return n[e]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function ui(n,e){let t=n[e];if(t!==at&&t!==Ft&&t!==So&&t!==Lt)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===at||t===Ft;return{type:t,cellCount:Io(n,e+3),rightChild:r?ke(n,e+8):0,cellPointers:e+(r?12:8)}}function Me(n,e,t){return Io(n,e.cellPointers+2*t)}var mi=4096,gi=4096,Ht=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let r=this.usable,o=t?Math.floor((r-12)*64/255)-23:r-35;if(e<=o)return e;let s=Math.floor((r-12)*32/255)-23,i=s+(e-s)%(r-4);return i<=o?i:s}async payload(e,t,r,o){let s=this.localPayloadSize(r,o);if(s===r)return e.subarray(t,t+r);let i=new Uint8Array(r);i.set(e.subarray(t,t+s),0);let a=s,f=ke(e,t+s);for(;f!==0&&a<r;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,r-a));i.set(l,a),a+=l.length,f=ke(c,0)}if(a!==r)throw new Error("SQLite overflow chain ended before the payload was complete");return i}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:ui(t,e===1?100:0)}}tableDepth(e,t){let r=this.tableDepths.get(e);return r||(r=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Lt)return s;if(a.type!==Ft)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:ke(i,Me(i,a,f))}})(),this.tableDepths.set(e,r),r.catch(()=>this.tableDepths.delete(e))),r}childIndexFor(e,t,r){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=ve(e,Me(e,t,i)+4);a<r?o=i+1:s=i}return o}async prefetchRowidRange(e,t,r){let o=await this.tableDepth(e,t),s=[e];for(let i=0;i<o;i++){let a=await Promise.all(s.map(c=>this.pageAt(c))),f=[];if(a.forEach(({page:c,header:l},d)=>{let h=d===0?this.childIndexFor(c,l,t):0,u=d===a.length-1?this.childIndexFor(c,l,r):l.cellCount;for(let p=h;p<=u;p++)f.push(p===l.cellCount?l.rightChild:ke(c,Me(c,l,p)))}),f.length>gi)return!1;this.pager.prefetch(f),s=f}return!0}async tableRowid(e,t){let r=e;for(;;){let{page:o,header:s}=await this.pageAt(r);if(s.type===Lt){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,d=Me(o,s,l),[h,u]=ve(o,d),[p,m]=ve(o,u);if(p===t)return Nt(await this.payload(o,m,h,!1));p<t?f=l+1:c=l}return}if(s.type!==Ft)throw new Error("SQLite table b-tree contains an index page");let i=0,a=s.cellCount;for(;i<a;){let f=i+a>>1,c=Me(o,s,f),[l]=ve(o,c+4);l<t?i=f+1:a=f}r=i===s.cellCount?s.rightChild:ke(o,Me(o,s,i))}}async*tableScan(e){let{page:t,header:r}=await this.pageAt(e);if(r.type===Lt)for(let o=0;o<r.cellCount;o++){let s=Me(t,r,o),[i,a]=ve(t,s),[f,c]=ve(t,a);yield{rowid:f,values:Nt(await this.payload(t,c,i,!1))}}else{let o=[];for(let s=0;s<r.cellCount;s++)o.push(ke(t,Me(t,r,s)));o.push(r.rightChild),this.pager.prefetch(o);for(let s of o)yield*this.tableScan(s)}}decodedCells(e,t){let r=this.decodedIndexPages.get(e);if(r)this.decodedIndexPages.delete(e);else if(r=new Array(t.cellCount),this.decodedIndexPages.size>=mi){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,r),r}async indexCell(e,t,r,o){let s=this.decodedCells(e,r),i=s[o];if(!i){let a=Me(t,r,o),f=r.type===at,[c,l]=ve(t,f?a+4:a);i={values:Nt(await this.payload(t,l,c,!0)),leftChild:f?ke(t,a):0},s[o]=i}return i}async*indexScanFrom(e,t){let{page:r,header:o}=await this.pageAt(e),s=0,i=o.cellCount;for(;s<i;){let a=s+i>>1,f=await this.indexCell(e,r,o,a);bo(f.values,t)<0?s=a+1:i=a}for(let a=s;a<o.cellCount;a++){let f=await this.indexCell(e,r,o,a);o.type===at&&(yield*this.indexScanFrom(f.leftChild,t)),yield f.values}o.type===at&&(yield*this.indexScanFrom(o.rightChild,t))}async indexSeekLE(e,t){let r,o=e;for(;;){let{page:s,header:i}=await this.pageAt(o),a=0,f=i.cellCount,c=0;for(;a<f;){let l=a+f>>1,d=await this.indexCell(o,s,i,l);bo(d.values,t)<=0?(r=d.values,a=l+1):(c=d.leftChild,f=l)}if(i.type===So)return r;o=a===i.cellCount?i.rightChild:c}}};function bo(n,e){for(let t=0;t<e.length;t++){let r=n[t],o=e[t];if(typeof r!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(r!==o)return r<o?-1:1}return 0}var $t=class{blocks=new Map;blockSize;maxBlocks;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,r,o={}){this.source=e,this.pageSize=t,this.fileSize=r;let s=o.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(s/t)*t),this.maxBlocks=o.maxBlocks??256}async read(e,t){let r=await this.readRetrying(e,t);if(this.bytesFetched+=r.length,r.length<e)throw new Error(`the file ends at byte ${t+r.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return r}async readRetrying(e,t){let r=0;for(;;)try{return await this.source.read(e,t)}catch(o){if(r+=1,r>=3)throw o;await new Promise(s=>setTimeout(s,200*r))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){let t=this.blocks.get(e);if(t)return this.blocks.delete(e),this.blocks.set(e,t),t;let r=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-r),s=this.read(o,r);return this.fetches+=1,this.blocks.set(e,s),this.forgetOnFailure(s,[e]),this.evict(),s}prefetch(e){let t=[...new Set(e.map(o=>Math.floor((o-1)*this.pageSize/this.blockSize)))].filter(o=>!this.blocks.has(o)).sort((o,s)=>o-s),r=0;for(;r<t.length;){let o=r+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[r],o-r),r=o}}fetchRun(e,t){let r=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-r),s=this.read(o,r);this.fetches+=1;let i=[];for(let a=0;a<t;a++){let f=a*this.blockSize;i.push(e+a),this.blocks.set(e+a,s.then(c=>c.subarray(f,f+this.blockSize)))}this.forgetOnFailure(s,i),this.evict()}forgetOnFailure(e,t){e.catch(()=>{for(let r of t)this.blocks.delete(r)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let r=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return r.subarray(o,o+this.pageSize)}};var ft=class n{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){let r=await e.read(t.blockSize??65536,0),o=r.subarray(0,100);if(new TextDecoder().decode(o.subarray(0,15))!=="SQLite format 3"||o.length<100)throw new Error("Not a SQLite database");let i=new DataView(o.buffer,o.byteOffset,o.byteLength),a=i.getUint16(16),f=a===1?65536:a,c=o[20]??0,l=i.getUint32(56);if(l!==1)throw new Error(`SQLite text encoding ${l} is not UTF-8`);let d=i.getUint32(28);if(d===0||i.getUint32(24)!==i.getUint32(92))throw new Error("SQLite header has no valid database size; the file was written by SQLite older than 3.7.0");let h=d*f,u=new $t(e,f,h,t);u.seed(0,r),u.fetches+=1,u.bytesFetched+=r.length;let p=new Ht(u,c),m=new Map;for await(let{values:w}of p.tableScan(1)){let[x,S,g,I,y]=w;typeof x=="string"&&typeof S=="string"&&typeof g=="string"&&typeof I=="number"&&m.set(S,{type:x,name:S,tableName:g,rootPage:I,sql:typeof y=="string"?y:""})}return new n(u,p,m)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}indexOn(e){let t=[...this.objects.values()].find(o=>o.type==="index"&&o.tableName===e);if(t)return t.rootPage;let r=this.objects.get(e);if(r?.type==="table"&&/without\s+rowid/i.test(r.sql))return r.rootPage;throw new Error(`SQLite table ${e} has no index`)}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,r){return this.btree.prefetchRowidRange(this.rootPage(e),t,r)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t){return this.btree.indexScanFrom(this.indexOn(e),t)}has(e){return this.objects.has(e)}};var Dn="GBZ-base version 4",Bt=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${ge(e)}`),this.path=e}},Gt=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},Dt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: its Tags table has no version":`unsupported database schema "${e}"; this reader understands "${Dn}"`),this.found=e}},Gn=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,r,o,s){this.handle=e,this.edges=t,this.bwt=r,this.encodedSequence=o,this.next=s,this.sequenceLen=Br(o)}get id(){return R(this.handle)}get orientation(){return je(this.handle)}get sequence(){return this.decoded??=Gr(this.encodedSequence),this.decoded}successors(){return this.edges.filter(e=>e.node!==0).map(e=>e.node)}gbwt(){if(this.edges.length===0)throw new Error(`GBWT record for handle ${this.handle} is empty`);return new It(this.edges,this.bwt)}};function q(n,e){if(typeof n!="number")throw new Error(`${e} is not a number in the database`);return n}function zt(n,e){if(typeof n!="string")throw new Error(`${e} is not text in the database`);return n}function qt(n,e){if(!(n instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return n}function vo(n,e){return{handle:n,fwStart:{node:q(e[1],"Paths.fw_node"),offset:q(e[2],"Paths.fw_offset")},revStart:{node:q(e[3],"Paths.rev_node"),offset:q(e[4],"Paths.rev_offset")},name:{sample:zt(e[5],"Paths.sample"),contig:zt(e[6],"Paths.contig"),haplotype:q(e[7],"Paths.haplotype"),fragment:q(e[8],"Paths.fragment")},isIndexed:q(e[9],"Paths.is_indexed")!==0}}async function Eo(n){let e=new Map;for await(let{values:t}of n.scan("Tags"))e.set(zt(t[0],"Tags.key"),zt(t[1],"Tags.value"));return e}var ct=class n{tagCache;pathCache;pathMapCache;indexTags=new Map;sqlite;index;constructor(e,t){this.sqlite=e,this.index=t}static async open(e){let{source:t,haplotypeIndex:r}=e,o={blockSize:e.blockSize,maxBlocks:e.maxBlocks},s=await ft.open(t,o);for(let c of["Tags","Nodes","Paths","ReferenceIndex"])s.rootPage(c);let i=r?await ft.open(r,o):void 0,a=new n(s,i),f=await a.tag("version");if(f!==Dn)throw new Dt(f);if(i){for(let u of["Tags","HaplotypeSamples","HaplotypeLengths"])i.rootPage(u);a.indexTags=await Eo(i);let c=a.indexTags.get("haplotype_index_paths"),l=await a.tag("paths");if(c!==l)throw new Error(`haplotype index was built for ${c??"an unknown number of"} paths but the graph has ${l}`);let d=a.indexTags.get("haplotype_index_nodes"),h=await a.tag("nodes");if(d!==void 0&&d!==h)throw new Error(`haplotype index was built for a graph with ${d} nodes but this one has ${h}`);if(a.indexTags.get("haplotype_index_orientations")==="forward")throw new Gt}return a}tags(){return this.tagCache??=Eo(this.sqlite),this.tagCache}async tag(e){return(await this.tags()).get(e)}prefetchRecords(e,t){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let r=t[4];return new Gn(e,qr(qt(t[1],"Nodes.edges")),qt(t[2],"Nodes.bwt"),qt(t[3],"Nodes.sequence"),typeof r=="number"?r:void 0)}paths(){return this.pathCache??=(async()=>{let e=[];for await(let{rowid:t,values:r}of this.sqlite.scan("Paths"))e.push(vo(t,r));return e})(),this.pathCache}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?vo(e,t):void 0}pathsByHandle(){return this.pathMapCache??=this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),this.pathMapCache}async findPath(e){return(await this.paths()).filter(r=>r.name.sample===e.sample&&r.name.contig===e.contig&&r.name.haplotype===e.haplotype&&r.name.fragment<=e.fragment).sort((r,o)=>o.name.fragment-r.name.fragment)[0]}async pathsNamed(e){let t=Qe(We(e),0);return(await this.paths()).filter(r=>r.name.sample===t.sample&&r.name.contig===t.contig&&r.name.haplotype===t.haplotype).sort((r,o)=>r.name.fragment-o.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let r=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!r){let i=await this.getPath(e);throw new Error(`${i?`The fragment of ${ge(i.name)} at ${i.name.fragment}`:`Path ${e}`} has not been indexed for random access`)}let o=r.pathOffset,s=r.pos;for(;;){let i=await this.getRecord(s.node);if(!i)throw new Error(`Node ${s.node} does not exist in the graph`);o+=i.sequenceLen;let a=i.gbwt().lf(s.offset);if(!a||a.node===0)return o;s=a}}return t}async getPathFragments(e){let{start:t,end:r}=e,o=await this.pathsNamed(e.path);if(o.length===0)throw new Bt(Qe(We(e.path),0));if(r<=t)return[];let s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<r);return(await Promise.all([...s,...i].map(async f=>({path:f,start:f.name.fragment,end:f.name.fragment+await this.pathLength(f.handle)})))).filter(f=>t<f.end)}async subgraphForFragment(e,t){let{sample:r,contig:o,haplotype:s}=e.path.name,i=Math.max(t.start,e.start),a=t.haplotypes??"all";try{let f=await Bn(this,{...t,path:{sample:r,contig:o,haplotype:s},start:i,end:Math.min(t.end,e.end)});return t.keep===void 0&&this.hasHaplotypeIndex&&(a==="all"||a==="distinct")&&await f.identifyPaths(),f}catch(f){throw f instanceof Se&&f.walkedBp!==void 0?new Se(f.limit,{windowBp:t.end-t.start,walkedBp:i-t.start+f.walkedBp}):f}}async getSubgraphs(e){let t=await this.getPathFragments(e);return(await Promise.allSettled(t.map(o=>this.subgraphForFragment(o,e)))).map(o=>{if(o.status==="rejected")throw o.reason;return o.value})}async getAlignments(e){return(await this.getSubgraphs(e)).flatMap(t=>t.alignments())}subgraphInInterval(e){return Bn(this,e)}subgraphAtOffset(e){return wo(this,e)}subgraphAroundNodes(e){return yo(this,e)}subgraphBetween(e){return xo(this,e)}fetchStats(){let e=({pager:t})=>({fetches:t.fetches,bytesFetched:t.bytesFetched});return{graph:e(this.sqlite),haplotypeIndex:this.index?e(this.index):void 0}}async graphName(){let e=new Map;for(let[r,o]of await this.tags())r.startsWith("gbz_")&&e.set(r.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=Ur(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeSampleGap(){let e=await this.haplotypeSampleInterval(),t=this.indexTags.get("haplotype_index_reference_interval");return e===void 0?void 0:Math.max(e,t===void 0?0:Number(t))}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeStrayOptions(){let e=r=>this.indexTags.get(`haplotype_index_stray_${r}`);if(!this.index?.has("HaplotypeStrays")||!this.index.has("HaplotypeBinNodes")||e("format")!=="2")return;let t=e("snarls")==="modeled"&&e("chain_links")===(await this.tag("chain_links")??"0");return{context:Number(e("context")),bin:Number(e("bin")),bound:Number(e("bound")),snarlNodes:t?Number(e("snarl_nodes")):void 0}}async haplotypeStraysInBins(e,t,r){let o=[];for await(let s of this.companion.indexScanFrom("HaplotypeStrays",[e,t])){let i=q(s[1],"HaplotypeStrays.bin");if(s[0]!==e||i>r)break;let a=q(s[4],"HaplotypeStrays.snarl_low"),f=q(s[5],"HaplotypeStrays.snarl_high");o.push({bin:i,pathHandle:q(s[2],"HaplotypeStrays.path_handle"),pathStart:q(s[3],"HaplotypeStrays.path_start"),snarl:f>0?[a,f]:void 0,pathEnd:q(s[6],"HaplotypeStrays.path_end"),node:q(s[7],"HaplotypeStrays.node_handle"),offset:q(s[8],"HaplotypeStrays.node_offset")})}return o}async haplotypeBinNodes(e,t,r){let o=[];for await(let a of this.companion.indexScanFrom("HaplotypeBinNodes",[e,t])){if(a[0]!==e||q(a[1],"HaplotypeBinNodes.bin")>r)break;let f=qt(a[3],"HaplotypeBinNodes.nodes"),c=0,l=0,d=()=>{let h=0,u=1;for(;;){let p=f[l++];if(p===void 0)throw new Error("HaplotypeBinNodes.nodes ends inside a number");if(h+=(p&127)*u,u*=128,(p&128)===0)return h}};for(;l<f.length;){let h=c+d();c=h+d(),o.push([h,c])}}o.sort((a,f)=>a[0]-f[0]);let s=[],i=[];for(let[a,f]of o){let c=i.length-1;c>=0&&a<=i[c]+1?i[c]=Math.max(i[c],f):(s.push(a),i.push(f))}return a=>{let f=0,c=s.length;for(;f<c;){let l=f+c>>1;s[l]<=a?f=l+1:c=l}return f>0&&a<=i[f-1]}}async haplotypeAnchor(e,t){let r=await this.companion.indexSeekLE("HaplotypeAnchors",[e,t]),o=r?.[0]===e&&r[1]===t?await this.companion.byRowid("HaplotypeAnchors",q(r[2],"HaplotypeAnchors rowid")):void 0;return o?{node:q(o[2],"HaplotypeAnchors.node_handle"),pathOffset:q(o[3],"HaplotypeAnchors.path_offset")}:void 0}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:q(e[0],"HaplotypeSamples.node_handle"),offset:q(e[1],"HaplotypeSamples.node_offset"),pathHandle:q(e[2],"HaplotypeSamples.path_handle"),orientation:q(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:q(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let r=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0])){if(q(o[0],"HaplotypeSamples.node_handle")>t)break;let i=await this.companion.byRowid("HaplotypeSamples",q(o[2],"HaplotypeSamples rowid"));i&&r.push(this.sampleFromRow(i))}return r}async haplotypeSampleAt(e,t){let r=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);if(r?.[0]!==e||r[1]!==t)return;let o=await this.companion.byRowid("HaplotypeSamples",q(r[2],"HaplotypeSamples rowid"));return o?this.sampleFromRow(o):void 0}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?q(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:q(t[1],"ReferenceIndex.path_offset"),pos:{node:q(t[2],"ReferenceIndex.node_handle"),offset:q(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let r=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return r?.[0]===e?q(r[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let r=await this.indexedRowid(e,t);return r===void 0?void 0:this.indexedRow(r)}async indexedPositionsBetween(e,t,r){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,r)]),i=[];if(o!==void 0&&s!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",o,s+1);for(let a=o;a<=s;a++)i.push(await this.indexedRow(a))}return i}};var lr=de(Mn(),1),dr=de(nt(),1),yn=de(Mr(),1),Is=de(Ps(),1);function zn(n){let e=/\.gbz\.db$/i;return e.test(n)?n.replace(e,".haplotype-index.db"):void 0}var Ao=de(Mr(),1);function wi(n){return _r(n)&&zn(Rr(n))?Pr(n,e=>zn(e)):void 0}function yi(n){return n instanceof Error&&(/\bHTTP 40[34]\b/.test(n.message)||n.code==="ENOENT")}async function Co(n,e){let t=wi(n);if(!t)return{};try{return await(0,Ao.openLocation)(t,e).stat(),{location:t}}catch(r){return yi(r)?{}:{unreadable:String(r)}}}var Ro=de(Mn(),1),xi=5e3,bi=50*2**20,jn=class extends Error{constructor(t){super(`this GAF is ${(t/2**20).toFixed(0)} MB without an index; bgzip it and index it with tabix -p gaf`);this.name="UnindexedGafTooLargeError"}};function Si(n,e){if(n.length<=e)return n;let t=n.length/e;return Array.from({length:e},(r,o)=>n[Math.floor(o*t)])}var Mo=(n,e)=>n.path.some(t=>e.has(t.name)),jt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=(0,Ro.cachedSetup)({setup:async()=>{let{size:e}=await this.file.stat();if(e>bi)throw new jn(e);let t=await this.file.readFile(),r=new TextDecoder().decode(t[0]===31&&t[1]===139?await kr(t):t);return Tr(r)}})}async readIndexed(e,t,r){let o=1/0,s=-1/0;for(let a of t){let f=Number(a);Number.isInteger(f)&&(o=Math.min(o,f),s=Math.max(s,f))}let i=[];return o<=s&&await e.getLines("{node}",o,s+1,{signal:r,lineCallback:a=>{let f=Or(a);f&&Mo(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let r=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(o=>Mo(o,e));return{records:Si(r,xi),total:r.length}}};var xs=de(Mn(),1),bs=de(nt(),1);var Un=function(n,e){return Un=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},Un(n,e)};function lt(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Un(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function _o(n,e,t,r){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function a(l){try{c(r.next(l))}catch(d){i(d)}}function f(l){try{c(r.throw(l))}catch(d){i(d)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((r=r.apply(n,e||[])).next())})}function Ut(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(l){return f([c,l])}}function f(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(r=1,o&&(s=c[0]&2?o.return:c[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,c[1])).done)return s;switch(o=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(l){c=[6,l],o=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Be(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ve(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return s}function Xe(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function Ge(n){return this instanceof Ge?(this.v=n,this):new Ge(n)}function Po(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(u){return function(p){return Promise.resolve(p).then(u,d)}}function a(u,p){r[u]&&(o[u]=function(m){return new Promise(function(w,x){s.push([u,m,w,x])>1||f(u,m)})},p&&(o[u]=p(o[u])))}function f(u,p){try{c(r[u](p))}catch(m){h(s[0][3],m)}}function c(u){u.value instanceof Ge?Promise.resolve(u.value.v).then(l,d):h(s[0][2],u)}function l(u){f("next",u)}function d(u){f("throw",u)}function h(u,p){u(p),s.shift(),s.length&&f(s[0][0],s[0][1])}}function ko(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Be=="function"?Be(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(i){return new Promise(function(a,f){i=n[s](i),o(a,f,i.done,i.value)})}}function o(s,i,a,f){Promise.resolve(f).then(function(c){s({value:c,done:a})},i)}}function D(n){return typeof n=="function"}function Oo(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Wt=Oo(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
6
+ `+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
7
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function Wn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Qt=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=Be(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(m){e={error:m}}finally{try{f&&!f.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(D(l))try{l()}catch(m){s=m instanceof Wt?m.errors:[m]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var h=Be(d),u=h.next();!u.done;u=h.next()){var p=u.value;try{To(p)}catch(m){s=s??[],m instanceof Wt?s=Xe(Xe([],Ve(s)),Ve(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{u&&!u.done&&(o=h.return)&&o.call(h)}finally{if(r)throw r.error}}}if(s)throw new Wt(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)To(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Wn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Wn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var uf=Qt.EMPTY;function Yt(n){return n instanceof Qt||n&&"closed"in n&&D(n.remove)&&D(n.add)&&D(n.unsubscribe)}function To(n){D(n)?n():n.unsubscribe()}var Ie={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ke={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=Ke.delegate;return o?.setTimeout?o.setTimeout.apply(o,Xe([n,e],Ve(t))):setTimeout.apply(void 0,Xe([n,e],Ve(t)))},clearTimeout:function(n){var e=Ke.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function Vt(n){Ke.setTimeout(function(){var e=Ie.onUnhandledError;if(e)e(n);else throw n})}function Qn(){}var No=(function(){return Yn("C",void 0,void 0)})();function Lo(n){return Yn("E",void 0,n)}function Fo(n){return Yn("N",n,void 0)}function Yn(n,e,t){return{kind:n,value:e,error:t}}var De=null;function Ho(n){if(Ie.useDeprecatedSynchronousErrorHandling){var e=!De;if(e&&(De={errorThrown:!1,error:null}),n(),e){var t=De,r=t.errorThrown,o=t.error;if(De=null,r)throw o}}else n()}function $o(n){Ie.useDeprecatedSynchronousErrorHandling&&De&&(De.errorThrown=!0,De.error=n)}var dt=(function(n){lt(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Yt(t)&&t.add(r)):r.destination=Ai,r}return e.create=function(t,r,o){return new Kt(t,r,o)},e.prototype.next=function(t){this.isStopped?Xn(Fo(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?Xn(Lo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?Xn(No,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Qt);var Ii=Function.prototype.bind;function Vn(n,e){return Ii.call(n,e)}var vi=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Xt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Xt(r)}else Xt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Xt(t)}},n})(),Kt=(function(n){lt(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(D(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&Ie.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Vn(t.next,a),error:t.error&&Vn(t.error,a),complete:t.complete&&Vn(t.complete,a)}):i=t}return s.destination=new vi(i),s}return e})(dt);function Xt(n){Ie.useDeprecatedSynchronousErrorHandling?$o(n):Vt(n)}function Ei(n){throw n}function Xn(n,e){var t=Ie.onStoppedNotification;t&&Ke.setTimeout(function(){return t(n,e)})}var Ai={closed:!0,next:Qn,error:Ei,complete:Qn};var Ze=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function qo(n){return n}function Bo(n){return n.length===0?qo:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var pe=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Mi(e)?e:new Kt(e,t,r);return Ho(function(){var i=o,a=i.operator,f=i.source;s.add(a?a.call(s,f):f?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Go(t),new t(function(o,s){var i=new Kt({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Ze]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Bo(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Go(e),new e(function(r,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},n.create=function(e){return new n(e)},n})();function Go(n){var e;return(e=n??Ie.Promise)!==null&&e!==void 0?e:Promise}function Ci(n){return n&&D(n.next)&&D(n.error)&&D(n.complete)}function Mi(n){return n&&n instanceof dt||Ci(n)&&Yt(n)}function Ri(n){return D(n?.lift)}function we(n){return function(e){if(Ri(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Re(n,e,t,r,o){return new _i(n,e,t,r,o)}var _i=(function(n){lt(e,n);function e(t,r,o,s,i,a){var f=n.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=r?function(c){try{r(c)}catch(l){t.error(l)}}:n.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(dt);var Zt=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function Jt(n){return D(n?.then)}function en(n){return D(n[Ze])}function tn(n){return Symbol.asyncIterator&&D(n?.[Symbol.asyncIterator])}function nn(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Pi(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var rn=Pi();function on(n){return D(n?.[rn])}function sn(n){return Po(this,arguments,function(){var t,r,o,s;return Ut(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Ge(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,Ge(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ge(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function an(n){return D(n?.getReader)}function Ee(n){if(n instanceof pe)return n;if(n!=null){if(en(n))return ki(n);if(Zt(n))return Oi(n);if(Jt(n))return Ti(n);if(tn(n))return Do(n);if(on(n))return Ni(n);if(an(n))return Li(n)}throw nn(n)}function ki(n){return new pe(function(e){var t=n[Ze]();if(D(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Oi(n){return new pe(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Ti(n){return new pe(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Vt)})}function Ni(n){return new pe(function(e){var t,r;try{for(var o=Be(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function Do(n){return new pe(function(e){Fi(n,e).catch(function(t){return e.error(t)})})}function Li(n){return Do(sn(n))}function Fi(n,e){var t,r,o,s;return _o(this,void 0,void 0,function(){var i,a;return Ut(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=ko(n),f.label=1;case 1:return[4,t.next()];case 2:if(r=f.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];f.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=f.sent(),o={error:a},[3,11];case 6:return f.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function ye(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function fn(n,e){return e===void 0&&(e=0),we(function(t,r){t.subscribe(Re(r,function(o){return ye(r,n,function(){return r.next(o)},e)},function(){return ye(r,n,function(){return r.complete()},e)},function(o){return ye(r,n,function(){return r.error(o)},e)}))})}function cn(n,e){return e===void 0&&(e=0),we(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function zo(n,e){return Ee(n).pipe(cn(e),fn(e))}function jo(n,e){return Ee(n).pipe(cn(e),fn(e))}function Uo(n,e){return new pe(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function Wo(n,e){return new pe(function(t){var r;return ye(t,e,function(){r=n[rn](),ye(t,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return D(r?.return)&&r.return()}})}function ln(n,e){if(!n)throw new Error("Iterable cannot be null");return new pe(function(t){ye(t,e,function(){var r=n[Symbol.asyncIterator]();ye(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function Qo(n,e){return ln(sn(n),e)}function Yo(n,e){if(n!=null){if(en(n))return zo(n,e);if(Zt(n))return Uo(n,e);if(Jt(n))return jo(n,e);if(tn(n))return ln(n,e);if(on(n))return Wo(n,e);if(an(n))return Qo(n,e)}throw nn(n)}function Kn(n,e){return e?Yo(n,e):Ee(n)}function ht(n,e){return we(function(t,r){var o=0;t.subscribe(Re(r,function(s){r.next(n.call(e,s,o++))}))})}function Vo(n,e,t,r,o,s,i,a){var f=[],c=0,l=0,d=!1,h=function(){d&&!f.length&&!c&&e.complete()},u=function(m){return c<r?p(m):f.push(m)},p=function(m){s&&e.next(m),c++;var w=!1;Ee(t(m,l++)).subscribe(Re(e,function(x){o?.(x),s?u(x):e.next(x)},function(){w=!0},void 0,function(){if(w)try{c--;for(var x=function(){var S=f.shift();i?ye(e,i,function(){return p(S)}):p(S)};f.length&&c<r;)x();h()}catch(S){e.error(S)}}))};return n.subscribe(Re(e,u,function(){d=!0,h()})),function(){a?.()}}function Je(n,e,t){return t===void 0&&(t=1/0),D(e)?Je(function(r,o){return ht(function(s,i){return e(r,s,o,i)})(Ee(n(r,o)))},t):(typeof e=="number"&&(t=e),we(function(r,o){return Vo(r,o,n,t)}))}function Xo(n,e,t,r,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Re(i,function(l){var d=c++;f=a?n(f,l,d):(a=!0,l),r&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function Ko(n,e){return we(Xo(n,e,arguments.length>=2,!1,!0))}var Hi=function(n,e){return n.push(e),n};function dn(){return we(function(n,e){Ko(Hi,[])(n).subscribe(e)})}function Zo(n){let e=[],t=0,r;for(let o=0,s=n.length;o<s;o++){let i=n.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)r=t,t=0;else{let a=n[o];a==="M"||a==="="||a==="X"?e.push({own:r===void 0?t:r,mate:t,op:"M"}):a==="I"?e.push({own:0,mate:t,op:a}):(a==="D"||a==="N")&&e.push({own:t,mate:0,op:a}),r=void 0,t=0}}return e}function er(n){let e="";for(let{own:t,mate:r,op:o}of Zo(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var Zn=2**28-1;function Jn(n,e,t){for(let r=e;r>0;r-=Zn)n.push((Math.min(r,Zn)<<4|t)>>>0)}function $i(n,e,t){if(e===t)Jn(n,e,0);else{let r=Math.ceil(Math.max(e,t)/Zn);for(let o=0;o<r;o++){let s=Math.floor(e*(o+1)/r)-Math.floor(e*o/r),i=Math.floor(t*(o+1)/r)-Math.floor(t*o/r);n.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function tr(n){let e=[];for(let{own:t,mate:r,op:o}of Zo(n))o==="M"?$i(e,t,r):o==="I"?Jn(e,r,1):Jn(e,t,o==="N"?3:2);return Uint32Array.from(e)}function qi(n){return n>=48&&n<=57}function Bi(n){return n!==void 0&&/[A-Za-z]/.test(n)}function Jo(n,e){let t=e;for(;t<n.length&&Bi(n[t]);)t++;return t}function es(n,e){let t=e,r=0;for(;t<n.length&&qi(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function ss(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=es(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=Jo(n,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(r==="*")e("*",1,1,t+1,Math.min(t+3,n.length)),t+=3;else if(r==="+"||r==="-"){let o=Jo(n,t+1),s=o-t-1;e(r,r==="-"?s:0,r==="+"?s:0,t+1,o),t=o}else if(r==="~"){let{value:o,next:s}=es(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function nr(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;ss(n,(a,f,c,l,d)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,n[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let h=n.slice(l,d);e(73,i,c,h,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function is(n,e,t,r){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=n.length;f<c;f++){let l=n[f],d=l>>>4,h=l&15;if(h===0||h===7){if(a)for(let u=0;u<d;u++)(e.charCodeAt(s+u)|32)!==(t.charCodeAt(o+u)|32)&&i.push({start:o+u,type:"mismatch",base:e[s+u],altbase:t[o+u],length:1});s+=d,o+=d}else if(h===1)i.push({start:o,type:"insertion",insertlen:d,insertedBases:e?.slice(s,s+d),length:0}),s+=d;else if(h===2)i.push({start:o,type:"deletion",length:d}),o+=d;else if(h===3)i.push({start:o,type:"skip",length:d}),o+=d;else if(h===8){for(let u=0;u<d;u++)i.push({start:o+u,type:"mismatch",base:e?.[s+u]||"X",qual:r?.[s+u],length:1});s+=d,o+=d}else h===5?i.push({start:o,type:"hardclip",cliplen:d,length:1}):h===4&&(i.push({start:o,type:"softclip",cliplen:d,length:1}),s+=d)}return i}function as(n,e,t,r,o){if(!e)return[];let s=[],i=e.length,a=r.length,f=o!==void 0,c=t.length,l=!1;for(let S=0;S<c;S++)if(t[S].type==="skip"){l=!0;break}let d=0,h=0,u=0,p=0,m=0,w=0,x=n.length;for(;w<x;){let S=n.charCodeAt(w);if(S>=48&&S<=57){let g=0;for(;w<x;){let I=n.charCodeAt(w);if(I>=48&&I<=57)g=g*10+(I-48),w++;else break}d+=g}else if(S===94)for(w++;w<x&&n.charCodeAt(w)>=65;)w++,d++;else if(S>=65){let g=n[w];if(w++,l&&c>0)for(let T=m;T<c;T++){let O=t[T];O.type==="skip"&&d>=O.start&&(d+=O.length,m=T+1)}let I=u,y=p;for(let T=h;T<i&&y<=d;T++,h=T){let O=e[T],F=O>>>4,M=O&15;M===4||M===1?I+=F:M===2||M===6||M===3?y+=F:M!==5&&(I+=F,y+=F)}u=I,p=y;let E=I-(y-d),A=E<a?r[E]:"X";s.push({start:d,base:A,qual:f?o[E]:void 0,altbase:g,length:1,type:"mismatch"}),d++}else w++}return s}var fs={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function cs(n=""){let e=0,t=[];for(let r=0,o=n.length;r<o;r++){let s=n.charCodeAt(r);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=fs[s];t.push(e<<4|i),e=0}}return t}function sr(n=""){let e=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),r=0,o=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);a>=48&&a<=57?r=r*10+(a-48):(t[o++]=r<<4|fs[a],r=0)}return t}function gn(n,e,t,r,o){let s=cs(n),i=n?is(s,t,r,o):[];return e&&t?i.concat(as(e,s,i,t,o)):i}var zi=397,ji=387,Ui=385;function ls(n){return(1<<n&zi)!==0}function ds(n){return(1<<n&ji)!==0}function hs(n){return(1<<n&Ui)!==0}function ir(n,e,t,r,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?r:t,l=[],d=1/0,h=-1/0,u=1/0,p=-1/0,m=(w,x)=>{u=Math.min(u,w,x),p=Math.max(p,w,x)};for(let w=0;w<n.length;w++){let x=n[w],S=x>>>4,g=x&15,I=g===9,y=I||ls(g)?S:0,E=I?n[++w]>>>4:ds(g)?S:0,A=f+y,T=c+E*a,O=f,F=A;if(F>=s&&O<=i)if(y>0){let M=Math.max(O,s),z=Math.min(F,i);if(z>M)if(d=Math.min(d,M),h=Math.max(h,z),I){let _=E/S,j=z-M,V=Math.round(j*_),ue=Math.round(c+(M-f)*_*a);l.push(j<<4|9,V<<4|9),m(ue,ue+V*a)}else l.push(z-M<<4|g),hs(g)?m(c+(M-f)*a,c+(z-f)*a):m(c,c)}else E>0&&(I?l.push(x,n[w]):l.push(x),d=Math.min(d,f),h=Math.max(h,f),m(c,T));if(f=A,c=T,f>i)break}if(l.length!==0)return{start:d,end:h,mateStart:u,mateEnd:p,cigar:Uint32Array.from(l)}}function Wi(n){return n===1||n===2||n===3}function ar(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?r:t,l,d=!1,h=()=>{l!==void 0&&d&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,d=!1};for(let u=0;u<n.length;u++){let p=n[u],m=p>>>4,w=p&15,x=w===9,S=x?n[++u]:void 0,g=x||ls(w)?m:0,I=S!==void 0?S>>>4:ds(w)?m:0,y=c+I*i;Wi(w)&&m>=s?h():(g>0||I>0)&&(l===void 0&&(l={qLo:f,qHi:f,tLo:c,tHi:c,ops:[]}),l.qHi=f+g,l.tLo=Math.min(l.tLo,c,y),l.tHi=Math.max(l.tHi,c,y),l.ops.push(p),S!==void 0&&l.ops.push(S),d=d||x||hs(w)),f+=g,c=y}return h(),a}function ps(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function us(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function fr(n){let e=ps(n),t=e===void 0?us(n):void 0;return e!==void 0?sr(e):t!==void 0?tr(t):void 0}var Qi=de(nt(),1),Yi=de(gs(),1);var Vi=de(nt(),1);var Xi=de(ks(),1);var ws=de(nt(),1),Oe=class extends ws.SimpleFeature{get(e){return e==="mismatches"?gn(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?er(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let r=this.get("start"),o=t?.start===void 0?void 0:t.start-r,s=t?.end===void 0?void 0:t.end-r,i=this.get("cs");if(i)nr(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of gn(this.walkableCigar))(c.type==="deletion"||c.type==="skip"?c.start<f&&c.start+c.length>a:c.start>=a&&c.start<=f)&&(c.type==="mismatch"?e(88,c.start,c.length,c.base,c.qual??-1,0,0):c.type==="insertion"?e(73,c.start,c.length,c.insertedBases??"",-1,0,c.insertlen):c.type==="deletion"?e(68,c.start,c.length,"",-1,0,0):c.type==="skip"&&e(78,c.start,c.length,"",-1,0,0))}}};var Ki=["CIGAR","cs","coarseCigar","cg","cr"];function Zi(n){return typeof n=="object"&&n!==null&&"refName"in n&&"start"in n&&"end"in n&&typeof n.refName=="string"&&typeof n.start=="number"&&typeof n.end=="number"}function Ji(n){let e=n.get("mate");return Zi(e)?e:void 0}function ea(n,e,t,r){let o=Math.max(n.start,r.start),s=Math.min(n.end,r.end),i=(e.end-e.start)/Math.max(n.end-n.start,1),a=l=>t===-1?e.end-(l-n.start)*i:e.start+(l-n.start)*i,f=Math.round(a(o)),c=Math.round(a(s));return s>o?{start:o,end:s,mateStart:Math.min(f,c),mateEnd:Math.max(f,c)}:void 0}function ta(n,e,t,r,o){let s={start:n.get("start"),end:n.get("end")},i=n.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&r===void 0&&!o?void 0:fr(n);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ea(s,e,i,t);return c===void 0?[]:[c]}else return(r===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:ar(f,s.start,e.start,e.end,i,r)).flatMap(l=>{let d=ir(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return d===void 0?[]:[d]})}function na(n,e,t,r,o,s){let i=`:${r.start}-${r.end}${o}`,a=n.toJSON(),f={...a,uniqueId:`${n.id()}${i}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};a.syntenyId!==void 0&&(f.syntenyId=`${String(a.syntenyId)}${i}`);for(let c of Ki)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Oe(f)}function ys(n,e,t,r=!1){let o=Ji(n);if(o===void 0)return[n];{let s=ta(n,o,e,t,r);return s.map((i,a)=>na(n,o,i,e,s.length>1?`/${a}`:"",r))}}var wn=class extends xs.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=r,f=o&&this.recordsAreAlignments,c=(0,bs.createStatusFanOut)(a.statusCallback);return Kn(t).pipe(Je((l,d)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(Je(h=>f?ys(h,h.get("assemblyName")===l.assemblyName?l:{start:h.get("start"),end:h.get("end")},s,i):[h]),dn(),ht(h=>({index:d,features:h})))),dn(),Je(l=>l.sort((d,h)=>d.index-h.index).flatMap(d=>d.features)))}};var xn=class extends Error{constructor(t){super(t===void 0?"no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation":`the haplotype index beside the graph database could not be checked (${t}), so the walks cannot be named; if it is there, reload to try again, or set haplotypeIndexLocation`);this.name="NoHaplotypeIndexError"}},hr=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}},pr=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Ss(n,e){let t=Ae(e);return n[t]??n[e.sample]??t}function ra(n,e){return`${Ae(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function oa({alignment:n,assemblyName:e,refName:t,lane:r}){let{refStart:o,refEnd:s,strand:i,cigar:a}=n;if(!(!n.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=n,d=ra(f,n),h={uniqueId:d,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:d,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new Oe(h)}}function sa({pair:n,lane:e,mateLane:t}){let r=`${Ae(n.target)}#${n.target.contig}:${n.targetStart}-${n.targetEnd}|${Ae(n.query)}#${n.query.contig}:${n.queryStart}-${n.queryEnd}`;return new Oe({uniqueId:r,assemblyName:e,refName:n.target.contig,start:n.targetStart,end:n.targetEnd,type:"match",strand:n.strand==="-"?-1:1,CIGAR:n.cigar,syntenyId:r,identity:n.matches/Math.max(n.columns,1),numMatches:n.matches,blockLen:n.columns,mate:{refName:n.query.contig,start:n.queryStart,end:n.queryEnd,assemblyName:t}})}var cr=n=>!("uri"in n)||n.uri!=="",ur=class extends wn{constructor(){super(...arguments);this.graph=(0,lr.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),r=this.getConf("haplotypeIndexLocation"),o=cr(r)?{location:r}:await Co(t,this.pluginManager),s=o.location,i=await ct.open({source:(0,yn.openLocation)(t,this.pluginManager),haplotypeIndex:s?(0,yn.openLocation)(s,this.pluginManager):void 0}),a=this.getConf("assemblyNames")[0];if(a===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let f=await En(i),c=gt({configured:this.getConf("referenceSample"),anchorPrefix:ze(this,a),referenceSamples:f});return{db:i,anchor:a,referenceSample:c,referenceSamples:f,unreadableIndex:o.unreadable}}});this.gaf=(0,lr.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),r=this.getConf(["readsIndex","location"]);return cr(t)?new jt((0,yn.openLocation)(t,this.pluginManager),cr(r)?Nr(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r);return An(o,s,t)}async getHaplotypes(t={}){let{db:r,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=Ae(i.name),f=s.get(a);f?f.contigs.includes(i.name.contig)||f.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:o.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:o,referenceSamples:s}=await this.graph(t),i=In(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:Ss(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:ze(this,i),f=(await r.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:mt(Ae(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,r){let o=t===void 0||t.length===0?void 0:t.map(s=>ze(this,s));return o===void 0&&r===void 0?void 0:s=>vn(s,o)&&(r===void 0||mt(Ae(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s,unreadableIndex:i}=await this.graph(),{assemblyName:a,refName:f,start:c,end:l}=t;if(a!==s)throw new pr(a,s);let d=await this.referenceQuery(f,{}),h=this.keepPredicate(r.haplotypes);if(h!==void 0&&!o.hasHaplotypeIndex)throw new xn(i);return Cn(o,d,c,l,{context:this.getConf("context"),snarls:r.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:r.signal,keep:h})}async getReads(t,r={}){let o=await this.gaf(r);return o?o.readsOver(new Set(t),r):{records:[],total:0}}async laneHaplotypes(t,r){let o=ze(this,t);return(await this.getHaplotypes(r)).filter(s=>mt(s.prefix,o))}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:f}=t,c=ze(this,r.targetAssemblyName),l=In(this),d=this.keepPredicate(r.haplotypes,c),h=await this.referenceQuery(i,r),u=this.getConf("nodeLimit");return(h?await(0,dr.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,r.statusCallback,()=>o.getAlignments({path:h,start:a,end:f,context:this.getConf("context"),haplotypes:"all",limit:u,signal:r.signal,keep:d}).catch(m=>{throw wt(m,u,f-a)??m})):[]).flatMap(m=>{let w=m.resolved?oa({alignment:m,assemblyName:s,refName:i,lane:Ss(l,m.name)}):void 0;return w===void 0?[]:[w]})}async pairFeatures(t,r,o){let{targetAssemblyName:s}=o;if(s===void 0)throw new hr(r);let{db:i}=await this.graph(o),{refName:a,start:f,end:c}=t,l=await this.laneHaplotypes(r,o),d=await this.laneHaplotypes(s,o),h=[...l,...d],u=await this.referenceQuery(a,o),p=this.getConf("nodeLimit"),m=x=>i.getSubgraphs({path:x,start:f,end:c,context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:p,signal:o.signal,keep:S=>h.some(g=>g.sample===S.sample&&g.haplotype===S.haplotype)}).catch(S=>{throw wt(S,p,c-f)??S});return(u&&l.length>0&&d.length>0?await(0,dr.updateStatus)(`Reading ${r} against ${s}`,o.statusCallback,()=>m(u)):[]).flatMap(x=>l.flatMap(S=>d.flatMap(g=>x.pairAlignments({target:S,query:g,bases:!1}).map(I=>sa({pair:I,lane:r,mateLane:s})))))}getFeatures(t,r={}){return(0,Is.ObservableCreate)(async o=>{let{db:s,anchor:i,unreadableIndex:a}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new xn(a);if(t.assemblyName===i){let f=r.queryAssemblyName===void 0?await this.anchorFeatures(t,r):await this.pairFeatures(t,r.queryAssemblyName,r);for(let c of f)o.next(c)}o.complete()},r.signal)}};export{pr as HaplotypeWindowError,xn as NoHaplotypeIndexError,Rs as NoReferenceSampleError,_s as NodeLimitError,hr as PairTargetError,ur as default,oa as fragmentFeature,Ae as haplotypePrefix,Ss as laneAssemblyName,wt as nodeLimitError,sa as pairFeature,gt as resolveReferenceSample};
8
+ //# sourceMappingURL=GbzBaseSyntenyAdapter-3BCUI2JI.js.map