jbrowse-plugin-graphgenomeviewer 4.0.24 → 4.0.25
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.
- package/dist/chunks/GbzBaseSyntenyAdapter-LTKB3OX7.js +8 -0
- package/dist/chunks/GbzBaseSyntenyAdapter-LTKB3OX7.js.map +7 -0
- package/dist/chunks/{GraphGenomeView-R5PVJLXR.js → GraphGenomeView-VONVAI25.js} +2 -2
- package/dist/chunks/{LinearGraphDisplay-AWNFBBQE.js → LinearGraphDisplay-7ARGHNNN.js} +2 -2
- package/dist/chunks/chunk-NPVRXR7A.js +2 -0
- package/dist/chunks/chunk-NPVRXR7A.js.map +7 -0
- package/dist/chunks/chunk-YXIK4NJS.js +3 -0
- package/dist/chunks/chunk-YXIK4NJS.js.map +7 -0
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +4 -3
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +3 -3
- package/src/GraphGenomeView/components/FacetPanels.tsx +1 -0
- package/src/GraphGenomeView/components/GraphCanvas.tsx +1 -0
- package/src/GraphGenomeView/components/WalkKey.tsx +9 -2
- package/src/GraphGenomeView/model.test.ts +20 -0
- package/src/GraphGenomeView/model.ts +128 -3
- package/src/GraphGenomeView/viewModel.ts +6 -0
- package/src/LinearGraphDisplay/model.ts +3 -0
- package/src/version.ts +1 -1
- package/dist/chunks/GbzBaseSyntenyAdapter-7ZKFAEJG.js +0 -8
- package/dist/chunks/GbzBaseSyntenyAdapter-7ZKFAEJG.js.map +0 -7
- package/dist/chunks/chunk-ICDR353R.js +0 -3
- package/dist/chunks/chunk-ICDR353R.js.map +0 -7
- package/dist/chunks/chunk-KFP4EQTM.js +0 -2
- package/dist/chunks/chunk-KFP4EQTM.js.map +0 -7
- /package/dist/chunks/{GraphGenomeView-R5PVJLXR.js.map → GraphGenomeView-VONVAI25.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-AWNFBBQE.js.map → LinearGraphDisplay-7ARGHNNN.js.map} +0 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{a as Er,b as Cr,c as Mr,d as Hs}from"./chunk-JAQ2RQAE.js";import{a as Pr}from"./chunk-QSH263Y6.js";import{a as kr}from"./chunk-KWAXLUPQ.js";import"./chunk-LGKM2PZH.js";import{a as Gs,e as _r,f as Or}from"./chunk-XK7OPCRQ.js";import{a as nt}from"./chunk-J4OLMLS5.js";import{a as Lr,b as Tr}from"./chunk-SCMIJAAX.js";import"./chunk-EFVAQ2KM.js";import{a as Rr,e as je,f as Ue,g as Pn}from"./chunk-KULNKXPT.js";import{a as qs,b as ue}from"./chunk-FY3BTKY4.js";var Is=qs((Rp,vs)=>{vs.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function ye(n,e){return 2*n+(e==="reverse"?1:0)}function O(n){return Math.floor(n/2)}function We(n){return n%2===0?"forward":"reverse"}function B(n){return n%2===1}function X(n){return n%2===0?n+1:n-1}function Nr(n){return n==="left"?"right":"left"}function xt(n){return n==="forward"?"left":"right"}function bt(n){return n==="forward"?"right":"left"}function Fr(n){return n==="left"?"forward":"reverse"}function $r(n){return n==="right"?"forward":"reverse"}function Qe(n,e){let t=O(n),r=O(e);return B(n)?r>t||r===t&&!B(e):r>=t}function qr(n){return Ne(n[0],n[n.length-1])}function Ne(n,e){return n===void 0||e===void 0?!0:B(n)===B(e)?!B(n):Qe(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}}},Hr=255,Ds=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<Hr?Math.floor(Ds/this.sigma):0}next(){if(this.sigma>=Hr){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 Gr(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 vt=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:X(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];O(s.node)===O(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 zs=["","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 Dr(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=zs[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var js={A:"T",C:"G",G:"C",T:"A",N:"N"};function It(n){let e="";for(let t=n.length-1;t>=0;t--)e+=js[n[t]]??"N";return e}function zr(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 Wr(n){return{name:n.get("pggname"),subgraph:zr(n.get("subgraph"),"subgraph"),translation:zr(n.get("translation"),"translation")}}function jr(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 Qr(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])),jr(t.subgraph,e.subgraph),jr(t.translation,e.translation)),t}function Ur(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function Vr(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of Ur(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of Ur(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 Us="_gbwt_ref";function xe(n,e){return`${n.sample}#${n.haplotype}#${n.contig}[${n.fragment}-${e}]`}var Ws=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Qs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Vs(n){let e=Ws.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Qs.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 Kr(n){return typeof n=="string"?Vs(n):n}function At(n,e){return{sample:n.sample??Us,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var Ys=4096;function Ks(n,e){let t=[];for(let[r,o]of[...n].sort((s,i)=>s[0]-i[0])){let s=t[t.length-1];s&&r<=s[1]+e?s[1]=Math.max(s[1],o):t.push([r,o])}return t}function _n(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=Ys?r[1]=t:e.push([t,t])}return e}var ae=32768,Xr=ae/2,Zr={mostChosenPaths:32},kn=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)}},oe=class extends Error{};function ot(n,e,t,r){return n==="forward"?e+t:e-r}function Mn(n,e,t,r){return n==="forward"?e-r:e+t}function Jr(n){return Ne(X(n.handles[n.handles.length-1]),X(n.handles[0]))}function Fe(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function eo(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let x=performance.now(),C=x-o;return o=x,C},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,seeds:0,pieces:0,sources:{reference:0,sample:0,interval:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,intervals:0,seeds:0,chains:0,twins:0}},a=(x,C)=>{let R=`${x}: ${C}`;i.walks[R]=(i.walks[R]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async x=>{let C=t.get(x)??c.get(x);if(C)return C;let R=await e.getRecord(x);if(i.graphFetches+=1,!R)throw new Error(`Node record ${x} is missing from the database`);return c.set(x,R),R},p=x=>t.get(x).sequenceLen,h=await e.pathsByHandle(),u=x=>{let C=h.get(x);return C!==void 0&&n.keep(C.name)},d=[],m=new kn,y=new Map,S=new Set,I=new Set,g=async x=>{let C=(await l(x.node)).gbwt().lf(x.offset);return C===void 0||C.node===0?void 0:C},v=async(x,C)=>{let R=(await l(X(x.node))).gbwt().predecessorAt(x.offset);if(R===void 0||C!==void 0&&!C.has(R))return;let D=(await l(R)).gbwt().offsetTo(x);if(D===void 0)throw new Error(`No offset in ${R} leads to ${x.node}:${x.offset}`);return{node:R,offset:D}},b=(x,C,R,D)=>{let V=R.map(he=>he.pos.node),Z=R.map(he=>he.pos.offset),J=0;for(let he of V)J+=p(he);let ee=C==="forward"?R[0].left:R[R.length-1].left,Ae=d.length;d.push({pathHandle:x,orientation:C,handles:V,offsets:Z,len:J,hapStart:ee,hapEnd:ee+J,canonical:Ne(V[0],V[V.length-1]),source:D});for(let he of R)m.set(he.pos,Ae);let Te=y.get(x);return Te?Te.push(Ae):y.set(x,[Ae]),Ae},E=async(x,C,R,D)=>{let V=[],Z=x;for(;;){r?.throwIfAborted();let ee=await v(Z.pos,t);if(!ee)break;Z={pos:ee,left:Mn(R,Z.left,p(Z.pos.node),p(ee.node))},V.push(Z)}V.reverse();let J=[x];for(Z=x;;){r?.throwIfAborted();let ee=await g(Z.pos);if(!ee||!t.has(ee.node))break;Z={pos:ee,left:ot(R,Z.left,p(Z.pos.node),p(ee.node))},J.push(Z)}return b(C,R,[...V,...J],D)},M=async(x,C,R,D)=>d[m.get(x.pos)??await E(x,C,R,D)],L=x=>{let C=x.handles[x.handles.length-1];return{pos:{node:C,offset:x.offsets[x.offsets.length-1]},left:x.orientation==="forward"?x.hapEnd-p(C):x.hapStart}},k=x=>{let C=x.handles[0];return{pos:{node:C,offset:x.offsets[0]},left:x.orientation==="forward"?x.hapStart:x.hapEnd-p(C)}},T=await E({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),P=d[T],G=()=>{if(i.fallback!==void 0)return{reference:P,pieces:[],stats:i};let x=new Map;d.forEach((R,D)=>{D!==T&&x.set(Fe(R),[...x.get(Fe(R))??[],R])});let C=[];for(let R of x.values()){let D=new Set;for(let V of R)V.canonical&&!D.has(V.orientation)&&(D.add(V.orientation),C.push(V),i.sources[V.source]+=1)}return i.sources.reference=1,i.pieces=C.length,{reference:P,pieces:C,stats:i}};try{let x=i.spacing;if(x===void 0)throw new oe("the haplotype index has no anchors");let C=Math.floor(n.window.start/x),R=Math.ceil(n.window.end/x),D=w=>w>=0?e.haplotypeAnchor(n.referenceHandle,w*x):Promise.resolve(void 0),[V,Z]=await Promise.all([Promise.all([0,1,2].map(w=>D(C-w))),Promise.all([0,1,2,3].map(w=>D(R+w)))]),J=V[0],ee=Z.slice(0,2).findIndex(w=>w!==void 0&&w.pathOffset>=n.window.end),Ae=Z[ee];if(!J)throw new oe("the haplotype index has no anchor before the window");if(!Ae)throw new oe("the haplotype index has no anchor after the window");i.anchors=[J.pathOffset,Ae.pathOffset];let Te=V.filter(w=>w!==void 0),he=Z.slice(ee,ee+3).filter(w=>w!==void 0),ks=w=>{let A=w-w%2;return e.haplotypeSamplesInRange(A,A+1)},ut=new Map,xn=[...Te,...he],_s=await Promise.all(xn.map(w=>ks(w.node)));if(xn.forEach((w,A)=>ut.set(w,_s[A])),i.anchorsRead=xn.length,!ut.get(J).some(w=>w.pathHandle===n.referenceHandle&&w.orientation==="forward"&&w.pathOffset===J.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${J.pathOffset} (node ${O(J.node)}); it does not match this graph`);let yr=(w,A)=>{for(let _ of w){let z=ut.get(_).filter(U=>U.pathHandle===A);if(z.length>0)return{anchor:_,rows:z}}},De=new Map,tt=[],bn=new Set,Os=async w=>{let A=yr(Te,w),_=yr(he,w);if(!A&&!_)return;let z=A?.rows??[],U=_?.rows??[],W=[],N=new Set,j=A?.anchor??J,F=_?.anchor??Ae,$=F.pathOffset-j.pathOffset,ce=u(w),te=!1;for(let q of z){let ie=q.orientation==="forward"?1:-1,Ee=U.filter(ke=>ke.orientation===q.orientation&&(ke.pathOffset-q.pathOffset)*ie>0).sort((ke,$s)=>(ke.pathOffset-$s.pathOffset)*ie)[0];if(!Ee)continue;let Me=q.node===j.node,ze=Ee.node===F.node,Y=Ee.pathOffset,ne=0;Me&&!ze?Y+=ie*((await l(Ee.node)).sequenceLen+$):!Me&&ze&&(ne=$);let re=q.pathOffset-ie*ne;W.push([Math.min(re,Y),Math.max(re,Y)]),N.add(q.pathOffset),N.add(Ee.pathOffset),te=!0,ce&&(tt.push({row:q,stopAt:Y,back:ne,kind:Me===ze?"interval":"inversion"}),bn.add(w))}let de=new Map;for(let q of[...z,...U])te?N.has(q.pathOffset)||(W.push([q.pathOffset,q.pathOffset]),de.set(q.pathOffset,q)):W.push([q.pathOffset-$,q.pathOffset+$]);let se=Ks(W,ae);if(se.length>1)throw new oe(`path ${w} visits the anchors from ${se.length} copies of the region, at ${se.map(([q,ie])=>`${q}-${ie}`).join(", ")}`);if(De.set(w,se[0]),ce)for(let q of de.values())tt.push({row:q,stopAt:q.pathOffset,back:0,kind:"interval"});if(!te){for(let q of[...z,...U])if(ce&&(q.node===j.node||q.node===X(F.node))){let ie=q.orientation==="forward"?1:-1;tt.push({row:q,stopAt:q.pathOffset+ie*$,back:0,kind:"one-sided"}),bn.add(w)}}return te?"paired":"one-sided"},xr=new Set([...ut.values()].flat().map(w=>w.pathHandle)),mt=[...xr].filter(u);if(i.chosenPaths=mt.length,mt.length>Zr.mostChosenPaths)throw new oe(`${mt.length} chosen paths pass the anchors, more than ${Zr.mostChosenPaths}`);for(let w of xr)await Os(w);let Sn=[],vn=[];i.scans=_n([...t.keys()].sort((w,A)=>w-A));for(let[w,A]of i.scans)for(let _ of await e.haplotypeSamplesInRange(w,A))i.scanRows+=1,t.has(_.node)&&(vn.push(_),u(_.pathHandle)&&Sn.push(_));if(mt.length===0&&Sn.length===0&&[...h.values()].some(w=>n.keep(w.name)))throw new oe("no chosen path passes the anchors or has a sample on the window's nodes");let In=new Set(vn.map(w=>w.pathHandle).filter(w=>!De.has(w))),Ls=he[he.length-1].pathOffset-Te[Te.length-1].pathOffset,br=w=>`${w.sample}#${w.haplotype}#${w.contig}`,An=new Map;for(let[w,[A,_]]of De){let z=h.get(w)?.name;if(z&&u(w)){let U=br(z),W=z.fragment+A-ae,N=z.fragment+_+ae,j=An.get(U);An.set(U,j?[Math.min(j[0],W),Math.max(j[1],N)]:[W,N])}}let Sr=[];for(let[w,A]of h){let _=An.get(br(A.name));if(_&&!De.has(w)&&!In.has(w)&&n.keep(A.name)){let z=await e.haplotypeLength(w)??0;A.name.fragment<_[1]&&A.name.fragment+z>_[0]&&Sr.push(w)}}for(let w of[...In,...Sr]){let A=await e.haplotypeLength(w)??Number.POSITIVE_INFINITY;if(A>Ls+2*ae)throw new oe(In.has(w)?`path ${w} of ${A} bp has a sample on the window's nodes and no visit to the anchors`:`chosen fragment ${w} of ${A} bp lies beside its contig's visits to the anchors without a visit of its own`);if(u(w)){let _=(await e.getPath(w))?.fwStart;if(!_)throw new Error(`Path ${w} is missing from the database`);tt.push({row:{node:_.node,offset:_.offset,pathHandle:w,orientation:"forward",pathOffset:0},stopAt:A,back:0,kind:"whole"})}}for(let w of De.keys())if(u(w)&&!bn.has(w))throw new oe(`chosen path ${w} has no walk from its visits to the anchors`);for(let w of vn){let A=De.get(w.pathHandle);if(A&&(w.pathOffset<A[0]-Xr||w.pathOffset>A[1]+Xr))throw new oe(`path ${w.pathHandle} has a sample at ${w.pathOffset} on the window's nodes far from its anchor visits at ${A[0]}-${A[1]}`)}i.ms.scan=s();let En=new Map;await n.prefetchReferenceRange(n.referenceHandle,Math.max(0,J.pathOffset-ae),Ae.pathOffset+ae+1);let vr=8*x+2*(n.window.end-n.window.start);for(let{row:w,stopAt:A,back:_,kind:z}of tt){let U=w.orientation,W=(Y,ne)=>U==="forward"?ne-Y:Y-ne,N=w.pathOffset,j=w.pathOffset,F={node:w.node,offset:w.offset},$=w.pathOffset,ce=!1,te=0,de=0,se="past the far anchor";for(;F&&(r?.throwIfAborted(),!ce&&W($,A)<=-ae&&(ce=!0),!(ce&&te>ae));){let Y;if(t.has(F.node)){let re=await M({pos:F,left:$},w.pathHandle,U,"interval"),ke=L(re);F=ke.pos,$=ke.left,Y=p(ke.pos.node),N=Math.min(N,re.hapStart),j=Math.max(j,re.hapEnd),te=0}else{if(Y=(await l(F.node)).sequenceLen,te+=Y,de+=Y,de>vr){se="cap";break}N=Math.min(N,$),j=Math.max(j,$+Y)}let ne=await g(F);ne&&($=ot(U,$,Y,(await l(ne.node)).sequenceLen)),F=ne}if(!F&&se!=="cap"&&(se="endmarker"),a(z,se),se==="cap")throw new oe(`the walk of path ${w.pathHandle} between the anchors reached its cap of ${vr} bp`);if(z==="one-sided"&&se!=="endmarker")throw new oe(`chosen path ${w.pathHandle} runs on past the stretch from its visit to one anchor without a visit to the other`);let q=ae,ie={pos:{node:w.node,offset:w.offset},left:w.pathOffset},Ee=0,Me=_;for(;q>0||Me>0;){r?.throwIfAborted();let Y=await v(ie.pos);if(!Y)break;let ne=Mn(U,ie.left,(await l(ie.pos.node)).sequenceLen,(await l(Y.node)).sequenceLen);if(t.has(Y.node)){let re=await M({pos:Y,left:ne},w.pathHandle,U,"interval");ie=k(re),N=Math.min(N,re.hapStart),j=Math.max(j,re.hapEnd),q=ae,Ee=0,Me-=re.len}else{let re=(await l(Y.node)).sequenceLen;if(Ee+=re,Ee>q&&Me<=0)break;Me-=re,ie={pos:Y,left:ne},N=Math.min(N,ne),j=Math.max(j,ne+re)}}let ze=En.get(w.pathHandle);ze?ze.push([N,j]):En.set(w.pathHandle,[[N,j]])}let Ts=w=>(En.get(w.pathHandle)??[]).some(([A,_])=>A<=w.hapStart&&w.hapEnd<=_);i.ms.intervals=s();for(let w of Sn)m.get(w)===void 0&&!(y.get(w.pathHandle)??[]).some(A=>{let _=d[A];return _.canonical&&!Jr(_)&&_.hapStart<=w.pathOffset&&w.pathOffset<_.hapEnd})&&(i.seeds+=1,await E({pos:{node:w.node,offset:w.offset},left:w.pathOffset},w.pathHandle,w.orientation,"sample"));i.ms.seeds=s();let gt=async(w,A)=>{let _=A?S:I,z=A?I:S,U=w;for(;;){if(_.has(U))return;_.add(U);let W=d[U],N=A?L(W):k(W),j=0,F;for(;F===void 0;){r?.throwIfAborted();let $=A?await g(N.pos):await v(N.pos);if(!$){F="endmarker";break}let ce=(await l(N.pos.node)).sequenceLen,te=(await l($.node)).sequenceLen,de=A?ot(W.orientation,N.left,ce,te):Mn(W.orientation,N.left,ce,te);if(t.has($.node)){let se=m.get($);se===void 0?(U=await E({pos:$,left:de},W.pathHandle,W.orientation,"chain"),z.add(U),F="landed"):(z.add(se),F="merge")}else j>ae?F="bound":(j+=te,N={pos:$,left:de})}if(a("chain",F),F!=="landed")return}};await Promise.all([n.prefetchReferenceRange(n.referenceHandle,Math.max(0,P.hapStart-ae),P.hapStart),n.prefetchReferenceRange(n.referenceHandle,P.hapEnd,P.hapEnd+ae)]);let Ir=new Set,Ns=d.map((w,A)=>({piece:w,id:A})).filter(({piece:w,id:A})=>A!==T&&!Ts(w)).sort((w,A)=>Number(A.piece.canonical)-Number(w.piece.canonical));for(let{piece:w,id:A}of Ns)Ir.has(Fe(w))||(Ir.add(Fe(w)),await gt(A,!0),await gt(A,!1));i.ms.chains=s();let Cn=new Map,Fs=w=>{let A=Fe(w),_=Cn.get(A);_?_.add(w.orientation):Cn.set(A,new Set([w.orientation]))},wt=0,Rn=()=>{for(;wt<d.length;wt++)wt!==T&&Fs(d[wt])};Rn();let yt=w=>(Cn.get(Fe(w))?.size??0)>1,Ar=2*f;for(let w=0;w<d.length;w++){let A=d[w];if(w===T||yt(A)||A.canonical&&!Jr(A))continue;i.twins.tried+=1;let _=A.orientation==="forward"?"reverse":"forward",z=L(A),U=0,W;for(;!W&&U<=Ar;){r?.throwIfAborted();let F=await g(z.pos);if(!F)break;let $=(await l(F.node)).sequenceLen,ce=ot(A.orientation,z.left,(await l(z.pos.node)).sequenceLen,$),te=X(F.node);W=(await e.haplotypeSamplesInRange(te,te)).find(de=>de.pathHandle===A.pathHandle&&de.orientation===_&&de.pathOffset===ce),U+=$,z={pos:F,left:ce}}let N=W&&{pos:{node:W.node,offset:W.offset},left:W.pathOffset},j=0;for(;N&&!yt(A)&&j<=Ar+A.len;){if(r?.throwIfAborted(),t.has(N.pos.node)){let F=await M(N,A.pathHandle,_,"twin"),$=d.indexOf(F);await gt($,!0),await gt($,!1),Rn(),N=L(F)}if(!yt(A)){let F=(await l(N.pos.node)).sequenceLen;j+=F;let $=await g(N.pos);N=$?{pos:$,left:ot(_,N.left,F,(await l($.node)).sequenceLen)}:void 0}}if(Rn(),!yt(A))throw new oe(`piece ${Fe(A)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()}catch(x){if(!(x instanceof oe))throw x;i.fallback=x.message}return G()}function to(n,e){let t=n.handles[0],r=e.handles[0];return Number(B(t))-Number(B(r))||t-r||n.offsets[0]-e.offsets[0]}function Et(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)}}},On=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+=Et(a,o)-Et(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]),p=Et(c,o),h=Et(c,s);for(let u=0;u<h-p;u++){let d=r===1?c[h-1-u]-o:s-1-c[p+u],m=i.bestBefore(d),y=(m===-1?0:i.ending[m])+l;if(y>i.ending[d]&&(i.raise(d,y),a)){let S=a.count++;a.row[S]=f,a.column[S]=d,a.previous[S]=m===-1?-1:a.endingMatch[m],a.endingMatch[d]=S}}}}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 p=0;p<=i;p++){let h=a[p]+f[i-p];h>l&&(l=h,c=p)}return o+c}};function no(n,e,t){let r=new On(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Xs=100,Nn=4e6,Zs=5e3,le=15,Js=64,ei=8,co=1,Fn=-4,fe=-6,Ce=-1,Ve=-(2**30),Pt=0,Ln=1,lo=2;function $e(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function Rt(n,e,t){return n>=t&&n>=e?Pt:t>=e?lo:Ln}function po(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Ve),f=new Int32Array(s).fill(Ve),c=new Int32Array(s).fill(Ve);a[0]=0;for(let d=1;d<=o;d++)c[d]=fe+(d-1)*Ce,i[d]=(d===1?Pt:lo)<<4;for(let d=1;d<=r;d++){let m=new Int32Array(s).fill(Ve),y=new Int32Array(s).fill(Ve),S=new Int32Array(s).fill(Ve);y[0]=fe+(d-1)*Ce,i[d*s]=(d===1?Pt:Ln)<<2;let I=n.charCodeAt(d-1);for(let g=1;g<=o;g++){let v=Rt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(I===e.charCodeAt(g-1)?co:Fn);let b=Rt(a[g]+fe,f[g]+Ce,c[g]+fe);y[g]=Math.max(a[g]+fe,f[g]+Ce,c[g]+fe);let E=Rt(m[g-1]+fe,y[g-1]+fe,S[g-1]+Ce);S[g]=Math.max(m[g-1]+fe,y[g-1]+fe,S[g-1]+Ce),i[d*s+g]=v|b<<2|E<<4}a=m,f=y,c=S}let l=[],p=r,h=o,u=Rt(a[o],f[o],c[o]);for(;p>0||h>0;){let d=i[p*s+h]>>2*u&3;u===Pt?(l.push(n[p-1]===e[h-1]?"=":"X"),p-=1,h-=1):u===Ln?(l.push("I"),p-=1):(l.push("D"),h-=1),u=d}for(let d of l.reverse())$e(t,d,1)}function ti(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-fe-(t-1)*Ce,-fe+10*Math.log2(t)))+(Math.min(n,e)>0?-Fn:0)}function ho(n,e){let t=Math.abs(n-e);return t===0?0:.01*le*t+.5*Math.log2(t)}function ro(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 ni(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>=le&&s.push(ro(n,i,a)),i=Math.max(i,f);return r-i>=le&&s.push(ro(n,i,r)),s}function $n(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),p=new Int32Array(f.length);for(let g=0;g<f.length;g++){let v=f[g],b=v.qe-v.qs;for(let E=g-1;E>=Math.max(0,g-Zs);E--){if(c[E]+b<=c[g])continue;let M=f[E];if(M.flipped===v.flipped&&M.qs<v.qs&&(v.flipped?v.te<M.te:M.ts<v.ts)){let k=Math.max(0,M.qe-v.qs,v.flipped?v.te-M.ts:M.te-v.ts),T=v.qs+k-M.qe,P=v.flipped?M.ts-(v.te-k):v.ts+k-M.te;if(k<b&&T<=e&&P<=e){let G=c[E]+b-k-r(T,P);G>c[g]&&(c[g]=G,l[g]=E,p[g]=k)}}}}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:p[g]});if(u.reverse(),u.reduce((g,{run:v,trim:b})=>g+v.qe-v.qs-b,0)<t)break;s.push(u);let m=u[0],y=u.at(-1),{flipped:S}=m.run,I=S?a.flipped:a.forward;I.query.push([m.run.qs+m.trim,y.run.qe]),I.target.push(S?[y.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,y.run.te]);for(let{run:g,trim:v}of u)i.query.push([g.qs+v,g.qe]),i.target.push(g.flipped?[g.ts,g.te-v]:[g.ts+v,g.te]);f=f.flatMap(g=>{let v=g.flipped?a.flipped:a.forward;return ni(g,[...i.query,...v.query],[...i.target,...v.target])}).sort((g,v)=>g.qs-v.qs||g.ts-v.ts)}return s}function Tn(n,e){let t=new Map;for(let s=0;s+le<=e.length;s++){let i=e.slice(s,s+le),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+le<=n.length;s++){let i=t.get(n.slice(s,s+le));if(i&&i.length<=Js)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+le,c.te=a+le;else{let l={qs:s,qe:s+le,ts:a,te:a+le,flipped:!1};o.set(f,l),r.push(l)}}}return r}function ri(n,e){return[...Tn(n,e),...Tn(n,It(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Mt(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,p=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?It(p):p,r,s.qe,c)}$e(r,"=",i.qe-f),s=i}}function qn(n,e,t){$e(t,"I",n.length),$e(t,"D",e.length)}function uo(n,e,t){n.length*e.length<=Nn?po(n,e,t):qn(n,e,t)}function Hn(n,e,t,r=0){let[o]=n.length*e.length>Nn&&r<ei?$n(Tn(n,e),1/0,le,ho,1):[];if(!o){uo(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),Mt(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function oi(n,e,t){Hn(n,e,t)}function si(n,e,t){let r=[];Mt(n,e,t,r,oi);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 ii(n,e,t,r){let o=[];if(n.length*e.length<=Nn)po(n,e,t);else{let s=$n(ri(n,e),1/0,Math.max(r,le),ho),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>si(a,n,e)),i){let a=(l,p,h,u,d)=>{o.some(y=>u<y.queryEnd&&y.queryStart<u+l.length||d<y.targetEnd&&y.targetStart<d+p.length)?uo(l,p,h):Hn(l,p,h)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Mt(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else qn(n,e,t)}return o}function Gn(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 oo(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return Gn(n,(i,a,f,c)=>{let l=e==="query"?f:c,p=h=>{let u=l+o*h;return u>=t&&u<r};if(i==="="||i==="X")for(let h=0;h<a;h++)p(h)&&(s+=i==="="?co:Fn);else if(i==="I"==(e==="query"))for(let h=0;h<a;h++)p(h)&&(s+=h===0?fe:Ce);else p(0)&&(s+=fe+(a-1)*Ce)}),s}function so(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function ai(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,d]of n.shared)f.fill(1,u-n.queryStart,d-n.queryStart);let c=u=>f[u-n.queryStart]===1,l=()=>{$e(r,"I",o),$e(r,"D",s),o=0,s=0};Gn(n,(u,d,m)=>{if(u==="I")o+=d;else if(u==="D")s+=d;else{for(let y=0;y<d;y++)e[i+y]?(o+=1,s+=1,c(t?m-y:m+y)&&(a+=1)):((o>0||s>0)&&l(),$e(r,u,1));i+=d}}),l();let p={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[u,d]=r.shift();p[u]+=d}let h={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[u,d]=r.pop();h[u]+=d}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?h.I:p.I),queryEnd:n.queryEnd-(t?p.I:h.I),targetStart:n.targetStart+p.D,targetEnd:n.targetEnd-h.D,edits:r,sharedBases:n.sharedBases-a}}function fi(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];Gn(c,(p,h,u,d)=>{if(p==="="||p==="X")for(let m=0;m<h;m++)l.push([c.strand==="-"?u-m:u+m,d+m])});for(let[p,h]of l)o.query[p]=Math.min(255,o.query[p]+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[p,h]of c)for(let[u,d]of[["query",p],["target",h]])if(o[u][d]>1){let m=i[u].get(d);m?m.at(-1)!==l&&m.push(l):i[u].set(d,[l])}});let a=new Map,f=(c,l,p)=>{let h=`${p}:${c}:${l}`,u=a.get(h);if(u===void 0){let[d,m]=so(n[c],p),[y,S]=so(n[l],p),I=Math.max(d,y),g=Math.min(m,S),[v,b]=[n[c],n[l]];u=[oo(b,p,I,g)-oo(v,p,I,g),b.sharedBases-v.sharedBases,c-l].find(M=>M!==0)>0,a.set(h,u)}return u};return n.flatMap((c,l)=>{let p=s[l],h=new Uint8Array(p.length);if(p.forEach(([m,y],S)=>{for(let[I,g]of[["query",m],["target",y]])!h[S]&&i[I].get(g)?.some(v=>v!==l&&f(l,v,I))&&(h[S]=1)}),!h.includes(1))return[c];let u=ai(c,h),d=u?.edits.reduce((m,[y,S])=>m+(y==="="?S:0),0)??0;return u&&d>=r?[u]:[]})}function io(n,e){return n.map(t=>{let r=e(O(t));return B(t)?It(r):r}).join("")}function ao(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(O(r)).length);return t}function fo(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=O(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 ci(n,e,t,r){let o=fo(n),s=fo(e),i=new Map;e.forEach((p,h)=>{s[h]||i.set(O(p),[h])});let a=2*e.length,f=(p,h,u)=>p*a+2*h+(u?1:0),c=new Set;n.forEach((p,h)=>{for(let u of o[h]?[]:i.get(O(p))??[])c.add(f(h,u,B(p)!==B(e[u])))});let l=[];return n.forEach((p,h)=>{for(let u of o[h]?[]:i.get(O(p))??[]){let d=B(p)!==B(e[u]),m=d?-1:1;if(!c.has(f(h-1,u-m,d))){let y=h,S=u;for(;y<n.length&&S>=0&&S<e.length&&c.has(f(y,S,d));)y+=1,S+=m;let I=S-m;l.push({qs:t[h],qe:t[y],ts:r[Math.min(u,I)],te:r[Math.max(u,I)+1],flipped:d})}}}),l}function mo(n,e,t,r={}){let o=io(n,t),s=io(e,t),i=ci(n,e,ao(n,t),ao(e,t)),a=r.minMatch??Xs,f=r.bases??!0,c=[];for(let l of $n(i,r.maxGap??1/0,a,ti)){let p=[],h=l[0],u=l.at(-1),{flipped:d}=h.run;Mt(l,o,s,p,f?(y,S,I,g,v)=>{for(let b of ii(y,S,I,a)){let E=v+S.length;c.push({...b,queryStart:g+b.queryStart,queryEnd:g+b.queryEnd,targetStart:d?E-b.targetEnd:v+b.targetStart,targetEnd:d?E-b.targetStart:v+b.targetEnd,strand:d?"+":"-",edits:d?b.edits.reverse():b.edits,shared:[]})}}:qn),c.push({queryStart:h.run.qs+h.trim,queryEnd:u.run.qe,targetStart:d?u.run.ts:h.run.ts+h.trim,targetEnd:d?h.run.te-h.trim:u.run.te,strand:d?"-":"+",edits:d?p.reverse():p,sharedBases:l.reduce((y,{run:S,trim:I})=>y+S.qe-S.qs-I,0),shared:l.map(({run:y,trim:S})=>[y.qs+S,y.qe])})}return fi(c,o.length,s.length,a).map(({shared:l,...p})=>p).sort((l,p)=>l.queryStart-p.queryStart)}function go(n){return n.map(([e,t])=>`${t}${e}`).join("")}var _e=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 Bn(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var st=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(Bn(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&&Bn(e[s],e[a])&&(a=s),i<e.length&&Bn(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 li(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 pi(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 qe(n){return`${n.node}:${n.offset}`}function wo(n){return n.map(e=>X(e)).reverse()}function hi(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 di(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);xo(s,t.insertion,t.deletion);for(let[c,l]of o.edits)K(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 ui(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,p)=>n[l].identity.hapStart-n[p].identity.hapStart);let a=i[0],f=n[a],c=[];for(let l of i.slice(1)){let p=n[l],h=c.length===0?hi(f,p):void 0;if(h){f=di(f,p,h),s.add(l);continue}if(!e(p)){c.push(l);continue}let u=e(f)?t([f,...c.map(d=>n[d]),p]):void 0;if(u){f=u;for(let d of[...c,l])s.add(d)}else o.set(a,f),a=l,f=p;c=[]}o.set(a,f)}return n.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function kt(n,e){return{node:n.path[e],offset:n.offsets[e]}}var mi=32768;function gi(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]<=mi?o[1]=r:t.push([r,r])}return t}var Lt=class{records=new Map;paths=[];twinStarts=new Set;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;stats={orderedAlignments:0,lcsAlignments: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}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(ye(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 _e(this.limit);let t=await this.db.getRecord(ye(e,"forward")),r=await this.db.getRecord(ye(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.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 ${xe(e,e.fragment)}`);if(!t.isIndexed)throw new Error(`Path ${xe(t.name,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(`Path ${xe(t.name,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(O(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(`Path ${xe(e.name,e.name.fragment)} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=O(e);await this.ensureNode(o);let s=this.record(e),i=We(e),a=new st;return a.push(t,o,xt(i)),a.push(s.sequenceLen-t-1,o,bt(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=gi(c.map(p=>p.pos.node));await Promise.all(l.map(([p,h])=>this.db.prefetchRecords(p,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 _e&&o.windowBp===void 0?new _e(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 st;for(;;){let f=O(o.node),c=We(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,xt(c));let p=l.sequenceLen-s;if(i<=p){a.push(i===p?0:p-i-1,f,bt(c));break}a.push(0,f,bt(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-=p}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new st;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();let r=new Set,o=new Set;for(let i of this.records.keys())o.add(O(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=Nr(f);if(!r.has(`${a}:${l}`)){let u=this.record(ye(a,Fr(f))),d=i+u.sequenceLen-1;d<=t&&e.push(d,a,l)}let p=this.record(ye(a,$r(f))),h=i+1;if(h<=t)for(let u of p.successors()){let d=O(u),m=xt(We(u));r.has(`${d}:${m}`)||e.push(h,d,m)}}for(let i of o)this.records.delete(ye(i,"forward")),this.records.delete(ye(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){this.clearPaths();let r=[e,X(t)],o=new Set([O(e),O(t)]),s=0;for(;r.length>0;){let i=r.pop(),a=O(i);this.hasNode(a)||(await this.addNode(a),s+=1);for(let f of this.record(i).successors()){let c=O(f);o.has(c)||(r.push(f,X(f)),o.add(c))}}return s}async extractSnarls(e){let t=0;for(let[r,o]of await this.overlappingSnarls(e))t+=await this.betweenNodes(r,o);return 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)?Qe(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(X(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(X(l))).successors().length>1},r=async f=>{let c=await e(X(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[X(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=O(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 p of["forward","reverse"])s.push(...(await e(ye(c,p))).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((b,E)=>i.set(b,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let b=0;b<s;b++){let E=this.record(o[b]),M=E.gbwt().decompressArrays();f[b]=E.sequenceLen,c.push(M),a[b+1]=a[b]+M.nodes.length}let l=a[s],p=new Int32Array(l),h=new Int32Array(l),u=new Uint8Array(l);for(let b=0;b<s;b++){let E=c[b];p.set(E.nodes,a[b]),h.set(E.offsets,a[b])}c.length=0;for(let b=0;b<l;b++){let E=i.get(p[b]);E===void 0?p[b]=-1:(p[b]=E,u[a[E]+h[b]]=1)}let d=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,y,S=(b,E,M)=>{let L=[],k=0,T=0,P=-1,G=b,x=E;for(;;){G===d&&x===m&&(P=k),M&&(M.push(o[G]),L.push(x)),k+=1,T+=f[G];let C=a[G]+x,R=p[C];if(R<0)break;x=h[C],G=R}return{offsets:L,len:T,refAt:P,last:G}},I=(b,E,M,L)=>{L>=0&&(this.refId=this.paths.length,y=L),this.paths.push({path:b,offsets:E,len:M,weight:void 0,identity:void 0})},g=new Int32Array(s),v=d!==void 0&&B(o[d]);for(let b=0;b<s;b++){let E=o[b];if(!B(E)){let M=a[b],L=a[b+1]-M;for(let k=0;k<L;k++)if(u[M+k]===0){let T=[],{offsets:P,len:G,refAt:x,last:C}=S(b,k,T),R=o[C];if(x>=0||Ne(E,R)){if(I(T,P,G,x),!B(R)){let D=i.get(X(R));g[D]=g[D]+1}}else this.twinStarts.add(qe({node:E,offset:k}))}}}for(let b=0;b<s;b++){let E=o[b];if(B(E)){let M=a[b],L=a[b+1]-M,k=0;for(let P=0;P<L;P++)u[M+P]===0&&(k+=1);let T=!v&&k===g[b];for(let P=0;P<L;P++)if(u[M+P]===0){let G=T?void 0:S(b,P,void 0);if(G&&(G.refAt>=0||Ne(E,o[G.last]))){let x=[],{offsets:C,len:R,refAt:D}=S(b,P,x);I(x,C,R,D)}else this.twinStarts.add(qe({node:E,offset:P}))}}}if(r){if(y===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let b=this.paths[this.refId],E=r.nodeOffset;for(let L of b.path.slice(0,y))E+=this.record(L).sequenceLen;let M=r.seqOffset-E;this.refInterval=[M,M+b.len],b.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:M,hapEnd:M+b.len}}if(t==="distinct")this.distinctPaths();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(){let e=this.refId===void 0?void 0:this.paths[this.refId].path;this.paths.sort((o,s)=>Dn(o.path,s.path)||o.len-s.len);let t=[],r;for(let o of this.paths){let s=t[t.length-1];s&&Dn(s.path,o.path)===0?s.weight=(s.weight??0)+1:(e&&Dn(o.path,e)===0&&(r=t.length),t.push({...o,weight:1}))}this.paths=t,this.refId=r}keepHaplotypes(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=this.paths.filter((s,i)=>i===this.refId||s.identity!==void 0&&e(s.identity.name)),o=new Set;for(let s of r)for(let i of s.path)o.add(O(i));for(let s of[...this.records.keys()])o.has(O(s))||this.records.delete(s);this.paths=r,this.refId=t===void 0?void 0:r.indexOf(t)}async extractChosenPaths(e,t,r){this.clearPaths();let o=e.position.seqOffset,s=await eo({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},keep:r,signal:this.signal,prefetchReferenceRange:(c,l,p)=>this.prefetchReferenceRange(c,l,p)});if(this.stats.keep=s.stats,s.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),a=c=>({path:c.handles,offsets:c.offsets,len:c.len,weight:void 0,identity:{pathHandle:c.pathHandle,name:c===s.reference?e.name:i.get(c.pathHandle).name,orientation:c.orientation,hapStart:c.hapStart,hapEnd:c.hapEnd}}),f=[s.reference,...s.pieces].sort(to);return this.paths=f.map(a),this.refId=f.indexOf(s.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[s.reference.hapStart,s.reference.hapEnd],!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.haplotypeSampleInterval()??4096,t=_n(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[d,m]of t)for(let y of await this.db.haplotypeSamplesInRange(d,m))r.set(qe(y),y);let o=d=>{let m=0,y=t.length-1;for(;m<y;){let I=m+y+1>>1;t[I][0]<=d?m=I:y=I-1}let S=t[m];return S[0]<=d&&d<=S[1]},s=new Map;this.paths.forEach((d,m)=>{d.path.length>0&&m!==this.refId&&s.set(qe(kt(d,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((d,m)=>{m!==this.refId&&i.fragmentLengths.push(d.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),f=d=>(i.graphLookups+=1,a(d)),c=async(d,m)=>{if(o(d.node))return r.get(qe(d));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let y=await this.db.haplotypeSampleAt(d.node,d.offset);return y||(i.companionMisses+=1),y},l=new Map,p=async d=>{let m=l.get(d);if(!m){let y=await this.db.getPath(d);if(!y)throw new Error(`Path ${d} is missing from the database`);m=y.name,l.set(d,m)}return m},h=(d,m,y)=>d.orientation==="forward"?{pathHandle:d.pathHandle,orientation:"forward",base:d.pathOffset-m}:{pathHandle:d.pathHandle,orientation:"reverse",base:d.pathOffset+m+y},u=(d,m)=>d.orientation==="forward"?{pathHandle:d.pathHandle,orientation:"forward",base:d.hapStart-m}:{pathHandle:d.pathHandle,orientation:"reverse",base:d.hapEnd+m};for(let d=0;d<this.paths.length;d++){let m=this.paths[d];if(d===this.refId||m.identity)continue;let y=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let g,v=0,b=d,E;for(;g===void 0;){if(this.signal?.throwIfAborted(),b!==void 0){if(S.has(b)){I.end="cycle";break}S.add(b);let P=this.paths[b];y.push({index:b,startBp:v}),I.fragments+=1;let G=v;for(let C=0;C<P.path.length;C++){let R=kt(P,C),D=r.get(qe(R)),V=this.record(R.node).sequenceLen;if(D){g=h(D,G,V);break}G+=V}if(v+=P.len,g){I.end="in-fragment sample";break}let x=kt(P,P.path.length-1);E=this.record(x.node).gbwt().lf(x.offset),b=void 0}if(E===void 0||E.node===0){I.end="endmarker";break}let M=qe(E),L=s.get(M);if(L!==void 0){let P=this.paths[L].identity;if(P){g=u(P,v),I.end="identified sibling";break}b=L;continue}this.records.has(E.node)&&(I.reentries+=1),this.twinStarts.has(M)&&(I.twinLandings+=1);let k=await c(E,I),T=await f(E.node);if(k){g=h(k,v,T.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,v-y[y.length-1].startBp>4*e+4*T.sequenceLen){I.end="bound";break}v+=T.sequenceLen,E=T.gbwt().lf(E.offset)}if(g){I.pathHandle=g.pathHandle;let M=await p(g.pathHandle);for(let{index:L,startBp:k}of y){let T=this.paths[L];T.identity=g.orientation==="forward"?{pathHandle:g.pathHandle,name:M,orientation:"forward",hapStart:g.base+k,hapEnd:g.base+k+T.len}:{pathHandle:g.pathHandle,name:M,orientation:"reverse",hapStart:g.base-k-T.len,hapEnd:g.base-k}}}}}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=pi(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),K(r,"M",i),xo(r,o-i-a,s-i-a),K(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??li(no(e,t,p=>this.record(p).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(p,h,u,d)=>{p===h?K(s,"D",i[d]-i[u]):u===d?K(s,"I",this.pathLen(e.slice(p,h))):this.align(e.slice(p,h),t.slice(u,d),s)},f=0,c=0,l=0;for(let p=0;p<o.count;p++){let h=o.pathAt[p],u=o.refAt[p];(c!==h||l!==u)&&a(c,h,l,u);let d=this.record(e[h]).sequenceLen;K(s,"M",d),f+=d,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(qr(r))o={...this.editsAgainst(t.path,r),flipped:!1};else{let s=wo(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,p,h,u)=>{let d=yi(l),m=this.paths[h[0]],y=this.paths[h[h.length-1]],S=m.identity,I=S?.orientation==="forward",[g,v]=I?[m,y]:[y,m];return{strand:p,refStart:e.start+d.leading,refEnd:e.start+r-d.trailing,edits:d.edits,weight:m.weight,path:h.flatMap(b=>this.paths[b].path),start:kt(m,0),pieces:h,soloAligned:u,identity:S===void 0?void 0:{pathHandle:S.pathHandle,name:S.name,hapStart:S.name.fragment+g.identity.hapStart,hapEnd:S.name.fragment+v.identity.hapEnd,walkForward:I}}},s=l=>l.soloAligned.reduce((p,h)=>p+h,0),i=l=>l.pieces.reduce((p,h)=>p+this.paths[h].len,0),a=l=>2*s(l)>=i(l),f=l=>{let p=l[0],h=l[l.length-1],u=p.identity.walkForward;if(l.some((x,C)=>x.strand!==p.strand||x.identity.walkForward!==u||C>0&&x.identity.hapStart<l[C-1].identity.hapEnd))return;let d=u?l:[...l].reverse(),m=d.flatMap(x=>x.pieces),y=d.flatMap(x=>x.soloAligned),S=p.strand==="+"!==u,I=m.map(x=>this.paths[x]),g=I.slice(1).map((x,C)=>{let R=I[C].identity;return u?x.identity.hapStart-R.hapEnd:R.hapStart-x.identity.hapEnd}),v=S?[...I].reverse():I,b=S?[...g].reverse():g,E=v.flatMap(x=>S?wo(x.path):x.path),{edits:M}=this.editsAgainst(E,t),L=yo(M,v.map(x=>x.len)),k=new Map((S?[...m].reverse():m).map((x,C)=>[x,L[C]])),T=x=>2*x.pieces.reduce((C,R)=>C+k.get(R),0)>=s(x);if(!T(p)||!T(h))return;let P=[],G=0;return v.slice(0,-1).forEach((x,C)=>{G+=x.len,P.push([G,b[C]])}),o(xi(M,P),p.strand,m,y)},c=[];return this.paths.forEach((l,p)=>{if(p===this.refId)return;let{edits:h,flipped:u}=this.alignment(p),d=l.identity,m=d?d.orientation==="forward"!==u:!u;c.push(o(h,m?"+":"-",[p],yo(h,[l.len])))}),ui(c,a,f).map(l=>{let{edits:p,identity:h,pieces:u,soloAligned:d,...m}=l,y={...m,cigar:bi(p)};return h?{...y,resolved:!0,name:h.name,label:xe({...h.name,fragment:h.hapStart},h.hapEnd),pathHandle:h.pathHandle,hapStart:h.hapStart,hapEnd:h.hapEnd}:{...y,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:p}=l;return p?[{name:p.name,start:p.name.fragment+p.hapStart,steps:Ot(l,p)}]:[]}),i=l=>p=>p.sample===l.sample&&p.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(ye(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(p=>f(p.name)).flatMap(p=>mo(p.steps,l.steps,c,o).map(h=>({query:p.name,queryStart:p.start+h.queryStart,queryEnd:p.start+h.queryEnd,strand:h.strand,target:l.name,targetStart:l.start+h.targetStart,targetEnd:l.start+h.targetEnd,cigar:go(h.edits),matches:h.edits.reduce((u,[d,m])=>u+(d==="="?m:0),0),columns:h.edits.reduce((u,[,d])=>u+d,0),sharedBases:h.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=ye(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&Qe(o,s)&&t.push([r==="reverse"?1:0,O(s),B(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(!B(r)){let o=O(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",...Vr(Qr(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)B(c)||r.push(`S ${O(c)} ${this.record(c).sequence}`);let s=c=>B(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&Qe(c,l)&&r.push(`L ${O(c)} ${s(c)} ${O(l)} ${s(l)} 0M`);let i=(c,l,p,h,u)=>{let d=Ot(c,l).map(S=>`${B(S)?"<":">"}${O(S)}`).join(""),m=c.weight===void 0?"":` WT:i:${c.weight}`,y=u===void 0?"":` CG:Z:${u}`;return`W ${p.sample} ${p.haplotype} ${p.contig} ${p.fragment} ${h} ${d}${m}${y}`},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 p=e.names==="resolved"?c.identity:void 0,h=t?this.alignToRef(l):void 0;r.push(p?i(c,p,{...p.name,fragment:p.name.fragment+p.hapStart},p.name.fragment+p.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:xe(i,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==="resolved"?i.identity:void 0;r.push({info:i,identity:f,name:f?xe({...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd):xe({sample:"unknown",contig:o,haplotype:s,fragment:0},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)&&Qe(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!B(s)).map(s=>({id:String(O(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(O(s)),from_is_reverse:B(s),to:String(O(i)),to_is_reverse:B(i)});let o=this.outputPaths(e).map(s=>wi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!B(i)),r=new Int32Array(t.length),o=[];t.forEach((i,a)=>{r[a]=O(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(Ot(i.info,i.identity))}))}}};function Ot(n,e){return e?.orientation==="reverse"?n.path.map(t=>X(t)).reverse():n.path}function wi(n,e,t,r){return{name:t,...n.weight===void 0?{}:{weight:n.weight},...r===void 0?{}:{cigar:r},path:Ot(n,e).map(o=>({id:String(O(o)),is_reverse:B(o)}))}}function Dn(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 K(n,e,t){if(t===0)return;let r=n[n.length-1];r?.[0]===e?r[1]+=t:n.push([e,t])}function _t(n){return n===0?0:6+(n-1)}function xo(n,e,t){if(e===0)K(n,"D",t);else if(t===0)K(n,"I",e);else{let r=Math.min(e,t),o=4*r+_t(e-r)+_t(t-r),s=_t(e)+_t(t);o<=s?(K(n,"M",r),K(n,"I",e-r),K(n,"D",t-r)):(K(n,"I",e),K(n,"D",t))}}function yi(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=[];K(i,"I",o.inserted);for(let[a,f]of n.slice(e,t))K(i,a,f);return K(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function yo(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 xi(n,e){let t=[],r=0,o=0;for(let[s,i]of n){if(s==="D"){K(t,s,i);continue}let a=r;for(;o<e.length&&e[o][0]<r+i;){let[f,c]=e[o];K(t,s,f-a),K(t,"I",c),a=f,o+=1}K(t,s,r+i-a),r+=i}for(;o<e.length;o++)K(t,"I",e[o][1]);return t}function bi(n){return n.map(([e,t])=>`${t}${e}`).join("")}async function bo(n,e,t,r,o){let s=new Lt(n,o);try{let i=await s.pathPosition(At(e,t));return await s.prefetchReferenceWalk(i,r-t),await s.aroundInterval(i.position,r-t,o.context??100),await s.extractSnarls(o.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof _e&&i.windowBp===void 0?new _e(i.limit,{windowBp:r-t,walkedBp:s.referenceWalkedBp??0}):i}}async function So(n,e,t,r,o={}){let{subgraph:s,reference:i}=await bo(n,e,t,r,o);return s.extractPaths(i,o.haplotypes??"all"),s}async function vo(n,e,t,r,o){if(!n.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await bo(n,e,t,r,o),a=o.haplotypes??"all";return(a!=="all"||!await s.extractChosenPaths(i,r-t,o.keep))&&(s.extractPaths(i,a),await s.identifyPaths()),s.keepHaplotypes(o.keep),s}function Se(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 Si(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 vi=new TextDecoder;function Tt(n){let[e,t]=Se(n,0),r=[],o=t;for(;o<e;){let[a,f]=Se(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=Si(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:vi.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var it=2,Ft=5,Ao=10,Nt=13;function Eo(n,e){return n[e]*256+n[e+1]}function Oe(n,e){return n[e]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function Ii(n,e){let t=n[e];if(t!==it&&t!==Ft&&t!==Ao&&t!==Nt)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===it||t===Ft;return{type:t,cellCount:Eo(n,e+3),rightChild:r?Oe(n,e+8):0,cellPointers:e+(r?12:8)}}function Re(n,e,t){return Eo(n,e.cellPointers+2*t)}var Ai=4096,Ei=4096,$t=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=Oe(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=Oe(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:Ii(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===Nt)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:Oe(i,Re(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]=Se(e,Re(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},p)=>{let h=p===0?this.childIndexFor(c,l,t):0,u=p===a.length-1?this.childIndexFor(c,l,r):l.cellCount;for(let d=h;d<=u;d++)f.push(d===l.cellCount?l.rightChild:Oe(c,Re(c,l,d)))}),f.length>Ei)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===Nt){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,p=Re(o,s,l),[h,u]=Se(o,p),[d,m]=Se(o,u);if(d===t)return Tt(await this.payload(o,m,h,!1));d<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=Re(o,s,f),[l]=Se(o,c+4);l<t?i=f+1:a=f}r=i===s.cellCount?s.rightChild:Oe(o,Re(o,s,i))}}async*tableScan(e){let{page:t,header:r}=await this.pageAt(e);if(r.type===Nt)for(let o=0;o<r.cellCount;o++){let s=Re(t,r,o),[i,a]=Se(t,s),[f,c]=Se(t,a);yield{rowid:f,values:Tt(await this.payload(t,c,i,!1))}}else{let o=[];for(let s=0;s<r.cellCount;s++)o.push(Oe(t,Re(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>=Ai){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=Re(t,r,o),f=r.type===it,[c,l]=Se(t,f?a+4:a);i={values:Tt(await this.payload(t,l,c,!0)),leftChild:f?Oe(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);Io(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===it&&(yield*this.indexScanFrom(f.leftChild,t)),yield f.values}o.type===it&&(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,p=await this.indexCell(o,s,i,l);Io(p.values,t)<=0?(r=p.values,a=l+1):(c=p.leftChild,f=l)}if(i.type===Ao)return r;o=a===i.cellCount?i.rightChild:c}}};function Io(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 qt=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=0;for(;;)try{let o=await this.source.read(e,t);return this.bytesFetched+=o.length,o}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 at=class n{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){let{size:r}=await e.stat(),o=await e.read(Math.min(t.blockSize??65536,r),0),s=o.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3")throw new Error("Not a SQLite database");let a=new DataView(s.buffer,s.byteOffset,s.byteLength),f=a.getUint16(16),c=f===1?65536:f,l=s[20]??0,p=a.getUint32(56);if(p!==1)throw new Error(`SQLite text encoding ${p} is not UTF-8`);let h=new qt(e,c,r,t);h.seed(0,o),h.fetches+=1,h.bytesFetched+=o.length;let u=new $t(h,l),d=new Map;for await(let{values:m}of u.tableScan(1)){let[y,S,I,g,v]=m;typeof y=="string"&&typeof S=="string"&&typeof I=="string"&&typeof g=="number"&&d.set(S,{type:y,name:S,tableName:I,rootPage:g,sql:typeof v=="string"?v:""})}return new n(h,u,d)}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(r=>r.type==="index"&&r.tableName===e);if(!t)throw new Error(`SQLite table ${e} has no index`);return t.rootPage}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 jn="GBZ-base version 4",Ht=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")}},Gt=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 "${jn}"`),this.found=e}},Bt=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 O(this.handle)}get orientation(){return We(this.handle)}get sequence(){return this.decoded??=Dr(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 vt(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 Dt(n,e){if(typeof n!="string")throw new Error(`${e} is not text in the database`);return n}function zn(n,e){if(!(n instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return n}function Co(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:Dt(e[5],"Paths.sample"),contig:Dt(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 Ro(n){let e=new Map;for await(let{values:t}of n.scan("Tags"))e.set(Dt(t[0],"Tags.key"),Dt(t[1],"Tags.value"));return e}var ft=class n{tagCache;pathCache;pathMapCache;indexTags=new Map;sqlite;index;constructor(e,t){this.sqlite=e,this.index=t}static async open(e,t={}){let{haplotypeIndex:r,...o}=t,s=await at.open(e,o);for(let c of["Tags","Nodes","Paths","ReferenceIndex"])s.rootPage(c);let i=r?await at.open(r,o):void 0,a=new n(s,i),f=await a.tag("version");if(f!==jn)throw new Gt(f);if(i){for(let u of["Tags","HaplotypeSamples","HaplotypeLengths"])i.rootPage(u);a.indexTags=await Ro(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 p=a.indexTags.get("haplotype_index_nodes"),h=await a.tag("nodes");if(p!==void 0&&p!==h)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${h}`);if(a.indexTags.get("haplotype_index_orientations")==="forward")throw new Ht}return a}tags(){return this.tagCache??=Ro(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 Bt(e,Gr(zn(t[1],"Nodes.edges")),zn(t[2],"Nodes.bwt"),zn(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(Co(t,r));return e})(),this.pathCache}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?Co(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 pathsForSample(e){return(await this.paths()).filter(t=>t.name.sample===e)}async pathsNamed(e){let t=At(Kr(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(`Path ${i?xe(i.name,i.name.fragment):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 pathFragmentsForRange(e,t,r){if(r<=t)return[];let o=await this.pathsNamed(e),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,r,o){let{keep:s,...i}=o;if(s!==void 0&&!this.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{sample:a,contig:f,haplotype:c}=e.path.name,l={sample:a,contig:f,haplotype:c},p=Math.max(t,e.start),h=Math.min(r,e.end),u=o.haplotypes??"all",d=u==="all"||u==="distinct",m;return s!==void 0&&u==="all"?m=await vo(this,l,p,h,{...i,keep:s}):(m=await So(this,l,p,h,i),this.hasHaplotypeIndex&&d&&(await m.identifyPaths(),s!==void 0&&m.keepHaplotypes(s))),m}async getSubgraphForRange(e,t,r,o={}){let[s]=await this.pathFragmentsForRange(e,t,r);return s?this.subgraphForFragment(s,t,r,o):void 0}async getAlignmentsForRange(e,t,r,o={}){let s=[];for(let i of await this.pathFragmentsForRange(e,t,r)){let a=await this.subgraphForFragment(i,t,r,o);s.push(...a.alignments())}return s}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=Wr(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 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 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 zt=class extends Error{constructor(t,r){super(r.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${t}" maps to none; set referenceSample`:`the anchor "${t}" is none of the graph's reference samples (${r.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`);this.name="NoReferenceSampleError"}},jt=class extends Error{constructor(t,r,o){super(`this ${r.toLocaleString()} bp window reads more than nodeLimit (${t.toLocaleString()}) graph nodes; zoom in to about ${o.toLocaleString()} bp or raise nodeLimit`);this.name="NodeLimitError"}};function ve(n){return`${n.sample}#${n.haplotype}`}function Po(n,e){let t=ve(n);return e===void 0||e.some(r=>je(t,r))}async function Mo(n){return(await n.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function Ci(n,e){let t=n.toLowerCase(),r=Pr(n)?.toLowerCase();return e.find(o=>o===n)??e.find(o=>o.toLowerCase()===t)??e.find(o=>o.toLowerCase()===r)}function Un({configured:n,anchorPrefix:e,referenceSamples:t}){if(n!=="")return n;let r=Ci(Rr(e),t)??(t.length===1?t[0]:void 0);if(r===void 0)throw new zt(e,t);return r}async function ko(n,e,t){let r=(await n.paths()).find(o=>o.isIndexed&&o.name.sample===e&&o.name.contig===t);return r?{sample:r.name.sample,contig:t,haplotype:r.name.haplotype}:void 0}function ct(n,e,t){if(n instanceof Error&&(n.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(n.message))){let o=n.walkedBp,s=typeof o=="number"&&o>0?Math.floor(o*.8):Math.floor(t/2);return new jt(e,t,Math.max(s,1))}else return}async function _o(n,e,t,r,{keep:o,...s}){let i=e?await n.getSubgraphForRange(e,t,r,{...s,haplotypes:"all",...o===void 0?{}:{keep:o}}).catch(a=>{throw ct(a,s.limit,r-t)??a}):void 0;return i?i.toGFA({names:"resolved"}):""}var hr=ue(Mr(),1),dr=ue(nt(),1),et=ue(kr(),1),Ms=ue(Hs(),1);var Lo=ue(kr(),1);var Oo=/\.gbz\.db$/i;function Ri(n){return Oo.test(_r(n))?Or(n,e=>e.replace(Oo,".haplotype-index.db")):void 0}async function To(n,e){let t=Ri(n);if(t)try{return await(0,Lo.openLocation)(t,e).stat(),t}catch{return}}var Pi=5e3,Mi=50*2**20,Wn=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 ki(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 No=(n,e)=>n.path.some(t=>e.has(t.name)),Ut=class{constructor(e,t){this.file=e;this.tabix=t}readWhole(e){return this.whole??=(async()=>{let{size:t}=await this.file.stat();if(t>Mi)throw new Wn(t);let r=await this.file.readFile({signal:e}),o=new TextDecoder().decode(r[0]===31&&r[1]===139?await Er(r):r);return Tr(o)})().catch(t=>{throw this.whole=void 0,t}),this.whole}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=Lr(a);f&&No(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let r=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.readWhole(t)).filter(o=>No(o,e));return{records:ki(r,Pi),total:r.length}}};var Cs=ue(Mr(),1),Rs=ue(nt(),1);var Qn=function(n,e){return Qn=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])},Qn(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");Qn(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Fo(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(p){i(p)}}function f(l){try{c(r.throw(l))}catch(p){i(p)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((r=r.apply(n,e||[])).next())})}function Wt(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 He(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 Ye(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 Ke(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 $o(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(d){return Promise.resolve(d).then(u,p)}}function a(u,d){r[u]&&(o[u]=function(m){return new Promise(function(y,S){s.push([u,m,y,S])>1||f(u,m)})},d&&(o[u]=d(o[u])))}function f(u,d){try{c(r[u](d))}catch(m){h(s[0][3],m)}}function c(u){u.value instanceof Ge?Promise.resolve(u.value.v).then(l,p):h(s[0][2],u)}function l(u){f("next",u)}function p(u){f("throw",u)}function h(u,d){u(d),s.shift(),s.length&&f(s[0][0],s[0][1])}}function qo(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 He=="function"?He(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 H(n){return typeof n=="function"}function Ho(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 Qt=Ho(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 Vn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Vt=(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=He(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(H(l))try{l()}catch(m){s=m instanceof Qt?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var h=He(p),u=h.next();!u.done;u=h.next()){var d=u.value;try{Go(d)}catch(m){s=s??[],m instanceof Qt?s=Ke(Ke([],Ye(s)),Ye(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 Qt(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Go(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)&&Vn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Vn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var bf=Vt.EMPTY;function Yt(n){return n instanceof Vt||n&&"closed"in n&&H(n.remove)&&H(n.add)&&H(n.unsubscribe)}function Go(n){H(n)?n():n.unsubscribe()}var be={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Xe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=Xe.delegate;return o?.setTimeout?o.setTimeout.apply(o,Ke([n,e],Ye(t))):setTimeout.apply(void 0,Ke([n,e],Ye(t)))},clearTimeout:function(n){var e=Xe.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function Kt(n){Xe.setTimeout(function(){var e=be.onUnhandledError;if(e)e(n);else throw n})}function Yn(){}var Bo=(function(){return Kn("C",void 0,void 0)})();function Do(n){return Kn("E",void 0,n)}function zo(n){return Kn("N",n,void 0)}function Kn(n,e,t){return{kind:n,value:e,error:t}}var Be=null;function jo(n){if(be.useDeprecatedSynchronousErrorHandling){var e=!Be;if(e&&(Be={errorThrown:!1,error:null}),n(),e){var t=Be,r=t.errorThrown,o=t.error;if(Be=null,r)throw o}}else n()}function Uo(n){be.useDeprecatedSynchronousErrorHandling&&Be&&(Be.errorThrown=!0,Be.error=n)}var pt=(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=Ti,r}return e.create=function(t,r,o){return new Zt(t,r,o)},e.prototype.next=function(t){this.isStopped?Zn(zo(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?Zn(Do(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?Zn(Bo,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})(Vt);var _i=Function.prototype.bind;function Xn(n,e){return _i.call(n,e)}var Oi=(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})(),Zt=(function(n){lt(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(H(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&be.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Xn(t.next,a),error:t.error&&Xn(t.error,a),complete:t.complete&&Xn(t.complete,a)}):i=t}return s.destination=new Oi(i),s}return e})(pt);function Xt(n){be.useDeprecatedSynchronousErrorHandling?Uo(n):Kt(n)}function Li(n){throw n}function Zn(n,e){var t=be.onStoppedNotification;t&&Xe.setTimeout(function(){return t(n,e)})}var Ti={closed:!0,next:Yn,error:Li,complete:Yn};var Ze=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Wo(n){return n}function Qo(n){return n.length===0?Wo: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=Fi(e)?e:new Zt(e,t,r);return jo(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=Vo(t),new t(function(o,s){var i=new Zt({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 Qo(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Vo(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 Vo(n){var e;return(e=n??be.Promise)!==null&&e!==void 0?e:Promise}function Ni(n){return n&&H(n.next)&&H(n.error)&&H(n.complete)}function Fi(n){return n&&n instanceof pt||Ni(n)&&Yt(n)}function $i(n){return H(n?.lift)}function ge(n){return function(e){if($i(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 Pe(n,e,t,r,o){return new qi(n,e,t,r,o)}var qi=(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})(pt);var Jt=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function en(n){return H(n?.then)}function tn(n){return H(n[Ze])}function nn(n){return Symbol.asyncIterator&&H(n?.[Symbol.asyncIterator])}function rn(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 Hi(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var on=Hi();function sn(n){return H(n?.[on])}function an(n){return $o(this,arguments,function(){var t,r,o,s;return Wt(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 fn(n){return H(n?.getReader)}function Ie(n){if(n instanceof pe)return n;if(n!=null){if(tn(n))return Gi(n);if(Jt(n))return Bi(n);if(en(n))return Di(n);if(nn(n))return Yo(n);if(sn(n))return zi(n);if(fn(n))return ji(n)}throw rn(n)}function Gi(n){return new pe(function(e){var t=n[Ze]();if(H(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Bi(n){return new pe(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Di(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,Kt)})}function zi(n){return new pe(function(e){var t,r;try{for(var o=He(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 Yo(n){return new pe(function(e){Ui(n,e).catch(function(t){return e.error(t)})})}function ji(n){return Yo(an(n))}function Ui(n,e){var t,r,o,s;return Fo(this,void 0,void 0,function(){var i,a;return Wt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=qo(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 we(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 cn(n,e){return e===void 0&&(e=0),ge(function(t,r){t.subscribe(Pe(r,function(o){return we(r,n,function(){return r.next(o)},e)},function(){return we(r,n,function(){return r.complete()},e)},function(o){return we(r,n,function(){return r.error(o)},e)}))})}function ln(n,e){return e===void 0&&(e=0),ge(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function Ko(n,e){return Ie(n).pipe(ln(e),cn(e))}function Xo(n,e){return Ie(n).pipe(ln(e),cn(e))}function Zo(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 Jo(n,e){return new pe(function(t){var r;return we(t,e,function(){r=n[on](),we(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 H(r?.return)&&r.return()}})}function pn(n,e){if(!n)throw new Error("Iterable cannot be null");return new pe(function(t){we(t,e,function(){var r=n[Symbol.asyncIterator]();we(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function es(n,e){return pn(an(n),e)}function ts(n,e){if(n!=null){if(tn(n))return Ko(n,e);if(Jt(n))return Zo(n,e);if(en(n))return Xo(n,e);if(nn(n))return pn(n,e);if(sn(n))return Jo(n,e);if(fn(n))return es(n,e)}throw rn(n)}function Jn(n,e){return e?ts(n,e):Ie(n)}function ht(n,e){return ge(function(t,r){var o=0;t.subscribe(Pe(r,function(s){r.next(n.call(e,s,o++))}))})}function ns(n,e,t,r,o,s,i,a){var f=[],c=0,l=0,p=!1,h=function(){p&&!f.length&&!c&&e.complete()},u=function(m){return c<r?d(m):f.push(m)},d=function(m){s&&e.next(m),c++;var y=!1;Ie(t(m,l++)).subscribe(Pe(e,function(S){o?.(S),s?u(S):e.next(S)},function(){y=!0},void 0,function(){if(y)try{c--;for(var S=function(){var I=f.shift();i?we(e,i,function(){return d(I)}):d(I)};f.length&&c<r;)S();h()}catch(I){e.error(I)}}))};return n.subscribe(Pe(e,u,function(){p=!0,h()})),function(){a?.()}}function Je(n,e,t){return t===void 0&&(t=1/0),H(e)?Je(function(r,o){return ht(function(s,i){return e(r,s,o,i)})(Ie(n(r,o)))},t):(typeof e=="number"&&(t=e),ge(function(r,o){return ns(r,o,n,t)}))}function rs(n,e,t,r,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var p=c++;f=a?n(f,l,p):(a=!0,l),r&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function os(n,e){return ge(rs(n,e,arguments.length>=2,!1,!0))}var Wi=function(n,e){return n.push(e),n};function hn(){return ge(function(n,e){os(Wi,[])(n).subscribe(e)})}function ss(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 nr(n){let e="";for(let{own:t,mate:r,op:o}of ss(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var er=2**28-1;function tr(n,e,t){for(let r=e;r>0;r-=er)n.push((Math.min(r,er)<<4|t)>>>0)}function Qi(n,e,t){if(e===t)tr(n,e,0);else{let r=Math.ceil(Math.max(e,t)/er);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 rr(n){let e=[];for(let{own:t,mate:r,op:o}of ss(n))o==="M"?Qi(e,t,r):o==="I"?tr(e,r,1):tr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function Vi(n){return n>=48&&n<=57}function Yi(n){return n!==void 0&&/[A-Za-z]/.test(n)}function is(n,e){let t=e;for(;t<n.length&&Yi(n[t]);)t++;return t}function as(n,e){let t=e,r=0;for(;t<n.length&&Vi(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function hs(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=as(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=is(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=is(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}=as(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function or(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;hs(n,(a,f,c,l,p)=>{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,p);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 ds(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],p=l>>>4,h=l&15;if(h===0||h===7){if(a)for(let u=0;u<p;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+=p,o+=p}else if(h===1)i.push({start:o,type:"insertion",insertlen:p,insertedBases:e?.slice(s,s+p),length:0}),s+=p;else if(h===2)i.push({start:o,type:"deletion",length:p}),o+=p;else if(h===3)i.push({start:o,type:"skip",length:p}),o+=p;else if(h===8){for(let u=0;u<p;u++)i.push({start:o+u,type:"mismatch",base:e?.[s+u]||"X",qual:r?.[s+u],length:1});s+=p,o+=p}else h===5?i.push({start:o,type:"hardclip",cliplen:p,length:1}):h===4&&(i.push({start:o,type:"softclip",cliplen:p,length:1}),s+=p)}return i}function us(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 I=0;I<c;I++)if(t[I].type==="skip"){l=!0;break}let p=0,h=0,u=0,d=0,m=0,y=0,S=n.length;for(;y<S;){let I=n.charCodeAt(y);if(I>=48&&I<=57){let g=0;for(;y<S;){let v=n.charCodeAt(y);if(v>=48&&v<=57)g=g*10+(v-48),y++;else break}p+=g}else if(I===94)for(y++;y<S&&n.charCodeAt(y)>=65;)y++,p++;else if(I>=65){let g=n[y];if(y++,l&&c>0)for(let L=m;L<c;L++){let k=t[L];k.type==="skip"&&p>=k.start&&(p+=k.length,m=L+1)}let v=u,b=d;for(let L=h;L<i&&b<=p;L++,h=L){let k=e[L],T=k>>>4,P=k&15;P===4||P===1?v+=T:P===2||P===6||P===3?b+=T:P!==5&&(v+=T,b+=T)}u=v,d=b;let E=v-(b-p),M=E<a?r[E]:"X";s.push({start:p,base:M,qual:f?o[E]:void 0,altbase:g,length:1,type:"mismatch"}),p++}else y++}return s}var ms={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function gs(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=ms[s];t.push(e<<4|i),e=0}}return t}function ar(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|ms[a],r=0)}return t}function wn(n,e,t,r,o){let s=gs(n),i=n?ds(s,t,r,o):[];return e&&t?i.concat(us(e,s,i,t,o)):i}var Zi=397,Ji=387,ea=385;function ws(n){return(1<<n&Zi)!==0}function ys(n){return(1<<n&Ji)!==0}function xs(n){return(1<<n&ea)!==0}function fr(n,e,t,r,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?r:t,l=[],p=1/0,h=-1/0,u=1/0,d=-1/0,m=(y,S)=>{u=Math.min(u,y,S),d=Math.max(d,y,S)};for(let y=0;y<n.length;y++){let S=n[y],I=S>>>4,g=S&15,v=g===9,b=v||ws(g)?I:0,E=v?n[++y]>>>4:ys(g)?I:0,M=f+b,L=c+E*a,k=f,T=M;if(T>=s&&k<=i)if(b>0){let P=Math.max(k,s),G=Math.min(T,i);if(G>P)if(p=Math.min(p,P),h=Math.max(h,G),v){let x=E/I,C=G-P,R=Math.round(C*x),D=Math.round(c+(P-f)*x*a);l.push(C<<4|9,R<<4|9),m(D,D+R*a)}else l.push(G-P<<4|g),xs(g)?m(c+(P-f)*a,c+(G-f)*a):m(c,c)}else E>0&&(v?l.push(S,n[y]):l.push(S),p=Math.min(p,f),h=Math.max(h,f),m(c,L));if(f=M,c=L,f>i)break}if(l.length!==0)return{start:p,end:h,mateStart:u,mateEnd:d,cigar:Uint32Array.from(l)}}function ta(n){return n===1||n===2||n===3}function cr(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?r:t,l,p=!1,h=()=>{l!==void 0&&p&&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,p=!1};for(let u=0;u<n.length;u++){let d=n[u],m=d>>>4,y=d&15,S=y===9,I=S?n[++u]:void 0,g=S||ws(y)?m:0,v=I!==void 0?I>>>4:ys(y)?m:0,b=c+v*i;ta(y)&&m>=s?h():(g>0||v>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,b),l.tHi=Math.max(l.tHi,c,b),l.ops.push(d),I!==void 0&&l.ops.push(I),p=p||S||xs(y)),f+=g,c=b}return h(),a}function bs(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function Ss(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function lr(n){let e=bs(n),t=e===void 0?Ss(n):void 0;return e!==void 0?ar(e):t!==void 0?rr(t):void 0}var na=ue(nt(),1),ra=ue(Is(),1);var oa=ue(nt(),1);var sa=ue(Gs(),1);var As=ue(nt(),1),Le=class extends As.SimpleFeature{get(e){return e==="mismatches"?wn(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"?nr(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)or(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of wn(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 ia=["CIGAR","cs","coarseCigar","cg","cr"];function aa(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 fa(n){let e=n.get("mate");return aa(e)?e:void 0}function ca(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 la(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:lr(n);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ca(s,e,i,t);return c===void 0?[]:[c]}else return(r===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:cr(f,s.start,e.start,e.end,i,r)).flatMap(l=>{let p=fr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return p===void 0?[]:[p]})}function pa(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 ia)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Le(f)}function Es(n,e,t,r=!1){let o=fa(n);if(o===void 0)return[n];{let s=la(n,o,e,t,r);return s.map((i,a)=>pa(n,o,i,e,s.length>1?`/${a}`:"",r))}}var yn=class extends Cs.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,Rs.createStatusFanOut)(a.statusCallback);return Jn(t).pipe(Je((l,p)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(Je(h=>f?Es(h,h.get("assemblyName")===l.assemblyName?l:{start:h.get("start"),end:h.get("end")},s,i):[h]),hn(),ht(h=>({index:p,features:h})))),hn(),Je(l=>l.sort((p,h)=>p.index-h.index).flatMap(p=>p.features)))}};var ur=class extends Error{constructor(){super("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");this.name="NoHaplotypeIndexError"}},mr=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}},gr=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 Ps(n,e){let t=ve(e);return n[t]??n[e.sample]??t}function ha(n,e){return`${ve(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function da({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,p=ha(f,n),h={uniqueId:p,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:p,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new Le(h)}}function ua({pair:n,lane:e,mateLane:t}){let r=`${ve(n.target)}#${n.target.contig}:${n.targetStart}-${n.targetEnd}|${ve(n.query)}#${n.query.contig}:${n.queryStart}-${n.queryEnd}`;return new Le({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 pr=n=>!("uri"in n)||n.uri!=="",wr=class extends yn{constructor(){super(...arguments);this.graph=(0,hr.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),r=this.getConf("haplotypeIndexLocation"),o=pr(r)?r:await To(t,this.pluginManager),s=await ft.open((0,et.openLocation)(t,this.pluginManager),o?{haplotypeIndex:(0,et.openLocation)(o,this.pluginManager)}:{}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let a=await Mo(s),f=Un({configured:this.getConf("referenceSample"),anchorPrefix:Ue(this,i),referenceSamples:a});return{db:s,anchor:i,referenceSample:f,referenceSamples:a}}});this.gaf=(0,hr.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),r=this.getConf(["readsIndex","location"]),o=this.pluginManager;if(!pr(t))return;let s=(0,et.openLocation)(t,o);return new Ut(s,pr(r)?new Cr({filehandle:s,...(0,et.openTabixIndexFilehandle)(r,this.getConf(["readsIndex","indexType"]),o)}):void 0)}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r);return ko(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=ve(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=Pn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:Ps(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:Ue(this,i),f=(await r.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:je(ve(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=>Ue(this,s));return o===void 0&&r===void 0?void 0:s=>Po(s,o)&&(r===void 0||je(ve(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s}=await this.graph(),{assemblyName:i,refName:a,start:f,end:c}=t;if(i!==s)throw new gr(i,s);let l=await this.referenceQuery(a,{}),p=this.keepPredicate(r.haplotypes);return _o(o,l,f,c,{context:this.getConf("context"),snarls:r.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:r.signal,...p===void 0?{}:{keep:p}})}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=Ue(this,t);return(await this.getHaplotypes(r)).filter(s=>je(s.prefix,o))}async referencePieces(t,r,o,s){let{db:i,referenceSample:a}=await this.graph(s),f=(await i.paths()).filter(l=>l.isIndexed&&l.name.sample===a&&l.name.contig===t&&l.name.fragment>r&&l.name.fragment<o).map(l=>l.name.fragment),c=[r,...[...new Set(f)].sort((l,p)=>l-p),o];return c.slice(1).map((l,p)=>({start:c[p],end:l}))}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:f}=t,c=Ue(this,r.targetAssemblyName),l=Pn(this),p=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.getAlignmentsForRange(h,a,f,{context:this.getConf("context"),haplotypes:"all",limit:u,signal:r.signal,...p===void 0?{}:{keep:p}}).catch(m=>{throw ct(m,u,f-a)??m})):[]).flatMap(m=>{let y=m.resolved?da({alignment:m,assemblyName:s,refName:i,lane:Ps(l,m.name)}):void 0;return y===void 0?[]:[y]})}async pairFeatures(t,r,o){let{targetAssemblyName:s}=o;if(s===void 0)throw new mr(r);let{db:i}=await this.graph(o),{refName:a,start:f,end:c}=t,l=await this.laneHaplotypes(r,o),p=await this.laneHaplotypes(s,o),h=[...l,...p],u=await this.referenceQuery(a,o),d=this.getConf("nodeLimit"),m=await i.haplotypeAnchorSpacing()!==void 0,y=(g,v)=>i.getSubgraphForRange(g,v.start,v.end,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:d,signal:o.signal,keep:b=>h.some(E=>E.sample===b.sample&&E.haplotype===b.haplotype)}).catch(b=>{throw ct(b,d,c-f)??b}),S=u&&m&&l.length>0&&p.length>0?(await(0,dr.updateStatus)(`Reading ${r} against ${s}`,o.statusCallback,async()=>Promise.all((await this.referencePieces(a,f,c,o)).map(g=>y(u,g))))).filter(g=>g!==void 0):[];return S.every(g=>{let v=g.stats.keep;return v!==void 0&&v.fallback===void 0})?S.flatMap(g=>l.flatMap(v=>p.flatMap(b=>g.pairAlignments({target:v,query:b,bases:!1}).map(E=>ua({pair:E,lane:r,mateLane:s}))))):[]}getFeatures(t,r={}){return(0,Ms.ObservableCreate)(async o=>{let{db:s,anchor:i}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new ur;if(t.assemblyName===i){let a=r.queryAssemblyName===void 0?await this.anchorFeatures(t,r):await this.pairFeatures(t,r.queryAssemblyName,r);for(let f of a)o.next(f)}o.complete()},r.signal)}};export{gr as HaplotypeWindowError,ur as NoHaplotypeIndexError,zt as NoReferenceSampleError,jt as NodeLimitError,mr as PairTargetError,wr as default,da as fragmentFeature,ve as haplotypePrefix,Ps as laneAssemblyName,ct as nodeLimitError,ua as pairFeature,Un as resolveReferenceSample};
|
|
8
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-LTKB3OX7.js.map
|