jbrowse-plugin-graphgenomeviewer 6.18.1 → 6.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{GbzBaseSyntenyAdapter-VFDJ76X6.js → GbzBaseSyntenyAdapter-UZGHQM5I.js} +2 -2
- package/dist/chunks/{GbzBaseSyntenyAdapter-VFDJ76X6.js.map → GbzBaseSyntenyAdapter-UZGHQM5I.js.map} +1 -1
- package/dist/chunks/{GraphGenomeView-WIL37EP3.js → GraphGenomeView-KF35DPWQ.js} +2 -2
- package/dist/chunks/{GraphTrackSettingsDialog-L74PFCPN.js → GraphTrackSettingsDialog-67LRAVT2.js} +2 -2
- package/dist/chunks/{HighlightColorDialog-AHLVCH42.js → HighlightColorDialog-HZM5OUNZ.js} +2 -2
- package/dist/chunks/{LinearGraphDisplay-IN6JHZVD.js → LinearGraphDisplay-2IOLKD4X.js} +2 -2
- package/dist/chunks/{MinigraphBubbleAdapter-7KDE3IR7.js → MinigraphBubbleAdapter-NAJ4YEQL.js} +2 -2
- package/dist/chunks/{RgfaTabixAdapter-F5ZYVJ4D.js → RgfaTabixAdapter-356L6GN3.js} +2 -2
- package/dist/chunks/{WalkTabixSyntenyAdapter-BC2QED5Y.js → WalkTabixSyntenyAdapter-IUJ5DGOA.js} +2 -2
- package/dist/chunks/{bandage-layout-3AR6BCUD-MAE7NZG2.js → bandage-layout-3AR6BCUD-DGTP6COV.js} +1 -1
- package/dist/chunks/{bandage-layout-3AR6BCUD-MAE7NZG2.js.map → bandage-layout-3AR6BCUD-DGTP6COV.js.map} +1 -1
- package/dist/chunks/{chunk-5S56JPL5.js → chunk-2NDAF7IS.js} +2 -2
- package/dist/chunks/{chunk-2N5OTRJM.js → chunk-5RBXMIOA.js} +2 -2
- package/dist/chunks/{chunk-2N5OTRJM.js.map → chunk-5RBXMIOA.js.map} +1 -1
- package/dist/chunks/chunk-7B33BUY7.js +2 -0
- package/dist/chunks/chunk-7B33BUY7.js.map +7 -0
- package/dist/chunks/{chunk-BXZD5UKL.js → chunk-CWV4SJHZ.js} +2 -2
- package/dist/chunks/{chunk-BXZD5UKL.js.map → chunk-CWV4SJHZ.js.map} +1 -1
- package/dist/chunks/{chunk-ZWPNOQ72.js → chunk-DLYWS5BL.js} +2 -2
- package/dist/chunks/{chunk-ZWPNOQ72.js.map → chunk-DLYWS5BL.js.map} +1 -1
- package/dist/chunks/{chunk-DGDSLDMB.js → chunk-DZPLNHLU.js} +3 -3
- package/dist/chunks/{chunk-DGDSLDMB.js.map → chunk-DZPLNHLU.js.map} +1 -1
- package/dist/chunks/{chunk-FTDRKDJC.js → chunk-FUJ7J4WY.js} +2 -2
- package/dist/chunks/{chunk-FTDRKDJC.js.map → chunk-FUJ7J4WY.js.map} +1 -1
- package/dist/chunks/{chunk-UKHCM7V3.js → chunk-G7AJ7UR4.js} +1 -1
- package/dist/chunks/{chunk-UKHCM7V3.js.map → chunk-G7AJ7UR4.js.map} +1 -1
- package/dist/chunks/{chunk-AIYBFEFP.js → chunk-GCMBACYH.js} +2 -2
- package/dist/chunks/{chunk-E3IZXWG6.js → chunk-GYNNWXIB.js} +2 -2
- package/dist/chunks/{chunk-B6JUCSWJ.js → chunk-NWVYDDZ5.js} +1 -1
- package/dist/chunks/{chunk-B6JUCSWJ.js.map → chunk-NWVYDDZ5.js.map} +1 -1
- package/dist/chunks/{chunk-AK4RVLBC.js → chunk-OCFNF6DB.js} +1 -1
- package/dist/chunks/{chunk-AK4RVLBC.js.map → chunk-OCFNF6DB.js.map} +1 -1
- package/dist/chunks/{chunk-4BTEDZYU.js → chunk-QLJJRSHX.js} +1 -1
- package/dist/chunks/{chunk-4BTEDZYU.js.map → chunk-QLJJRSHX.js.map} +1 -1
- package/dist/chunks/chunk-TLVHPGHQ.js +3 -0
- package/dist/chunks/chunk-TLVHPGHQ.js.map +7 -0
- package/dist/chunks/{chunk-FC5FYQXH.js → chunk-U74FYIHC.js} +2 -2
- package/dist/chunks/{chunk-FC5FYQXH.js.map → chunk-U74FYIHC.js.map} +1 -1
- package/dist/chunks/{chunk-LWKSHCM6.js → chunk-YBFFQGX7.js} +2 -2
- package/dist/chunks/{chunk-LWKSHCM6.js.map → chunk-YBFFQGX7.js.map} +1 -1
- package/dist/chunks/{chunk-CBIQCOGA.js → chunk-ZVLVSWEZ.js} +1 -1
- package/dist/chunks/{chunk-CBIQCOGA.js.map → chunk-ZVLVSWEZ.js.map} +1 -1
- package/dist/chunks/renderSvg-YTO6B3CI.js +2 -0
- package/dist/chunks/renderSvg-YTO6B3CI.js.map +7 -0
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +5 -5
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +2 -2
- package/src/GraphGenomeView/components/LabelLayer.tsx +9 -4
- package/src/GraphGenomeView/components/PaneSvg.tsx +8 -0
- package/src/GraphGenomeView/components/TubeMapOverlay.tsx +34 -1
- package/src/GraphGenomeView/model.test.ts +11 -2
- package/src/GraphGenomeView/pane/fitViews.ts +32 -8
- package/src/GraphGenomeView/pane/graphViews.ts +17 -4
- package/src/GraphGenomeView/tubeMapPanels.ts +18 -0
- package/src/version.ts +1 -1
- package/dist/chunks/chunk-BHJALK4L.js +0 -2
- package/dist/chunks/chunk-BHJALK4L.js.map +0 -7
- package/dist/chunks/chunk-TFCWM3QU.js +0 -3
- package/dist/chunks/chunk-TFCWM3QU.js.map +0 -7
- package/dist/chunks/renderSvg-A4RK2FEC.js +0 -2
- package/dist/chunks/renderSvg-A4RK2FEC.js.map +0 -7
- /package/dist/chunks/{GraphGenomeView-WIL37EP3.js.map → GraphGenomeView-KF35DPWQ.js.map} +0 -0
- /package/dist/chunks/{GraphTrackSettingsDialog-L74PFCPN.js.map → GraphTrackSettingsDialog-67LRAVT2.js.map} +0 -0
- /package/dist/chunks/{HighlightColorDialog-AHLVCH42.js.map → HighlightColorDialog-HZM5OUNZ.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-IN6JHZVD.js.map → LinearGraphDisplay-2IOLKD4X.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-7KDE3IR7.js.map → MinigraphBubbleAdapter-NAJ4YEQL.js.map} +0 -0
- /package/dist/chunks/{RgfaTabixAdapter-F5ZYVJ4D.js.map → RgfaTabixAdapter-356L6GN3.js.map} +0 -0
- /package/dist/chunks/{WalkTabixSyntenyAdapter-BC2QED5Y.js.map → WalkTabixSyntenyAdapter-IUJ5DGOA.js.map} +0 -0
- /package/dist/chunks/{chunk-5S56JPL5.js.map → chunk-2NDAF7IS.js.map} +0 -0
- /package/dist/chunks/{chunk-AIYBFEFP.js.map → chunk-GCMBACYH.js.map} +0 -0
- /package/dist/chunks/{chunk-E3IZXWG6.js.map → chunk-GYNNWXIB.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as ue,b as M,c as Re,d as re,e as te,f as dn,g as Ke,h as Ye,i as fn,j as ln,k as Be,l as Fe,m as Ae,n as pn,o as un,p as gn,q as wn,r as mn,s as Mt,t as Sn,u as ns,v as In}from"./chunk-AIYBFEFP.js";import{b as _e,c as yn,d as bn,e as xn}from"./chunk-5S56JPL5.js";import{a as Nt,b as $t}from"./chunk-B6JUCSWJ.js";import{f as ts,g as an,h as pe,i as kt,j as Pt,k as Xe,l as vt,m as Rt,o as At}from"./chunk-LWKSHCM6.js";import"./chunk-CBIQCOGA.js";import{a as Ne}from"./chunk-OGQ6OQDN.js";import"./chunk-YBLNN5FU.js";import{e as Ze,f as ve,g as Et}from"./chunk-AK4RVLBC.js";import"./chunk-E7J6SB5P.js";import{b as on,c as hn,d as cn}from"./chunk-R3TRNF7N.js";import"./chunk-7WIBGKBU.js";import{e as rn,o as It}from"./chunk-TENPGIPX.js";var Te=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 n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},En=255,ss=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new Te(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<En?Math.floor(ss/this.sigma):0}next(){if(this.sigma>=En){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function kn(o){let e=new Te(o),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let a=e.int(),i=e.int();if(a===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=a,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(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(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),a=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:a+(e-n)};t[s.value]=a+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:te(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],a=t[s];M(r.node)===M(a.node)&&(t[s-1]=a,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(a=>a.offset),t=0;for(let a of this.runs())t+=a.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let a of this.runs()){let i=this.edge(a.value),h=e[a.value];for(let c=0;c<a.len;c++)n[r]=i.node,s[r]=h,h+=1,r+=1;e[a.value]=h}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var rs=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(o,e)=>o>>>e|o<<32-e;function Pn(o){let e=Math.ceil((o.length+9)/64),t=new Uint8Array(e*64);t.set(o),t[o.length]=128;let n=new DataView(t.buffer),s=o.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let c=0;c<e;c++){for(let A=0;A<16;A++)a[A]=n.getUint32(c*64+A*4);for(let A=16;A<64;A++){let x=a[A-15],E=a[A-2],g=we(x,7)^we(x,18)^x>>>3,S=we(E,17)^we(E,19)^E>>>10;a[A]=a[A-16]+g+a[A-7]+S}let d=r[0],f=r[1],p=r[2],y=r[3],m=r[4],l=r[5],b=r[6],I=r[7];for(let A=0;A<64;A++){let x=we(m,6)^we(m,11)^we(m,25),E=m&l^~m&b,g=I+x+E+rs[A]+a[A]|0,S=we(d,2)^we(d,13)^we(d,22),P=d&f^d&p^f&p;I=b,b=l,l=m,m=y+g|0,y=p,p=f,f=d,d=g+S+P|0}[d,f,p,y,m,l,b,I].forEach((A,x)=>{r[x]=r[x]+A})}let i=new Uint8Array(32),h=new DataView(i.buffer);for(let c=0;c<8;c++)h.setUint32(c*4,r[c]);return i}function vn(o,e){let t=new Map;if(o!==void 0)for(let n of o.split(";")){let s=n.split(","),[r,a]=s;if(s.length!==2||!r||!a)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(a)}return t}function Nn(o){return{name:o.get("pggname"),subgraph:vn(o.get("subgraph"),"subgraph"),translation:vn(o.get("translation"),"translation")}}function Rn(o,e){for(let[t,n]of e){let s=o.get(t);s||(s=new Set,o.set(t,s));for(let r of n)s.add(r)}}function $n(o,e){let t={name:o,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(o,new Set([e.name])),Rn(t.subgraph,e.subgraph),Rn(t.translation,e.translation)),t}function An(o){return[...o.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function Mn(o){let e=[];o.name!==void 0&&e.push(`H NM:Z:${o.name}`);for(let[t,n]of An(o.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of An(o.translation))e.push(`H TL:Z:${t},${n}`);return e}async function Ln(o){let e=o.reduce((a,i)=>a+i.length,0),t=new Uint8Array(e),n=0;for(let a of o)t.set(a,n),n+=a.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Pn(t)].map(a=>a.toString(16).padStart(2,"0")).join("")}var as="_gbwt_ref";function fe(o){let e=`${o.sample}#${o.haplotype}#${o.contig}`;return o.end===void 0?e:`${e}[${o.fragment}-${o.end}]`}var os=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,is=/^([^#]+?)(?:\[\d+-\d+\])?$/;function hs(o){let e=os.exec(o);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=is.exec(o);if(t)return{contig:t[1]};throw new Error(`"${o}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function $e(o){return typeof o=="string"?hs(o):o}function Me(o,e){return{sample:o.sample??as,contig:o.contig,haplotype:o.haplotype??0,fragment:e}}var cs=4096;function Ht(o){let e=[];for(let t of o){let n=e[e.length-1];n&&t-n[1]<=cs?n[1]=t:e.push([t,t])}return e}var ds=32768,Hn={mostChosenPaths:32},Lt=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},ae=class extends Error{};function tt(o,e,t,n){return o==="forward"?e+t:e-n}function On(o,e,t,n){return o==="forward"?e-n:e+t}function Cn(o){return Ae(te(o.handles[o.handles.length-1]),te(o.handles[0]))}function ze(o){return`${o.pathHandle}:${o.hapStart}:${o.hapEnd}`}async function Bn(o){let{db:e,records:t,signal:n}=o,s=performance.now(),r=()=>{let w=performance.now(),k=w-s;return s=w,k},a={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}},i=(w,k)=>{let N=`${w}: ${k}`;a.walks[N]=(a.walks[N]??0)+1},h=await e.haplotypeSampleInterval()??4096,c=new Map,d=async w=>{let k=t.get(w)??c.get(w);if(k)return k;let N=await e.getRecord(w);if(a.graphFetches+=1,!N)throw new Error(`Node record ${w} is missing from the database`);return c.set(w,N),N},f=w=>t.get(w).sequenceLen,p=await e.pathsByHandle(),y=w=>{let k=p.get(w);return k!==void 0&&o.keep(k.name)},m=[],l=new Lt,b=new Map,I=new Set,A=new Set,x=async w=>{let k=(await d(w.node)).gbwt().lf(w.offset);return k===void 0||k.node===0?void 0:k},E=async(w,k)=>{let N=(await d(te(w.node))).gbwt().predecessorAt(w.offset);if(N===void 0||k!==void 0&&!k.has(N))return;let $=(await d(N)).gbwt().offsetTo(w);if($===void 0)throw new Error(`No offset in ${N} leads to ${w.node}:${w.offset}`);return{node:N,offset:$}},g=(w,k,N,$)=>{let F=N.map(j=>j.pos.node),U=N.map(j=>j.pos.offset),K=0;for(let j of F)K+=f(j);let O=k==="forward"?N[0].left:N[N.length-1].left,L=m.length;m.push({pathHandle:w,orientation:k,handles:F,offsets:U,len:K,hapStart:O,hapEnd:O+K,canonical:Ae(F[0],F[F.length-1]),source:$});for(let j of N)l.set(j.pos,L);let V=b.get(w);return V?V.push(L):b.set(w,[L]),L},S=async(w,k,N,$)=>{let F=[],U=w;for(;;){n?.throwIfAborted();let O=await E(U.pos,t);if(!O)break;U={pos:O,left:On(N,U.left,f(U.pos.node),f(O.node))},F.push(U)}F.reverse();let K=[w];for(U=w;;){n?.throwIfAborted();let O=await x(U.pos);if(!O||!t.has(O.node))break;U={pos:O,left:tt(N,U.left,f(U.pos.node),f(O.node))},K.push(U)}return g(k,N,[...F,...K],$)},P=async(w,k,N,$)=>m[l.get(w.pos)??await S(w,k,N,$)],_=w=>{let k=w.handles[w.handles.length-1];return{pos:{node:k,offset:w.offsets[w.offsets.length-1]},left:w.orientation==="forward"?w.hapEnd-f(k):w.hapStart}},B=w=>{let k=w.handles[0];return{pos:{node:k,offset:w.offsets[0]},left:w.orientation==="forward"?w.hapStart:w.hapEnd-f(k)}},D=await S({pos:o.referencePos,left:o.referenceLeft},o.referenceHandle,"forward","reference"),C=m[D],H=()=>{if(a.fallback!==void 0)return{reference:C,pieces:[],stats:a};let w=new Map;m.forEach((N,$)=>{$!==D&&w.set(ze(N),[...w.get(ze(N))??[],N])});let k=[];for(let N of w.values()){let $=new Set;for(let F of N)F.canonical&&!$.has(F.orientation)&&($.add(F.orientation),k.push(F),a.sources[F.source]+=1)}return a.sources.reference=1,a.pieces=k.length+1,{reference:C,pieces:k,stats:a}},v=async(w,k)=>{let N=k?I:A,$=k?A:I,F=w;for(;;){if(N.has(F))return;N.add(F);let U=m[F],K=k?_(U):B(U),O=0,L;for(;L===void 0;){n?.throwIfAborted();let V=k?await x(K.pos):await E(K.pos);if(!V){L="endmarker";break}let j=(await d(K.pos.node)).sequenceLen,ge=(await d(V.node)).sequenceLen,ne=k?tt(U.orientation,K.left,j,ge):On(U.orientation,K.left,j,ge);if(t.has(V.node)){let Y=l.get(V);Y===void 0?(F=await S({pos:V,left:ne},U.pathHandle,U.orientation,"chain"),$.add(F),L="landed"):($.add(Y),L="merge")}else O>ds?L="bound":(O+=ge,K={pos:V,left:ne})}if(i("chain",L),L!=="landed")return}},G=async w=>{if(o.context>w.context)throw new ae(`the context of ${o.context} bp exceeds the ${w.context} bp the haplotype index's stray rows cover`);let k=a.spacing;if(k===void 0)throw new ae("the haplotype index has no anchors");let{bin:N,bound:$}=w,{fills:F,inserted:U}=o.snarls;if(o.snarls.mode==="overlapping"&&F.length>0)throw new ae("the haplotype index's stray rows cover contained snarls only");for(let u of F){if(u.inserted>0&&u.low===u.high)throw new ae(`the haplotype index's stray rows leave out the snarl bounded by node ${u.low} at both ends`);if(u.inserted>0&&(w.snarlNodes===void 0||u.nodes>w.snarlNodes))throw new ae(w.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${u.nodes} nodes exceeds the ${w.snarlNodes} the haplotype index's stray rows cover`)}let K=Math.floor(o.window.start/N),O=Math.floor((o.window.end-1)/N),L=K*N,V=(O+1)*N,j=new Map,ge=async(u,R)=>{let q=await e.haplotypeAnchorsBetween(o.referenceHandle,u*k,R*k);for(let T of q)j.set(T.anchorOffset/k,T)},ne=Math.max(0,Math.floor((L-$)/k)-1),Y=Math.ceil((V+$)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(o.referenceHandle,K,O),ge(ne,Y)]);for(let u of t.keys()){let R=M(u);if(!re(u)&&!Ve(R)&&!U.has(R))throw new ae(`the haplotype index lists node ${R} of the subgraph in no bin that the window touches`)}a.scans=Ht([...t.keys()].sort((u,R)=>u-R));let he=Promise.all(a.scans.map(([u,R])=>e.haplotypeSamplesInRange(u,R)));for(he.catch(()=>{});ne>0&&(j.get(ne)?.pathOffset??Number.POSITIVE_INFINITY)>=L-$;)ne-=1,await ge(ne,ne);for(;j.has(Y)&&j.get(Y).pathOffset<=V+$;)Y+=1,await ge(Y,Y);let le=[...j.keys()].sort((u,R)=>u-R),be=j.get(le[0]??-1);if(!be)throw new ae("the haplotype index has no anchors on this path");let ce=u=>j.get(u).pathOffset,He=new Map;for(let u of le){let R=M(j.get(u).node);He.set(R,[...He.get(R)??[],u])}let bt=[...He.keys()],Vt=bt.map(u=>j.get(He.get(u)[0]).visits);if(!Vt[bt.indexOf(M(be.node))].some(u=>u.pathHandle===o.referenceHandle&&u.orientation==="forward"&&u.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${o.referenceHandle} at offset ${be.pathOffset} (node ${M(be.node)}); it does not match this graph`);let Wt=le.filter(u=>ce(u)<=o.window.start),Kn=le.filter(u=>ce(u)>=o.window.end);a.anchors=[ce(Wt[Wt.length-1]??le[0]),ce(Kn[0]??le[le.length-1])],a.anchorsRead=le.length;let xt=new Map,Zt=new Set;if(bt.forEach((u,R)=>{let q=He.get(u),T=q.length===1?q[0]:void 0;for(let z of Vt[R])Zt.add(z.pathHandle),z.orientation==="forward"&&y(z.pathHandle)&&xt.set(z.pathHandle,[...xt.get(z.pathHandle)??[],{k:T,row:z}])}),a.chosenPaths=[...Zt].filter(y).length,a.chosenPaths>Hn.mostChosenPaths)throw new ae(`${a.chosenPaths} chosen paths pass the anchors, more than ${Hn.mostChosenPaths}`);let We=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[u,R]of xt){R.sort((q,T)=>q.row.pathOffset-T.row.pathOffset);for(let q=0;q+1<R.length;q++){let T=R[q],z=R[q+1];if(T.k===void 0||z.k===void 0||Math.abs(T.k-z.k)!==1)continue;let[Z,J]=ce(T.k)<=ce(z.k)?[T,z]:[z,T],ee=ce(Z.k),se=ce(J.k);ee<V&&se>=L?(We.push({pathHandle:u,from:T.row,to:z.row}),Ee=Math.min(Ee,ee-$),xe=Math.max(xe,se+$)):ee>=V&&ee-V<=$?(We.push({pathHandle:u,from:Z.row,to:void 0}),Ee=Math.min(Ee,ee-$),xe=Math.max(xe,ee+$)):se<L&&L-se<=$&&(We.push({pathHandle:u,from:J.row,to:void 0}),Ee=Math.min(Ee,se-$),xe=Math.max(xe,se+$))}}let Yn=new Set(F.map(u=>`${u.low}:${u.high}`)),Jn=ie.filter(u=>y(u.pathHandle)&&(u.snarl===void 0||Yn.has(`${u.snarl[0]}:${u.snarl[1]}`))).sort((u,R)=>u.pathHandle-R.pathHandle||u.pathStart-R.pathStart);a.strays={bins:O-K+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await o.prefetchReferenceRange(o.referenceHandle,Math.max(0,Ee),xe+1),a.ms.scan=r();let Xt=8*k+2*(o.window.end-o.window.start),Kt=a.strays,Oe=0,Yt=u=>{if(Kt.outsideBp+=u,Oe+=u,Oe>Xt)throw new ae(`a walk of a chosen path near the window went past its cap of ${Xt} bp`)},St=new Map,Jt=(u,R,q)=>(St.get(u)??[]).some(([T,z])=>T<=R&&q<z),en=(u,R,q)=>{St.set(u,[...St.get(u)??[],[R,q]])},tn=async(u,R,q,T,z)=>{let Z=R,J=q,ee=J;for(;Z&&J<=T;){n?.throwIfAborted();let se;if(t.has(Z.node)){let Ce=await P({pos:Z,left:J},u,"forward",z),sn=_(Ce);Z=sn.pos,J=sn.left,se=f(Z.node),ee=Math.max(ee,Ce.hapEnd)}else se=(await d(Z.node)).sequenceLen,Yt(se),ee=Math.max(ee,J+se);Z=await x(Z),J+=se}return ee},es=async(u,R,q,T)=>{let z={pos:R,left:q},Z=q;for(;z.left>T;){n?.throwIfAborted();let J=await E(z.pos);if(!J)break;let ee=(await d(J.node)).sequenceLen,se=z.left-ee;if(t.has(J.node)){let Ce=await P({pos:J,left:se},u,"forward","section");z=B(Ce),Z=Math.min(Z,Ce.hapStart)}else Yt(ee),z={pos:J,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:u,from:R,to:q}of We){let T=R.pathOffset,z=(q??R).pathOffset+$;if(Jt(u,T-$,z))continue;let Z={node:R.node,offset:R.offset};Oe=0;let J=await tn(u,Z,T,z,"section");Oe=0;let ee=await es(u,Z,T,T-$);en(u,Math.min(ee,T-$),Math.max(J,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let u of Jn){if(Jt(u.pathHandle,u.pathStart,u.pathEnd))continue;Oe=0;let R=await tn(u.pathHandle,{node:u.node,offset:u.offset},u.pathStart,u.pathEnd,"stray");en(u.pathHandle,u.pathStart,Math.max(R,u.pathEnd+1)),Kt.walked+=1}a.ms.walks=r();let nn=[];for(let u of await he)for(let R of u)if(a.scanRows+=1,t.has(R.node)&&y(R.pathHandle)){if(!(b.get(R.pathHandle)??[]).some(q=>{let T=m[q];return T.hapStart<=R.pathOffset&&R.pathOffset<T.hapEnd}))throw new ae(`chosen path ${R.pathHandle} has a sample at ${R.pathOffset} on the window's nodes that no walk reached`);R.orientation==="reverse"&&nn.push(R)}for(let u of nn)await P({pos:{node:u.node,offset:u.offset},left:u.pathOffset},u.pathHandle,"reverse","twin");a.ms.check=r()},X=async()=>{let w=new Map,k=O=>{let L=ze(O),V=w.get(L);V?V.add(O.orientation):w.set(L,new Set([O.orientation]))},N=0,$=()=>{for(;N<m.length;N++)k(m[N])};$();let F=O=>(w.get(ze(O))?.size??0)>1,U=2*h,K=(O,L)=>L===D?y(o.referenceHandle)&&Cn(O):!O.canonical||Cn(O);for(let O=0;O<m.length;O++){let L=m[O];if(F(L)||!K(L,O))continue;a.twins.tried+=1;let V=L.orientation==="forward"?"reverse":"forward",j=_(L),ge=0,ne;for(;!ne&&ge<=U;){n?.throwIfAborted();let ie=await x(j.pos);if(!ie)break;let he=(await d(ie.node)).sequenceLen,le=tt(L.orientation,j.left,(await d(j.pos.node)).sequenceLen,he),be=te(ie.node);ne=(await e.haplotypeSamplesInRange(be,be)).find(ce=>ce.pathHandle===L.pathHandle&&ce.orientation===V&&ce.pathOffset===le),ge+=he,j={pos:ie,left:le}}let Y=ne&&{pos:{node:ne.node,offset:ne.offset},left:ne.pathOffset},Ve=0;for(;Y&&!F(L)&&Ve<=U+L.len;){if(n?.throwIfAborted(),t.has(Y.pos.node)){let ie=await P(Y,L.pathHandle,V,"twin"),he=m.indexOf(ie);await v(he,!0),await v(he,!1),$(),Y=_(ie)}if(!F(L)){let ie=(await d(Y.pos.node)).sequenceLen;Ve+=ie;let he=await x(Y.pos);Y=he?{pos:he,left:tt(V,Y.left,ie,(await d(he.node)).sequenceLen)}:void 0}}if($(),!F(L))throw new ae(`piece ${ze(L)} was found in one orientation where extractPaths keeps the other`);a.twins.found+=1}a.ms.twins=r()};try{let w=await e.haplotypeStrayOptions();if(w===void 0)throw new ae("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(w),await X()}catch(w){if(!(w instanceof ae))throw w;a.fallback=w.message}return H()}function Fn(o,e){return o.handles[0]-e.handles[0]||o.offsets[0]-e.offsets[0]}var oe=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 Ot(o,e){return o[0]<e[0]||o[0]===e[0]&&(o[1]<e[1]||o[1]===e[1]&&o[2]<e[2])}var De=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let a=r-1>>1;if(Ot(s[r],s[a]))[s[r],s[a]]=[s[a],s[r]],r=a;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,a=r+1,i=s;if(r<e.length&&Ot(e[r],e[i])&&(i=r),a<e.length&&Ot(e[a],e[i])&&(i=a),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function fs(o){let e=new Int32Array(o.length),t=new Int32Array(o.length);return o.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:o.length}}function ls(o,e){let t=0,n=o.length;for(;t<n;){let s=t+n>>1;o[s]>e?n=s:t=s+1}return o[t]}function ke(o){return`${o.node}:${o.offset}`}function qe(o){return o.map(e=>te(e)).reverse()}function ps(o,e){let t=e.identity.hapStart-o.identity.hapEnd,n=o.strand==="+"?e.refStart-o.refEnd:o.refStart-e.refEnd;return o.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function us(o,e,t){let[n,s]=o.strand==="+"?[o,e]:[e,o],r=n.edits.map(([c,d])=>[c,d]);Tn(r,t.insertion,t.deletion);for(let[c,d]of s.edits)W(r,c,d);let a=o.identity.walkForward,[i,h]=a?[o,e]:[e,o];return{strand:o.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...h.path],start:i.start,pieces:[...i.pieces,...h.pieces],soloAligned:[...i.soloAligned,...h.soloAligned],identity:{pathHandle:o.identity.pathHandle,name:o.identity.name,hapStart:o.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:a}}}function gs(o,e,t){if(o.some(a=>a.weight!==void 0))return o;let n=new Map;o.forEach((a,i)=>{if(a.identity){let h=n.get(a.identity.pathHandle);h?h.push(i):n.set(a.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let a of n.values()){a.sort((d,f)=>o[d].identity.hapStart-o[f].identity.hapStart);let i=a[0],h=o[i],c=[];for(let d of a.slice(1)){let f=o[d],p=c.length===0?ps(h,f):void 0;if(p){h=us(h,f,p),r.add(d);continue}if(!e(f)){c.push(d);continue}let y=e(h)?t([h,...c.map(m=>o[m]),f]):void 0;if(y){h=y;for(let m of[...c,d])r.add(m)}else s.set(i,h),i=d,h=f;c=[]}s.set(i,h)}return o.flatMap((a,i)=>r.has(i)?[]:[s.get(i)??a])}function nt(o,e){return{node:o.path[e],offset:o.offsets[e]}}var ws=32768;function ms(o){let e=[...o].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=ws?s[1]=n:t.push([n,n])}return t}var Ge=class o{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new o(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),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(ue(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 oe(this.limit);let t=await this.db.getRecord(ue(e,"forward")),n=await this.db.getRecord(ue(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${fe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,a=s;for(;;){await this.ensureNode(M(a.node));let i=this.record(a.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:a.node,nodeOffset:t-r,gbwtOffset:a.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let h=i.gbwt().lf(a.offset);if(!h)throw new Error(`The fragment of ${fe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);a=h}}async aroundPosition(e,t,n){let s=M(e);await this.ensureNode(s);let r=this.record(e),a=Re(e),i=new De;return i.push(t,s,Ke(a)),i.push(r.sequenceLen-t-1,s,Ye(a)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let a=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(a,i),Math.max(a,i)+1]])){let c=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(ms(c.map(d=>d.pos.node)).map(([d,f])=>[d,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof oe&&s.windowBp===void 0?new oe(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,a=t,i=new De;for(;;){let h=M(s.node),c=Re(s.node);this.walkedBp=t-a,await this.ensureNode(h);let d=this.record(s.node);if(r>=d.sequenceLen)throw new Error(`Offset ${r} in node ${h} of length ${d.sequenceLen}`);i.push(r,h,Ke(c));let f=d.sequenceLen-r;if(a<=f){i.push(a===f?0:f-a-1,h,Ye(c));break}i.push(0,h,Ye(c));let p=d.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,a-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new De;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let a of this.records.keys())s.add(M(a));let r=0;for(;e.size>0;){let[a,i,h]=e.pop(),c=`${i}:${h}`;if(n.has(c))continue;n.add(c),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let d=dn(h);if(!n.has(`${i}:${d}`)){let y=this.record(ue(i,fn(h))),m=a+y.sequenceLen-1;m<=t&&e.push(m,i,d)}let f=this.record(ue(i,ln(h))),p=a+1;if(p<=t)for(let y of f.successors()){let m=M(y),l=Ke(Re(y));n.has(`${m}:${l}`)||e.push(p,m,l)}}for(let a of s)this.records.delete(ue(a,"forward")),this.records.delete(ue(a,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,te(t)],s=new Set([M(e),M(t)]),r=[];for(;n.length>0;){let a=n.pop(),i=M(a);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let h of this.record(a).successors()){let c=M(h);s.has(c)||(n.push(h,te(h)),s.add(c))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:a}=await this.fillBetween(n,s),i=M(n),h=M(s);this.snarlFills.push({low:Math.min(i,h),high:Math.max(i,h),nodes:a,inserted:r.length});for(let c of r)this.snarlNodes.add(c);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),a=r.next;a!==void 0&&(n=!0,this.hasHandle(a)?Be(s,a)&&t.push([s,a]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,a]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(te(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async h=>{let c=h.successors(),d=c[0];return d===void 0?!1:c.length>1||(await e(te(d))).successors().length>1},n=async h=>{let c=await e(te(h));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[te(h),c.next]}:{kind:"chain"}:(await e(h)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(h=>this.record(h).successors()),a,i=!1;for(;!i&&r.length>0;){let h=r.shift(),c=M(h);if(!this.hasHandle(h)&&!s.has(c)){s.add(c);let d=await n(h);if(d.kind==="snarl-exit")a=d.snarl,i=!0;else if(d.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(ue(c,f))).successors())}}return a}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,a=new Map;s.forEach((g,S)=>a.set(g,S));let i=new Int32Array(r+1),h=new Int32Array(r),c=[];for(let g=0;g<r;g++){let S=this.record(s[g]),P=S.gbwt().decompressArrays();h[g]=S.sequenceLen,c.push(P),i[g+1]=i[g]+P.nodes.length}let d=i[r],f=new Int32Array(d),p=new Int32Array(d),y=new Uint8Array(d);for(let g=0;g<r;g++){let S=c[g];f.set(S.nodes,i[g]),p.set(S.offsets,i[g])}c.length=0;for(let g=0;g<d;g++){let S=a.get(f[g]);S===void 0?f[g]=-1:(f[g]=S,y[i[S]+p[g]]=1)}let m=n===void 0?void 0:a.get(n.handle),l=n?.gbwtOffset,b,I=(g,S,P)=>{let _=[],B=0,D=0,C=-1,H=g,v=S;for(;;){H===m&&v===l&&(C=B),P&&(P.push(s[H]),_.push(v)),B+=1,D+=h[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:_,len:D,refAt:C,last:H}},A=(g,S,P,_)=>{_>=0&&(this.refId=this.paths.length,b=_),this.paths.push({path:g,offsets:S,len:P,weight:void 0,identity:void 0})},x=new Int32Array(r);for(let g=0;g<r;g++){let S=s[g];if(!re(S)){let P=i[g],_=i[g+1]-P;for(let B=0;B<_;B++)if(y[P+B]===0){let D=[],{offsets:C,len:H,refAt:v,last:G}=I(g,B,D),X=s[G];if(v>=0||Ae(S,X)){if(A(D,C,H,v),!re(X)){let w=a.get(te(X));x[w]=x[w]+1}}else this.twinStarts.add(ke({node:S,offset:B}))}}}for(let g=0;g<r;g++){let S=s[g];if(re(S)){let P=i[g],_=i[g+1]-P,B=0;for(let C=0;C<_;C++)y[P+C]===0&&(B+=1);let D=(m===void 0||b!==void 0)&&B===x[g];for(let C=0;C<_;C++)if(y[P+C]===0){let H=D?void 0:I(g,C,void 0);if(H&&(H.refAt>=0||Ae(S,s[H.last]))){let v=[],{offsets:G,len:X,refAt:w}=I(g,C,v);A(v,G,X,w)}else this.twinStarts.add(ke({node:S,offset:C}))}}}let E=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((g,S)=>g.path[0]-S.path[0]||g.offsets[0]-S.offsets[0]),E&&(this.refId=this.paths.indexOf(E)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let g=this.paths[this.refId],S=n.nodeOffset;for(let _ of g.path.slice(0,b))S+=this.record(_).sequenceLen;let P=n.seqOffset-S;this.refInterval=[P,P+g.len],g.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:P,hapEnd:P+g.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],n=t?.path,s=n&&!Fe(n)?qe(n):void 0,r=c=>s!==void 0&&Ct(c,s)===0||Fe(qe(c)),a=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,d)=>Ct(c.path,d.path)||c.len-d.len||(c===t?-1:d===t?1:0));let i=[],h;for(let c of this.paths){let d=i[i.length-1],f=a&&c!==t&&r(c.path);this.twinDeferred||=f,d&&Ct(d.path,c.path)===0&&!f?d.weight=(d.weight??1)+(c.weight??1):(c===t&&(h=i.length),i.push({...c,weight:c.weight??1}))}this.paths=i,this.refId=h}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=a=>`${a.pathHandle}:${a.hapStart}-${a.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let a of this.paths)a!==e&&a.identity?.orientation==="forward"&&s.add(n(a.identity));let r=this.paths.filter(a=>a===e||a.identity?.orientation!=="reverse"||!s.has(n(a.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(a=>a.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((a,i)=>i!==this.refId&&a.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 n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((a,i)=>i===this.refId||a.identity!==void 0&&e(a.identity.name)),r=new Set;for(let a of s)for(let i of a.path)r.add(M(i));for(let a of[...this.records.keys()])r.has(M(a))||this.records.delete(a);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,a=await Bn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(d,f,p)=>this.prefetchReferenceRange(d,f,p)});if(this.stats.keep=a.stats,a.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),h=d=>({path:d.handles,offsets:d.offsets,len:d.len,weight:void 0,identity:{pathHandle:d.pathHandle,name:d===a.reference?e.name:i.get(d.pathHandle).name,orientation:d.orientation,hapStart:d.hapStart,hapEnd:d.hapEnd}}),c=[a.reference,...a.pieces].sort(Fn);return this.paths=c.map(h),this.refId=c.indexOf(a.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[a.reference.hapStart,a.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");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ht(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ke(l),l);let r=l=>{let b=0,I=t.length-1;for(;b<I;){let x=b+I+1>>1;t[x][0]<=l?b=x:I=x-1}let A=t[b];return A[0]<=l&&l<=A[1]},a=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&a.set(ke(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let h=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=l=>(i.graphLookups+=1,h(l)),d=async(l,b)=>{if(r(l.node))return n.get(ke(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let I=await this.db.haplotypeSampleAt(l.node,l.offset);return I||(i.companionMisses+=1),I},f=new Map,p=async l=>{let b=f.get(l);if(!b){let I=await this.db.getPath(l);if(!I)throw new Error(`Path ${l} is missing from the database`);b=I.name,f.set(l,b)}return b},y=(l,b,I)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+I},m=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let I=[],A=new Set,x={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(x);let E,g=0,S=l,P;for(;E===void 0;){if(this.signal?.throwIfAborted(),S!==void 0){if(A.has(S)){x.end="cycle";break}A.add(S);let H=this.paths[S];I.push({index:S,startBp:g}),x.fragments+=1;let v=g;for(let X=0;X<H.path.length;X++){let w=nt(H,X),k=n.get(ke(w)),N=this.record(w.node).sequenceLen;if(k){E=y(k,v,N);break}v+=N}if(g+=H.len,E){x.end="in-fragment sample";break}let G=nt(H,H.path.length-1);P=this.record(G.node).gbwt().lf(G.offset),S=void 0}if(P===void 0||P.node===0){x.end="endmarker";break}let _=ke(P),B=a.get(_);if(B!==void 0){let H=this.paths[B].identity;if(H){E=m(H,g),x.end="identified sibling";break}S=B;continue}this.records.has(P.node)&&(x.reentries+=1),this.twinStarts.has(_)&&(x.twinLandings+=1);let D=await d(P,x),C=await c(P.node);if(D){E=y(D,g,C.sequenceLen),x.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,x.steps+=1,g-I[I.length-1].startBp>4*e+4*C.sequenceLen){x.end="bound";break}g+=C.sequenceLen,P=C.gbwt().lf(P.offset)}if(E){x.pathHandle=E.pathHandle;let _=await p(E.pathHandle);for(let{index:B,startBp:D}of I){let C=this.paths[B];C.identity=E.orientation==="forward"?{pathHandle:E.pathHandle,name:_,orientation:"forward",hapStart:E.base+D,hapEnd:E.base+D+C.len}:{pathHandle:E.pathHandle,name:_,orientation:"reverse",hapStart:E.base-D-C.len,hapEnd:E.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),a=0,i=-1;for(let h=0;h<e.length;h++){let c=n.get(e[h]);if(c){let d=ls(c,i);if(d===void 0)return;s[a]=h,r[a]=d,a+=1,i=d}}return{pathAt:s,refAt:r,count:a}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,a=0,i=0;for(;s<e.length&&r<t.length;){let h=this.record(e[s]).sequence,c=this.record(t[r]).sequence;for(;a<h.length&&i<c.length;){if(h[a]!==c[i])return n;a+=1,i+=1,n+=1}a===h.length&&(s+=1,a=0),i===c.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,a=0,i=0;for(;s<e.length&&r<t.length;){let h=this.record(e[e.length-s-1]).sequence,c=this.record(t[t.length-r-1]).sequence;for(;a<h.length&&i<c.length;){if(h[h.length-a-1]!==c[c.length-i-1])return n;a+=1,i+=1,n+=1}a===h.length&&(s+=1,a=0),i===c.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),a=this.prefixMatches(e,t),i=this.suffixMatches(e,t);a+i>s&&(i=s-a),a+i>r&&(i=r-a),W(n,"M",a),Tn(n,s-a-i,r-a-i),W(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??fs(gn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],a=this.refPrefix(t),i=(f,p,y,m)=>{f===p?W(r,"D",a[m]-a[y]):y===m?W(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(y,m),r)},h=0,c=0,d=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],y=s.refAt[f];(c!==p||d!==y)&&i(c,p,d,y);let m=this.record(e[p]).sequenceLen;W(r,"M",m),h+=m,c=p+1,d=y+1}return i(c,e.length,d,t.length),{edits:r,matched:h,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Fe(n)&&(t.identity===void 0||!Fe(qe(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=qe(t.path),a=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(a===0)s={...this.editsAgainst(r,n),flipped:!0};else{let h=this.editsAgainst(t.path,n),c=this.editsAgainst(r,n);s=c.matched>h.matched?{...c,flipped:!0}:{...h,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();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,n=this.refPrefix(t)[t.length],s=(d,f,p,y)=>{let m=bs(d),l=this.paths[p[0]],b=this.paths[p[p.length-1]],I=l.identity,A=I?.orientation==="forward",[x,E]=A?[l,b]:[b,l];return{strand:f,refStart:e.start+m.leading,refEnd:e.start+n-m.trailing,edits:m.edits,weight:l.weight,path:p.flatMap(g=>this.paths[g].path),start:nt(l,0),pieces:p,soloAligned:y,identity:I===void 0?void 0:{pathHandle:I.pathHandle,name:I.name,hapStart:I.name.fragment+x.identity.hapStart,hapEnd:I.name.fragment+E.identity.hapEnd,walkForward:A}}},r=d=>d.soloAligned.reduce((f,p)=>f+p,0),a=d=>d.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=d=>2*r(d)>=a(d),h=d=>{let f=d[0],p=d[d.length-1],y=f.identity.walkForward;if(d.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==y||G>0&&v.identity.hapStart<d[G-1].identity.hapEnd))return;let m=y?d:[...d].reverse(),l=m.flatMap(v=>v.pieces),b=m.flatMap(v=>v.soloAligned),I=f.strand==="+"!==y,A=l.map(v=>this.paths[v]),x=A.slice(1).map((v,G)=>{let X=A[G].identity;return y?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),E=I?[...A].reverse():A,g=I?[...x].reverse():x,S=E.flatMap(v=>I?qe(v.path):v.path),{edits:P}=this.editsAgainst(S,t),_=_n(P,E.map(v=>v.len)),B=new Map((I?[...l].reverse():l).map((v,G)=>[v,_[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+B.get(X),0)>=r(v);if(!D(f)||!D(p))return;let C=[],H=0;return E.slice(0,-1).forEach((v,G)=>{H+=v.len,C.push([H,g[G]])}),s(xs(P,C),f.strand,l,b)},c=[];return this.paths.forEach((d,f)=>{if(f===this.refId)return;let{edits:p,flipped:y}=this.alignment(f),m=d.identity,l=m?m.orientation==="forward"!==y:!y;c.push(s(p,l?"+":"-",[f],_n(p,[d.len])))}),gs(c,i,h).map(d=>{let{edits:f,identity:p,pieces:y,soloAligned:m,...l}=d,b={...l,cigar:Ss(f)};return p?{...b,resolved:!0,name:p.name,label:fe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(d=>{let{identity:f}=d;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(d,f)}]:[]}),a=d=>f=>f.sample===d.sample&&f.haplotype===d.haplotype,i=a(t),h=n?a(n):d=>!i(d),c=d=>this.record(ue(d,"forward")).sequence;return r.filter(d=>i(d.name)).flatMap(d=>r.filter(f=>h(f.name)).flatMap(f=>wn({...s,query:f.steps,target:d.steps,sequenceOf:c}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:d.name,targetStart:d.start+p.targetStart,targetEnd:d.start+p.targetEnd,cigar:mn(p.edits),matches:p.edits.reduce((y,[m,l])=>y+(m==="="?l:0),0),columns:p.edits.reduce((y,[,m])=>y+m,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=ue(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Be(s,r)&&t.push([n==="reverse"?1:0,M(r),re(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!re(n)){let s=M(n),r=`S ${s} ${this.record(n).sequence}
|
|
1
|
+
import{a as ue,b as M,c as Re,d as re,e as te,f as dn,g as Ke,h as Ye,i as fn,j as ln,k as Be,l as Fe,m as Ae,n as pn,o as un,p as gn,q as wn,r as mn,s as Mt,t as Sn,u as ns,v as In}from"./chunk-GCMBACYH.js";import{b as _e,c as yn,d as bn,e as xn}from"./chunk-2NDAF7IS.js";import{a as Nt,b as $t}from"./chunk-NWVYDDZ5.js";import{f as ts,g as an,h as pe,i as kt,j as Pt,k as Xe,l as vt,m as Rt,o as At}from"./chunk-YBFFQGX7.js";import"./chunk-ZVLVSWEZ.js";import{a as Ne}from"./chunk-OGQ6OQDN.js";import"./chunk-YBLNN5FU.js";import{e as Ze,f as ve,g as Et}from"./chunk-OCFNF6DB.js";import"./chunk-E7J6SB5P.js";import{b as on,c as hn,d as cn}from"./chunk-R3TRNF7N.js";import"./chunk-7WIBGKBU.js";import{e as rn,o as It}from"./chunk-TENPGIPX.js";var Te=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 n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},En=255,ss=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new Te(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<En?Math.floor(ss/this.sigma):0}next(){if(this.sigma>=En){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function kn(o){let e=new Te(o),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let a=e.int(),i=e.int();if(a===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=a,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(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(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),a=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:a+(e-n)};t[s.value]=a+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:te(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],a=t[s];M(r.node)===M(a.node)&&(t[s-1]=a,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(a=>a.offset),t=0;for(let a of this.runs())t+=a.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let a of this.runs()){let i=this.edge(a.value),h=e[a.value];for(let c=0;c<a.len;c++)n[r]=i.node,s[r]=h,h+=1,r+=1;e[a.value]=h}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var rs=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(o,e)=>o>>>e|o<<32-e;function Pn(o){let e=Math.ceil((o.length+9)/64),t=new Uint8Array(e*64);t.set(o),t[o.length]=128;let n=new DataView(t.buffer),s=o.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a=new Uint32Array(64);for(let c=0;c<e;c++){for(let A=0;A<16;A++)a[A]=n.getUint32(c*64+A*4);for(let A=16;A<64;A++){let x=a[A-15],E=a[A-2],g=we(x,7)^we(x,18)^x>>>3,S=we(E,17)^we(E,19)^E>>>10;a[A]=a[A-16]+g+a[A-7]+S}let d=r[0],f=r[1],p=r[2],y=r[3],m=r[4],l=r[5],b=r[6],I=r[7];for(let A=0;A<64;A++){let x=we(m,6)^we(m,11)^we(m,25),E=m&l^~m&b,g=I+x+E+rs[A]+a[A]|0,S=we(d,2)^we(d,13)^we(d,22),P=d&f^d&p^f&p;I=b,b=l,l=m,m=y+g|0,y=p,p=f,f=d,d=g+S+P|0}[d,f,p,y,m,l,b,I].forEach((A,x)=>{r[x]=r[x]+A})}let i=new Uint8Array(32),h=new DataView(i.buffer);for(let c=0;c<8;c++)h.setUint32(c*4,r[c]);return i}function vn(o,e){let t=new Map;if(o!==void 0)for(let n of o.split(";")){let s=n.split(","),[r,a]=s;if(s.length!==2||!r||!a)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(a)}return t}function Nn(o){return{name:o.get("pggname"),subgraph:vn(o.get("subgraph"),"subgraph"),translation:vn(o.get("translation"),"translation")}}function Rn(o,e){for(let[t,n]of e){let s=o.get(t);s||(s=new Set,o.set(t,s));for(let r of n)s.add(r)}}function $n(o,e){let t={name:o,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(o,new Set([e.name])),Rn(t.subgraph,e.subgraph),Rn(t.translation,e.translation)),t}function An(o){return[...o.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function Mn(o){let e=[];o.name!==void 0&&e.push(`H NM:Z:${o.name}`);for(let[t,n]of An(o.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of An(o.translation))e.push(`H TL:Z:${t},${n}`);return e}async function Ln(o){let e=o.reduce((a,i)=>a+i.length,0),t=new Uint8Array(e),n=0;for(let a of o)t.set(a,n),n+=a.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Pn(t)].map(a=>a.toString(16).padStart(2,"0")).join("")}var as="_gbwt_ref";function fe(o){let e=`${o.sample}#${o.haplotype}#${o.contig}`;return o.end===void 0?e:`${e}[${o.fragment}-${o.end}]`}var os=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,is=/^([^#]+?)(?:\[\d+-\d+\])?$/;function hs(o){let e=os.exec(o);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=is.exec(o);if(t)return{contig:t[1]};throw new Error(`"${o}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function $e(o){return typeof o=="string"?hs(o):o}function Me(o,e){return{sample:o.sample??as,contig:o.contig,haplotype:o.haplotype??0,fragment:e}}var cs=4096;function Ht(o){let e=[];for(let t of o){let n=e[e.length-1];n&&t-n[1]<=cs?n[1]=t:e.push([t,t])}return e}var ds=32768,Hn={mostChosenPaths:32},Lt=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},ae=class extends Error{};function tt(o,e,t,n){return o==="forward"?e+t:e-n}function On(o,e,t,n){return o==="forward"?e-n:e+t}function Cn(o){return Ae(te(o.handles[o.handles.length-1]),te(o.handles[0]))}function ze(o){return`${o.pathHandle}:${o.hapStart}:${o.hapEnd}`}async function Bn(o){let{db:e,records:t,signal:n}=o,s=performance.now(),r=()=>{let w=performance.now(),k=w-s;return s=w,k},a={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}},i=(w,k)=>{let N=`${w}: ${k}`;a.walks[N]=(a.walks[N]??0)+1},h=await e.haplotypeSampleInterval()??4096,c=new Map,d=async w=>{let k=t.get(w)??c.get(w);if(k)return k;let N=await e.getRecord(w);if(a.graphFetches+=1,!N)throw new Error(`Node record ${w} is missing from the database`);return c.set(w,N),N},f=w=>t.get(w).sequenceLen,p=await e.pathsByHandle(),y=w=>{let k=p.get(w);return k!==void 0&&o.keep(k.name)},m=[],l=new Lt,b=new Map,I=new Set,A=new Set,x=async w=>{let k=(await d(w.node)).gbwt().lf(w.offset);return k===void 0||k.node===0?void 0:k},E=async(w,k)=>{let N=(await d(te(w.node))).gbwt().predecessorAt(w.offset);if(N===void 0||k!==void 0&&!k.has(N))return;let $=(await d(N)).gbwt().offsetTo(w);if($===void 0)throw new Error(`No offset in ${N} leads to ${w.node}:${w.offset}`);return{node:N,offset:$}},g=(w,k,N,$)=>{let F=N.map(j=>j.pos.node),U=N.map(j=>j.pos.offset),K=0;for(let j of F)K+=f(j);let O=k==="forward"?N[0].left:N[N.length-1].left,L=m.length;m.push({pathHandle:w,orientation:k,handles:F,offsets:U,len:K,hapStart:O,hapEnd:O+K,canonical:Ae(F[0],F[F.length-1]),source:$});for(let j of N)l.set(j.pos,L);let V=b.get(w);return V?V.push(L):b.set(w,[L]),L},S=async(w,k,N,$)=>{let F=[],U=w;for(;;){n?.throwIfAborted();let O=await E(U.pos,t);if(!O)break;U={pos:O,left:On(N,U.left,f(U.pos.node),f(O.node))},F.push(U)}F.reverse();let K=[w];for(U=w;;){n?.throwIfAborted();let O=await x(U.pos);if(!O||!t.has(O.node))break;U={pos:O,left:tt(N,U.left,f(U.pos.node),f(O.node))},K.push(U)}return g(k,N,[...F,...K],$)},P=async(w,k,N,$)=>m[l.get(w.pos)??await S(w,k,N,$)],_=w=>{let k=w.handles[w.handles.length-1];return{pos:{node:k,offset:w.offsets[w.offsets.length-1]},left:w.orientation==="forward"?w.hapEnd-f(k):w.hapStart}},B=w=>{let k=w.handles[0];return{pos:{node:k,offset:w.offsets[0]},left:w.orientation==="forward"?w.hapStart:w.hapEnd-f(k)}},D=await S({pos:o.referencePos,left:o.referenceLeft},o.referenceHandle,"forward","reference"),C=m[D],H=()=>{if(a.fallback!==void 0)return{reference:C,pieces:[],stats:a};let w=new Map;m.forEach((N,$)=>{$!==D&&w.set(ze(N),[...w.get(ze(N))??[],N])});let k=[];for(let N of w.values()){let $=new Set;for(let F of N)F.canonical&&!$.has(F.orientation)&&($.add(F.orientation),k.push(F),a.sources[F.source]+=1)}return a.sources.reference=1,a.pieces=k.length+1,{reference:C,pieces:k,stats:a}},v=async(w,k)=>{let N=k?I:A,$=k?A:I,F=w;for(;;){if(N.has(F))return;N.add(F);let U=m[F],K=k?_(U):B(U),O=0,L;for(;L===void 0;){n?.throwIfAborted();let V=k?await x(K.pos):await E(K.pos);if(!V){L="endmarker";break}let j=(await d(K.pos.node)).sequenceLen,ge=(await d(V.node)).sequenceLen,ne=k?tt(U.orientation,K.left,j,ge):On(U.orientation,K.left,j,ge);if(t.has(V.node)){let Y=l.get(V);Y===void 0?(F=await S({pos:V,left:ne},U.pathHandle,U.orientation,"chain"),$.add(F),L="landed"):($.add(Y),L="merge")}else O>ds?L="bound":(O+=ge,K={pos:V,left:ne})}if(i("chain",L),L!=="landed")return}},G=async w=>{if(o.context>w.context)throw new ae(`the context of ${o.context} bp exceeds the ${w.context} bp the haplotype index's stray rows cover`);let k=a.spacing;if(k===void 0)throw new ae("the haplotype index has no anchors");let{bin:N,bound:$}=w,{fills:F,inserted:U}=o.snarls;if(o.snarls.mode==="overlapping"&&F.length>0)throw new ae("the haplotype index's stray rows cover contained snarls only");for(let u of F){if(u.inserted>0&&u.low===u.high)throw new ae(`the haplotype index's stray rows leave out the snarl bounded by node ${u.low} at both ends`);if(u.inserted>0&&(w.snarlNodes===void 0||u.nodes>w.snarlNodes))throw new ae(w.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${u.nodes} nodes exceeds the ${w.snarlNodes} the haplotype index's stray rows cover`)}let K=Math.floor(o.window.start/N),O=Math.floor((o.window.end-1)/N),L=K*N,V=(O+1)*N,j=new Map,ge=async(u,R)=>{let q=await e.haplotypeAnchorsBetween(o.referenceHandle,u*k,R*k);for(let T of q)j.set(T.anchorOffset/k,T)},ne=Math.max(0,Math.floor((L-$)/k)-1),Y=Math.ceil((V+$)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(o.referenceHandle,K,O),ge(ne,Y)]);for(let u of t.keys()){let R=M(u);if(!re(u)&&!Ve(R)&&!U.has(R))throw new ae(`the haplotype index lists node ${R} of the subgraph in no bin that the window touches`)}a.scans=Ht([...t.keys()].sort((u,R)=>u-R));let he=Promise.all(a.scans.map(([u,R])=>e.haplotypeSamplesInRange(u,R)));for(he.catch(()=>{});ne>0&&(j.get(ne)?.pathOffset??Number.POSITIVE_INFINITY)>=L-$;)ne-=1,await ge(ne,ne);for(;j.has(Y)&&j.get(Y).pathOffset<=V+$;)Y+=1,await ge(Y,Y);let le=[...j.keys()].sort((u,R)=>u-R),be=j.get(le[0]??-1);if(!be)throw new ae("the haplotype index has no anchors on this path");let ce=u=>j.get(u).pathOffset,He=new Map;for(let u of le){let R=M(j.get(u).node);He.set(R,[...He.get(R)??[],u])}let bt=[...He.keys()],Vt=bt.map(u=>j.get(He.get(u)[0]).visits);if(!Vt[bt.indexOf(M(be.node))].some(u=>u.pathHandle===o.referenceHandle&&u.orientation==="forward"&&u.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${o.referenceHandle} at offset ${be.pathOffset} (node ${M(be.node)}); it does not match this graph`);let Wt=le.filter(u=>ce(u)<=o.window.start),Kn=le.filter(u=>ce(u)>=o.window.end);a.anchors=[ce(Wt[Wt.length-1]??le[0]),ce(Kn[0]??le[le.length-1])],a.anchorsRead=le.length;let xt=new Map,Zt=new Set;if(bt.forEach((u,R)=>{let q=He.get(u),T=q.length===1?q[0]:void 0;for(let z of Vt[R])Zt.add(z.pathHandle),z.orientation==="forward"&&y(z.pathHandle)&&xt.set(z.pathHandle,[...xt.get(z.pathHandle)??[],{k:T,row:z}])}),a.chosenPaths=[...Zt].filter(y).length,a.chosenPaths>Hn.mostChosenPaths)throw new ae(`${a.chosenPaths} chosen paths pass the anchors, more than ${Hn.mostChosenPaths}`);let We=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[u,R]of xt){R.sort((q,T)=>q.row.pathOffset-T.row.pathOffset);for(let q=0;q+1<R.length;q++){let T=R[q],z=R[q+1];if(T.k===void 0||z.k===void 0||Math.abs(T.k-z.k)!==1)continue;let[Z,J]=ce(T.k)<=ce(z.k)?[T,z]:[z,T],ee=ce(Z.k),se=ce(J.k);ee<V&&se>=L?(We.push({pathHandle:u,from:T.row,to:z.row}),Ee=Math.min(Ee,ee-$),xe=Math.max(xe,se+$)):ee>=V&&ee-V<=$?(We.push({pathHandle:u,from:Z.row,to:void 0}),Ee=Math.min(Ee,ee-$),xe=Math.max(xe,ee+$)):se<L&&L-se<=$&&(We.push({pathHandle:u,from:J.row,to:void 0}),Ee=Math.min(Ee,se-$),xe=Math.max(xe,se+$))}}let Yn=new Set(F.map(u=>`${u.low}:${u.high}`)),Jn=ie.filter(u=>y(u.pathHandle)&&(u.snarl===void 0||Yn.has(`${u.snarl[0]}:${u.snarl[1]}`))).sort((u,R)=>u.pathHandle-R.pathHandle||u.pathStart-R.pathStart);a.strays={bins:O-K+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await o.prefetchReferenceRange(o.referenceHandle,Math.max(0,Ee),xe+1),a.ms.scan=r();let Xt=8*k+2*(o.window.end-o.window.start),Kt=a.strays,Oe=0,Yt=u=>{if(Kt.outsideBp+=u,Oe+=u,Oe>Xt)throw new ae(`a walk of a chosen path near the window went past its cap of ${Xt} bp`)},St=new Map,Jt=(u,R,q)=>(St.get(u)??[]).some(([T,z])=>T<=R&&q<z),en=(u,R,q)=>{St.set(u,[...St.get(u)??[],[R,q]])},tn=async(u,R,q,T,z)=>{let Z=R,J=q,ee=J;for(;Z&&J<=T;){n?.throwIfAborted();let se;if(t.has(Z.node)){let Ce=await P({pos:Z,left:J},u,"forward",z),sn=_(Ce);Z=sn.pos,J=sn.left,se=f(Z.node),ee=Math.max(ee,Ce.hapEnd)}else se=(await d(Z.node)).sequenceLen,Yt(se),ee=Math.max(ee,J+se);Z=await x(Z),J+=se}return ee},es=async(u,R,q,T)=>{let z={pos:R,left:q},Z=q;for(;z.left>T;){n?.throwIfAborted();let J=await E(z.pos);if(!J)break;let ee=(await d(J.node)).sequenceLen,se=z.left-ee;if(t.has(J.node)){let Ce=await P({pos:J,left:se},u,"forward","section");z=B(Ce),Z=Math.min(Z,Ce.hapStart)}else Yt(ee),z={pos:J,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:u,from:R,to:q}of We){let T=R.pathOffset,z=(q??R).pathOffset+$;if(Jt(u,T-$,z))continue;let Z={node:R.node,offset:R.offset};Oe=0;let J=await tn(u,Z,T,z,"section");Oe=0;let ee=await es(u,Z,T,T-$);en(u,Math.min(ee,T-$),Math.max(J,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let u of Jn){if(Jt(u.pathHandle,u.pathStart,u.pathEnd))continue;Oe=0;let R=await tn(u.pathHandle,{node:u.node,offset:u.offset},u.pathStart,u.pathEnd,"stray");en(u.pathHandle,u.pathStart,Math.max(R,u.pathEnd+1)),Kt.walked+=1}a.ms.walks=r();let nn=[];for(let u of await he)for(let R of u)if(a.scanRows+=1,t.has(R.node)&&y(R.pathHandle)){if(!(b.get(R.pathHandle)??[]).some(q=>{let T=m[q];return T.hapStart<=R.pathOffset&&R.pathOffset<T.hapEnd}))throw new ae(`chosen path ${R.pathHandle} has a sample at ${R.pathOffset} on the window's nodes that no walk reached`);R.orientation==="reverse"&&nn.push(R)}for(let u of nn)await P({pos:{node:u.node,offset:u.offset},left:u.pathOffset},u.pathHandle,"reverse","twin");a.ms.check=r()},X=async()=>{let w=new Map,k=O=>{let L=ze(O),V=w.get(L);V?V.add(O.orientation):w.set(L,new Set([O.orientation]))},N=0,$=()=>{for(;N<m.length;N++)k(m[N])};$();let F=O=>(w.get(ze(O))?.size??0)>1,U=2*h,K=(O,L)=>L===D?y(o.referenceHandle)&&Cn(O):!O.canonical||Cn(O);for(let O=0;O<m.length;O++){let L=m[O];if(F(L)||!K(L,O))continue;a.twins.tried+=1;let V=L.orientation==="forward"?"reverse":"forward",j=_(L),ge=0,ne;for(;!ne&&ge<=U;){n?.throwIfAborted();let ie=await x(j.pos);if(!ie)break;let he=(await d(ie.node)).sequenceLen,le=tt(L.orientation,j.left,(await d(j.pos.node)).sequenceLen,he),be=te(ie.node);ne=(await e.haplotypeSamplesInRange(be,be)).find(ce=>ce.pathHandle===L.pathHandle&&ce.orientation===V&&ce.pathOffset===le),ge+=he,j={pos:ie,left:le}}let Y=ne&&{pos:{node:ne.node,offset:ne.offset},left:ne.pathOffset},Ve=0;for(;Y&&!F(L)&&Ve<=U+L.len;){if(n?.throwIfAborted(),t.has(Y.pos.node)){let ie=await P(Y,L.pathHandle,V,"twin"),he=m.indexOf(ie);await v(he,!0),await v(he,!1),$(),Y=_(ie)}if(!F(L)){let ie=(await d(Y.pos.node)).sequenceLen;Ve+=ie;let he=await x(Y.pos);Y=he?{pos:he,left:tt(V,Y.left,ie,(await d(he.node)).sequenceLen)}:void 0}}if($(),!F(L))throw new ae(`piece ${ze(L)} was found in one orientation where extractPaths keeps the other`);a.twins.found+=1}a.ms.twins=r()};try{let w=await e.haplotypeStrayOptions();if(w===void 0)throw new ae("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(w),await X()}catch(w){if(!(w instanceof ae))throw w;a.fallback=w.message}return H()}function Fn(o,e){return o.handles[0]-e.handles[0]||o.offsets[0]-e.offsets[0]}var oe=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 Ot(o,e){return o[0]<e[0]||o[0]===e[0]&&(o[1]<e[1]||o[1]===e[1]&&o[2]<e[2])}var De=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let a=r-1>>1;if(Ot(s[r],s[a]))[s[r],s[a]]=[s[a],s[r]],r=a;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,a=r+1,i=s;if(r<e.length&&Ot(e[r],e[i])&&(i=r),a<e.length&&Ot(e[a],e[i])&&(i=a),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function fs(o){let e=new Int32Array(o.length),t=new Int32Array(o.length);return o.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:o.length}}function ls(o,e){let t=0,n=o.length;for(;t<n;){let s=t+n>>1;o[s]>e?n=s:t=s+1}return o[t]}function ke(o){return`${o.node}:${o.offset}`}function qe(o){return o.map(e=>te(e)).reverse()}function ps(o,e){let t=e.identity.hapStart-o.identity.hapEnd,n=o.strand==="+"?e.refStart-o.refEnd:o.refStart-e.refEnd;return o.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function us(o,e,t){let[n,s]=o.strand==="+"?[o,e]:[e,o],r=n.edits.map(([c,d])=>[c,d]);Tn(r,t.insertion,t.deletion);for(let[c,d]of s.edits)W(r,c,d);let a=o.identity.walkForward,[i,h]=a?[o,e]:[e,o];return{strand:o.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...h.path],start:i.start,pieces:[...i.pieces,...h.pieces],soloAligned:[...i.soloAligned,...h.soloAligned],identity:{pathHandle:o.identity.pathHandle,name:o.identity.name,hapStart:o.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:a}}}function gs(o,e,t){if(o.some(a=>a.weight!==void 0))return o;let n=new Map;o.forEach((a,i)=>{if(a.identity){let h=n.get(a.identity.pathHandle);h?h.push(i):n.set(a.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let a of n.values()){a.sort((d,f)=>o[d].identity.hapStart-o[f].identity.hapStart);let i=a[0],h=o[i],c=[];for(let d of a.slice(1)){let f=o[d],p=c.length===0?ps(h,f):void 0;if(p){h=us(h,f,p),r.add(d);continue}if(!e(f)){c.push(d);continue}let y=e(h)?t([h,...c.map(m=>o[m]),f]):void 0;if(y){h=y;for(let m of[...c,d])r.add(m)}else s.set(i,h),i=d,h=f;c=[]}s.set(i,h)}return o.flatMap((a,i)=>r.has(i)?[]:[s.get(i)??a])}function nt(o,e){return{node:o.path[e],offset:o.offsets[e]}}var ws=32768;function ms(o){let e=[...o].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=ws?s[1]=n:t.push([n,n])}return t}var Ge=class o{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new o(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),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(ue(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 oe(this.limit);let t=await this.db.getRecord(ue(e,"forward")),n=await this.db.getRecord(ue(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${fe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,a=s;for(;;){await this.ensureNode(M(a.node));let i=this.record(a.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:a.node,nodeOffset:t-r,gbwtOffset:a.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let h=i.gbwt().lf(a.offset);if(!h)throw new Error(`The fragment of ${fe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);a=h}}async aroundPosition(e,t,n){let s=M(e);await this.ensureNode(s);let r=this.record(e),a=Re(e),i=new De;return i.push(t,s,Ke(a)),i.push(r.sequenceLen-t-1,s,Ye(a)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let a=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(a,i),Math.max(a,i)+1]])){let c=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(ms(c.map(d=>d.pos.node)).map(([d,f])=>[d,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof oe&&s.windowBp===void 0?new oe(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,a=t,i=new De;for(;;){let h=M(s.node),c=Re(s.node);this.walkedBp=t-a,await this.ensureNode(h);let d=this.record(s.node);if(r>=d.sequenceLen)throw new Error(`Offset ${r} in node ${h} of length ${d.sequenceLen}`);i.push(r,h,Ke(c));let f=d.sequenceLen-r;if(a<=f){i.push(a===f?0:f-a-1,h,Ye(c));break}i.push(0,h,Ye(c));let p=d.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,a-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new De;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let a of this.records.keys())s.add(M(a));let r=0;for(;e.size>0;){let[a,i,h]=e.pop(),c=`${i}:${h}`;if(n.has(c))continue;n.add(c),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let d=dn(h);if(!n.has(`${i}:${d}`)){let y=this.record(ue(i,fn(h))),m=a+y.sequenceLen-1;m<=t&&e.push(m,i,d)}let f=this.record(ue(i,ln(h))),p=a+1;if(p<=t)for(let y of f.successors()){let m=M(y),l=Ke(Re(y));n.has(`${m}:${l}`)||e.push(p,m,l)}}for(let a of s)this.records.delete(ue(a,"forward")),this.records.delete(ue(a,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,te(t)],s=new Set([M(e),M(t)]),r=[];for(;n.length>0;){let a=n.pop(),i=M(a);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let h of this.record(a).successors()){let c=M(h);s.has(c)||(n.push(h,te(h)),s.add(c))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:a}=await this.fillBetween(n,s),i=M(n),h=M(s);this.snarlFills.push({low:Math.min(i,h),high:Math.max(i,h),nodes:a,inserted:r.length});for(let c of r)this.snarlNodes.add(c);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),a=r.next;a!==void 0&&(n=!0,this.hasHandle(a)?Be(s,a)&&t.push([s,a]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,a]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(te(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async h=>{let c=h.successors(),d=c[0];return d===void 0?!1:c.length>1||(await e(te(d))).successors().length>1},n=async h=>{let c=await e(te(h));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[te(h),c.next]}:{kind:"chain"}:(await e(h)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(h=>this.record(h).successors()),a,i=!1;for(;!i&&r.length>0;){let h=r.shift(),c=M(h);if(!this.hasHandle(h)&&!s.has(c)){s.add(c);let d=await n(h);if(d.kind==="snarl-exit")a=d.snarl,i=!0;else if(d.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(ue(c,f))).successors())}}return a}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,a=new Map;s.forEach((g,S)=>a.set(g,S));let i=new Int32Array(r+1),h=new Int32Array(r),c=[];for(let g=0;g<r;g++){let S=this.record(s[g]),P=S.gbwt().decompressArrays();h[g]=S.sequenceLen,c.push(P),i[g+1]=i[g]+P.nodes.length}let d=i[r],f=new Int32Array(d),p=new Int32Array(d),y=new Uint8Array(d);for(let g=0;g<r;g++){let S=c[g];f.set(S.nodes,i[g]),p.set(S.offsets,i[g])}c.length=0;for(let g=0;g<d;g++){let S=a.get(f[g]);S===void 0?f[g]=-1:(f[g]=S,y[i[S]+p[g]]=1)}let m=n===void 0?void 0:a.get(n.handle),l=n?.gbwtOffset,b,I=(g,S,P)=>{let _=[],B=0,D=0,C=-1,H=g,v=S;for(;;){H===m&&v===l&&(C=B),P&&(P.push(s[H]),_.push(v)),B+=1,D+=h[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:_,len:D,refAt:C,last:H}},A=(g,S,P,_)=>{_>=0&&(this.refId=this.paths.length,b=_),this.paths.push({path:g,offsets:S,len:P,weight:void 0,identity:void 0})},x=new Int32Array(r);for(let g=0;g<r;g++){let S=s[g];if(!re(S)){let P=i[g],_=i[g+1]-P;for(let B=0;B<_;B++)if(y[P+B]===0){let D=[],{offsets:C,len:H,refAt:v,last:G}=I(g,B,D),X=s[G];if(v>=0||Ae(S,X)){if(A(D,C,H,v),!re(X)){let w=a.get(te(X));x[w]=x[w]+1}}else this.twinStarts.add(ke({node:S,offset:B}))}}}for(let g=0;g<r;g++){let S=s[g];if(re(S)){let P=i[g],_=i[g+1]-P,B=0;for(let C=0;C<_;C++)y[P+C]===0&&(B+=1);let D=(m===void 0||b!==void 0)&&B===x[g];for(let C=0;C<_;C++)if(y[P+C]===0){let H=D?void 0:I(g,C,void 0);if(H&&(H.refAt>=0||Ae(S,s[H.last]))){let v=[],{offsets:G,len:X,refAt:w}=I(g,C,v);A(v,G,X,w)}else this.twinStarts.add(ke({node:S,offset:C}))}}}let E=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((g,S)=>g.path[0]-S.path[0]||g.offsets[0]-S.offsets[0]),E&&(this.refId=this.paths.indexOf(E)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let g=this.paths[this.refId],S=n.nodeOffset;for(let _ of g.path.slice(0,b))S+=this.record(_).sequenceLen;let P=n.seqOffset-S;this.refInterval=[P,P+g.len],g.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:P,hapEnd:P+g.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],n=t?.path,s=n&&!Fe(n)?qe(n):void 0,r=c=>s!==void 0&&Ct(c,s)===0||Fe(qe(c)),a=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,d)=>Ct(c.path,d.path)||c.len-d.len||(c===t?-1:d===t?1:0));let i=[],h;for(let c of this.paths){let d=i[i.length-1],f=a&&c!==t&&r(c.path);this.twinDeferred||=f,d&&Ct(d.path,c.path)===0&&!f?d.weight=(d.weight??1)+(c.weight??1):(c===t&&(h=i.length),i.push({...c,weight:c.weight??1}))}this.paths=i,this.refId=h}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=a=>`${a.pathHandle}:${a.hapStart}-${a.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let a of this.paths)a!==e&&a.identity?.orientation==="forward"&&s.add(n(a.identity));let r=this.paths.filter(a=>a===e||a.identity?.orientation!=="reverse"||!s.has(n(a.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(a=>a.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((a,i)=>i!==this.refId&&a.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 n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((a,i)=>i===this.refId||a.identity!==void 0&&e(a.identity.name)),r=new Set;for(let a of s)for(let i of a.path)r.add(M(i));for(let a of[...this.records.keys()])r.has(M(a))||this.records.delete(a);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,a=await Bn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(d,f,p)=>this.prefetchReferenceRange(d,f,p)});if(this.stats.keep=a.stats,a.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),h=d=>({path:d.handles,offsets:d.offsets,len:d.len,weight:void 0,identity:{pathHandle:d.pathHandle,name:d===a.reference?e.name:i.get(d.pathHandle).name,orientation:d.orientation,hapStart:d.hapStart,hapEnd:d.hapEnd}}),c=[a.reference,...a.pieces].sort(Fn);return this.paths=c.map(h),this.refId=c.indexOf(a.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[a.reference.hapStart,a.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");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ht(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ke(l),l);let r=l=>{let b=0,I=t.length-1;for(;b<I;){let x=b+I+1>>1;t[x][0]<=l?b=x:I=x-1}let A=t[b];return A[0]<=l&&l<=A[1]},a=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&a.set(ke(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let h=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=l=>(i.graphLookups+=1,h(l)),d=async(l,b)=>{if(r(l.node))return n.get(ke(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let I=await this.db.haplotypeSampleAt(l.node,l.offset);return I||(i.companionMisses+=1),I},f=new Map,p=async l=>{let b=f.get(l);if(!b){let I=await this.db.getPath(l);if(!I)throw new Error(`Path ${l} is missing from the database`);b=I.name,f.set(l,b)}return b},y=(l,b,I)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+I},m=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let I=[],A=new Set,x={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(x);let E,g=0,S=l,P;for(;E===void 0;){if(this.signal?.throwIfAborted(),S!==void 0){if(A.has(S)){x.end="cycle";break}A.add(S);let H=this.paths[S];I.push({index:S,startBp:g}),x.fragments+=1;let v=g;for(let X=0;X<H.path.length;X++){let w=nt(H,X),k=n.get(ke(w)),N=this.record(w.node).sequenceLen;if(k){E=y(k,v,N);break}v+=N}if(g+=H.len,E){x.end="in-fragment sample";break}let G=nt(H,H.path.length-1);P=this.record(G.node).gbwt().lf(G.offset),S=void 0}if(P===void 0||P.node===0){x.end="endmarker";break}let _=ke(P),B=a.get(_);if(B!==void 0){let H=this.paths[B].identity;if(H){E=m(H,g),x.end="identified sibling";break}S=B;continue}this.records.has(P.node)&&(x.reentries+=1),this.twinStarts.has(_)&&(x.twinLandings+=1);let D=await d(P,x),C=await c(P.node);if(D){E=y(D,g,C.sequenceLen),x.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,x.steps+=1,g-I[I.length-1].startBp>4*e+4*C.sequenceLen){x.end="bound";break}g+=C.sequenceLen,P=C.gbwt().lf(P.offset)}if(E){x.pathHandle=E.pathHandle;let _=await p(E.pathHandle);for(let{index:B,startBp:D}of I){let C=this.paths[B];C.identity=E.orientation==="forward"?{pathHandle:E.pathHandle,name:_,orientation:"forward",hapStart:E.base+D,hapEnd:E.base+D+C.len}:{pathHandle:E.pathHandle,name:_,orientation:"reverse",hapStart:E.base-D-C.len,hapEnd:E.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),a=0,i=-1;for(let h=0;h<e.length;h++){let c=n.get(e[h]);if(c){let d=ls(c,i);if(d===void 0)return;s[a]=h,r[a]=d,a+=1,i=d}}return{pathAt:s,refAt:r,count:a}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,a=0,i=0;for(;s<e.length&&r<t.length;){let h=this.record(e[s]).sequence,c=this.record(t[r]).sequence;for(;a<h.length&&i<c.length;){if(h[a]!==c[i])return n;a+=1,i+=1,n+=1}a===h.length&&(s+=1,a=0),i===c.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,a=0,i=0;for(;s<e.length&&r<t.length;){let h=this.record(e[e.length-s-1]).sequence,c=this.record(t[t.length-r-1]).sequence;for(;a<h.length&&i<c.length;){if(h[h.length-a-1]!==c[c.length-i-1])return n;a+=1,i+=1,n+=1}a===h.length&&(s+=1,a=0),i===c.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),a=this.prefixMatches(e,t),i=this.suffixMatches(e,t);a+i>s&&(i=s-a),a+i>r&&(i=r-a),W(n,"M",a),Tn(n,s-a-i,r-a-i),W(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??fs(gn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],a=this.refPrefix(t),i=(f,p,y,m)=>{f===p?W(r,"D",a[m]-a[y]):y===m?W(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(y,m),r)},h=0,c=0,d=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],y=s.refAt[f];(c!==p||d!==y)&&i(c,p,d,y);let m=this.record(e[p]).sequenceLen;W(r,"M",m),h+=m,c=p+1,d=y+1}return i(c,e.length,d,t.length),{edits:r,matched:h,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Fe(n)&&(t.identity===void 0||!Fe(qe(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=qe(t.path),a=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(a===0)s={...this.editsAgainst(r,n),flipped:!0};else{let h=this.editsAgainst(t.path,n),c=this.editsAgainst(r,n);s=c.matched>h.matched?{...c,flipped:!0}:{...h,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();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,n=this.refPrefix(t)[t.length],s=(d,f,p,y)=>{let m=bs(d),l=this.paths[p[0]],b=this.paths[p[p.length-1]],I=l.identity,A=I?.orientation==="forward",[x,E]=A?[l,b]:[b,l];return{strand:f,refStart:e.start+m.leading,refEnd:e.start+n-m.trailing,edits:m.edits,weight:l.weight,path:p.flatMap(g=>this.paths[g].path),start:nt(l,0),pieces:p,soloAligned:y,identity:I===void 0?void 0:{pathHandle:I.pathHandle,name:I.name,hapStart:I.name.fragment+x.identity.hapStart,hapEnd:I.name.fragment+E.identity.hapEnd,walkForward:A}}},r=d=>d.soloAligned.reduce((f,p)=>f+p,0),a=d=>d.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=d=>2*r(d)>=a(d),h=d=>{let f=d[0],p=d[d.length-1],y=f.identity.walkForward;if(d.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==y||G>0&&v.identity.hapStart<d[G-1].identity.hapEnd))return;let m=y?d:[...d].reverse(),l=m.flatMap(v=>v.pieces),b=m.flatMap(v=>v.soloAligned),I=f.strand==="+"!==y,A=l.map(v=>this.paths[v]),x=A.slice(1).map((v,G)=>{let X=A[G].identity;return y?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),E=I?[...A].reverse():A,g=I?[...x].reverse():x,S=E.flatMap(v=>I?qe(v.path):v.path),{edits:P}=this.editsAgainst(S,t),_=_n(P,E.map(v=>v.len)),B=new Map((I?[...l].reverse():l).map((v,G)=>[v,_[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+B.get(X),0)>=r(v);if(!D(f)||!D(p))return;let C=[],H=0;return E.slice(0,-1).forEach((v,G)=>{H+=v.len,C.push([H,g[G]])}),s(xs(P,C),f.strand,l,b)},c=[];return this.paths.forEach((d,f)=>{if(f===this.refId)return;let{edits:p,flipped:y}=this.alignment(f),m=d.identity,l=m?m.orientation==="forward"!==y:!y;c.push(s(p,l?"+":"-",[f],_n(p,[d.len])))}),gs(c,i,h).map(d=>{let{edits:f,identity:p,pieces:y,soloAligned:m,...l}=d,b={...l,cigar:Ss(f)};return p?{...b,resolved:!0,name:p.name,label:fe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(d=>{let{identity:f}=d;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(d,f)}]:[]}),a=d=>f=>f.sample===d.sample&&f.haplotype===d.haplotype,i=a(t),h=n?a(n):d=>!i(d),c=d=>this.record(ue(d,"forward")).sequence;return r.filter(d=>i(d.name)).flatMap(d=>r.filter(f=>h(f.name)).flatMap(f=>wn({...s,query:f.steps,target:d.steps,sequenceOf:c}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:d.name,targetStart:d.start+p.targetStart,targetEnd:d.start+p.targetEnd,cigar:mn(p.edits),matches:p.edits.reduce((y,[m,l])=>y+(m==="="?l:0),0),columns:p.edits.reduce((y,[,m])=>y+m,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=ue(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Be(s,r)&&t.push([n==="reverse"?1:0,M(r),re(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!re(n)){let s=M(n),r=`S ${s} ${this.record(n).sequence}
|
|
2
2
|
`;for(let[a,i,h]of this.canonicalEdges(s))r+=`L ${s} ${a?"-":"+"} ${i} ${h?"-":"+"}
|
|
3
3
|
`;t.push(e.encode(r))}return Ln(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...Mn($n(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let c of s)re(c)||n.push(`S ${M(c)} ${this.record(c).sequence}`);let r=c=>re(c)?"-":"+";for(let c of s)for(let d of this.record(c).successors())this.hasHandle(d)&&Be(c,d)&&n.push(`L ${M(c)} ${r(c)} ${M(d)} ${r(d)} 0M`);let a=(c,d,f,p,y)=>{let m=rt(c,d).map(I=>`${re(I)?"<":">"}${M(I)}`).join(""),l=c.weight===void 0?"":` WT:i:${c.weight}`,b=y===void 0?"":` CG:Z:${y}`;return`W ${f.sample} ${f.haplotype} ${f.contig} ${f.fragment} ${p} ${m}${l}${b}`},i=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.push(a(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let h=1;return this.paths.forEach((c,d)=>{if(d!==this.refId){let f=e.names!=="anonymous"?c.identity:void 0,p=t?this.alignToRef(d):void 0;n.push(f?a(c,f,{...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd,p):a(c,void 0,{sample:"unknown",contig:i,haplotype:h,fragment:0},c.len,p)),h+=1}}),`${n.join(`
|
|
4
4
|
`)}
|
|
5
5
|
`}outputPaths(e){this.settleDeferred();let t=e.cigar??!1,n=[],s=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let a={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};n.push({info:this.paths[this.refId],identity:void 0,name:fe({...a,end:this.refPath.fragment+this.refInterval[1]}),cigar:void 0})}let r=1;return this.paths.forEach((a,i)=>{if(i===this.refId)return;let h=e.names!=="anonymous"?a.identity:void 0;n.push({info:a,identity:h,name:h?fe({...h.name,fragment:h.name.fragment+h.hapStart,end:h.name.fragment+h.hapEnd}):fe({sample:"unknown",contig:s,haplotype:r,fragment:0,end:a.len}),cigar:t?this.alignToRef(i):void 0}),r+=1}),n}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Be(e,t)&&(yield[e,t])}walkSpans(){return this.settleDeferred(),this.paths.flatMap((e,t)=>{let n=t===this.refId?void 0:e.identity;return n?[{name:n.name,start:n.name.fragment+n.hapStart,end:n.name.fragment+n.hapEnd}]:[]})}toSubgraphJson(e={}){let t=this.sortedHandles().filter(r=>!re(r)).map(r=>({id:String(M(r)),sequence:this.record(r).sequence})),n=[];for(let[r,a]of this.outputEdges())n.push({from:String(M(r)),from_is_reverse:re(r),to:String(M(a)),to_is_reverse:re(a)});let s=this.outputPaths(e).map(r=>ys(r.info,r.identity,r.name,r.cigar));return{nodes:t,edges:n,paths:s}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(a=>!re(a)),n=new Int32Array(t.length),s=[];t.forEach((a,i)=>{n[i]=M(a),s.push(this.record(a).sequence)});let r=[];for(let[a,i]of this.outputEdges())r.push(a,i);return{nodeIds:n,nodeSequences:s,edges:Int32Array.from(r),paths:this.outputPaths(e).map(a=>({name:a.name,weight:a.info.weight,cigar:a.cigar,steps:Int32Array.from(rt(a.info,a.identity))}))}}};function rt(o,e){return e?.orientation==="reverse"?o.path.map(t=>te(t)).reverse():o.path}function ys(o,e,t,n){return{name:t,...o.weight===void 0?{}:{weight:o.weight},...n===void 0?{}:{cigar:n},path:rt(o,e).map(s=>({id:String(M(s)),is_reverse:re(s)}))}}function Ct(o,e){let t=Math.min(o.length,e.length);for(let n=0;n<t;n++){let s=o[n],r=e[n];if(s!==r)return s<r?-1:1}return o.length-e.length}function W(o,e,t){if(t===0)return;let n=o[o.length-1];n?.[0]===e?n[1]+=t:o.push([e,t])}function st(o){return o===0?0:6+(o-1)}function Tn(o,e,t){if(e===0)W(o,"D",t);else if(t===0)W(o,"I",e);else{let n=Math.min(e,t),s=4*n+st(e-n)+st(t-n),r=st(e)+st(t);s<=r?(W(o,"M",n),W(o,"I",e-n),W(o,"D",t-n)):(W(o,"I",e),W(o,"D",t))}}function bs(o){let e=0;for(;e<o.length&&o[e][0]!=="M";)e+=1;if(e===o.length){let i=o.filter(([c])=>c==="I"),h=o.filter(([c])=>c==="D").reduce((c,[,d])=>c+d,0);return{edits:i.map(([c,d])=>[c,d]),leading:0,trailing:h}}let t=o.length;for(;o[t-1][0]!=="M";)t-=1;let n=i=>({inserted:i.reduce((h,[c,d])=>h+(c==="I"?d:0),0),deleted:i.reduce((h,[c,d])=>h+(c==="D"?d:0),0)}),s=n(o.slice(0,e)),r=n(o.slice(t)),a=[];W(a,"I",s.inserted);for(let[i,h]of o.slice(e,t))W(a,i,h);return W(a,"I",r.inserted),{edits:a,leading:s.deleted,trailing:r.deleted}}function _n(o,e){let t=e.map(()=>0),n=e.length-1,s=0,r=e[0],a=0;for(let[i,h]of o){if(i==="D")continue;let c=h;for(;c>0;){for(;s<n&&a>=r;)s+=1,r+=e[s];let d=s<n?Math.min(c,r-a):c;i==="M"&&(t[s]+=d),a+=d,c-=d}}return t}function xs(o,e){let t=[],n=0,s=0;for(let[r,a]of o){if(r==="D"){W(t,r,a);continue}let i=n;for(;s<e.length&&e[s][0]<n+a;){let[h,c]=e[s];W(t,r,h-i),W(t,"I",c),i=h,s+=1}W(t,r,n+a-i),n+=a}for(;s<e.length;s++)W(t,"I",e[s][1]);return t}function Ss(o){return o.map(([e,t])=>`${t}${e}`).join("")}function Se(o,e,t=0){if(!Number.isSafeInteger(e)||e<t)throw new Error(`${o} must be a whole number${t>0?` of at least ${t}`:""}, not ${e}`);return e}function at(o){return Se("context",o.context??100)}function ot(o,e){return e.limit!==void 0&&Se("limit",e.limit),Ge.create(o,e)}async function zn(o,e){let t=at(e),n=ot(o,e),s=await n.pathPosition(Me($e(e.path),Se("offset",e.offset)));return await n.aroundPosition(s.position.handle,s.position.nodeOffset,t),await n.extractSnarls(e.snarls??"none"),n.extractPaths(s,e.haplotypes??"all"),n}async function Is(o,e){let t=Se("start",e.start),n=Se("end",e.end),s=at(e),r=ot(o,e);try{let a=await r.pathPosition(Me($e(e.path),t));return await r.prefetchReferenceWalk(a,n-t),await r.aroundInterval(a.position,n-t,s),await r.extractSnarls(e.snarls??"none"),{subgraph:r,reference:a}}catch(a){throw a instanceof oe&&a.windowBp===void 0?new oe(a.limit,{windowBp:n-t,walkedBp:r.referenceWalkedBp??0}):a}}async function Bt(o,e){let{keep:t}=e,n=e.haplotypes??"all",s=n==="all"||n==="distinct";if(t!==void 0&&s&&!o.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:r,reference:a}=await Is(o,e);return t===void 0||!s?(r.extractPaths(a,n),r):(await r.extractChosenPaths(a,e.end-e.start,t,at(e))||(r.extractPaths(a,"all"),await r.identifyPaths()),r.keepHaplotypes(t),n==="distinct"&&r.mergeDistinct(),r)}async function qn(o,e){let t=e.haplotypes??"all",n=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(n==="overlapping"&&new Set(e.nodeIds).size>1)throw new Error("Overlapping snarls cannot be extracted for a node-based query with multiple nodes");let s=at(e);for(let a of e.nodeIds)Se("node id",a,1);let r=ot(o,e);return await r.aroundNodes(e.nodeIds,s),await r.extractSnarls(n),r.extractPaths(void 0,t),r}async function Dn(o,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let n=ot(o,e);return await n.betweenNodes(Se("startHandle",e.startHandle,2),Se("endHandle",e.endHandle,2)),n.extractPaths(void 0,t),n}function me(o,e){let t=0;for(let s=0;s<8;s++){let r=o[e+s];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(r&127),(r&128)===0){if(s===7&&!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+s+1]}}let n=o[e+8];if(n===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+n,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function Es(o,e,t){switch(t){case 1:return o.getInt8(e);case 2:return o.getInt16(e);case 3:return o.getInt8(e)<<16|o.getUint16(e+1);case 4:return o.getInt32(e);case 6:return o.getInt16(e)*4294967296+o.getUint32(e+2);default:{let n=o.getBigInt64(e);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${n} exceeds the safe integer range`);return Number(n)}}}var ks=new TextDecoder;function it(o){let[e,t]=me(o,0),n=[],s=t;for(;s<e;){let[i,h]=me(o,s);n.push(i),s=h}let r=new DataView(o.buffer,o.byteOffset,o.byteLength),a=e;return n.map(i=>{if(i===0)return null;if(i>=1&&i<=6){let h=i<=4?i:i===5?6:8,c=Es(r,a,h);return a+=h,c}if(i===7){let h=r.getFloat64(a);return a+=8,h}if(i===8)return 0;if(i===9)return 1;if(i>=12){let h=i-12>>1,c=o.subarray(a,a+h);return a+=h,i%2===0?c:ks.decode(c)}throw new Error(`SQLite serial type ${i} is reserved`)})}var ct=2,dt=5,Gn=10,ht=13;function Un(o,e){return o[e]*256+o[e+1]}function Ie(o,e){return o[e]*16777216+o[e+1]*65536+o[e+2]*256+o[e+3]}function Ps(o,e){let t=o[e];if(t!==ct&&t!==dt&&t!==Gn&&t!==ht)throw new Error(`SQLite page has unknown b-tree type ${t}`);let n=t===ct||t===dt;return{type:t,cellCount:Un(o,e+3),rightChild:n?Ie(o,e+8):0,cellPointers:e+(n?12:8)}}function ye(o,e,t){return Un(o,e.cellPointers+2*t)}var vs=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 n=this.usable,s=t?Math.floor((n-12)*64/255)-23:n-35;if(e<=s)return e;let r=Math.floor((n-12)*32/255)-23,a=r+(e-r)%(n-4);return a<=s?a:r}async payload(e,t,n,s){let r=this.localPayloadSize(n,s);if(r===n)return e.subarray(t,t+n);let a=new Uint8Array(n);a.set(e.subarray(t,t+r),0);let i=r,h=Ie(e,t+r);for(;h!==0&&i<n;){let c=await this.pager.page(h),d=c.subarray(4,4+Math.min(this.usable-4,n-i));a.set(d,i),i+=d.length,h=Ie(c,0)}if(i!==n)throw new Error("SQLite overflow chain ended before the payload was complete");return a}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:Ps(t,e===1?100:0)}}tableDepth(e,t){let n=this.tableDepths.get(e);return n||(n=(async()=>{let s=e;for(let r=0;;r++){let{page:a,header:i}=await this.pageAt(s);if(i.type===ht)return r;if(i.type!==dt)throw new Error("SQLite table b-tree contains an index page");let h=this.childIndexFor(a,i,t);s=h===i.cellCount?i.rightChild:Ie(a,ye(a,i,h))}})(),this.tableDepths.set(e,n),n.catch(()=>this.tableDepths.delete(e))),n}childIndexFor(e,t,n){let s=0,r=t.cellCount;for(;s<r;){let a=s+r>>1,[i]=me(e,ye(e,t,a)+4);i<n?s=a+1:r=a}return s}async prefetchRowidRanges(e,t,n=!1){if(t.length===0)return!0;let s=await this.tableDepth(e,t[0][0]),r=t.map(()=>[e]);for(let a=0;a<s;a++){r=await Promise.all(r.map((h,c)=>this.childrenInRange(h,...t[c])));let i=r.flat();if(n)this.pager.prefetchLeading(i);else if(!this.pager.prefetch(i))return!1}return!0}async childrenInRange(e,t,n){let s=await Promise.all(e.map(a=>this.pageAt(a))),r=[];return s.forEach(({page:a,header:i},h)=>{let c=h===0?this.childIndexFor(a,i,t):0,d=h===s.length-1?this.childIndexFor(a,i,n):i.cellCount;for(let f=c;f<=d;f++)r.push(f===i.cellCount?i.rightChild:Ie(a,ye(a,i,f)))}),r}async tableRowid(e,t){let n=e;for(;;){let{page:s,header:r}=await this.pageAt(n);if(r.type===ht){let h=0,c=r.cellCount;for(;h<c;){let d=h+c>>1,f=ye(s,r,d),[p,y]=me(s,f),[m,l]=me(s,y);if(m===t)return it(await this.payload(s,l,p,!1));m<t?h=d+1:c=d}return}if(r.type!==dt)throw new Error("SQLite table b-tree contains an index page");let a=0,i=r.cellCount;for(;a<i;){let h=a+i>>1,c=ye(s,r,h),[d]=me(s,c+4);d<t?a=h+1:i=h}n=a===r.cellCount?r.rightChild:Ie(s,ye(s,r,a))}}async*tableScan(e){yield*this.scanPage(e,await this.tableDepth(e,0))}async*scanPage(e,t){let{page:n,header:s}=await this.pageAt(e);if(s.type===ht)for(let r=0;r<s.cellCount;r++){let a=ye(n,s,r),[i,h]=me(n,a),[c,d]=me(n,h);yield{rowid:c,values:it(await this.payload(n,d,i,!1))}}else{let r=[];for(let a=0;a<s.cellCount;a++)r.push(Ie(n,ye(n,s,a)));r.push(s.rightChild),t===1&&this.pager.prefetchLeading(r);for(let a of r)yield*this.scanPage(a,t-1)}}decodedCells(e,t){let n=this.decodedIndexPages.get(e);if(n)this.decodedIndexPages.delete(e);else if(n=new Array(t.cellCount),this.decodedIndexPages.size>=vs){let s=this.decodedIndexPages.keys().next().value;s!==void 0&&this.decodedIndexPages.delete(s)}return this.decodedIndexPages.set(e,n),n}async indexCell(e,t,n,s){let r=this.decodedCells(e,n),a=r[s];if(!a){let i=ye(t,n,s),h=n.type===ct,[c,d]=me(t,h?i+4:i);a={values:it(await this.payload(t,d,c,!0)),leftChild:h?Ie(t,i):0},r[s]=a}return a}async lowerBound(e,t,n,s,r,a){let i=r,h=n.cellCount;for(;i<h;){let c=i+h>>1,d=await this.indexCell(e,t,n,c),f=Ft(d.values,s);f<0||a&&f===0?i=c+1:h=c}return i}async*indexScanFrom(e,t,n){let{page:s,header:r}=await this.pageAt(e),a=await this.lowerBound(e,s,r,t,0,!1),i=r.type===ct;if(i&&n){let h=await this.lowerBound(e,s,r,n,a,!0),c=[];for(let d=a;d<=h;d++)c.push(d===r.cellCount?r.rightChild:(await this.indexCell(e,s,r,d)).leftChild);this.pager.prefetchLeading(c)}for(let h=a;h<r.cellCount;h++){let c=await this.indexCell(e,s,r,h);if(i&&(yield*this.indexScanFrom(c.leftChild,t,n)),n&&Ft(c.values,n)>0)return;yield c.values}i&&(yield*this.indexScanFrom(r.rightChild,t,n))}async indexSeekLE(e,t){let n,s=e;for(;;){let{page:r,header:a}=await this.pageAt(s),i=0,h=a.cellCount,c=0;for(;i<h;){let d=i+h>>1,f=await this.indexCell(s,r,a,d);Ft(f.values,t)<=0?(n=f.values,i=d+1):(c=f.leftChild,h=d)}if(a.type===Gn)return n;s=i===a.cellCount?a.rightChild:c}}};function Ft(o,e){for(let t=0;t<e.length;t++){let n=o[t],s=e[t];if(typeof n!="number"||s===void 0)throw new Error("SQLite index key is not numeric");if(n!==s)return n<s?-1:1}return 0}function jn({blockSize:o,maxBlocks:e}){if(o!==void 0&&!(Number.isSafeInteger(o)&&o>0))throw new Error(`blockSize must be a positive integer, not ${o}`);if(e!==void 0&&!(Number.isSafeInteger(e)&&e>0))throw new Error(`maxBlocks must be a positive integer, not ${e}`)}var lt=class{blocks=new Map;blockSize;maxBlocks;plan;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,n,s={}){this.source=e,this.pageSize=t,this.fileSize=n;let r=s.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(r/t)*t),this.maxBlocks=s.maxBlocks??256}async read(e,t){let n=await this.readRetrying(e,t);if(this.bytesFetched+=n.length,n.length<e)throw new Error(`the file ends at byte ${t+n.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return n}async readRetrying(e,t){let n=0;for(;;)try{return await this.source.read(e,t)}catch(s){if(n+=1,n>=3)throw s;await new Promise(r=>setTimeout(r,200*n))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){this.follow(e);let t=this.touch(e);if(t)return t;let n=e*this.blockSize,s=Math.min(this.blockSize,this.fileSize-n),r=this.read(s,n);return this.fetches+=1,this.store(e,r),this.evict(),r}touch(e){let t=this.blocks.get(e);return t&&(this.blocks.delete(e),this.blocks.set(e,t)),t}blockOf(e){return Math.floor((e-1)*this.pageSize/this.blockSize)}get prefetchBudget(){return Math.max(1,Math.floor(this.maxBlocks/2))}get chunk(){return Math.max(1,Math.floor(this.prefetchBudget/2))}prefetch(e){let t=new Set(e.map(n=>this.blockOf(n)));return t.size>this.prefetchBudget?!1:(this.fetchBlocks(t),!0)}prefetchLeading(e){let t=[],n=new Map;for(let s of e){let r=this.blockOf(s);n.has(r)||(n.set(r,t.length),t.push(r))}this.plan={blocks:t,position:n,next:0},this.advance(this.prefetchBudget)}advance(e){let t=this.plan;if(!t)return;let n=t.blocks.slice(t.next,t.next+e);t.next+=n.length,t.next>=t.blocks.length&&(this.plan=void 0),this.fetchBlocks(new Set(n))}follow(e){let t=this.plan,n=t?.position.get(e);t&&n!==void 0&&n>=t.next-Math.ceil(this.chunk/2)&&this.advance(this.chunk)}fetchBlocks(e){let t=[...e].filter(s=>!this.touch(s)).sort((s,r)=>s-r),n=0;for(;n<t.length;){let s=n+1;for(;s<t.length&&t[s]===t[s-1]+1;)s+=1;this.fetchRun(t[n],s-n),n=s}}fetchRun(e,t){let n=e*this.blockSize,s=Math.min(t*this.blockSize,this.fileSize-n),r=this.read(s,n);this.fetches+=1;for(let a=0;a<t;a++){let i=a*this.blockSize;this.store(e+a,r.then(h=>h.subarray(i,i+this.blockSize)))}this.evict()}store(e,t){this.blocks.set(e,t),t.catch(()=>{this.blocks.get(e)===t&&this.blocks.delete(e)})}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 n=await this.block(Math.floor(t/this.blockSize)),s=t%this.blockSize;return n.subarray(s,s+this.pageSize)}};var Ue=class o{pager;btree;objects;constructor(e,t,n){this.pager=e,this.btree=t,this.objects=n}static async open(e,t={}){jn(t);let n=await e.read(Math.max(512,t.blockSize??65536),0),s=n.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3"||s.length<100)throw new Error("Not a SQLite database");let a=new DataView(s.buffer,s.byteOffset,s.byteLength),i=a.getUint16(16),h=i===1?65536:i,c=s[20]??0,d=a.getUint32(56);if(d!==1)throw new Error(`SQLite text encoding ${d} is not UTF-8`);let f=a.getUint32(28);if(f===0||a.getUint32(24)!==a.getUint32(92))throw new Error("SQLite header has no valid database size; the file was written by SQLite older than 3.7.0");let p=f*h,y=new lt(e,h,p,t);y.seed(0,n),y.fetches+=1,y.bytesFetched+=n.length;let m=new ft(y,c),l=new Map;for await(let{values:b}of m.tableScan(1)){let[I,A,x,E,g]=b;typeof I=="string"&&typeof A=="string"&&typeof x=="string"&&typeof E=="number"&&l.set(A,{type:I,name:A,tableName:x,rootPage:E,sql:typeof g=="string"?g:""})}return new o(y,m,l)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}withoutRowid(e){let t=this.objects.get(e);return t?.type==="table"&&/without\s+rowid/i.test(t.sql)}indexOn(e){let t=[...this.objects.values()].find(n=>n.type==="index"&&n.tableName===e);if(t)return t.rootPage;if(this.withoutRowid(e))return this.rootPage(e);throw new Error(`SQLite table ${e} has no index`)}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,n=!1){return this.btree.prefetchRowidRanges(this.rootPage(e),t,n)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t,n){return this.btree.indexScanFrom(this.indexOn(e),t,n)}has(e){return this.objects.has(e)}};var qt="GBZ-base version 4",pt=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${fe(e)}`),this.path=e}},ut=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},gt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: it has no version tag":`unsupported database schema "${e}"; this reader understands "${qt}"`),this.found=e}};function Rs(o){if(o.length===1)return o[0];let e=new Uint8Array(o.reduce((n,s)=>n+s.length,0)),t=0;for(let n of o)e.set(n,t),t+=n.length;return e}var _t=3,Le=class{at=0;bytes;constructor(e){this.bytes=e}get done(){return this.at>=this.bytes.length}next(){let e=0,t=1;for(;;){let n=this.bytes[this.at++];if(n===void 0)throw new Error("a haplotype index blob ends inside a number");if(e+=(n&127)*t,t*=128,(n&128)===0)return e}}};function As(o,e){let t=new Le(o),n=0;for(;!t.done;){let s=n+t.next();n=s+t.next(),e.push([s,n])}}function Ns(o){o.sort((n,s)=>n[0]-s[0]);let e=[],t=[];for(let[n,s]of o){let r=t.length-1;r>=0&&n<=t[r]+1?t[r]=Math.max(t[r],s):(e.push(n),t.push(s))}return n=>{let s=0,r=e.length;for(;s<r;){let a=s+r>>1;e[a]<=n?s=a+1:r=a}return s>0&&n<=t[s-1]}}function $s(o,e,t){let n=new Le(e);for(;!n.done;){let s=n.next(),r=n.next(),a=n.next(),i=n.next(),h=n.next();t.push({bin:o,pathHandle:s,pathStart:r,pathEnd:a,snarl:h>0?[i,h]:void 0,node:n.next(),offset:n.next()})}}function Ms(o,e,t){let n=M(o);for(let s of e){let r=new Le(s);for(;!r.done;){let a=r.next(),i=a%2;t.push({node:2*n+i,offset:r.next(),pathHandle:(a-i)/2,orientation:"forward",pathOffset:r.next()})}}}var zt=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,n,s,r){this.handle=e,this.edges=t,this.bwt=n,this.encodedSequence=s,this.next=r,this.sequenceLen=pn(s)}get id(){return M(this.handle)}get orientation(){return Re(this.handle)}get sequence(){return this.decoded??=un(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 et(this.edges,this.bwt)}};function Q(o,e){if(typeof o!="number")throw new Error(`${e} is not a number in the database`);return o}function je(o,e){if(typeof o!="string")throw new Error(`${e} is not text in the database`);return o}function Pe(o,e){if(!(o instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return o}function Qn(o,e){return{handle:o,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:je(e[5],"Paths.sample"),contig:je(e[6],"Paths.contig"),haplotype:Q(e[7],"Paths.haplotype"),fragment:Q(e[8],"Paths.fragment")},isIndexed:Q(e[9],"Paths.is_indexed")!==0}}function Tt(o,e){return o.catch(e),o}async function Vn(o){let e=new Map;for await(let{values:t}of o.scan("Tags"))e.set(je(t[0],"Tags.key"),je(t[1],"Tags.value"));return e}var Qe=class o{pathCache;pathMapCache;indexTags=new Map;overviewRowsCache;sqlite;index;tagMap;constructor(e,t,n){this.sqlite=e,this.index=t,this.tagMap=n}static async open(e){let{source:t,haplotypeIndex:n}=e,s={blockSize:e.blockSize,maxBlocks:e.maxBlocks},r=await Ue.open(t,s),a=r.objects.has("Tags")?await Vn(r):new Map,i=a.get("version");if(i!==qt)throw new gt(i);for(let d of["Nodes","Paths","ReferenceIndex"])r.rootPage(d);let h=n?await Ue.open(n,s):void 0,c=new o(r,h,a);if(h){for(let l of["Tags","HaplotypeSamples","HaplotypeLengths"])if(!h.objects.has(l))throw new Error(`haplotypeIndex is not a gbz-base haplotype index: it has no ${l} table`);c.indexTags=await Vn(h);let d=c.indexTags.get("haplotype_index_paths"),f=await c.tag("paths");if(d!==f)throw new Error(`haplotype index was built for ${d??"an unknown number of"} paths but the graph has ${f}`);let p=c.indexTags.get("haplotype_index_nodes"),y=await c.tag("nodes");if(p!==void 0&&p!==y)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${y}`);if(c.indexTags.get("haplotype_index_orientations")==="forward")throw new ut;let m=c.indexTags.get("haplotype_index_format");if(Number(m)!==_t)throw new Error(m===void 0?`the haplotype index predates format ${_t}; rebuild it with gbz-haplotype-index 0.3`:`the haplotype index has format ${m}; this version of @gmod/gbz-base reads format ${_t}`)}return c}async tags(){return this.tagMap}async tag(e){return this.tagMap.get(e)}prefetchRecords(e,t=!1){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let n=t[4];return new zt(e,kn(Pe(t[1],"Nodes.edges")),Pe(t[2],"Nodes.bwt"),Pe(t[3],"Nodes.sequence"),typeof n=="number"?n:void 0)}paths(){return this.pathCache??=Tt(this.scanPaths(),()=>{this.pathCache=void 0}),this.pathCache}async scanPaths(){let e=[];for await(let{rowid:t,values:n}of this.sqlite.scan("Paths"))e.push(Qn(t,n));return e}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?Qn(e,t):void 0}pathsByHandle(){return this.pathMapCache??=Tt(this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),()=>{this.pathMapCache=void 0}),this.pathMapCache}async findPath(e){return(await this.paths()).filter(n=>n.name.sample===e.sample&&n.name.contig===e.contig&&n.name.haplotype===e.haplotype&&n.name.fragment<=e.fragment).sort((n,s)=>s.name.fragment-n.name.fragment)[0]}async pathsNamed(e){let t=Me($e(e),0);return(await this.paths()).filter(n=>n.name.sample===t.sample&&n.name.contig===t.contig&&n.name.haplotype===t.haplotype).sort((n,s)=>n.name.fragment-s.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 n=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!n){let a=await this.getPath(e);throw new Error(`${a?`The fragment of ${fe(a.name)} at ${a.name.fragment}`:`Path ${e}`} has not been indexed for random access`)}let s=n.pathOffset,r=n.pos;for(;;){let a=await this.getRecord(r.node);if(!a)throw new Error(`Node ${r.node} does not exist in the graph`);s+=a.sequenceLen;let i=a.gbwt().lf(r.offset);if(!i||i.node===0)return s;r=i}}return t}async getPathFragments(e){let{start:t,end:n}=e;if(Number.isNaN(t)||Number.isNaN(n))throw new Error(`The window ${t}..${n} is not a number range`);let s=await this.pathsNamed(e.path);if(s.length===0)throw new pt(Me($e(e.path),0));if(n<=t)return[];let r=s.filter(h=>h.name.fragment<=t).slice(-1),a=s.filter(h=>h.name.fragment>t&&h.name.fragment<n);return(await Promise.all([...r,...a].map(async h=>({path:h,start:h.name.fragment,end:h.name.fragment+await this.pathLength(h.handle)})))).filter(h=>t<h.end)}async subgraphForFragment(e,t){let{sample:n,contig:s,haplotype:r}=e.path.name,a=Math.max(t.start,e.start),i=t.haplotypes??"all";try{let h=await Bt(this,{...t,path:{sample:n,contig:s,haplotype:r},start:a,end:Math.min(t.end,e.end)});return t.keep===void 0&&this.hasHaplotypeIndex&&(i==="all"||i==="distinct")&&await h.identifyPaths(),h}catch(h){throw h instanceof oe&&h.walkedBp!==void 0?new oe(h.limit,{windowBp:t.end-t.start,walkedBp:a-t.start+h.walkedBp}):h}}async getSubgraphs(e){let t=await this.getPathFragments(e);return(await Promise.allSettled(t.map(s=>this.subgraphForFragment(s,e)))).map(s=>{if(s.status==="rejected")throw s.reason;return s.value})}async getAlignments(e){return(await this.getSubgraphs(e)).flatMap(t=>t.alignments())}subgraphInInterval(e){return Bt(this,e)}subgraphAtOffset(e){return zn(this,e)}subgraphAroundNodes(e){return qn(this,e)}subgraphBetween(e){return Dn(this,e)}fetchStats(){let e=({pager:t})=>({fetches:t.fetches,bytesFetched:t.bytesFetched});return{graph:e(this.sqlite),haplotypeIndex:this.index?e(this.index):void 0}}async graphName(){let e=new Map;for(let[n,s]of await this.tags())n.startsWith("gbz_")&&e.set(n.slice(4),s);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=Nn(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=n=>this.indexTags.get(`haplotype_index_stray_${n}`);if(!this.index?.has("HaplotypeBins")||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 blobRows(e,t,n){let s=[],r=[];for await(let a of this.companion.indexScanFrom(e,t,n))r.push(Q(a[a.length-1],`${e} rowid`));r.length>1&&await this.companion.prefetchRows(e,[[Math.min(...r),Math.max(...r)+1]],!0);for(let a of r){let i=await this.companion.byRowid(e,a);i&&s.push(i)}return s}async haplotypeBinData(e,t,n){let s=[],r=[];for(let a of await this.blobRows("HaplotypeBins",[e,t],[e,n])){let i=Q(a[1],"HaplotypeBins.bin");As(Pe(a[3],"HaplotypeBins.nodes"),s),$s(i,Pe(a[4],"HaplotypeBins.strays"),r)}return{listed:Ns(s),strays:r}}async haplotypeAnchorsBetween(e,t,n){let s=[],r=[],a=()=>{let i=s[s.length-1];i&&Ms(i.node,r,i.visits),r=[]};for(let i of await this.blobRows("HaplotypeAnchors",[e,t],[e,n])){let h=Q(i[1],"HaplotypeAnchors.anchor_offset");s[s.length-1]?.anchorOffset!==h&&(a(),s.push({anchorOffset:h,node:Q(i[3],"HaplotypeAnchors.node_handle"),pathOffset:Q(i[4],"HaplotypeAnchors.path_offset"),visits:[]})),r.push(Pe(i[5],"HaplotypeAnchors.visits"))}return a(),s}async haplotypeAnchor(e,t){let[n]=await this.haplotypeAnchorsBetween(e,t,t);return n&&{node:n.node,pathOffset:n.pathOffset}}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 n=[];for await(let s of this.companion.indexScanFrom("HaplotypeSamples",[e,0],[t,Number.MAX_SAFE_INTEGER]))n.push(this.sampleFromRow(s));return n}async haplotypeSampleAt(e,t){let n=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);return n?.[0]===e&&n[1]===t?this.sampleFromRow(n):void 0}overviewRows(){return this.overviewRowsCache??=Tt((async()=>{let e=[];for await(let{rowid:t,values:n}of this.companion.scan("HaplotypeOverviewRows"))e[t]={sample:je(n[1],"HaplotypeOverviewRows.sample"),haplotype:Q(n[2],"HaplotypeOverviewRows.haplotype")};return e})(),()=>{this.overviewRowsCache=void 0}),this.overviewRowsCache}async overviewChunks(e,t,n,s,r){let a=new Map;for(let i of await this.blobRows(e,[t,n,s],[t,n,r])){let h=Q(i[2],`${e}.chunk`),c=a.get(h)??[];c.push(Pe(i[4],`${e} blob`)),a.set(h,c)}return new Map([...a].map(([i,h])=>[i,Rs(h)]))}async haplotypeOverview(e){let{signal:t}=e;t?.throwIfAborted();let n=l=>this.indexTags.get(`haplotype_index_overview_${l}`);if(!this.index?.has("HaplotypeOverviewClasses")||n("format")!=="1")return;let s=Number(n("bin")),r=Number(n("chunk")),a=Number(n("levels")),i=Math.max(0,Math.min(Math.floor(e.level??0)||0,a-1));if(e.level===void 0&&e.bpPerPixel!==void 0)for(;i+1<a&&s*4**(i+1)<=e.bpPerPixel;)i+=1;let h=s*4**i,[c,d]=await Promise.all([this.getPathFragments(e),this.overviewRows()]);t?.throwIfAborted();let f=Math.ceil(d.length/2),p=[],y=[];for(let l of c){let b=l.end-l.start,I=Math.max(e.start,l.start)-l.start,A=Math.min(e.end,l.end)-l.start,x=Math.floor(I/h),E=Math.floor((A-1)/h),g=Math.floor(x/r),S=Math.floor(E/r),[P,_]=await Promise.all([this.overviewChunks("HaplotypeOverviewBins",l.path.handle,i,g,S),this.overviewChunks("HaplotypeOverviewClasses",l.path.handle,i,g,S)]);t?.throwIfAborted();for(let B=g;B<=S;B++){let D=new Le(P.get(B)??new Uint8Array),C=_.get(B)??new Uint8Array;for(let H=B*r;!D.done;H++){let v=Array.from({length:7},()=>D.next());if(H<x||H>E)continue;p.push({start:l.start+H*h,end:l.start+Math.min((H+1)*h,b),classes:[v[0],v[1],v[2],v[3]],excursions:v[4],variants:v[5],longestExcursion:v[6]});let G=(H-B*r)*f;y.push(C.subarray(G,G+f))}}}if(p.length===0)return;let m=new Uint8Array(p.length*d.length);return y.forEach((l,b)=>{for(let I=0;I<d.length;I++)m[b*d.length+I]=(l[I>>1]??0)>>4*(I%2)&15}),{level:i,bin:h,haplotypes:d,bins:p,cells:m}}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 n=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return n?.[0]===e?Q(n[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let n=await this.indexedRowid(e,t);return n===void 0?void 0:this.indexedRow(n)}async indexedPositionsBetween(e,t,n){let[s,r]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,n)]),a=[];if(s!==void 0&&r!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",[[s,r+1]]);for(let i=s;i<=r;i++)a.push(await this.indexedRow(i))}return a}};function wt(o){let e=/\.gbz\.db$/i;return e.test(o)?o.replace(e,".haplotype-index.db"):void 0}function Ls(o){return hn(o)&&wt(on(o))?cn(o,e=>wt(e)):void 0}function Hs(o){return o instanceof Error&&(/\bHTTP 40[34]\b/.test(o.message)||o.code==="ENOENT")}async function Wn(o,e){let t=Ls(o);if(!t)return{};try{return await Ne(t,e).stat(),{location:t}}catch(n){return Hs(n)?{}:{unreadable:String(n)}}}var Os=5e3,Cs=50*2**20,Dt=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 Bs(o,e){if(o.length<=e)return o;let t=o.length/e;return Array.from({length:e},(n,s)=>o[Math.floor(s*t)])}var Zn=(o,e)=>o.path.some(t=>e.has(t.name)),mt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=_e({setup:async({signal:e})=>{let{size:t}=await this.file.stat();if(t>Cs)throw new Dt(t);let n=await this.file.readFile({signal:e}),s=new TextDecoder().decode(n[0]===31&&n[1]===139?await bn(n):n);return $t(s)}})}async readIndexed(e,t,n){let s=1/0,r=-1/0;for(let i of t){let h=Number(i);Number.isInteger(h)&&(s=Math.min(s,h),r=Math.max(r,h))}let a=[];return s<=r&&await e.getLines("{node}",s,r+1,{signal:n,lineCallback:i=>{let h=Nt(i);h&&Zn(h,t)&&a.push(h)}}),a}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(s=>Zn(s,e));return{records:Bs(n,Os),total:n.length}}};var yt=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"}},jt=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Xn(o,e){let t=pe(e);return o[t]??o[e.sample]??t}function Fs(o,e){return`${pe(o)}#${o.contig}@${e.start.node}.${e.start.offset}`}function _s({alignment:o,assemblyName:e,refName:t,lane:n}){let{refStart:s,refEnd:r,strand:a,cigar:i}=o;if(!(!o.resolved||r<=s)){let{name:h,hapStart:c,hapEnd:d}=o,f=Fs(h,o),p={uniqueId:f,assemblyName:e,refName:t,start:s,end:r,type:"match",strand:a==="-"?-1:1,CIGAR:i,syntenyId:f,mate:{refName:h.contig,start:c,end:d,assemblyName:n}};return new Mt(p)}}function Ts({pair:o,lane:e,mateLane:t}){let n=`${pe(o.target)}#${o.target.contig}:${o.targetStart}-${o.targetEnd}|${pe(o.query)}#${o.query.contig}:${o.queryStart}-${o.queryEnd}`;return new Mt({uniqueId:n,assemblyName:e,refName:o.target.contig,start:o.targetStart,end:o.targetEnd,type:"match",strand:o.strand==="-"?-1:1,CIGAR:o.cigar,syntenyId:n,identity:o.matches/Math.max(o.columns,1),numMatches:o.matches,blockLen:o.columns,mate:{refName:o.query.contig,start:o.queryStart,end:o.queryEnd,assemblyName:t}})}var zs=12e4;function qs(o,e){let t=new Map;for(let s of o)for(let{name:r,start:a,end:i}of s.walkSpans()){let h=pe(r);if(e.has(h)){let c=`${h}#${r.contig}`;t.set(c,[...t.get(c)??[],[a,i]])}}let n=0;for(let s of t.values()){s.sort((r,a)=>r[0]-a[0]);for(let r=1;r<s.length;r++){let a=s[r][0]-s[r-1][1];a>0&&a<=zs&&(n=Math.max(n,a))}}return n}function Gt(o,e){return o instanceof an&&(o.message=`Zoom in to about ${rn(o.fitsBp)} to see ${e}`),o}var Ut=o=>!("uri"in o)||o.uri!=="",Qt=class extends Sn{constructor(){super(...arguments);this.graph=_e({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),s=Ut(n)?{location:n}:await Wn(t,this.pluginManager),r=s.location,a=await Qe.open({source:Ne(t,this.pluginManager),haplotypeIndex:r?Ne(r,this.pluginManager):void 0}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let h=await Pt(a),c=Xe({configured:this.getConf("referenceSample"),anchorPrefix:ve(this,i),referenceSamples:h});return{db:a,anchor:i,referenceSample:c,referenceSamples:h,unreadableIndex:s.unreadable}}});this.gaf=_e({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return Ut(t)?new mt(Ne(t,this.pluginManager),Ut(n)?xn(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:s,referenceSample:r}=await this.graph(n);return vt(s,r,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:s}=await this.graph(t),r=new Map;for(let a of await n.paths()){let i=pe(a.name),h=r.get(i);h?h.contigs.includes(a.name.contig)||h.contigs.push(a.name.contig):r.set(i,{prefix:i,sample:a.name.sample,haplotype:a.name.haplotype,contigs:[a.name.contig],isReference:s.includes(a.name.sample)})}return[...r.values()]}async getHeader(t={}){let{anchor:n,referenceSample:s,referenceSamples:r}=await this.graph(t),a=Et(this),i=[];for(let h of await this.getHaplotypes(t))h.sample!==s&&i.push({name:Xn(a,h),label:h.prefix,group:h.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,referenceSample:s,referenceSamples:r,lanes:i}}async getRefNames(t={}){let{db:n,anchor:s,referenceSample:r}=await this.graph(t),{assemblyName:a}=t,i=a===s?void 0:ve(this,a),h=(await n.paths()).filter(c=>a===s?c.isIndexed&&c.name.sample===r:Ze(pe(c.name),i)).map(c=>c.name.contig);return[...new Set(h)]}keepPredicate(t,n){let s=t===void 0||t.length===0?void 0:t.map(r=>ve(this,r));return s===void 0&&n===void 0?void 0:r=>kt(r,s)&&(n===void 0||Ze(pe(r),n))}async getSubgraph(t,n={}){let{signal:s}=n,{db:r,anchor:a,referenceSample:i,unreadableIndex:h}=await this.graph({signal:s}),{assemblyName:c,refName:d,start:f,end:p}=t;if(c!==a)throw new jt(c,a);let y=await this.referenceQuery(d,{signal:s});if(!y)throw new Error(`${i} has no indexed path ${d} in this graph`);let m=this.keepPredicate(n.haplotypes);if(m!==void 0&&!r.hasHaplotypeIndex)throw new yt(h);return At(r,y,f,p,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:m}).catch(l=>{throw Gt(l,"the graph")})}async getReads(t,n={}){let s=await this.gaf(n);return s?s.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let s=ve(this,t);return(await this.getHaplotypes(n)).filter(r=>Ze(r.prefix,s))}async anchorFeatures(t,n){let{db:s}=await this.graph(n),{assemblyName:r,refName:a,start:i,end:h}=t,c=ve(this,n.targetAssemblyName),d=Et(this),f=this.keepPredicate(n.haplotypes,c),p=await this.referenceQuery(a,n),y=this.getConf("nodeLimit");return(p?await It(`Reading graph ${a}:${i.toLocaleString()}-${h.toLocaleString()}`,n.statusCallback,()=>s.getAlignments({path:p,start:i,end:h,context:this.getConf("context"),haplotypes:"all",limit:y,signal:n.signal,keep:f}).catch(l=>{throw Gt(Rt(l,y,h-i)??l,"lanes")})):[]).flatMap(l=>{let b=l.resolved?_s({alignment:l,assemblyName:r,refName:a,lane:Xn(d,l.name)}):void 0;return b===void 0?[]:[b]})}async pairFeatures(t,n,s){let{db:r}=await this.graph(s),{refName:a,start:i,end:h}=t,d=(await Promise.all(n.map(async x=>({pair:x,featureSide:await this.laneHaplotypes(x.queryAssemblyName,s),mateSide:await this.laneHaplotypes(x.targetAssemblyName,s)})))).filter(({featureSide:x,mateSide:E})=>x.length>0&&E.length>0),f=new Set(d.flatMap(({featureSide:x,mateSide:E})=>[...x,...E].map(pe))),p=await this.referenceQuery(a,s),y=this.getConf("nodeLimit"),m=this.getConf("context"),[l]=n,b=(x,E)=>r.getSubgraphs({path:x,start:i,end:h,context:E,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:y,signal:s.signal,keep:g=>f.has(pe(g))}),I=async x=>{let E=await b(x,m).catch(P=>{throw Gt(Rt(P,y,h-i)??P,"lanes")}),g=qs(E,f),S=Math.ceil(g/2)+2e3;return g>0&&S>m?b(x,S).catch(P=>{if(P instanceof oe)return E;throw P}):E};return(p&&l&&d.length>0?await It(n.length===1?`Reading ${l.queryAssemblyName} against ${l.targetAssemblyName}`:`Reading ${n.length} lane pairs`,s.statusCallback,()=>I(p)):[]).flatMap(x=>d.flatMap(({pair:E,featureSide:g,mateSide:S})=>g.flatMap(P=>S.flatMap(_=>x.pairAlignments({target:P,query:_,bases:!1}).map(B=>Ts({pair:B,lane:E.queryAssemblyName,mateLane:E.targetAssemblyName}))))))}getFeatures(t,n={}){return yn(async s=>{let{db:r,anchor:a,unreadableIndex:i}=await this.graph(n);if(!r.hasHaplotypeIndex)throw new yt(i);if(t.assemblyName===a){let h=In(n),c=h.length>0?await this.pairFeatures(t,h,n):await this.anchorFeatures(t,n);for(let d of c)s.next(d)}s.complete()},n.signal)}};export{jt as HaplotypeWindowError,yt as NoHaplotypeIndexError,ts as NoReferenceSampleError,ns as PairTargetError,Qt as default,_s as fragmentFeature,Xn as laneAssemblyName,Ts as pairFeature,Xe as resolveReferenceSample,qs as widestWalkGap};
|
|
6
|
-
//# sourceMappingURL=GbzBaseSyntenyAdapter-
|
|
6
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-UZGHQM5I.js.map
|