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