jbrowse-plugin-graphgenomeviewer 3.0.3 → 3.0.5

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/README.md CHANGED
@@ -145,7 +145,7 @@ Load the plugin from any JBrowse config, 5.0.0-beta.9 or later, with an
145
145
  "plugins": [
146
146
  {
147
147
  "name": "GraphGenomeView",
148
- "esmUrl": "https://your-host/jbrowse-plugin-graphgenomeviewer.esm.js"
148
+ "esmUrl": "https://unpkg.com/jbrowse-plugin-graphgenomeviewer/dist/jbrowse-plugin-graphgenomeviewer.esm.js"
149
149
  }
150
150
  ]
151
151
  }
@@ -0,0 +1,8 @@
1
+ import"./chunk-LGKM2PZH.js";import{a as oo}from"./chunk-D7XFR2IV.js";import{a as gr,b as no}from"./chunk-TN6FK5UD.js";import{a as ro}from"./chunk-KWAXLUPQ.js";import{a as Ie}from"./chunk-J4OLMLS5.js";import{a as wr,d as Fe,e as Ae,f as Tt}from"./chunk-F4C3BEPV.js";import{a as to,b as Y}from"./chunk-FY3BTKY4.js";var jn=to((Pc,zn)=>{zn.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function V(n,e){return 2*n+(e==="reverse"?1:0)}function A(n){return Math.floor(n/2)}function de(n){return n%2===0?"forward":"reverse"}function T(n){return n%2===1}function G(n){return n%2===0?n+1:n-1}function yr(n){return n==="left"?"right":"left"}function He(n){return n==="forward"?"left":"right"}function qe(n){return n==="forward"?"right":"left"}function xr(n){return n==="left"?"forward":"reverse"}function br(n){return n==="right"?"forward":"reverse"}function ue(n,e){let t=A(n),r=A(e);return T(n)?r>t||r===t&&!T(e):r>=t}function Sr(n){return $e(n[0],n[n.length-1])}function $e(n,e){return n===void 0||e===void 0?!0:T(n)===T(e)?!T(n):ue(n,e)}var Ee=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},vr=255,io=256,Be=class{source;sigma;threshold;constructor(e,t){this.source=new Ee(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<vr?Math.floor(io/this.sigma):0}next(){if(this.sigma>=vr){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let o=this.source.int();if(o===void 0)return;r+=o}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Ir(n){let e=new Ee(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var Ge=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Be(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:G(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];A(s.node)===A(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),c=e[i.value];for(let f=0;f<i.len;f++)r[s]=a.node,o[s]=c,c+=1,s+=1;e[i.value]=c}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var ao=["","A","C","G","T","N"];function Ar(n){let e=n[n.length-1];if(e===void 0)return 0;let t=e,r=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),r+=1;return 3*(n.length-1)+r}function Er(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=ao[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var fo={A:"T",C:"G",G:"C",T:"A",N:"N"};function De(n){let e="";for(let t=n.length-1;t>=0;t--)e+=fo[n[t]]??"N";return e}function Cr(n,e){let t=new Map;if(n!==void 0)for(let r of n.split(";")){let o=r.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function Pr(n){return{name:n.get("pggname"),subgraph:Cr(n.get("subgraph"),"subgraph"),translation:Cr(n.get("translation"),"translation")}}function Rr(n,e){for(let[t,r]of e){let o=n.get(t);o||(o=new Set,n.set(t,o));for(let s of r)o.add(s)}}function kr(n,e){let t={name:n,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(n,new Set([e.name])),Rr(t.subgraph,e.subgraph),Rr(t.translation,e.translation)),t}function _r(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function Mr(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of _r(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of _r(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function Or(n){let e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;let o=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(o)].map(s=>s.toString(16).padStart(2,"0")).join("")}var co="_gbwt_ref";function q(n,e){return`${n.sample}#${n.haplotype}#${n.contig}[${n.fragment}-${e}]`}var lo=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,po=/^([^#]+?)(?:\[\d+-\d+\])?$/;function ho(n){let e=lo.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=po.exec(n);if(t)return{contig:t[1]};throw new Error(`"${n}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Tr(n){return typeof n=="string"?ho(n):n}function Ce(n,e){return{sample:n.sample??co,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}function ze(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var je=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},Lt=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=ze(a,o)-ze(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let c=e;c!==t;c+=r){let f=this.occurrences.get(this.a[c]);if(!f)continue;let l=this.weight(this.a[c]),p=ze(f,o),d=ze(f,s);for(let h=0;h<d-p;h++){let u=r===1?f[d-1-h]-o:s-1-f[p+h],m=i.bestBefore(u),w=(m===-1?0:i.ending[m])+l;if(w>i.ending[u]&&(i.raise(u,w),a)){let x=a.count++;a.row[x]=c,a.column[x]=u,a.previous[x]=m===-1?-1:a.endingMatch[m],a.endingMatch[u]=x}}}}chain(e,t,r,o,s){let i=new je(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let c=i.bestBefore(o-r);if(c===-1)return;this.total+=i.ending[c];let f=[];for(let l=a.endingMatch[c];l!==-1;l=a.previous[l])f.push([a.row[l],r+a.column[l]]);for(let l=f.length-1;l>=0;l--)this.pairs.push(f[l])}frontier(e,t,r,o,s){let i=new je(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let c=0;c<s-o;c++)a[c+1]=Math.max(a[c],i.ending[c]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),c=this.frontier(r-1,t-1,-1,o,s),f=0,l=-1;for(let p=0;p<=i;p++){let d=a[p]+c[i-p];d>l&&(l=d,f=p)}return o+f}};function Lr(n,e,t){let r=new Lt(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var uo=100,Ht=4e6,mo=5e3,D=15,go=64,wo=8,Gr=1,qt=-4,B=-6,ee=-1,me=-(2**30),We=0,Nt=1,Dr=2;function te(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function Ue(n,e,t){return n>=t&&n>=e?We:t>=e?Dr:Nt}function zr(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(me),c=new Int32Array(s).fill(me),f=new Int32Array(s).fill(me);a[0]=0;for(let u=1;u<=o;u++)f[u]=B+(u-1)*ee,i[u]=(u===1?We:Dr)<<4;for(let u=1;u<=r;u++){let m=new Int32Array(s).fill(me),w=new Int32Array(s).fill(me),x=new Int32Array(s).fill(me);w[0]=B+(u-1)*ee,i[u*s]=(u===1?We:Nt)<<2;let b=n.charCodeAt(u-1);for(let g=1;g<=o;g++){let S=Ue(a[g-1],c[g-1],f[g-1]);m[g]=Math.max(a[g-1],c[g-1],f[g-1])+(b===e.charCodeAt(g-1)?Gr:qt);let y=Ue(a[g]+B,c[g]+ee,f[g]+B);w[g]=Math.max(a[g]+B,c[g]+ee,f[g]+B);let v=Ue(m[g-1]+B,w[g-1]+B,x[g-1]+ee);x[g]=Math.max(m[g-1]+B,w[g-1]+B,x[g-1]+ee),i[u*s+g]=S|y<<2|v<<4}a=m,c=w,f=x}let l=[],p=r,d=o,h=Ue(a[o],c[o],f[o]);for(;p>0||d>0;){let u=i[p*s+d]>>2*h&3;h===We?(l.push(n[p-1]===e[d-1]?"=":"X"),p-=1,d-=1):h===Nt?(l.push("I"),p-=1):(l.push("D"),d-=1),h=u}for(let u of l.reverse())te(t,u,1)}function yo(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-B-(t-1)*ee,-B+10*Math.log2(t)))+(Math.min(n,e)>0?-qt:0)}function jr(n,e){let t=Math.abs(n-e);return t===0?0:.01*D*t+.5*Math.log2(t)}function Nr(n,e,t){return{qs:n.qs+e,qe:n.qs+t,ts:n.flipped?n.te-t:n.ts+e,te:n.flipped?n.te-e:n.ts+t,flipped:n.flipped}}function xo(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,c]of e){let f=Math.max(0,a-n.qs),l=Math.min(r,c-n.qs);f<l&&o.push([f,l])}for(let[a,c]of t){let f=Math.max(0,n.flipped?n.te-c:a-n.ts),l=Math.min(r,n.flipped?n.te-a:c-n.ts);f<l&&o.push([f,l])}if(o.length===0)return[n];o.sort((a,c)=>a[0]-c[0]);let s=[],i=0;for(let[a,c]of o)a-i>=D&&s.push(Nr(n,i,a)),i=Math.max(i,c);return r-i>=D&&s.push(Nr(n,i,r)),s}function $t(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},c=[...n].sort((f,l)=>f.qs-l.qs||f.ts-l.ts);for(;c.length>0&&s.length<o;){let f=c.map(g=>g.qe-g.qs),l=new Int32Array(c.length).fill(-1),p=new Int32Array(c.length);for(let g=0;g<c.length;g++){let S=c[g],y=S.qe-S.qs;for(let v=g-1;v>=Math.max(0,g-mo);v--){if(f[v]+y<=f[g])continue;let I=c[v];if(I.flipped===S.flipped&&I.qs<S.qs&&(S.flipped?S.te<I.te:I.ts<S.ts)){let C=Math.max(0,I.qe-S.qs,S.flipped?S.te-I.ts:I.te-S.ts),_=S.qs+C-I.qe,E=S.flipped?I.ts-(S.te-C):S.ts+C-I.te;if(C<y&&_<=e&&E<=e){let k=f[v]+y-C-r(_,E);k>f[g]&&(f[g]=k,l[g]=v,p[g]=C)}}}}let d=0;for(let g=1;g<c.length;g++)f[g]>f[d]&&(d=g);let h=[];for(let g=d;g>=0;g=l[g])h.push({run:c[g],trim:p[g]});if(h.reverse(),h.reduce((g,{run:S,trim:y})=>g+S.qe-S.qs-y,0)<t)break;s.push(h);let m=h[0],w=h.at(-1),{flipped:x}=m.run,b=x?a.flipped:a.forward;b.query.push([m.run.qs+m.trim,w.run.qe]),b.target.push(x?[w.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,w.run.te]);for(let{run:g,trim:S}of h)i.query.push([g.qs+S,g.qe]),i.target.push(g.flipped?[g.ts,g.te-S]:[g.ts+S,g.te]);c=c.flatMap(g=>{let S=g.flipped?a.flipped:a.forward;return xo(g,[...i.query,...S.query],[...i.target,...S.target])}).sort((g,S)=>g.qs-S.qs||g.ts-S.ts)}return s}function Ft(n,e){let t=new Map;for(let s=0;s+D<=e.length;s++){let i=e.slice(s,s+D),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+D<=n.length;s++){let i=t.get(n.slice(s,s+D));if(i&&i.length<=go)for(let a of i){let c=a-s,f=o.get(c);if(f&&s<=f.qe)f.qe=s+D,f.te=a+D;else{let l={qs:s,qe:s+D,ts:a,te:a+D,flipped:!1};o.set(c,l),r.push(l)}}}return r}function bo(n,e){return[...Ft(n,e),...Ft(n,De(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Qe(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let c=i.qs+a;if(s){let f=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,p=t.slice(f,l);o(e.slice(s.qe,c),i.flipped?De(p):p,r,s.qe,f)}te(r,"=",i.qe-c),s=i}}function Ur(n,e,t){n.length*e.length<=Ht?zr(n,e,t):(te(t,"I",n.length),te(t,"D",e.length))}function Bt(n,e,t,r=0){let[o]=n.length*e.length>Ht&&r<wo?$t(Ft(n,e),1/0,D,jr,1):[];if(!o){Ur(n,e,t);return}let s=(c,f,l)=>{Bt(c,f,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),Qe(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function So(n,e,t){Bt(n,e,t)}function vo(n,e,t){let r=[];Qe(n,e,t,r,So);let o=n[0],s=n.at(-1),{flipped:i}=o.run;return{queryStart:o.run.qs+o.trim,queryEnd:s.run.qe,targetStart:i?s.run.ts:o.run.ts+o.trim,targetEnd:i?o.run.te-o.trim:s.run.te,strand:i?"-":"+",edits:i?r.reverse():r,sharedBases:0}}function Io(n,e,t,r){let o=[];if(n.length*e.length<=Ht)zr(n,e,t);else{let s=$t(bo(n,e),1/0,Math.max(r,D),jr),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>vo(a,n,e)),i){let a=(l,p,d,h,u)=>{o.some(w=>h<w.queryEnd&&w.queryStart<h+l.length||u<w.targetEnd&&w.targetStart<u+p.length)?Ur(l,p,d):Bt(l,p,d)},c=i[0].run,f=i.at(-1).run;a(n.slice(0,c.qs),e.slice(0,c.ts),t,0,0),Qe(i,n,e,t,a),a(n.slice(f.qe),e.slice(f.te),t,f.qe,f.te)}else te(t,"I",n.length),te(t,"D",e.length)}return o}function Gt(n,e){let t=n.strand==="-",r=0,o=0;for(let[s,i]of n.edits)e(s,i,t?n.queryEnd-1-r:n.queryStart+r,n.targetStart+o),s!=="D"&&(r+=i),s!=="I"&&(o+=i)}function Fr(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return Gt(n,(i,a,c,f)=>{let l=e==="query"?c:f,p=d=>{let h=l+o*d;return h>=t&&h<r};if(i==="="||i==="X")for(let d=0;d<a;d++)p(d)&&(s+=i==="="?Gr:qt);else if(i==="I"==(e==="query"))for(let d=0;d<a;d++)p(d)&&(s+=d===0?B:ee);else p(0)&&(s+=B+(a-1)*ee)}),s}function Hr(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function Ao(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,c=new Uint8Array(n.queryEnd-n.queryStart);for(let[h,u]of n.shared)c.fill(1,h-n.queryStart,u-n.queryStart);let f=h=>c[h-n.queryStart]===1,l=()=>{te(r,"I",o),te(r,"D",s),o=0,s=0};Gt(n,(h,u,m)=>{if(h==="I")o+=u;else if(h==="D")s+=u;else{for(let w=0;w<u;w++)e[i+w]?(o+=1,s+=1,f(t?m-w:m+w)&&(a+=1)):((o>0||s>0)&&l(),te(r,h,1));i+=u}}),l();let p={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[h,u]=r.shift();p[h]+=u}let d={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[h,u]=r.pop();d[h]+=u}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?d.I:p.I),queryEnd:n.queryEnd-(t?p.I:d.I),targetStart:n.targetStart+p.D,targetEnd:n.targetEnd-d.D,edits:r,sharedBases:n.sharedBases-a}}function Eo(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(f=>{let l=[];Gt(f,(p,d,h,u)=>{if(p==="="||p==="X")for(let m=0;m<d;m++)l.push([f.strand==="-"?h-m:h+m,u+m])});for(let[p,d]of l)o.query[p]=Math.min(255,o.query[p]+1),o.target[d]=Math.min(255,o.target[d]+1);return l}),i={query:new Map,target:new Map};s.forEach((f,l)=>{for(let[p,d]of f)for(let[h,u]of[["query",p],["target",d]])if(o[h][u]>1){let m=i[h].get(u);m?m.at(-1)!==l&&m.push(l):i[h].set(u,[l])}});let a=new Map,c=(f,l,p)=>{let d=`${p}:${f}:${l}`,h=a.get(d);if(h===void 0){let[u,m]=Hr(n[f],p),[w,x]=Hr(n[l],p),b=Math.max(u,w),g=Math.min(m,x);h=Fr(n[f],p,b,g)<Fr(n[l],p,b,g),a.set(d,h)}return h};return n.flatMap((f,l)=>{let p=s[l],d=new Uint8Array(p.length);if(p.forEach(([m,w],x)=>{for(let[b,g]of[["query",m],["target",w]])!d[x]&&i[b].get(g)?.some(S=>S!==l&&c(l,S,b))&&(d[x]=1)}),!d.includes(1))return[f];let h=Ao(f,d),u=h?.edits.reduce((m,[w,x])=>m+(w==="="?x:0),0)??0;return h&&u>=r?[h]:[]})}function qr(n,e){return n.map(t=>{let r=e(A(t));return T(t)?De(r):r}).join("")}function $r(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(A(r)).length);return t}function Br(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let c=A(i);e.has(c)?t.set(c,a):e.set(c,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function Co(n,e,t,r){let o=Br(n),s=Br(e),i=new Map;e.forEach((p,d)=>{s[d]||i.set(A(p),[d])});let a=2*e.length,c=(p,d,h)=>p*a+2*d+(h?1:0),f=new Set;n.forEach((p,d)=>{for(let h of o[d]?[]:i.get(A(p))??[])f.add(c(d,h,T(p)!==T(e[h])))});let l=[];return n.forEach((p,d)=>{for(let h of o[d]?[]:i.get(A(p))??[]){let u=T(p)!==T(e[h]),m=u?-1:1;if(!f.has(c(d-1,h-m,u))){let w=d,x=h;for(;w<n.length&&x>=0&&x<e.length&&f.has(c(w,x,u));)w+=1,x+=m;let b=x-m;l.push({qs:t[d],qe:t[w],ts:r[Math.min(h,b)],te:r[Math.max(h,b)+1],flipped:u})}}}),l}function Wr(n,e,t,r={}){let o=qr(n,t),s=qr(e,t),i=Co(n,e,$r(n,t),$r(e,t)),a=r.minMatch??uo,c=[];for(let f of $t(i,r.maxGap??1/0,a,yo)){let l=[],p=f[0],d=f.at(-1),{flipped:h}=p.run;Qe(f,o,s,l,(u,m,w,x,b)=>{for(let g of Io(u,m,w,a)){let S=b+m.length;c.push({...g,queryStart:x+g.queryStart,queryEnd:x+g.queryEnd,targetStart:h?S-g.targetEnd:b+g.targetStart,targetEnd:h?S-g.targetStart:b+g.targetEnd,strand:h?"+":"-",edits:h?g.edits.reverse():g.edits,shared:[]})}}),c.push({queryStart:p.run.qs+p.trim,queryEnd:d.run.qe,targetStart:h?d.run.ts:p.run.ts+p.trim,targetEnd:h?p.run.te-p.trim:d.run.te,strand:h?"-":"+",edits:h?l.reverse():l,sharedBases:f.reduce((u,{run:m,trim:w})=>u+m.qe-m.qs-w,0),shared:f.map(({run:u,trim:m})=>[u.qs+m,u.qe])})}return Eo(c,o.length,s.length,a).map(({shared:f,...l})=>l).sort((f,l)=>f.queryStart-l.queryStart)}function Qr(n){return n.map(([e,t])=>`${t}${e}`).join("")}var X=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 Dt(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var Re=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Dt(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Dt(e[s],e[a])&&(a=s),i<e.length&&Dt(e[i],e[a])&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}}return t}get size(){return this.heap.length}};function Ro(n){let e=new Int32Array(n.length),t=new Int32Array(n.length);return n.forEach(([r,o],s)=>{e[s]=r,t[s]=o}),{pathAt:e,refAt:t,count:n.length}}function _o(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function ie(n){return`${n.node}:${n.offset}`}function Po(n,e){let t=e.identity.hapStart-n.identity.hapEnd,r=n.strand==="+"?e.refStart-n.refEnd:n.refStart-e.refEnd;return n.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function ko(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([f,l])=>[f,l]);Vr(s,t.insertion,t.deletion);for(let[f,l]of o.edits)z(s,f,l);let i=n.identity.walkForward,[a,c]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...c.path],start:a.start,identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function Mo(n){if(n.some(o=>o.weight!==void 0))return n;let e=new Map;n.forEach((o,s)=>{if(o.identity){let i=e.get(o.identity.pathHandle);i?i.push(s):e.set(o.identity.pathHandle,[s])}});let t=new Map,r=new Set;for(let o of e.values()){o.sort((a,c)=>n[a].identity.hapStart-n[c].identity.hapStart);let s=o[0],i=n[s];for(let a of o.slice(1)){let c=n[a],f=Po(i,c);f?(i=ko(i,c,f),r.add(a)):(t.set(s,i),s=a,i=c)}t.set(s,i)}return n.flatMap((o,s)=>r.has(s)?[]:[t.get(s)??o])}function Ye(n,e){return{node:n.path[e],offset:n.offsets[e]}}var Oo=4096;function Yr(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=Oo?r[1]=t:e.push([t,t])}return e}var To=32768,Lo=65536;function No(n){let e=[...n].sort((r,o)=>r-o),t=[];for(let r of e){let o=t[t.length-1];o&&r-o[1]<=To?o[1]=r:t.push([r,r])}return t}var _e=class{records=new Map;paths=[];twinStarts=new Set;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;stats={orderedAlignments:0,lcsAlignments:0,identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},anchorWalk:void 0};db;limit;signal;constructor(e,t={}){this.db=e,this.limit=t.limit,this.signal=t.signal}get nodeCount(){return this.records.size/2}get pathCount(){return this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(V(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 X(this.limit);let t=await this.db.getRecord(V(e,"forward")),r=await this.db.getRecord(V(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering ${q(e,e.fragment)}`);if(!t.isIndexed)throw new Error(`Path ${q(t.name,t.name.fragment)} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`Path ${q(t.name,t.name.fragment)} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(A(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let c=a.gbwt().lf(i.offset);if(!c)throw new Error(`Path ${q(e.name,e.name.fragment)} does not contain offset ${t}`);i=c}}async aroundPosition(e,t,r){let o=A(e);await this.ensureNode(o);let s=this.record(e),i=de(e),a=new Re;return a.push(t,o,He(i)),a.push(s.sequenceLen-t-1,o,qe(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords(Math.min(i,a),Math.max(i,a)+1)){let f=await this.db.indexedPositionsBetween(e,t,r),l=No(f.map(p=>p.pos.node));await Promise.all(l.map(([p,d])=>this.db.prefetchRecords(p,d+2)))}}return o}async aroundInterval(e,t,r){if(t===0)throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof X&&o.windowBp===void 0?new X(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new Re;for(;;){let c=A(o.node),f=de(o.node);this.walkedBp=t-i,await this.ensureNode(c);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${c} of length ${l.sequenceLen}`);a.push(s,c,He(f));let p=l.sequenceLen-s;if(i<=p){a.push(i===p?0:p-i-1,c,qe(f));break}a.push(0,c,qe(f));let d=l.gbwt().lf(o.offset);if(!d)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=d,s=0,i-=p}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new Re;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths();let r=new Set,o=new Set;for(let i of this.records.keys())o.add(A(i));let s=0;for(;e.size>0;){let[i,a,c]=e.pop(),f=`${a}:${c}`;if(r.has(f))continue;r.add(f),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=yr(c);if(!r.has(`${a}:${l}`)){let h=this.record(V(a,xr(c))),u=i+h.sequenceLen-1;u<=t&&e.push(u,a,l)}let p=this.record(V(a,br(c))),d=i+1;if(d<=t)for(let h of p.successors()){let u=A(h),m=He(de(h));r.has(`${u}:${m}`)||e.push(d,u,m)}}for(let i of o)this.records.delete(V(i,"forward")),this.records.delete(V(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){this.clearPaths();let r=[e,G(t)],o=new Set([A(e),A(t)]),s=0;for(;r.length>0;){let i=r.pop(),a=A(i);this.hasNode(a)||(await this.addNode(a),s+=1);for(let c of this.record(i).successors()){let f=A(c);o.has(f)||(r.push(c,G(c)),o.add(f))}}return s}async extractSnarls(e){let t=0;for(let[r,o]of await this.overlappingSnarls(e))t+=await this.betweenNodes(r,o);return t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(o=>this.hasHandle(o));return r===void 0?!1:t.length>1||this.record(G(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async c=>{let f=c.successors(),l=f[0];return l===void 0?!1:f.length>1||(await e(G(l))).successors().length>1},r=async c=>{let f=await e(G(c));return f.next!==void 0?await t(f)?{kind:"snarl-exit",snarl:[G(c),f.next]}:{kind:"chain"}:(await e(c)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(c=>this.record(c).successors()),i,a=!1;for(;!a&&s.length>0;){let c=s.shift(),f=A(c);if(!this.hasHandle(c)&&!o.has(f)){o.add(f);let l=await r(c);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let p of["forward","reverse"])s.push(...(await e(V(f,p))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((y,v)=>i.set(y,v));let a=new Int32Array(s+1),c=new Int32Array(s),f=[];for(let y=0;y<s;y++){let v=this.record(o[y]),I=v.gbwt().decompressArrays();c[y]=v.sequenceLen,f.push(I),a[y+1]=a[y]+I.nodes.length}let l=a[s],p=new Int32Array(l),d=new Int32Array(l),h=new Uint8Array(l);for(let y=0;y<s;y++){let v=f[y];p.set(v.nodes,a[y]),d.set(v.offsets,a[y])}f.length=0;for(let y=0;y<l;y++){let v=i.get(p[y]);v===void 0?p[y]=-1:(p[y]=v,h[a[v]+d[y]]=1)}let u=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,w,x=(y,v,I)=>{let R=[],C=0,_=0,E=-1,k=y,O=v;for(;;){k===u&&O===m&&(E=C),I&&(I.push(o[k]),R.push(O)),C+=1,_+=c[k];let N=a[k]+O,F=p[N];if(F<0)break;O=d[N],k=F}return{offsets:R,len:_,refAt:E,last:k}},b=(y,v,I,R)=>{R>=0&&(this.refId=this.paths.length,w=R),this.paths.push({path:y,offsets:v,len:I,weight:void 0,identity:void 0})},g=new Int32Array(s),S=u!==void 0&&T(o[u]);for(let y=0;y<s;y++){let v=o[y];if(!T(v)){let I=a[y],R=a[y+1]-I;for(let C=0;C<R;C++)if(h[I+C]===0){let _=[],{offsets:E,len:k,refAt:O,last:N}=x(y,C,_),F=o[N];if(O>=0||$e(v,F)){if(b(_,E,k,O),!T(F)){let H=i.get(G(F));g[H]=g[H]+1}}else this.twinStarts.add(ie({node:v,offset:C}))}}}for(let y=0;y<s;y++){let v=o[y];if(T(v)){let I=a[y],R=a[y+1]-I,C=0;for(let E=0;E<R;E++)h[I+E]===0&&(C+=1);let _=!S&&C===g[y];for(let E=0;E<R;E++)if(h[I+E]===0){let k=_?void 0:x(y,E,void 0);if(k&&(k.refAt>=0||$e(v,o[k.last]))){let O=[],{offsets:N,len:F,refAt:H}=x(y,E,O);b(O,N,F,H)}else this.twinStarts.add(ie({node:v,offset:E}))}}}if(r){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],v=r.nodeOffset;for(let R of y.path.slice(0,w))v+=this.record(R).sequenceLen;let I=r.seqOffset-v;this.refInterval=[I,I+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:I,hapEnd:I+y.len}}if(t==="distinct")this.distinctPaths();else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(){let e=this.refId===void 0?void 0:this.paths[this.refId].path;this.paths.sort((o,s)=>zt(o.path,s.path)||o.len-s.len);let t=[],r;for(let o of this.paths){let s=t[t.length-1];s&&zt(s.path,o.path)===0?s.weight=(s.weight??0)+1:(e&&zt(o.path,e)===0&&(r=t.length),t.push({...o,weight:1}))}this.paths=t,this.refId=r}keepHaplotypes(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=this.paths.filter((s,i)=>i===this.refId||s.identity!==void 0&&e(s.identity.name)),o=new Set;for(let s of r)for(let i of s.path)o.add(A(i));for(let s of[...this.records.keys()])o.has(A(s))||this.records.delete(s);this.paths=r,this.refId=t===void 0?void 0:r.indexOf(t)}async walkHaplotypesFromAnchor(e,t,r,o,s){let i=e.position.seqOffset,a=i+t,c=Math.floor(i/r)*r,f=Math.min(r,Lo),l=4*(r+t)+f,p={spacing:r,anchorOffset:c,anchorNodeOffset:-1,anchorHandle:-1,referenceSteps:0,rows:0,walks:[],graphFetches:0,scans:[],scanRows:0,fallback:void 0,ms:{reference:0,rows:0,walks:0,scan:0,sampled:0}};this.stats.anchorWalk=p;let d=performance.now(),h=()=>{let M=performance.now(),U=M-d;return d=M,U};this.clearPaths(),this.records.clear();let u=this.recordReader(()=>{p.graphFetches+=1}),m=await this.db.haplotypeAnchor(e.handle,c);if(m===void 0)throw new Error(`The haplotype index names no anchor for ${q(e.name,e.name.fragment)} at offset ${c}; it was not built with anchors at ${r} bp for this graph`);p.anchorNodeOffset=m.pathOffset;let w=await this.prefetchReferenceRange(e.handle,m.pathOffset,a+f);if(!w)throw new Error(`Path ${q(e.name,e.name.fragment)} has not been indexed for random access`);let x=await this.walkReference(u,w,m,i,a,a+f),{anchor:b,refOffsetOf:g,refHandles:S,windowSteps:y}=x;p.anchorHandle=b.pos.node,p.referenceSteps=x.steps,this.walkedBp=t;let v=[],I=[],R=0;for(let M of y)await this.ensureNode(A(M.pos.node)),v.push(M.pos.node),I.push(M.pos.offset),R+=this.record(M.pos.node).sequenceLen;let C=y[0];if(C===void 0)throw new Error("The reference walk has no node in the window");this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[C.refOffset,C.refOffset+R],this.refId=0,this.paths.push({path:v,offsets:I,len:R,weight:void 0,identity:{pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:C.refOffset,hapEnd:C.refOffset+R}}),p.ms.reference=h();let _=await this.db.haplotypeSamplesAtNode(b.pos.node);p.rows=_.length,p.ms.rows=h();let E=_.find(M=>M.offset===b.pos.offset&&M.pathHandle===e.handle&&M.pathOffset===b.offset);if(E===void 0)throw new Error(`The haplotype index has no anchor row for ${q(e.name,e.name.fragment)} at offset ${b.offset} (node ${A(b.pos.node)}); it was not built with anchors at ${r} bp for this graph`);let k=await this.db.pathsByHandle(),O=M=>{let U=k.get(M);if(!U)throw new Error(`Path ${M} is missing from the database`);return U.name},N=new Set([e.handle]),F=new Map;for(let M of _)if(M!==E&&o(O(M.pathHandle))){let U=F.get(M.pathHandle);U?U.push(M):F.set(M.pathHandle,[M])}let H;for(let[M,U]of F)if(H===void 0){let pe=se=>Math.abs(se.offset-E.offset);U.sort((se,eo)=>pe(se)-pe(eo));let he;for(let se of U)N.has(M)||(he=await this.walkAndKeep(u,se,"anchor",O(M),g,a,l,s,N,p));N.has(M)||(H=he)}p.ms.walks=h();let ve=H===void 0?await this.samplesOfUnwalkedContigs(v,g,S,o,N,O,p):new Map;if(p.ms.scan=h(),ve.size>0){await this.mapReferenceBefore(u,e.handle,Math.max(0,m.pathOffset-2*r),m.pathOffset,g,S);for(let[M,U]of ve)if(H===void 0){let pe=O(M),he;for(let se of U)he??=await this.entryBefore(u,se,g,S,this.refInterval[0],l);H=he===void 0?`no sample of ${q(pe,pe.fragment)} on the window's nodes runs with the reference`:await this.walkAndKeep(u,he,"sample",pe,g,a,l,s,N,p)}p.ms.sampled=h()}return p.fallback=H,H}async walkAndKeep(e,t,r,o,s,i,a,c,f,l){let p=await this.walkFromRow(e,t,o,s,this.refInterval[0],i,a,c);l.walks.push({pathHandle:t.pathHandle,from:r,steps:p.steps,pieces:p.infos.length,end:p.end});let d;return p.end==="bound"||p.infos.length===0?d=`${q(o,t.pathOffset)} walked ${p.steps} steps from its ${r} without writing a walk through the window (${p.end})`:(f.add(t.pathHandle),this.paths.push(...p.infos)),d}async mapReferenceBefore(e,t,r,o,s,i){let a=await this.prefetchReferenceRange(t,r,o),c=a?.pos,f=a?.pathOffset??o;for(;c!==void 0&&c.node!==0&&f<o;){this.signal?.throwIfAborted();let l=await e(c.node),p=A(c.node);s.has(p)||(s.set(p,f),i.add(c.node)),f+=l.sequenceLen,c=l.gbwt().lf(c.offset)}}async runsWithReference(e,t,r,o,s){let i={node:t.node,offset:t.offset},a=0,c;for(;c===void 0;)if(this.signal?.throwIfAborted(),i===void 0||i.node===0||a>s)c=!1;else if(r.has(A(i.node)))c=o.has(i.node);else{let f=await e(i.node);a+=f.sequenceLen,i=f.gbwt().lf(i.offset)}return c}async entryBefore(e,t,r,o,s,i){let a=(await e(t.node)).sequenceLen,c=async(h,u)=>{let m=(await e(h.node)).sequenceLen;return{node:h.node,offset:h.offset,pathHandle:t.pathHandle,orientation:t.orientation,pathOffset:t.orientation==="forward"?t.pathOffset-u:t.pathOffset+a+u-m}},f={node:t.node,offset:t.offset},l=0,p,d=!await this.runsWithReference(e,t,r,o,i);for(;!d;){this.signal?.throwIfAborted();let h=r.get(A(f.node));if(h!==void 0&&h<s)p=await c(f,l),d=!0;else if(l>i)p={...t},d=!0;else{let m=(await e(G(f.node))).gbwt().predecessorAt(f.offset);if(m===void 0)p=await c(f,l),d=!0;else{let w=await e(m),x=w.gbwt().offsetTo(f);if(x===void 0)throw new Error(`No offset in ${m} leads to ${f.node}:${f.offset}`);f={node:m,offset:x},l+=w.sequenceLen}}}return p}async walkReference(e,t,r,o,s,i){let a=new Map,c=new Set,f=[],l,p=t.pos,d=t.pathOffset,h=0;for(;p!==void 0&&p.node!==0&&d<i;){this.signal?.throwIfAborted();let u=await e(p.node),m=d+u.sequenceLen;if(l===void 0&&d===r.pathOffset){if(p.node!==r.node)throw new Error(`The reference walk reaches node ${A(p.node)} at offset ${d} where the haplotype index names node ${A(r.node)} as the anchor`);l={pos:p,offset:d}}if(l!==void 0){h+=1;let w=A(p.node);a.has(w)||(a.set(w,d),c.add(p.node)),d<s&&m>o&&f.push({pos:p,refOffset:d})}d=m,p=u.gbwt().lf(p.offset)}if(l===void 0)throw new Error(`The reference walk from offset ${t.pathOffset} never starts a node at the anchor offset ${r.pathOffset}`);return{anchor:l,refOffsetOf:a,refHandles:c,windowSteps:f,steps:h}}async walkFromRow(e,t,r,o,s,i,a,c){let f=(await e(t.node)).sequenceLen,l=t.orientation==="forward"?t.pathOffset:t.pathOffset+f,p=[],d=[],h=[],u=0,m=0,w=0,x,b,g={node:t.node,offset:t.offset};for(;b===void 0;)if(this.signal?.throwIfAborted(),g===void 0||g.node===0)b=x===void 0?"before the window":"ended in the window";else if(m>a)b="bound";else{let y=o.get(A(g.node)),v=x!==void 0;if(y!==void 0&&y>=i)b=v?"through the window":"past the window";else{!v&&y!==void 0&&y>=s&&(x=m);let I=await e(g.node);if(x!==void 0){let R={pos:g,at:m,len:I.sequenceLen};y===void 0?(h.push(R),u+=R.len):(u>c&&y<s?(p.push(d),d=[]):d.push(...h),h=[],u=0,d.push(R))}w+=1,m+=I.sequenceLen,g=I.gbwt().lf(g.offset)}}p.push(d);let S=[];for(let y of p){let v=y[0],I=y[y.length-1];if(v!==void 0&&I!==void 0){let R=[],C=[],_=0;for(let O of y)await this.ensureNode(A(O.pos.node)),R.push(O.pos.node),C.push(O.pos.offset),_+=O.len;let E=v.at,k=I.at+I.len;S.push({path:R,offsets:C,len:_,weight:void 0,identity:t.orientation==="forward"?{pathHandle:t.pathHandle,name:r,orientation:"forward",hapStart:l+E,hapEnd:l+k}:{pathHandle:t.pathHandle,name:r,orientation:"reverse",hapStart:l-k,hapEnd:l-E}})}}return{steps:w,end:b,infos:S}}async samplesOfUnwalkedContigs(e,t,r,o,s,i,a){let c=Yr([...e].sort((l,p)=>l-p));a.scans=c;let f=new Map;for(let[l,p]of c){let d=await this.db.haplotypeSamplesInRange(l,p);a.scanRows+=d.length;for(let h of d){let u=t.has(A(h.node));if(!s.has(h.pathHandle)&&(!u||r.has(h.node))&&o(i(h.pathHandle))){let m=f.get(h.pathHandle)??[];u?m.unshift(h):m.push(h),f.set(h.pathHandle,m)}}}return f}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");let e=await this.db.haplotypeSampleInterval()??4096,t=Yr(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[u,m]of t)for(let w of await this.db.haplotypeSamplesInRange(u,m))r.set(ie(w),w);let o=u=>{let m=0,w=t.length-1;for(;m<w;){let b=m+w+1>>1;t[b][0]<=u?m=b:w=b-1}let x=t[m];return x[0]<=u&&u<=x[1]},s=new Map;this.paths.forEach((u,m)=>{u.path.length>0&&m!==this.refId&&s.set(ie(Ye(u,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((u,m)=>{m!==this.refId&&i.fragmentLengths.push(u.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=u=>(i.graphLookups+=1,a(u)),f=async(u,m)=>{if(o(u.node))return r.get(ie(u));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let w=await this.db.haplotypeSampleAt(u.node,u.offset);return w||(i.companionMisses+=1),w},l=new Map,p=async u=>{let m=l.get(u);if(!m){let w=await this.db.getPath(u);if(!w)throw new Error(`Path ${u} is missing from the database`);m=w.name,l.set(u,m)}return m},d=(u,m,w)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.pathOffset-m}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.pathOffset+m+w},h=(u,m)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.hapStart-m}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.hapEnd+m};for(let u=0;u<this.paths.length;u++){let m=this.paths[u];if(u===this.refId||m.identity)continue;let w=[],x=new Set,b={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(b);let g,S=0,y=u,v;for(;g===void 0;){if(this.signal?.throwIfAborted(),y!==void 0){if(x.has(y)){b.end="cycle";break}x.add(y);let E=this.paths[y];w.push({index:y,startBp:S}),b.fragments+=1;let k=S;for(let N=0;N<E.path.length;N++){let F=Ye(E,N),H=r.get(ie(F)),ve=this.record(F.node).sequenceLen;if(H){g=d(H,k,ve);break}k+=ve}if(S+=E.len,g){b.end="in-fragment sample";break}let O=Ye(E,E.path.length-1);v=this.record(O.node).gbwt().lf(O.offset),y=void 0}if(v===void 0||v.node===0){b.end="endmarker";break}let I=ie(v),R=s.get(I);if(R!==void 0){let E=this.paths[R].identity;if(E){g=h(E,S),b.end="identified sibling";break}y=R;continue}this.records.has(v.node)&&(b.reentries+=1),this.twinStarts.has(I)&&(b.twinLandings+=1);let C=await f(v,b),_=await c(v.node);if(C){g=d(C,S,_.sequenceLen),b.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,b.steps+=1,S-w[w.length-1].startBp>4*e+4*_.sequenceLen){b.end="bound";break}S+=_.sequenceLen,v=_.gbwt().lf(v.offset)}if(g){b.pathHandle=g.pathHandle;let I=await p(g.pathHandle);for(let{index:R,startBp:C}of w){let _=this.paths[R];_.identity=g.orientation==="forward"?{pathHandle:g.pathHandle,name:I,orientation:"forward",hapStart:g.base+C,hapEnd:g.base+C+_.len}:{pathHandle:g.pathHandle,name:I,orientation:"reverse",hapStart:g.base-C-_.len,hapEnd:g.base-C}}}}}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let c=0;c<e.length;c++){let f=r.get(e[c]);if(f){let l=_o(f,a);if(l===void 0)return;o[i]=c,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let c=this.record(e[o]).sequence,f=this.record(t[s]).sequence;for(;i<c.length&&a<f.length;){if(c[i]!==f[a])return r;i+=1,a+=1,r+=1}i===c.length&&(o+=1,i=0),a===f.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let c=this.record(e[e.length-o-1]).sequence,f=this.record(t[t.length-s-1]).sequence;for(;i<c.length&&a<f.length;){if(c[c.length-i-1]!==f[f.length-a-1])return r;i+=1,a+=1,r+=1}i===c.length&&(o+=1,i=0),a===f.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),z(r,"M",i),Vr(r,o-i-a,s-i-a),z(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??Ro(Lr(e,t,p=>this.record(p).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(p,d,h,u)=>{p===d?z(s,"D",i[u]-i[h]):h===u?z(s,"I",this.pathLen(e.slice(p,d))):this.align(e.slice(p,d),t.slice(h,u),s)},c=0,f=0,l=0;for(let p=0;p<o.count;p++){let d=o.pathAt[p],h=o.refAt[p];(f!==d||l!==h)&&a(f,d,l,h);let u=this.record(e[d]).sequenceLen;z(s,"M",u),c+=u,f=d+1,l=h+1}return a(f,e.length,l,t.length),{edits:s,matched:c}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(Sr(r))o={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else{let s=t.path.map(c=>G(c)).reverse(),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else if(i===0)o={edits:this.editsAgainst(s,r).edits,flipped:!0};else{let c=this.editsAgainst(t.path,r),f=this.editsAgainst(s,r);o=f.matched>c.matched?{edits:f.edits,flipped:!0}:{edits:c.edits,flipped:!1}}}return o}alignToRef(e){return this.alignment(e)?.edits.map(([t,r])=>`${r}${t}`).join("")}alignments(){let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,r=this.refPrefix(t)[t.length],o=[];return this.paths.forEach((s,i)=>{if(i===this.refId)return;let{edits:a,flipped:c}=this.alignment(i),f=0,l=0;for(;f<a.length&&a[f][0]==="D";)l+=a[f][1],f+=1;let p=a.length,d=0;for(;p>f&&a[p-1][0]==="D";)d+=a[p-1][1],p-=1;let h=s.identity,u=h?h.orientation==="forward"!==c:!c;o.push({strand:u?"+":"-",refStart:e.start+l,refEnd:e.start+r-d,edits:a.slice(f,p),weight:s.weight,path:s.path,start:Ye(s,0),identity:h===void 0?void 0:{pathHandle:h.pathHandle,name:h.name,hapStart:h.name.fragment+h.hapStart,hapEnd:h.name.fragment+h.hapEnd,walkForward:h.orientation==="forward"}})}),Mo(o).map(s=>{let{edits:i,identity:a,...c}=s,f={...c,cigar:Ho(i)};return a?{...f,resolved:!0,name:a.name,label:q({...a.name,fragment:a.hapStart},a.hapEnd),pathHandle:a.pathHandle,hapStart:a.hapStart,hapEnd:a.hapEnd}:{...f,resolved:!1}})}pairAlignments(e){let{target:t,query:r,maxGap:o}=e,s=this.paths.flatMap(l=>{let{identity:p}=l;return p?[{name:p.name,start:p.name.fragment+p.hapStart,steps:Ke(l,p)}]:[]}),i=l=>p=>p.sample===l.sample&&p.haplotype===l.haplotype,a=i(t),c=r?i(r):l=>!a(l),f=l=>this.record(V(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(p=>c(p.name)).flatMap(p=>Wr(p.steps,l.steps,f,o===void 0?{}:{maxGap:o}).map(d=>({query:p.name,queryStart:p.start+d.queryStart,queryEnd:p.start+d.queryEnd,strand:d.strand,target:l.name,targetStart:l.start+d.targetStart,targetEnd:l.start+d.targetEnd,cigar:Qr(d.edits),matches:d.edits.reduce((h,[u,m])=>h+(u==="="?m:0),0),columns:d.edits.reduce((h,[,u])=>h+u,0),sharedBases:d.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=V(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&ue(o,s)&&t.push([r==="reverse"?1:0,A(s),T(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!T(r)){let o=A(r),s=`S ${o} ${this.record(r).sequence}
2
+ `;for(let[i,a,c]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${c?"-":"+"}
3
+ `;t.push(e.encode(s))}return Or(t)}async toGFA(e={}){let t=e.cigar??!1,r=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...Mr(kr(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let f of o)T(f)||r.push(`S ${A(f)} ${this.record(f).sequence}`);let s=f=>T(f)?"-":"+";for(let f of o)for(let l of this.record(f).successors())this.hasHandle(l)&&ue(f,l)&&r.push(`L ${A(f)} ${s(f)} ${A(l)} ${s(l)} 0M`);let i=(f,l,p,d,h)=>{let u=Ke(f,l).map(x=>`${T(x)?"<":">"}${A(x)}`).join(""),m=f.weight===void 0?"":` WT:i:${f.weight}`,w=h===void 0?"":` CG:Z:${h}`;return`W ${p.sample} ${p.haplotype} ${p.contig} ${p.fragment} ${d} ${u}${m}${w}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&r.push(i(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let c=1;return this.paths.forEach((f,l)=>{if(l!==this.refId){let p=e.names==="resolved"?f.identity:void 0,d=t?this.alignToRef(l):void 0;r.push(p?i(f,p,{...p.name,fragment:p.name.fragment+p.hapStart},p.name.fragment+p.hapEnd,d):i(f,void 0,{sample:"unknown",contig:a,haplotype:c,fragment:0},f.len,d)),c+=1}}),`${r.join(`
4
+ `)}
5
+ `}outputPaths(e){let t=e.cigar??!1,r=[],o=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let i={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};r.push({info:this.paths[this.refId],identity:void 0,name:q(i,this.refPath.fragment+this.refInterval[1]),cigar:void 0})}let s=1;return this.paths.forEach((i,a)=>{if(a===this.refId)return;let c=e.names==="resolved"?i.identity:void 0;r.push({info:i,identity:c,name:c?q({...c.name,fragment:c.name.fragment+c.hapStart},c.name.fragment+c.hapEnd):q({sample:"unknown",contig:o,haplotype:s,fragment:0},i.len),cigar:t?this.alignToRef(a):void 0}),s+=1}),r}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&ue(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!T(s)).map(s=>({id:String(A(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(A(s)),from_is_reverse:T(s),to:String(A(i)),to_is_reverse:T(i)});let o=this.outputPaths(e).map(s=>Fo(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!T(i)),r=new Int32Array(t.length),o=[];t.forEach((i,a)=>{r[a]=A(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:r,nodeSequences:o,edges:Int32Array.from(s),paths:this.outputPaths(e).map(i=>({name:i.name,weight:i.info.weight,cigar:i.cigar,steps:Int32Array.from(Ke(i.info,i.identity))}))}}};function Ke(n,e){return e?.orientation==="reverse"?n.path.map(t=>G(t)).reverse():n.path}function Fo(n,e,t,r){return{name:t,...n.weight===void 0?{}:{weight:n.weight},...r===void 0?{}:{cigar:r},path:Ke(n,e).map(o=>({id:String(A(o)),is_reverse:T(o)}))}}function zt(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n[r],s=e[r];if(o!==s)return o<s?-1:1}return n.length-e.length}function z(n,e,t){if(t===0)return;let r=n[n.length-1];r?.[0]===e?r[1]+=t:n.push([e,t])}function Ve(n){return n===0?0:6+(n-1)}function Vr(n,e,t){if(e===0)z(n,"D",t);else if(t===0)z(n,"I",e);else{let r=Math.min(e,t),o=4*r+Ve(e-r)+Ve(t-r),s=Ve(e)+Ve(t);o<=s?(z(n,"M",r),z(n,"I",e-r),z(n,"D",t-r)):(z(n,"I",e),z(n,"D",t))}}function Ho(n){return n.map(([e,t])=>`${t}${e}`).join("")}async function Xe(n,e,t,r,o={}){let s=new _e(n,o);try{let i=await s.pathPosition(Ce(e,t));await s.prefetchReferenceWalk(i,r-t),await s.aroundInterval(i.position,r-t,o.context??100),await s.extractSnarls(o.snarls??"none"),s.extractPaths(i,o.haplotypes??"all")}catch(i){throw i instanceof X&&i.windowBp===void 0?new X(i.limit,{windowBp:r-t,walkedBp:s.referenceWalkedBp??0}):i}return s}async function Kr(n,e,t,r,o){if(!n.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let s=await n.haplotypeAnchorSpacing(),i,a;if(s!==void 0&&(o.haplotypes??"all")==="all"){let c=new _e(n,o);try{let f=await c.pathPosition(Ce(e,t));a=await c.walkHaplotypesFromAnchor(f,r-t,s,o.keep,o.context??100)}catch(f){throw f instanceof X&&f.windowBp===void 0?new X(f.limit,{windowBp:r-t,walkedBp:c.referenceWalkedBp??0}):f}if(a===void 0)i=c;else{a=`${a}; identified from the per-path samples instead`;let f=await Xe(n,e,t,r,o);await f.identifyPaths(),f.keepHaplotypes(o.keep),f.stats.anchorWalk=c.stats.anchorWalk,f.stats.anchorWalk&&(f.stats.anchorWalk.fallback=a),i=f}}else i=await Xe(n,e,t,r,o),await i.identifyPaths(),i.keepHaplotypes(o.keep);return i}function Z(n,e){let t=0;for(let o=0;o<8;o++){let s=n[e+o];if(s===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(s&127),(s&128)===0)return[t,e+o+1]}let r=n[e+8];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+r,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function qo(n,e,t){switch(t){case 1:return n.getInt8(e);case 2:return n.getInt16(e);case 3:return n.getInt8(e)<<16|n.getUint16(e+1);case 4:return n.getInt32(e);case 6:return n.getInt16(e)*4294967296+n.getUint32(e+2);default:{let r=n.getBigInt64(e);if(r>BigInt(Number.MAX_SAFE_INTEGER)||r<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${r} exceeds the safe integer range`);return Number(r)}}}var $o=new TextDecoder;function Ze(n){let[e,t]=Z(n,0),r=[],o=t;for(;o<e;){let[a,c]=Z(n,o);r.push(a),o=c}let s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=e;return r.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let c=a<=4?a:a===5?6:8,f=qo(s,i,c);return i+=c,f}if(a===7){let c=s.getFloat64(i);return i+=8,c}if(a===8)return 0;if(a===9)return 1;if(a>=12){let c=a-12>>1,f=n.subarray(i,i+c);return i+=c,a%2===0?f:$o.decode(f)}throw new Error(`SQLite serial type ${a} is reserved`)})}var Pe=2,et=5,Zr=10,Je=13;function Jr(n,e){return n[e]*256+n[e+1]}function oe(n,e){return n[e]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function Bo(n,e){let t=n[e];if(t!==Pe&&t!==et&&t!==Zr&&t!==Je)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===Pe||t===et;return{type:t,cellCount:Jr(n,e+3),rightChild:r?oe(n,e+8):0,cellPointers:e+(r?12:8)}}function re(n,e,t){return Jr(n,e.cellPointers+2*t)}var Go=4096,Do=4096,tt=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let r=this.usable,o=t?Math.floor((r-12)*64/255)-23:r-35;if(e<=o)return e;let s=Math.floor((r-12)*32/255)-23,i=s+(e-s)%(r-4);return i<=o?i:s}async payload(e,t,r,o){let s=this.localPayloadSize(r,o);if(s===r)return e.subarray(t,t+r);let i=new Uint8Array(r);i.set(e.subarray(t,t+s),0);let a=s,c=oe(e,t+s);for(;c!==0&&a<r;){let f=await this.pager.page(c),l=f.subarray(4,4+Math.min(this.usable-4,r-a));i.set(l,a),a+=l.length,c=oe(f,0)}if(a!==r)throw new Error("SQLite overflow chain ended before the payload was complete");return i}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:Bo(t,e===1?100:0)}}tableDepth(e,t){let r=this.tableDepths.get(e);return r||(r=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Je)return s;if(a.type!==et)throw new Error("SQLite table b-tree contains an index page");let c=this.childIndexFor(i,a,t);o=c===a.cellCount?a.rightChild:oe(i,re(i,a,c))}})(),this.tableDepths.set(e,r),r.catch(()=>this.tableDepths.delete(e))),r}childIndexFor(e,t,r){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=Z(e,re(e,t,i)+4);a<r?o=i+1:s=i}return o}async prefetchRowidRange(e,t,r){let o=await this.tableDepth(e,t),s=[e];for(let i=0;i<o;i++){let a=await Promise.all(s.map(f=>this.pageAt(f))),c=[];if(a.forEach(({page:f,header:l},p)=>{let d=p===0?this.childIndexFor(f,l,t):0,h=p===a.length-1?this.childIndexFor(f,l,r):l.cellCount;for(let u=d;u<=h;u++)c.push(u===l.cellCount?l.rightChild:oe(f,re(f,l,u)))}),c.length>Do)return!1;this.pager.prefetch(c),s=c}return!0}async tableRowid(e,t){let r=e;for(;;){let{page:o,header:s}=await this.pageAt(r);if(s.type===Je){let c=0,f=s.cellCount;for(;c<f;){let l=c+f>>1,p=re(o,s,l),[d,h]=Z(o,p),[u,m]=Z(o,h);if(u===t)return Ze(await this.payload(o,m,d,!1));u<t?c=l+1:f=l}return}if(s.type!==et)throw new Error("SQLite table b-tree contains an index page");let i=0,a=s.cellCount;for(;i<a;){let c=i+a>>1,f=re(o,s,c),[l]=Z(o,f+4);l<t?i=c+1:a=c}r=i===s.cellCount?s.rightChild:oe(o,re(o,s,i))}}async*tableScan(e){let{page:t,header:r}=await this.pageAt(e);if(r.type===Je)for(let o=0;o<r.cellCount;o++){let s=re(t,r,o),[i,a]=Z(t,s),[c,f]=Z(t,a);yield{rowid:c,values:Ze(await this.payload(t,f,i,!1))}}else{let o=[];for(let s=0;s<r.cellCount;s++)o.push(oe(t,re(t,r,s)));o.push(r.rightChild),this.pager.prefetch(o);for(let s of o)yield*this.tableScan(s)}}decodedCells(e,t){let r=this.decodedIndexPages.get(e);if(r)this.decodedIndexPages.delete(e);else if(r=new Array(t.cellCount),this.decodedIndexPages.size>=Go){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,r),r}async indexCell(e,t,r,o){let s=this.decodedCells(e,r),i=s[o];if(!i){let a=re(t,r,o),c=r.type===Pe,[f,l]=Z(t,c?a+4:a);i={values:Ze(await this.payload(t,l,f,!0)),leftChild:c?oe(t,a):0},s[o]=i}return i}async*indexScanFrom(e,t){let{page:r,header:o}=await this.pageAt(e),s=0,i=o.cellCount;for(;s<i;){let a=s+i>>1,c=await this.indexCell(e,r,o,a);Xr(c.values,t)<0?s=a+1:i=a}for(let a=s;a<o.cellCount;a++){let c=await this.indexCell(e,r,o,a);o.type===Pe&&(yield*this.indexScanFrom(c.leftChild,t)),yield c.values}o.type===Pe&&(yield*this.indexScanFrom(o.rightChild,t))}async indexSeekLE(e,t){let r,o=e;for(;;){let{page:s,header:i}=await this.pageAt(o),a=0,c=i.cellCount,f=0;for(;a<c;){let l=a+c>>1,p=await this.indexCell(o,s,i,l);Xr(p.values,t)<=0?(r=p.values,a=l+1):(f=p.leftChild,c=l)}if(i.type===Zr)return r;o=a===i.cellCount?i.rightChild:f}}};function Xr(n,e){for(let t=0;t<e.length;t++){let r=n[t],o=e[t];if(typeof r!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(r!==o)return r<o?-1:1}return 0}var rt=class{blocks=new Map;blockSize;maxBlocks;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,r,o={}){this.source=e,this.pageSize=t,this.fileSize=r;let s=o.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(s/t)*t),this.maxBlocks=o.maxBlocks??256}async read(e,t){let r=0;for(;;)try{let o=await this.source.read(e,t);return this.bytesFetched+=o.length,o}catch(o){if(r+=1,r>=3)throw o;await new Promise(s=>setTimeout(s,200*r))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){let t=this.blocks.get(e);if(t)return this.blocks.delete(e),this.blocks.set(e,t),t;let r=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-r),s=this.read(o,r);return this.fetches+=1,this.blocks.set(e,s),this.forgetOnFailure(s,[e]),this.evict(),s}prefetch(e){let t=[...new Set(e.map(o=>Math.floor((o-1)*this.pageSize/this.blockSize)))].filter(o=>!this.blocks.has(o)).sort((o,s)=>o-s),r=0;for(;r<t.length;){let o=r+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[r],o-r),r=o}}fetchRun(e,t){let r=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-r),s=this.read(o,r);this.fetches+=1;let i=[];for(let a=0;a<t;a++){let c=a*this.blockSize;i.push(e+a),this.blocks.set(e+a,s.then(f=>f.subarray(c,c+this.blockSize)))}this.forgetOnFailure(s,i),this.evict()}forgetOnFailure(e,t){e.catch(()=>{for(let r of t)this.blocks.delete(r)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let r=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return r.subarray(o,o+this.pageSize)}};var ke=class n{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){let{size:r}=await e.stat(),o=await e.read(Math.min(t.blockSize??65536,r),0),s=o.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3")throw new Error("Not a SQLite database");let a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=a.getUint16(16),f=c===1?65536:c,l=s[20]??0,p=a.getUint32(56);if(p!==1)throw new Error(`SQLite text encoding ${p} is not UTF-8`);let d=new rt(e,f,r,t);d.seed(0,o),d.fetches+=1,d.bytesFetched+=o.length;let h=new tt(d,l),u=new Map;for await(let{values:m}of h.tableScan(1)){let[w,x,b,g,S]=m;typeof w=="string"&&typeof x=="string"&&typeof b=="string"&&typeof g=="number"&&u.set(x,{type:w,name:x,tableName:b,rootPage:g,sql:typeof S=="string"?S:""})}return new n(d,h,u)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}indexOn(e){let t=[...this.objects.values()].find(r=>r.type==="index"&&r.tableName===e);if(!t)throw new Error(`SQLite table ${e} has no index`);return t.rootPage}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,r){return this.btree.prefetchRowidRange(this.rootPage(e),t,r)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t){return this.btree.indexScanFrom(this.indexOn(e),t)}has(e){return this.objects.has(e)}};var Ut="GBZ-base version 4",nt=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")}},ot=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: its Tags table has no version":`unsupported database schema "${e}"; this reader understands "${Ut}"`),this.found=e}},st=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,r,o,s){this.handle=e,this.edges=t,this.bwt=r,this.encodedSequence=o,this.next=s,this.sequenceLen=Ar(o)}get id(){return A(this.handle)}get orientation(){return de(this.handle)}get sequence(){return this.decoded??=Er(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 Ge(this.edges,this.bwt)}};function L(n,e){if(typeof n!="number")throw new Error(`${e} is not a number in the database`);return n}function it(n,e){if(typeof n!="string")throw new Error(`${e} is not text in the database`);return n}function jt(n,e){if(!(n instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return n}function en(n,e){return{handle:n,fwStart:{node:L(e[1],"Paths.fw_node"),offset:L(e[2],"Paths.fw_offset")},revStart:{node:L(e[3],"Paths.rev_node"),offset:L(e[4],"Paths.rev_offset")},name:{sample:it(e[5],"Paths.sample"),contig:it(e[6],"Paths.contig"),haplotype:L(e[7],"Paths.haplotype"),fragment:L(e[8],"Paths.fragment")},isIndexed:L(e[9],"Paths.is_indexed")!==0}}async function tn(n){let e=new Map;for await(let{values:t}of n.scan("Tags"))e.set(it(t[0],"Tags.key"),it(t[1],"Tags.value"));return e}var Me=class n{tagCache;pathCache;pathMapCache;indexTags;sqlite;index;constructor(e,t){this.sqlite=e,this.index=t}static async open(e,t={}){let{haplotypeIndex:r,...o}=t,s=await ke.open(e,o);for(let f of["Tags","Nodes","Paths","ReferenceIndex"])s.rootPage(f);let i=r?await ke.open(r,o):s,a=new n(s,i),c=await a.tag("version");if(c!==Ut)throw new ot(c);if(r){for(let h of["Tags","HaplotypeSamples","HaplotypeLengths"])i.rootPage(h);a.indexTags=await tn(i);let f=a.indexTags.get("haplotype_index_paths"),l=await a.tag("paths");if(f!==l)throw new Error(`haplotype index was built for ${f??"an unknown number of"} paths but the graph has ${l}`);let p=a.indexTags.get("haplotype_index_nodes"),d=await a.tag("nodes");if(p!==void 0&&p!==d)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${d}`)}if(a.hasHaplotypeIndex&&await a.haplotypeIndexTag("haplotype_index_orientations")==="forward")throw new nt;return a}tags(){return this.tagCache??=tn(this.sqlite),this.tagCache}async tag(e){return(await this.tags()).get(e)}prefetchRecords(e,t){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let r=t[4];return new st(e,Ir(jt(t[1],"Nodes.edges")),jt(t[2],"Nodes.bwt"),jt(t[3],"Nodes.sequence"),typeof r=="number"?r:void 0)}paths(){return this.pathCache??=(async()=>{let e=[];for await(let{rowid:t,values:r}of this.sqlite.scan("Paths"))e.push(en(t,r));return e})(),this.pathCache}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?en(e,t):void 0}pathsByHandle(){return this.pathMapCache??=this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),this.pathMapCache}async findPath(e){return(await this.paths()).filter(r=>r.name.sample===e.sample&&r.name.contig===e.contig&&r.name.haplotype===e.haplotype&&r.name.fragment<=e.fragment).sort((r,o)=>o.name.fragment-r.name.fragment)[0]}async pathsForSample(e){return(await this.paths()).filter(t=>t.name.sample===e)}async pathsNamed(e){let t=Ce(Tr(e),0);return(await this.paths()).filter(r=>r.name.sample===t.sample&&r.name.contig===t.contig&&r.name.haplotype===t.haplotype).sort((r,o)=>r.name.fragment-o.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let r=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!r){let i=await this.getPath(e);throw new Error(`Path ${i?q(i.name,i.name.fragment):e} has not been indexed for random access`)}let o=r.pathOffset,s=r.pos;for(;;){let i=await this.getRecord(s.node);if(!i)throw new Error(`Node ${s.node} does not exist in the graph`);o+=i.sequenceLen;let a=i.gbwt().lf(s.offset);if(!a||a.node===0)return o;s=a}}return t}async pathFragmentsForRange(e,t,r){if(r<=t)return[];let o=await this.pathsNamed(e),s=o.filter(c=>c.name.fragment<=t).slice(-1),i=o.filter(c=>c.name.fragment>t&&c.name.fragment<r);return(await Promise.all([...s,...i].map(async c=>({path:c,start:c.name.fragment,end:c.name.fragment+await this.pathLength(c.handle)})))).filter(c=>t<c.end)}async subgraphForFragment(e,t,r,o){let{keep:s,...i}=o;if(s!==void 0&&!this.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{sample:a,contig:c,haplotype:f}=e.path.name,l={sample:a,contig:c,haplotype:f},p=Math.max(t,e.start),d=Math.min(r,e.end),h=o.haplotypes??"all",u=h==="all"||h==="distinct",m;return s!==void 0&&h==="all"?m=await Kr(this,l,p,d,{...i,keep:s}):(m=await Xe(this,l,p,d,i),this.hasHaplotypeIndex&&u&&(await m.identifyPaths(),s!==void 0&&m.keepHaplotypes(s))),m}async getSubgraphForRange(e,t,r,o={}){let[s]=await this.pathFragmentsForRange(e,t,r);return s?this.subgraphForFragment(s,t,r,o):void 0}async getAlignmentsForRange(e,t,r,o={}){let s=[];for(let i of await this.pathFragmentsForRange(e,t,r)){let a=await this.subgraphForFragment(i,t,r,o);s.push(...a.alignments())}return s}async graphName(){let e=new Map;for(let[r,o]of await this.tags())r.startsWith("gbz_")&&e.set(r.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=Pr(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.has("HaplotypeSamples")&&this.index.has("HaplotypeLengths")}async haplotypeIndexTag(e){return this.indexTags?this.indexTags.get(e):await this.tag(e)}async haplotypeSampleInterval(){let e=await this.haplotypeIndexTag("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeAnchorSpacing(){let e=this.hasHaplotypeIndex&&this.index.has("HaplotypeAnchors")?await this.haplotypeIndexTag("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeAnchor(e,t){let r=await this.index.indexSeekLE("HaplotypeAnchors",[e,t]),o=r?.[0]===e&&r[1]===t?await this.index.byRowid("HaplotypeAnchors",L(r[2],"HaplotypeAnchors rowid")):void 0;return o?{node:L(o[2],"HaplotypeAnchors.node_handle"),pathOffset:L(o[3],"HaplotypeAnchors.path_offset")}:void 0}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:L(e[0],"HaplotypeSamples.node_handle"),offset:L(e[1],"HaplotypeSamples.node_offset"),pathHandle:L(e[2],"HaplotypeSamples.path_handle"),orientation:L(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:L(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let r=[];for await(let o of this.index.indexScanFrom("HaplotypeSamples",[e,0])){if(L(o[0],"HaplotypeSamples.node_handle")>t)break;let i=await this.index.byRowid("HaplotypeSamples",L(o[2],"HaplotypeSamples rowid"));i&&r.push(this.sampleFromRow(i))}return r}async haplotypeSampleAt(e,t){let r=await this.index.indexSeekLE("HaplotypeSamples",[e,t]);if(r?.[0]!==e||r[1]!==t)return;let o=await this.index.byRowid("HaplotypeSamples",L(r[2],"HaplotypeSamples rowid"));return o?this.sampleFromRow(o):void 0}async haplotypeLength(e){let t=await this.index.byRowid("HaplotypeLengths",e);return t?L(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:L(t[1],"ReferenceIndex.path_offset"),pos:{node:L(t[2],"ReferenceIndex.node_handle"),offset:L(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let r=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return r?.[0]===e?L(r[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let r=await this.indexedRowid(e,t);return r===void 0?void 0:this.indexedRow(r)}async indexedPositionsBetween(e,t,r){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,r)]),i=[];if(o!==void 0&&s!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",o,s+1);for(let a=o;a<=s;a++)i.push(await this.indexedRow(a))}return i}};var Xn=Y(gr(),1),Zn=Y(Ie(),1),lr=Y(ro(),1),Jn=Y(no(),1);var Qn=Y(gr(),1),Yn=Y(Ie(),1);var Wt=function(n,e){return Wt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},Wt(n,e)};function Oe(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Wt(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function rn(n,e,t,r){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function a(l){try{f(r.next(l))}catch(p){i(p)}}function c(l){try{f(r.throw(l))}catch(p){i(p)}}function f(l){l.done?s(l.value):o(l.value).then(a,c)}f((r=r.apply(n,e||[])).next())})}function at(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(f){return function(l){return c([f,l])}}function c(f){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,f[0]&&(t=0)),t;)try{if(r=1,o&&(s=f[0]&2?o.return:f[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,f[1])).done)return s;switch(o=0,s&&(f=[f[0]&2,s.value]),f[0]){case 0:case 1:s=f;break;case 4:return t.label++,{value:f[1],done:!1};case 5:t.label++,o=f[1],f=[0];continue;case 7:f=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(f[0]===6||f[0]===2)){t=0;continue}if(f[0]===3&&(!s||f[1]>s[0]&&f[1]<s[3])){t.label=f[1];break}if(f[0]===6&&t.label<s[1]){t.label=s[1],s=f;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(f);break}s[2]&&t.ops.pop(),t.trys.pop();continue}f=e.call(n,t)}catch(l){f=[6,l],o=0}finally{r=s=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function ae(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ge(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return s}function we(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function fe(n){return this instanceof fe?(this.v=n,this):new fe(n)}function nn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(h){return function(u){return Promise.resolve(u).then(h,p)}}function a(h,u){r[h]&&(o[h]=function(m){return new Promise(function(w,x){s.push([h,m,w,x])>1||c(h,m)})},u&&(o[h]=u(o[h])))}function c(h,u){try{f(r[h](u))}catch(m){d(s[0][3],m)}}function f(h){h.value instanceof fe?Promise.resolve(h.value.v).then(l,p):d(s[0][2],h)}function l(h){c("next",h)}function p(h){c("throw",h)}function d(h,u){h(u),s.shift(),s.length&&c(s[0][0],s[0][1])}}function on(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof ae=="function"?ae(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(i){return new Promise(function(a,c){i=n[s](i),o(a,c,i.done,i.value)})}}function o(s,i,a,c){Promise.resolve(c).then(function(f){s({value:f,done:a})},i)}}function P(n){return typeof n=="function"}function sn(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var ft=sn(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
6
+ `+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
7
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function Qt(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var ct=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=ae(i),c=a.next();!c.done;c=a.next()){var f=c.value;f.remove(this)}}catch(m){e={error:m}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(P(l))try{l()}catch(m){s=m instanceof ft?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var d=ae(p),h=d.next();!h.done;h=d.next()){var u=h.value;try{an(u)}catch(m){s=s??[],m instanceof ft?s=we(we([],ge(s)),ge(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{h&&!h.done&&(o=d.return)&&o.call(d)}finally{if(r)throw r.error}}}if(s)throw new ft(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)an(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Qt(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Qt(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var Si=ct.EMPTY;function lt(n){return n instanceof ct||n&&"closed"in n&&P(n.remove)&&P(n.add)&&P(n.unsubscribe)}function an(n){P(n)?n():n.unsubscribe()}var K={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var ye={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=ye.delegate;return o?.setTimeout?o.setTimeout.apply(o,we([n,e],ge(t))):setTimeout.apply(void 0,we([n,e],ge(t)))},clearTimeout:function(n){var e=ye.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function pt(n){ye.setTimeout(function(){var e=K.onUnhandledError;if(e)e(n);else throw n})}function Yt(){}var fn=(function(){return Vt("C",void 0,void 0)})();function cn(n){return Vt("E",void 0,n)}function ln(n){return Vt("N",n,void 0)}function Vt(n,e,t){return{kind:n,value:e,error:t}}var ce=null;function pn(n){if(K.useDeprecatedSynchronousErrorHandling){var e=!ce;if(e&&(ce={errorThrown:!1,error:null}),n(),e){var t=ce,r=t.errorThrown,o=t.error;if(ce=null,r)throw o}}else n()}function hn(n){K.useDeprecatedSynchronousErrorHandling&&ce&&(ce.errorThrown=!0,ce.error=n)}var Te=(function(n){Oe(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,lt(t)&&t.add(r)):r.destination=Wo,r}return e.create=function(t,r,o){return new dt(t,r,o)},e.prototype.next=function(t){this.isStopped?Xt(ln(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?Xt(cn(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?Xt(fn,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(ct);var zo=Function.prototype.bind;function Kt(n,e){return zo.call(n,e)}var jo=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){ht(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){ht(r)}else ht(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){ht(t)}},n})(),dt=(function(n){Oe(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(P(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&K.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Kt(t.next,a),error:t.error&&Kt(t.error,a),complete:t.complete&&Kt(t.complete,a)}):i=t}return s.destination=new jo(i),s}return e})(Te);function ht(n){K.useDeprecatedSynchronousErrorHandling?hn(n):pt(n)}function Uo(n){throw n}function Xt(n,e){var t=K.onStoppedNotification;t&&ye.setTimeout(function(){return t(n,e)})}var Wo={closed:!0,next:Yt,error:Uo,complete:Yt};var xe=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function dn(n){return n}function un(n){return n.length===0?dn:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var j=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Yo(e)?e:new dt(e,t,r);return pn(function(){var i=o,a=i.operator,c=i.source;s.add(a?a.call(s,c):c?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=mn(t),new t(function(o,s){var i=new dt({next:function(a){try{e(a)}catch(c){s(c),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[xe]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return un(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=mn(e),new e(function(r,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},n.create=function(e){return new n(e)},n})();function mn(n){var e;return(e=n??K.Promise)!==null&&e!==void 0?e:Promise}function Qo(n){return n&&P(n.next)&&P(n.error)&&P(n.complete)}function Yo(n){return n&&n instanceof Te||Qo(n)&&lt(n)}function Vo(n){return P(n?.lift)}function W(n){return function(e){if(Vo(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function ne(n,e,t,r,o){return new Ko(n,e,t,r,o)}var Ko=(function(n){Oe(e,n);function e(t,r,o,s,i,a){var c=n.call(this,t)||this;return c.onFinalize=i,c.shouldUnsubscribe=a,c._next=r?function(f){try{r(f)}catch(l){t.error(l)}}:n.prototype._next,c._error=s?function(f){try{s(f)}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=o?function(){try{o()}catch(f){t.error(f)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(Te);var ut=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function mt(n){return P(n?.then)}function gt(n){return P(n[xe])}function wt(n){return Symbol.asyncIterator&&P(n?.[Symbol.asyncIterator])}function yt(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Xo(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var xt=Xo();function bt(n){return P(n?.[xt])}function St(n){return nn(this,arguments,function(){var t,r,o,s;return at(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,fe(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,fe(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,fe(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function vt(n){return P(n?.getReader)}function J(n){if(n instanceof j)return n;if(n!=null){if(gt(n))return Zo(n);if(ut(n))return Jo(n);if(mt(n))return es(n);if(wt(n))return gn(n);if(bt(n))return ts(n);if(vt(n))return rs(n)}throw yt(n)}function Zo(n){return new j(function(e){var t=n[xe]();if(P(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Jo(n){return new j(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function es(n){return new j(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,pt)})}function ts(n){return new j(function(e){var t,r;try{for(var o=ae(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function gn(n){return new j(function(e){ns(n,e).catch(function(t){return e.error(t)})})}function rs(n){return gn(St(n))}function ns(n,e){var t,r,o,s;return rn(this,void 0,void 0,function(){var i,a;return at(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=on(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Q(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function It(n,e){return e===void 0&&(e=0),W(function(t,r){t.subscribe(ne(r,function(o){return Q(r,n,function(){return r.next(o)},e)},function(){return Q(r,n,function(){return r.complete()},e)},function(o){return Q(r,n,function(){return r.error(o)},e)}))})}function At(n,e){return e===void 0&&(e=0),W(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function wn(n,e){return J(n).pipe(At(e),It(e))}function yn(n,e){return J(n).pipe(At(e),It(e))}function xn(n,e){return new j(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function bn(n,e){return new j(function(t){var r;return Q(t,e,function(){r=n[xt](),Q(t,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return P(r?.return)&&r.return()}})}function Et(n,e){if(!n)throw new Error("Iterable cannot be null");return new j(function(t){Q(t,e,function(){var r=n[Symbol.asyncIterator]();Q(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function Sn(n,e){return Et(St(n),e)}function vn(n,e){if(n!=null){if(gt(n))return wn(n,e);if(ut(n))return xn(n,e);if(mt(n))return yn(n,e);if(wt(n))return Et(n,e);if(bt(n))return bn(n,e);if(vt(n))return Sn(n,e)}throw yt(n)}function Zt(n,e){return e?vn(n,e):J(n)}function Le(n,e){return W(function(t,r){var o=0;t.subscribe(ne(r,function(s){r.next(n.call(e,s,o++))}))})}function In(n,e,t,r,o,s,i,a){var c=[],f=0,l=0,p=!1,d=function(){p&&!c.length&&!f&&e.complete()},h=function(m){return f<r?u(m):c.push(m)},u=function(m){s&&e.next(m),f++;var w=!1;J(t(m,l++)).subscribe(ne(e,function(x){o?.(x),s?h(x):e.next(x)},function(){w=!0},void 0,function(){if(w)try{f--;for(var x=function(){var b=c.shift();i?Q(e,i,function(){return u(b)}):u(b)};c.length&&f<r;)x();d()}catch(b){e.error(b)}}))};return n.subscribe(ne(e,h,function(){p=!0,d()})),function(){a?.()}}function be(n,e,t){return t===void 0&&(t=1/0),P(e)?be(function(r,o){return Le(function(s,i){return e(r,s,o,i)})(J(n(r,o)))},t):(typeof e=="number"&&(t=e),W(function(r,o){return In(r,o,n,t)}))}function An(n,e,t,r,o){return function(s,i){var a=t,c=e,f=0;s.subscribe(ne(i,function(l){var p=f++;c=a?n(c,l,p):(a=!0,l),r&&i.next(c)},o&&(function(){a&&i.next(c),i.complete()})))}}function En(n,e){return W(An(n,e,arguments.length>=2,!1,!0))}var os=function(n,e){return n.push(e),n};function Ct(){return W(function(n,e){En(os,[])(n).subscribe(e)})}function Cn(n){let e=[],t=0,r;for(let o=0,s=n.length;o<s;o++){let i=n.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)r=t,t=0;else{let a=n[o];a==="M"||a==="="||a==="X"?e.push({own:r===void 0?t:r,mate:t,op:"M"}):a==="I"?e.push({own:0,mate:t,op:a}):(a==="D"||a==="N")&&e.push({own:t,mate:0,op:a}),r=void 0,t=0}}return e}function tr(n){let e="";for(let{own:t,mate:r,op:o}of Cn(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var Jt=2**28-1;function er(n,e,t){for(let r=e;r>0;r-=Jt)n.push((Math.min(r,Jt)<<4|t)>>>0)}function ss(n,e,t){if(e===t)er(n,e,0);else{let r=Math.ceil(Math.max(e,t)/Jt);for(let o=0;o<r;o++){let s=Math.floor(e*(o+1)/r)-Math.floor(e*o/r),i=Math.floor(t*(o+1)/r)-Math.floor(t*o/r);n.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function rr(n){let e=[];for(let{own:t,mate:r,op:o}of Cn(n))o==="M"?ss(e,t,r):o==="I"?er(e,r,1):er(e,t,o==="N"?3:2);return Uint32Array.from(e)}function is(n){return n>=48&&n<=57}function as(n){return n!==void 0&&/[A-Za-z]/.test(n)}function Rn(n,e){let t=e;for(;t<n.length&&as(n[t]);)t++;return t}function _n(n,e){let t=e,r=0;for(;t<n.length&&is(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function Tn(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=_n(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=Rn(n,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(r==="*")e("*",1,1,t+1,Math.min(t+3,n.length)),t+=3;else if(r==="+"||r==="-"){let o=Rn(n,t+1),s=o-t-1;e(r,r==="-"?s:0,r==="+"?s:0,t+1,o),t=o}else if(r==="~"){let{value:o,next:s}=_n(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function nr(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;Tn(n,(a,c,f,l,p)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,n[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let d=n.slice(l,p);e(73,i,f,d,-1,0,f)}}else(a==="-"||a==="~")&&i<s&&i+c>o&&e(a==="-"?68:78,i,c,"",-1,0,0);i+=c})}function Ln(n,e,t,r){let o=0,s=0,i=[],a=t&&e;for(let c=0,f=n.length;c<f;c++){let l=n[c],p=l>>>4,d=l&15;if(d===0||d===7){if(a)for(let h=0;h<p;h++)(e.charCodeAt(s+h)|32)!==(t.charCodeAt(o+h)|32)&&i.push({start:o+h,type:"mismatch",base:e[s+h],altbase:t[o+h],length:1});s+=p,o+=p}else if(d===1)i.push({start:o,type:"insertion",insertlen:p,insertedBases:e?.slice(s,s+p),length:0}),s+=p;else if(d===2)i.push({start:o,type:"deletion",length:p}),o+=p;else if(d===3)i.push({start:o,type:"skip",length:p}),o+=p;else if(d===8){for(let h=0;h<p;h++)i.push({start:o+h,type:"mismatch",base:e?.[s+h]||"X",qual:r?.[s+h],length:1});s+=p,o+=p}else d===5?i.push({start:o,type:"hardclip",cliplen:p,length:1}):d===4&&(i.push({start:o,type:"softclip",cliplen:p,length:1}),s+=p)}return i}function Nn(n,e,t,r,o){if(!e)return[];let s=[],i=e.length,a=r.length,c=o!==void 0,f=t.length,l=!1;for(let b=0;b<f;b++)if(t[b].type==="skip"){l=!0;break}let p=0,d=0,h=0,u=0,m=0,w=0,x=n.length;for(;w<x;){let b=n.charCodeAt(w);if(b>=48&&b<=57){let g=0;for(;w<x;){let S=n.charCodeAt(w);if(S>=48&&S<=57)g=g*10+(S-48),w++;else break}p+=g}else if(b===94)for(w++;w<x&&n.charCodeAt(w)>=65;)w++,p++;else if(b>=65){let g=n[w];if(w++,l&&f>0)for(let R=m;R<f;R++){let C=t[R];C.type==="skip"&&p>=C.start&&(p+=C.length,m=R+1)}let S=h,y=u;for(let R=d;R<i&&y<=p;R++,d=R){let C=e[R],_=C>>>4,E=C&15;E===4||E===1?S+=_:E===2||E===6||E===3?y+=_:E!==5&&(S+=_,y+=_)}h=S,u=y;let v=S-(y-p),I=v<a?r[v]:"X";s.push({start:p,base:I,qual:c?o[v]:void 0,altbase:g,length:1,type:"mismatch"}),p++}else w++}return s}var Fn={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function Hn(n=""){let e=0,t=[];for(let r=0,o=n.length;r<o;r++){let s=n.charCodeAt(r);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=Fn[s];t.push(e<<4|i),e=0}}return t}function ir(n=""){let e=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),r=0,o=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);a>=48&&a<=57?r=r*10+(a-48):(t[o++]=r<<4|Fn[a],r=0)}return t}function Mt(n,e,t,r,o){let s=Hn(n),i=n?Ln(s,t,r,o):[];return e&&t?i.concat(Nn(e,s,i,t,o)):i}var ls=397,ps=387,hs=385;function qn(n){return(1<<n&ls)!==0}function $n(n){return(1<<n&ps)!==0}function Bn(n){return(1<<n&hs)!==0}function ar(n,e,t,r,o,s,i){let a=o===-1?-1:1,c=e,f=o===-1?r:t,l=[],p=1/0,d=-1/0,h=1/0,u=-1/0,m=(w,x)=>{h=Math.min(h,w,x),u=Math.max(u,w,x)};for(let w=0;w<n.length;w++){let x=n[w],b=x>>>4,g=x&15,S=g===9,y=S||qn(g)?b:0,v=S?n[++w]>>>4:$n(g)?b:0,I=c+y,R=f+v*a,C=c,_=I;if(_>=s&&C<=i)if(y>0){let E=Math.max(C,s),k=Math.min(_,i);if(k>E)if(p=Math.min(p,E),d=Math.max(d,k),S){let O=v/b,N=k-E,F=Math.round(N*O),H=Math.round(f+(E-c)*O*a);l.push(N<<4|9,F<<4|9),m(H,H+F*a)}else l.push(k-E<<4|g),Bn(g)?m(f+(E-c)*a,f+(k-c)*a):m(f,f)}else v>0&&(S?l.push(x,n[w]):l.push(x),p=Math.min(p,c),d=Math.max(d,c),m(f,R));if(c=I,f=R,c>i)break}if(l.length!==0)return{start:p,end:d,mateStart:h,mateEnd:u,cigar:Uint32Array.from(l)}}function ds(n){return n===1||n===2||n===3}function fr(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],c=e,f=o===-1?r:t,l,p=!1,d=()=>{l!==void 0&&p&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,p=!1};for(let h=0;h<n.length;h++){let u=n[h],m=u>>>4,w=u&15,x=w===9,b=x?n[++h]:void 0,g=x||qn(w)?m:0,S=b!==void 0?b>>>4:$n(w)?m:0,y=f+S*i;ds(w)&&m>=s?d():(g>0||S>0)&&(l===void 0&&(l={qLo:c,qHi:c,tLo:f,tHi:f,ops:[]}),l.qHi=c+g,l.tLo=Math.min(l.tLo,f,y),l.tHi=Math.max(l.tHi,f,y),l.ops.push(u),b!==void 0&&l.ops.push(b),p=p||x||Bn(w)),c+=g,f=y}return d(),a}function Gn(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function Dn(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function cr(n){let e=Gn(n),t=e===void 0?Dn(n):void 0;return e!==void 0?ir(e):t!==void 0?rr(t):void 0}var us=Y(Ie(),1),ms=Y(jn(),1);var gs=Y(Ie(),1);var ws=Y(oo(),1);var Un=Y(Ie(),1),le=class extends Un.SimpleFeature{get(e){return e==="mismatches"?Mt(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?tr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let r=this.get("start"),o=t?.start===void 0?void 0:t.start-r,s=t?.end===void 0?void 0:t.end-r,i=this.get("cs");if(i)nr(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,c=s??Number.POSITIVE_INFINITY;for(let f of Mt(this.walkableCigar))(f.type==="deletion"||f.type==="skip"?f.start<c&&f.start+f.length>a:f.start>=a&&f.start<=c)&&(f.type==="mismatch"?e(88,f.start,f.length,f.base,f.qual??-1,0,0):f.type==="insertion"?e(73,f.start,f.length,f.insertedBases??"",-1,0,f.insertlen):f.type==="deletion"?e(68,f.start,f.length,"",-1,0,0):f.type==="skip"&&e(78,f.start,f.length,"",-1,0,0))}}};var ys=["CIGAR","cs","coarseCigar","cg","cr"];function xs(n){return typeof n=="object"&&n!==null&&"refName"in n&&"start"in n&&"end"in n&&typeof n.refName=="string"&&typeof n.start=="number"&&typeof n.end=="number"}function bs(n){let e=n.get("mate");return xs(e)?e:void 0}function Ss(n,e,t,r){let o=Math.max(n.start,r.start),s=Math.min(n.end,r.end),i=(e.end-e.start)/Math.max(n.end-n.start,1),a=l=>t===-1?e.end-(l-n.start)*i:e.start+(l-n.start)*i,c=Math.round(a(o)),f=Math.round(a(s));return s>o?{start:o,end:s,mateStart:Math.min(c,f),mateEnd:Math.max(c,f)}:void 0}function vs(n,e,t,r){let o={start:n.get("start"),end:n.get("end")},s=n.get("strand")===-1?-1:1,i=o.start>=t.start&&o.end<=t.end,a=i&&r===void 0?void 0:cr(n);if(a===void 0){let c=i?{...o,mateStart:e.start,mateEnd:e.end}:Ss(o,e,s,t);return c===void 0?[]:[c]}else return(r===void 0?[{...o,mateStart:e.start,mateEnd:e.end,cigar:a}]:fr(a,o.start,e.start,e.end,s,r)).flatMap(f=>{let l=ar(f.cigar,f.start,f.mateStart,f.mateEnd,s,t.start,t.end);return l===void 0?[]:[l]})}function Is(n,e,t,r,o){let s=`:${r.start}-${r.end}${o}`,i=n.toJSON(),a={...i,uniqueId:`${n.id()}${s}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};i.syntenyId!==void 0&&(a.syntenyId=`${String(i.syntenyId)}${s}`);for(let c of ys)delete a[c];return new le(a)}function Wn(n,e,t){let r=bs(n);if(r===void 0)return[n];{let o=vs(n,r,e,t);return o.map((s,i)=>Is(n,r,s,e,o.length>1?`/${i}`:""))}}var Ot=class extends Qn.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:o,splitAtGapBp:s,...i}=r,a=o&&this.recordsAreAlignments,c=(0,Yn.createStatusFanOut)(i.statusCallback);return Zt(t).pipe(be((f,l)=>this.getFeatures(f,{...i,statusCallback:c()}).pipe(be(p=>a?Wn(p,p.get("assemblyName")===f.assemblyName?f:{start:p.get("start"),end:p.get("end")},s):[p]),Ct(),Le(p=>({index:l,features:p})))),Ct(),be(f=>f.sort((l,p)=>l.index-p.index).flatMap(l=>l.features)))}};var pr=class extends Error{constructor(){super("this .gbz.db has no HaplotypeSamples/HaplotypeLengths tables, so its walks cannot be named; run gbz-haplotype-index (from @gmod/gbz-base) over it first");this.name="NoHaplotypeIndexError"}},hr=class extends Error{constructor(t,r){super(r.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${t}" maps to none; set referenceSample`:`the anchor "${t}" is none of the graph's reference samples (${r.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`);this.name="NoReferenceSampleError"}};function Se(n){return`${n.sample}#${n.haplotype}`}function As(n,e){let t=Se(n);return e===void 0||e.some(r=>Fe(t,r))}var dr=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}},ur=class extends Error{constructor(t,r,o){super(`this ${r.toLocaleString()} bp window reads more than nodeLimit (${t.toLocaleString()}) graph nodes; zoom in to about ${o.toLocaleString()} bp or raise nodeLimit`);this.name="NodeLimitError"}};function Vn(n,e,t){if(n instanceof Error&&(n.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(n.message))){let o=n.walkedBp,s=typeof o=="number"&&o>0?Math.floor(o*.8):Math.floor(t/2);return new ur(e,t,Math.max(s,1))}else return}function Kn(n,e){let t=Se(e);return n[t]??n[e.sample]??t}function Es({configured:n,anchorPrefix:e,referenceSamples:t}){let r=wr(e);if(n!=="")return n;if(t.includes(r))return r;if(t.length===1)return t[0];throw new hr(e,t)}function Cs(n,e){return`${Se(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function Rs({alignment:n,assemblyName:e,refName:t,lane:r}){let{refStart:o,refEnd:s,strand:i,cigar:a}=n;if(!(!n.resolved||s<=o)){let{name:c,hapStart:f,hapEnd:l}=n,p=Cs(c,n),d={uniqueId:p,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:p,mate:{refName:c.contig,start:f,end:l,assemblyName:r}};return new le(d)}}var mr=class extends Ot{constructor(){super(...arguments);this.graph=(0,Xn.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("haplotypeIndexLocation"),r=!("uri"in t)||t.uri!=="",o=await Me.open((0,lr.openLocation)(this.getConf("gbzDbLocation"),this.pluginManager),r?{haplotypeIndex:(0,lr.openLocation)(t,this.pluginManager)}:{}),s=this.getConf("assemblyNames")[0];if(s===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let i=(await o.tag("gbwt_reference_samples")??"").split(/\s+/).filter(c=>c!==""),a=Es({configured:this.getConf("referenceSample"),anchorPrefix:Ae(this,s),referenceSamples:i});return{db:o,anchor:s,referenceSample:a,referenceSamples:i}}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r),i=(await o.paths()).find(a=>a.isIndexed&&a.name.sample===s&&a.name.contig===t);return i?{sample:i.name.sample,contig:t,haplotype:i.name.haplotype}:void 0}async getHaplotypes(t={}){let{db:r,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=Se(i.name),c=s.get(a);c?c.contigs.includes(i.name.contig)||c.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:o.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Tt(this),a=[];for(let c of await this.getHaplotypes(t))c.sample!==o&&a.push({name:Kn(i,c),label:c.prefix,group:c.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:Ae(this,i),c=(await r.paths()).filter(f=>i===o?f.isIndexed&&f.name.sample===s:Fe(Se(f.name),a)).map(f=>f.name.contig);return[...new Set(c)]}keepPredicate(t,r){let o=t===void 0||t.length===0?void 0:t.map(s=>Ae(this,s));return o===void 0&&r===void 0?void 0:s=>As(s,o)&&(r===void 0||Fe(Se(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s}=await this.graph(),{assemblyName:i,refName:a,start:c,end:f}=t;if(i!==s)throw new dr(i,s);let l=await this.referenceQuery(a,{}),p=this.getConf("nodeLimit"),d=this.keepPredicate(r.haplotypes),h=l?await o.getSubgraphForRange(l,c,f,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:p,signal:r.signal,...d===void 0?{}:{keep:d}}).catch(u=>{throw Vn(u,p,f-c)??u}):void 0;return h?h.toGFA({names:"resolved"}):""}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:c}=t,f=Ae(this,r.targetAssemblyName),l=Tt(this),p=this.keepPredicate(r.haplotypes,f),d=await this.referenceQuery(i,r),h=this.getConf("nodeLimit");return(d?await(0,Zn.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${c.toLocaleString()}`,r.statusCallback,()=>o.getAlignmentsForRange(d,a,c,{context:this.getConf("context"),haplotypes:"all",limit:h,signal:r.signal,...p===void 0?{}:{keep:p}}).catch(m=>{throw Vn(m,h,c-a)??m})):[]).flatMap(m=>{let w=m.resolved?Rs({alignment:m,assemblyName:s,refName:i,lane:Kn(l,m.name)}):void 0;return w===void 0?[]:[w]})}getFeatures(t,r={}){return(0,Jn.ObservableCreate)(async o=>{let{db:s,anchor:i}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new pr;if(t.assemblyName===i){let a=await this.anchorFeatures(t,r);for(let c of a)o.next(c)}o.complete()},r.signal)}};export{dr as HaplotypeWindowError,pr as NoHaplotypeIndexError,hr as NoReferenceSampleError,ur as NodeLimitError,mr as default,Rs as fragmentFeature,Se as haplotypePrefix,Kn as laneAssemblyName,Vn as nodeLimitError,Es as resolveReferenceSample};
8
+ //# sourceMappingURL=GbzBaseSyntenyAdapter-QT5CVRL2.js.map