jbrowse-plugin-graphgenomeviewer 4.0.26 → 4.0.28
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 +1 -0
- package/dist/chunks/{AddTrackWorkflow-WYRVQYH2.js → AddTrackWorkflow-F6FBBEJM.js} +2 -2
- package/dist/chunks/GbzBaseSyntenyAdapter-FK6PVNBV.js +8 -0
- package/dist/chunks/GbzBaseSyntenyAdapter-FK6PVNBV.js.map +7 -0
- package/dist/chunks/{GraphGenomeView-CGV6NQQZ.js → GraphGenomeView-T2FW4BLC.js} +2 -2
- package/dist/chunks/{GraphTrackSettingsDialog-IK3Y3PW6.js → GraphTrackSettingsDialog-RQ4O7NUQ.js} +2 -2
- package/dist/chunks/{LinearGraphDisplay-ZM6IMPJE.js → LinearGraphDisplay-PIVJ7WE5.js} +2 -2
- package/dist/chunks/MinigraphBubbleAdapter-CK7AE4QT.js +2 -0
- package/dist/chunks/{MinigraphBubbleAdapter-NRDD66AK.js.map → MinigraphBubbleAdapter-CK7AE4QT.js.map} +1 -1
- package/dist/chunks/RgfaTabixAdapter-5MD2ZZ2F.js +3 -0
- package/dist/chunks/{RgfaTabixAdapter-NQEERXXI.js.map → RgfaTabixAdapter-5MD2ZZ2F.js.map} +2 -2
- package/dist/chunks/chunk-22N3NFQP.js +5 -0
- package/dist/chunks/chunk-22N3NFQP.js.map +7 -0
- package/dist/chunks/chunk-4T7DPQTR.js +2 -0
- package/dist/chunks/chunk-4T7DPQTR.js.map +7 -0
- package/dist/chunks/chunk-KDIBFGZM.js +2 -0
- package/dist/chunks/{chunk-JAQ2RQAE.js.map → chunk-KDIBFGZM.js.map} +4 -4
- package/dist/chunks/chunk-Q36VDIWB.js +2 -0
- package/dist/chunks/chunk-Q36VDIWB.js.map +7 -0
- package/dist/chunks/chunk-SGA5LPIL.js +2 -0
- package/dist/chunks/{chunk-MMGD6ESZ.js.map → chunk-SGA5LPIL.js.map} +1 -1
- package/dist/chunks/chunk-T6LGFR3R.js +3 -0
- package/dist/chunks/chunk-T6LGFR3R.js.map +7 -0
- package/dist/chunks/chunk-X2HKDCRG.js +2 -0
- package/dist/chunks/chunk-X2HKDCRG.js.map +7 -0
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +6 -4
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +3 -3
- package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.test.ts +50 -15
- package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.ts +13 -52
- package/src/GbzBaseSyntenyAdapter/companion.ts +4 -4
- package/src/GbzBaseSyntenyAdapter/configSchema.ts +4 -3
- package/src/GraphAddTrackWorkflow/buildTrackConfig.test.ts +60 -0
- package/src/GraphAddTrackWorkflow/buildTrackConfig.ts +19 -6
- package/src/GraphGenomeView/components/GraphCanvas.tsx +21 -23
- package/src/GraphGenomeView/components/ReferenceStripOverlay.tsx +8 -6
- package/src/GraphGenomeView/components/TubeMapOverlay.tsx +2 -0
- package/src/GraphGenomeView/components/legendStyles.ts +0 -3
- package/src/GraphGenomeView/model.test.ts +75 -39
- package/src/GraphGenomeView/model.ts +104 -76
- package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +34 -0
- package/src/LinearGraphDisplay/model.ts +20 -0
- package/src/RgfaTabixAdapter/rgfaBed.test.ts +8 -0
- package/src/RgfaTabixAdapter/rgfaBed.ts +3 -2
- package/src/gaf/gafFile.test.ts +20 -0
- package/src/gaf/gafFile.ts +15 -18
- package/src/graphTrackDefaults/graphTrackDefaults.test.ts +12 -0
- package/src/graphTrackDefaults/index.ts +1 -9
- package/src/hoverSync/graphViewHighlights.test.ts +23 -0
- package/src/hoverSync/graphViewHighlights.ts +4 -6
- package/src/hoverSync/lgvHover.ts +2 -4
- package/src/hoverSync/rowWalks.test.ts +58 -0
- package/src/hoverSync/rowWalks.ts +44 -0
- package/src/isRecord.ts +5 -0
- package/src/launchFromGraph/launchFromGraph.test.ts +3 -2
- package/src/launchFromGraph/launchFromGraph.ts +34 -8
- package/src/launchFromGraph/linearViewTarget.ts +2 -14
- package/src/launchFromGraph/syntenyTracks.test.ts +22 -0
- package/src/launchFromGraph/syntenyTracks.ts +7 -1
- package/src/version.ts +1 -1
- package/dist/chunks/GbzBaseSyntenyAdapter-LTKB3OX7.js +0 -8
- package/dist/chunks/GbzBaseSyntenyAdapter-LTKB3OX7.js.map +0 -7
- package/dist/chunks/MinigraphBubbleAdapter-NRDD66AK.js +0 -2
- package/dist/chunks/RgfaTabixAdapter-NQEERXXI.js +0 -3
- package/dist/chunks/chunk-33VHHB43.js +0 -2
- package/dist/chunks/chunk-33VHHB43.js.map +0 -7
- package/dist/chunks/chunk-BIZ6OLP5.js +0 -3
- package/dist/chunks/chunk-BIZ6OLP5.js.map +0 -7
- package/dist/chunks/chunk-JAQ2RQAE.js +0 -2
- package/dist/chunks/chunk-MMGD6ESZ.js +0 -2
- package/dist/chunks/chunk-NXI6CVEJ.js +0 -2
- package/dist/chunks/chunk-NXI6CVEJ.js.map +0 -7
- package/dist/chunks/chunk-QSH263Y6.js +0 -2
- package/dist/chunks/chunk-QSH263Y6.js.map +0 -7
- package/dist/chunks/chunk-WAW3QC3R.js +0 -2
- package/dist/chunks/chunk-WAW3QC3R.js.map +0 -7
- package/dist/chunks/chunk-XK7OPCRQ.js +0 -2
- package/dist/chunks/chunk-XK7OPCRQ.js.map +0 -7
- /package/dist/chunks/{AddTrackWorkflow-WYRVQYH2.js.map → AddTrackWorkflow-F6FBBEJM.js.map} +0 -0
- /package/dist/chunks/{GraphGenomeView-CGV6NQQZ.js.map → GraphGenomeView-T2FW4BLC.js.map} +0 -0
- /package/dist/chunks/{GraphTrackSettingsDialog-IK3Y3PW6.js.map → GraphTrackSettingsDialog-RQ4O7NUQ.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-ZM6IMPJE.js.map → LinearGraphDisplay-PIVJ7WE5.js.map} +0 -0
package/README.md
CHANGED
|
@@ -47,6 +47,7 @@ node in the view bands its bp in the linear view:
|
|
|
47
47
|
- Seven layouts: force-directed (Bandage FMMM), ordered, anchored, sample rows,
|
|
48
48
|
walk rows, and sequenceTubeMap's tube map on its own axis or the reference's
|
|
49
49
|
- Genes from the session's annotation track, drawn on the graph
|
|
50
|
+
- Hovering a callset or MAF row in the same view lifts that haplotype's walk
|
|
50
51
|
- Bubbles from `gfatools bubble` or the graph itself, opened level by level
|
|
51
52
|
- gbz-base haplotypes as walks: carriage as node thickness, walks lifted out as
|
|
52
53
|
metro-map lanes or side by side, a panel per walk or a row per sample, each
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as F,c as T,i as y}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=AddTrackWorkflow-
|
|
1
|
+
import{b as F,c as T,i as y}from"./chunk-4T7DPQTR.js";import{a as N}from"./chunk-J4OLMLS5.js";import{a as W}from"./chunk-FCWXYIFC.js";import{a as C,b as B,c as H,d as _,e as O}from"./chunk-XEJ47DLD.js";import{a as w,b as t}from"./chunk-FY3BTKY4.js";var S=w((q,L)=>{L.exports=JBrowseExports["@jbrowse/core/util/tss-react"]});var s=t(O(),1),i=t(_(),1),l=t(N(),1),A=t(S(),1),R=t(W(),1),e=t(H(),1),x=t(B(),1);var o=t(C(),1),j=(0,A.makeStyles)()(n=>({paper:{margin:n.spacing(),padding:n.spacing()},field:{marginTop:n.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),D=["RgfaTabixAdapter","MinigraphBubbleAdapter"],J=(0,x.observer)(function({model:r}){let{classes:c}=j(),h=(0,l.getSession)(r),b=(0,R.getRoot)(r),[m,G]=(0,s.useState)("RgfaTabixAdapter"),[p,v]=(0,s.useState)(),[g,P]=(0,s.useState)(),[u,I]=(0,s.useState)(""),[d,M]=(0,s.useState)("Pangenome graph"),[f,k]=(0,s.useState)();function E(){if(!(!p||!r.assembly))try{k(void 0);let a=d.trim();(0,l.addTrackFromWidget)({model:r,session:h,conf:y({choice:m,loc:p,indexLoc:g,assembly:r.assembly,sample:u,trackId:(0,l.makeTrackId)({name:a}),name:a})})}catch(a){k(a)}}return(0,o.jsxs)(e.Paper,{className:c.paper,children:[f?(0,o.jsx)(i.ErrorMessage,{error:f}):null,(0,o.jsxs)(e.FormControl,{children:[(0,o.jsx)(e.FormLabel,{children:"File type"}),(0,o.jsx)(e.RadioGroup,{value:m,onChange:a=>{G(a.target.value)},children:D.map(a=>(0,o.jsx)(e.FormControlLabel,{value:a,control:(0,o.jsx)(e.Radio,{}),label:F[a]},a))})]}),(0,o.jsx)(i.FileSelector,{location:p,name:T[m],rootModel:b,setLocation:v}),(0,o.jsx)(i.FileSelector,{location:g,name:"Path to tabix index (optional; the sibling .tbi is assumed, a .csi is recognised by name)",rootModel:b,setLocation:P}),(0,o.jsx)(e.TextField,{className:c.field,value:u,onChange:a=>{I(a.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare",placeholder:"GRCh38",fullWidth:!0}),(0,o.jsx)(e.TextField,{className:c.field,value:d,helperText:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:a=>{M(a.target.value)}}),(0,o.jsx)(i.AssemblySelector,{session:h,helperText:"Select assembly to add track to",selected:r.assembly,onChange:a=>{r.setAssembly(a)},fullWidth:!0}),(0,o.jsx)(e.Button,{variant:"contained",className:c.submit,disabled:!p||!d.trim()||!r.assembly,onClick:E,children:"Submit"})]})}),K=J;export{K as default};
|
|
2
|
+
//# sourceMappingURL=AddTrackWorkflow-F6FBBEJM.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{a as On,b as Gs,c as Tr,d as $r}from"./chunk-KDIBFGZM.js";import{e as qs,f as Hs,g as Ee,h as Pn,i as Mn,j as wt,k as _n,l as yt,n as Mr,o as kn}from"./chunk-22N3NFQP.js";import{a as _r}from"./chunk-KWAXLUPQ.js";import"./chunk-LGKM2PZH.js";import{a as Bs,d as kr,e as Or,f as Lr}from"./chunk-4T7DPQTR.js";import{a as et}from"./chunk-J4OLMLS5.js";import{a as Nr,b as Fr}from"./chunk-SCMIJAAX.js";import"./chunk-EFVAQ2KM.js";import{e as gt,f as je,g as Rn}from"./chunk-KULNKXPT.js";import{a as $s,b as le}from"./chunk-FY3BTKY4.js";var vs=$s((Pp,Ss)=>{Ss.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function ye(n,e){return 2*n+(e==="reverse"?1:0)}function O(n){return Math.floor(n/2)}function Ue(n){return n%2===0?"forward":"reverse"}function B(n){return n%2===1}function K(n){return n%2===0?n+1:n-1}function qr(n){return n==="left"?"right":"left"}function xt(n){return n==="forward"?"left":"right"}function bt(n){return n==="forward"?"right":"left"}function Hr(n){return n==="left"?"forward":"reverse"}function Gr(n){return n==="right"?"forward":"reverse"}function We(n,e){let t=O(n),r=O(e);return B(n)?r>t||r===t&&!B(e):r>=t}function Br(n){return Ne(n[0],n[n.length-1])}function Ne(n,e){return n===void 0||e===void 0?!0:B(n)===B(e)?!B(n):We(n,e)}var tt=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}}},Dr=255,zs=256,St=class{source;sigma;threshold;constructor(e,t){this.source=new tt(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<Dr?Math.floor(zs/this.sigma):0}next(){if(this.sigma>=Dr){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 zr(n){let e=new tt(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var vt=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new St(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:K(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];O(s.node)===O(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var js=["","A","C","G","T","N"];function jr(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 Ur(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=js[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var Us={A:"T",C:"G",G:"C",T:"A",N:"N"};function It(n){let e="";for(let t=n.length-1;t>=0;t--)e+=Us[n[t]]??"N";return e}function Wr(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 Yr(n){return{name:n.get("pggname"),subgraph:Wr(n.get("subgraph"),"subgraph"),translation:Wr(n.get("translation"),"translation")}}function Qr(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 Xr(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])),Qr(t.subgraph,e.subgraph),Qr(t.translation,e.translation)),t}function Vr(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function Kr(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of Vr(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of Vr(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function Zr(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 Ws="_gbwt_ref";function xe(n,e){return`${n.sample}#${n.haplotype}#${n.contig}[${n.fragment}-${e}]`}var Qs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Vs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ys(n){let e=Qs.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Vs.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 Jr(n){return typeof n=="string"?Ys(n):n}function At(n,e){return{sample:n.sample??Ws,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var Xs=4096;function Ks(n,e){let t=[];for(let[r,o]of[...n].sort((s,i)=>s[0]-i[0])){let s=t[t.length-1];s&&r<=s[1]+e?s[1]=Math.max(s[1],o):t.push([r,o])}return t}function Nn(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=Xs?r[1]=t:e.push([t,t])}return e}var ae=32768,eo=ae/2,to={mostChosenPaths:32},Tn=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let r=this.byNode.get(e.node);r||(r=new Map,this.byNode.set(e.node,r)),r.set(e.offset,t)}},oe=class extends Error{};function nt(n,e,t,r){return n==="forward"?e+t:e-r}function Ln(n,e,t,r){return n==="forward"?e-r:e+t}function no(n){return Ne(K(n.handles[n.handles.length-1]),K(n.handles[0]))}function Fe(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function ro(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let x=performance.now(),C=x-o;return o=x,C},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,seeds:0,pieces:0,sources:{reference:0,sample:0,interval:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,intervals:0,seeds:0,chains:0,twins:0}},a=(x,C)=>{let R=`${x}: ${C}`;i.walks[R]=(i.walks[R]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async x=>{let C=t.get(x)??c.get(x);if(C)return C;let R=await e.getRecord(x);if(i.graphFetches+=1,!R)throw new Error(`Node record ${x} is missing from the database`);return c.set(x,R),R},p=x=>t.get(x).sequenceLen,h=await e.pathsByHandle(),u=x=>{let C=h.get(x);return C!==void 0&&n.keep(C.name)},d=[],m=new Tn,y=new Map,S=new Set,I=new Set,g=async x=>{let C=(await l(x.node)).gbwt().lf(x.offset);return C===void 0||C.node===0?void 0:C},v=async(x,C)=>{let R=(await l(K(x.node))).gbwt().predecessorAt(x.offset);if(R===void 0||C!==void 0&&!C.has(R))return;let D=(await l(R)).gbwt().offsetTo(x);if(D===void 0)throw new Error(`No offset in ${R} leads to ${x.node}:${x.offset}`);return{node:R,offset:D}},b=(x,C,R,D)=>{let V=R.map(de=>de.pos.node),Z=R.map(de=>de.pos.offset),J=0;for(let de of V)J+=p(de);let ee=C==="forward"?R[0].left:R[R.length-1].left,Ie=d.length;d.push({pathHandle:x,orientation:C,handles:V,offsets:Z,len:J,hapStart:ee,hapEnd:ee+J,canonical:Ne(V[0],V[V.length-1]),source:D});for(let de of R)m.set(de.pos,Ie);let Te=y.get(x);return Te?Te.push(Ie):y.set(x,[Ie]),Ie},E=async(x,C,R,D)=>{let V=[],Z=x;for(;;){r?.throwIfAborted();let ee=await v(Z.pos,t);if(!ee)break;Z={pos:ee,left:Ln(R,Z.left,p(Z.pos.node),p(ee.node))},V.push(Z)}V.reverse();let J=[x];for(Z=x;;){r?.throwIfAborted();let ee=await g(Z.pos);if(!ee||!t.has(ee.node))break;Z={pos:ee,left:nt(R,Z.left,p(Z.pos.node),p(ee.node))},J.push(Z)}return b(C,R,[...V,...J],D)},M=async(x,C,R,D)=>d[m.get(x.pos)??await E(x,C,R,D)],L=x=>{let C=x.handles[x.handles.length-1];return{pos:{node:C,offset:x.offsets[x.offsets.length-1]},left:x.orientation==="forward"?x.hapEnd-p(C):x.hapStart}},_=x=>{let C=x.handles[0];return{pos:{node:C,offset:x.offsets[0]},left:x.orientation==="forward"?x.hapStart:x.hapEnd-p(C)}},T=await E({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),P=d[T],G=()=>{if(i.fallback!==void 0)return{reference:P,pieces:[],stats:i};let x=new Map;d.forEach((R,D)=>{D!==T&&x.set(Fe(R),[...x.get(Fe(R))??[],R])});let C=[];for(let R of x.values()){let D=new Set;for(let V of R)V.canonical&&!D.has(V.orientation)&&(D.add(V.orientation),C.push(V),i.sources[V.source]+=1)}return i.sources.reference=1,i.pieces=C.length,{reference:P,pieces:C,stats:i}};try{let x=i.spacing;if(x===void 0)throw new oe("the haplotype index has no anchors");let C=Math.floor(n.window.start/x),R=Math.ceil(n.window.end/x),D=w=>w>=0?e.haplotypeAnchor(n.referenceHandle,w*x):Promise.resolve(void 0),[V,Z]=await Promise.all([Promise.all([0,1,2].map(w=>D(C-w))),Promise.all([0,1,2,3].map(w=>D(R+w)))]),J=V[0],ee=Z.slice(0,2).findIndex(w=>w!==void 0&&w.pathOffset>=n.window.end),Ie=Z[ee];if(!J)throw new oe("the haplotype index has no anchor before the window");if(!Ie)throw new oe("the haplotype index has no anchor after the window");i.anchors=[J.pathOffset,Ie.pathOffset];let Te=V.filter(w=>w!==void 0),de=Z.slice(ee,ee+3).filter(w=>w!==void 0),Ms=w=>{let A=w-w%2;return e.haplotypeSamplesInRange(A,A+1)},pt=new Map,yn=[...Te,...de],_s=await Promise.all(yn.map(w=>Ms(w.node)));if(yn.forEach((w,A)=>pt.set(w,_s[A])),i.anchorsRead=yn.length,!pt.get(J).some(w=>w.pathHandle===n.referenceHandle&&w.orientation==="forward"&&w.pathOffset===J.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${J.pathOffset} (node ${O(J.node)}); it does not match this graph`);let vr=(w,A)=>{for(let k of w){let z=pt.get(k).filter(U=>U.pathHandle===A);if(z.length>0)return{anchor:k,rows:z}}},De=new Map,Je=[],xn=new Set,ks=async w=>{let A=vr(Te,w),k=vr(de,w);if(!A&&!k)return;let z=A?.rows??[],U=k?.rows??[],W=[],N=new Set,j=A?.anchor??J,F=k?.anchor??Ie,$=F.pathOffset-j.pathOffset,ce=u(w),te=!1;for(let q of z){let ie=q.orientation==="forward"?1:-1,Ae=U.filter(_e=>_e.orientation===q.orientation&&(_e.pathOffset-q.pathOffset)*ie>0).sort((_e,Fs)=>(_e.pathOffset-Fs.pathOffset)*ie)[0];if(!Ae)continue;let Me=q.node===j.node,ze=Ae.node===F.node,Y=Ae.pathOffset,ne=0;Me&&!ze?Y+=ie*((await l(Ae.node)).sequenceLen+$):!Me&&ze&&(ne=$);let re=q.pathOffset-ie*ne;W.push([Math.min(re,Y),Math.max(re,Y)]),N.add(q.pathOffset),N.add(Ae.pathOffset),te=!0,ce&&(Je.push({row:q,stopAt:Y,back:ne,kind:Me===ze?"interval":"inversion"}),xn.add(w))}let ue=new Map;for(let q of[...z,...U])te?N.has(q.pathOffset)||(W.push([q.pathOffset,q.pathOffset]),ue.set(q.pathOffset,q)):W.push([q.pathOffset-$,q.pathOffset+$]);let se=Ks(W,ae);if(se.length>1)throw new oe(`path ${w} visits the anchors from ${se.length} copies of the region, at ${se.map(([q,ie])=>`${q}-${ie}`).join(", ")}`);if(De.set(w,se[0]),ce)for(let q of ue.values())Je.push({row:q,stopAt:q.pathOffset,back:0,kind:"interval"});if(!te){for(let q of[...z,...U])if(ce&&(q.node===j.node||q.node===K(F.node))){let ie=q.orientation==="forward"?1:-1;Je.push({row:q,stopAt:q.pathOffset+ie*$,back:0,kind:"one-sided"}),xn.add(w)}}return te?"paired":"one-sided"},Ir=new Set([...pt.values()].flat().map(w=>w.pathHandle)),ht=[...Ir].filter(u);if(i.chosenPaths=ht.length,ht.length>to.mostChosenPaths)throw new oe(`${ht.length} chosen paths pass the anchors, more than ${to.mostChosenPaths}`);for(let w of Ir)await ks(w);let bn=[],Sn=[];i.scans=Nn([...t.keys()].sort((w,A)=>w-A));for(let[w,A]of i.scans)for(let k of await e.haplotypeSamplesInRange(w,A))i.scanRows+=1,t.has(k.node)&&(Sn.push(k),u(k.pathHandle)&&bn.push(k));if(ht.length===0&&bn.length===0&&[...h.values()].some(w=>n.keep(w.name)))throw new oe("no chosen path passes the anchors or has a sample on the window's nodes");let vn=new Set(Sn.map(w=>w.pathHandle).filter(w=>!De.has(w))),Os=de[de.length-1].pathOffset-Te[Te.length-1].pathOffset,Ar=w=>`${w.sample}#${w.haplotype}#${w.contig}`,In=new Map;for(let[w,[A,k]]of De){let z=h.get(w)?.name;if(z&&u(w)){let U=Ar(z),W=z.fragment+A-ae,N=z.fragment+k+ae,j=In.get(U);In.set(U,j?[Math.min(j[0],W),Math.max(j[1],N)]:[W,N])}}let Er=[];for(let[w,A]of h){let k=In.get(Ar(A.name));if(k&&!De.has(w)&&!vn.has(w)&&n.keep(A.name)){let z=await e.haplotypeLength(w)??0;A.name.fragment<k[1]&&A.name.fragment+z>k[0]&&Er.push(w)}}for(let w of[...vn,...Er]){let A=await e.haplotypeLength(w)??Number.POSITIVE_INFINITY;if(A>Os+2*ae)throw new oe(vn.has(w)?`path ${w} of ${A} bp has a sample on the window's nodes and no visit to the anchors`:`chosen fragment ${w} of ${A} bp lies beside its contig's visits to the anchors without a visit of its own`);if(u(w)){let k=(await e.getPath(w))?.fwStart;if(!k)throw new Error(`Path ${w} is missing from the database`);Je.push({row:{node:k.node,offset:k.offset,pathHandle:w,orientation:"forward",pathOffset:0},stopAt:A,back:0,kind:"whole"})}}for(let w of De.keys())if(u(w)&&!xn.has(w))throw new oe(`chosen path ${w} has no walk from its visits to the anchors`);for(let w of Sn){let A=De.get(w.pathHandle);if(A&&(w.pathOffset<A[0]-eo||w.pathOffset>A[1]+eo))throw new oe(`path ${w.pathHandle} has a sample at ${w.pathOffset} on the window's nodes far from its anchor visits at ${A[0]}-${A[1]}`)}i.ms.scan=s();let An=new Map;await n.prefetchReferenceRange(n.referenceHandle,Math.max(0,J.pathOffset-ae),Ie.pathOffset+ae+1);let Cr=8*x+2*(n.window.end-n.window.start);for(let{row:w,stopAt:A,back:k,kind:z}of Je){let U=w.orientation,W=(Y,ne)=>U==="forward"?ne-Y:Y-ne,N=w.pathOffset,j=w.pathOffset,F={node:w.node,offset:w.offset},$=w.pathOffset,ce=!1,te=0,ue=0,se="past the far anchor";for(;F&&(r?.throwIfAborted(),!ce&&W($,A)<=-ae&&(ce=!0),!(ce&&te>ae));){let Y;if(t.has(F.node)){let re=await M({pos:F,left:$},w.pathHandle,U,"interval"),_e=L(re);F=_e.pos,$=_e.left,Y=p(_e.pos.node),N=Math.min(N,re.hapStart),j=Math.max(j,re.hapEnd),te=0}else{if(Y=(await l(F.node)).sequenceLen,te+=Y,ue+=Y,ue>Cr){se="cap";break}N=Math.min(N,$),j=Math.max(j,$+Y)}let ne=await g(F);ne&&($=nt(U,$,Y,(await l(ne.node)).sequenceLen)),F=ne}if(!F&&se!=="cap"&&(se="endmarker"),a(z,se),se==="cap")throw new oe(`the walk of path ${w.pathHandle} between the anchors reached its cap of ${Cr} bp`);if(z==="one-sided"&&se!=="endmarker")throw new oe(`chosen path ${w.pathHandle} runs on past the stretch from its visit to one anchor without a visit to the other`);let q=ae,ie={pos:{node:w.node,offset:w.offset},left:w.pathOffset},Ae=0,Me=k;for(;q>0||Me>0;){r?.throwIfAborted();let Y=await v(ie.pos);if(!Y)break;let ne=Ln(U,ie.left,(await l(ie.pos.node)).sequenceLen,(await l(Y.node)).sequenceLen);if(t.has(Y.node)){let re=await M({pos:Y,left:ne},w.pathHandle,U,"interval");ie=_(re),N=Math.min(N,re.hapStart),j=Math.max(j,re.hapEnd),q=ae,Ae=0,Me-=re.len}else{let re=(await l(Y.node)).sequenceLen;if(Ae+=re,Ae>q&&Me<=0)break;Me-=re,ie={pos:Y,left:ne},N=Math.min(N,ne),j=Math.max(j,ne+re)}}let ze=An.get(w.pathHandle);ze?ze.push([N,j]):An.set(w.pathHandle,[[N,j]])}let Ls=w=>(An.get(w.pathHandle)??[]).some(([A,k])=>A<=w.hapStart&&w.hapEnd<=k);i.ms.intervals=s();for(let w of bn)m.get(w)===void 0&&!(y.get(w.pathHandle)??[]).some(A=>{let k=d[A];return k.canonical&&!no(k)&&k.hapStart<=w.pathOffset&&w.pathOffset<k.hapEnd})&&(i.seeds+=1,await E({pos:{node:w.node,offset:w.offset},left:w.pathOffset},w.pathHandle,w.orientation,"sample"));i.ms.seeds=s();let dt=async(w,A)=>{let k=A?S:I,z=A?I:S,U=w;for(;;){if(k.has(U))return;k.add(U);let W=d[U],N=A?L(W):_(W),j=0,F;for(;F===void 0;){r?.throwIfAborted();let $=A?await g(N.pos):await v(N.pos);if(!$){F="endmarker";break}let ce=(await l(N.pos.node)).sequenceLen,te=(await l($.node)).sequenceLen,ue=A?nt(W.orientation,N.left,ce,te):Ln(W.orientation,N.left,ce,te);if(t.has($.node)){let se=m.get($);se===void 0?(U=await E({pos:$,left:ue},W.pathHandle,W.orientation,"chain"),z.add(U),F="landed"):(z.add(se),F="merge")}else j>ae?F="bound":(j+=te,N={pos:$,left:ue})}if(a("chain",F),F!=="landed")return}};await Promise.all([n.prefetchReferenceRange(n.referenceHandle,Math.max(0,P.hapStart-ae),P.hapStart),n.prefetchReferenceRange(n.referenceHandle,P.hapEnd,P.hapEnd+ae)]);let Rr=new Set,Ts=d.map((w,A)=>({piece:w,id:A})).filter(({piece:w,id:A})=>A!==T&&!Ls(w)).sort((w,A)=>Number(A.piece.canonical)-Number(w.piece.canonical));for(let{piece:w,id:A}of Ts)Rr.has(Fe(w))||(Rr.add(Fe(w)),await dt(A,!0),await dt(A,!1));i.ms.chains=s();let En=new Map,Ns=w=>{let A=Fe(w),k=En.get(A);k?k.add(w.orientation):En.set(A,new Set([w.orientation]))},ut=0,Cn=()=>{for(;ut<d.length;ut++)ut!==T&&Ns(d[ut])};Cn();let mt=w=>(En.get(Fe(w))?.size??0)>1,Pr=2*f;for(let w=0;w<d.length;w++){let A=d[w];if(w===T||mt(A)||A.canonical&&!no(A))continue;i.twins.tried+=1;let k=A.orientation==="forward"?"reverse":"forward",z=L(A),U=0,W;for(;!W&&U<=Pr;){r?.throwIfAborted();let F=await g(z.pos);if(!F)break;let $=(await l(F.node)).sequenceLen,ce=nt(A.orientation,z.left,(await l(z.pos.node)).sequenceLen,$),te=K(F.node);W=(await e.haplotypeSamplesInRange(te,te)).find(ue=>ue.pathHandle===A.pathHandle&&ue.orientation===k&&ue.pathOffset===ce),U+=$,z={pos:F,left:ce}}let N=W&&{pos:{node:W.node,offset:W.offset},left:W.pathOffset},j=0;for(;N&&!mt(A)&&j<=Pr+A.len;){if(r?.throwIfAborted(),t.has(N.pos.node)){let F=await M(N,A.pathHandle,k,"twin"),$=d.indexOf(F);await dt($,!0),await dt($,!1),Cn(),N=L(F)}if(!mt(A)){let F=(await l(N.pos.node)).sequenceLen;j+=F;let $=await g(N.pos);N=$?{pos:$,left:nt(k,N.left,F,(await l($.node)).sequenceLen)}:void 0}}if(Cn(),!mt(A))throw new oe(`piece ${Fe(A)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()}catch(x){if(!(x instanceof oe))throw x;i.fallback=x.message}return G()}function oo(n,e){let t=n.handles[0],r=e.handles[0];return Number(B(t))-Number(B(r))||t-r||n.offsets[0]-e.offsets[0]}function Et(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var Ct=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},Fn=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Et(a,o)-Et(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),p=Et(c,o),h=Et(c,s);for(let u=0;u<h-p;u++){let d=r===1?c[h-1-u]-o:s-1-c[p+u],m=i.bestBefore(d),y=(m===-1?0:i.ending[m])+l;if(y>i.ending[d]&&(i.raise(d,y),a)){let S=a.count++;a.row[S]=f,a.column[S]=d,a.previous[S]=m===-1?-1:a.endingMatch[m],a.endingMatch[d]=S}}}}chain(e,t,r,o,s){let i=new Ct(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let f=i.bestBefore(o-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,o,s){let i=new Ct(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let f=0;f<s-o;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(r-1,t-1,-1,o,s),c=0,l=-1;for(let p=0;p<=i;p++){let h=a[p]+f[i-p];h>l&&(l=h,c=p)}return o+c}};function so(n,e,t){let r=new Fn(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Zs=100,Hn=4e6,Js=5e3,pe=15,ei=64,ti=8,ho=1,Gn=-4,fe=-6,Ce=-1,Qe=-(2**30),Pt=0,$n=1,uo=2;function $e(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function Rt(n,e,t){return n>=t&&n>=e?Pt:t>=e?uo:$n}function mo(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Qe),f=new Int32Array(s).fill(Qe),c=new Int32Array(s).fill(Qe);a[0]=0;for(let d=1;d<=o;d++)c[d]=fe+(d-1)*Ce,i[d]=(d===1?Pt:uo)<<4;for(let d=1;d<=r;d++){let m=new Int32Array(s).fill(Qe),y=new Int32Array(s).fill(Qe),S=new Int32Array(s).fill(Qe);y[0]=fe+(d-1)*Ce,i[d*s]=(d===1?Pt:$n)<<2;let I=n.charCodeAt(d-1);for(let g=1;g<=o;g++){let v=Rt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(I===e.charCodeAt(g-1)?ho:Gn);let b=Rt(a[g]+fe,f[g]+Ce,c[g]+fe);y[g]=Math.max(a[g]+fe,f[g]+Ce,c[g]+fe);let E=Rt(m[g-1]+fe,y[g-1]+fe,S[g-1]+Ce);S[g]=Math.max(m[g-1]+fe,y[g-1]+fe,S[g-1]+Ce),i[d*s+g]=v|b<<2|E<<4}a=m,f=y,c=S}let l=[],p=r,h=o,u=Rt(a[o],f[o],c[o]);for(;p>0||h>0;){let d=i[p*s+h]>>2*u&3;u===Pt?(l.push(n[p-1]===e[h-1]?"=":"X"),p-=1,h-=1):u===$n?(l.push("I"),p-=1):(l.push("D"),h-=1),u=d}for(let d of l.reverse())$e(t,d,1)}function ni(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-fe-(t-1)*Ce,-fe+10*Math.log2(t)))+(Math.min(n,e)>0?-Gn:0)}function go(n,e){let t=Math.abs(n-e);return t===0?0:.01*pe*t+.5*Math.log2(t)}function io(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 ri(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-n.qs),l=Math.min(r,f-n.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,n.flipped?n.te-f:a-n.ts),l=Math.min(r,n.flipped?n.te-a:f-n.ts);c<l&&o.push([c,l])}if(o.length===0)return[n];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=pe&&s.push(io(n,i,a)),i=Math.max(i,f);return r-i>=pe&&s.push(io(n,i,r)),s}function Bn(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...n].sort((c,l)=>c.qs-l.qs||c.ts-l.ts);for(;f.length>0&&s.length<o;){let c=f.map(g=>g.qe-g.qs),l=new Int32Array(f.length).fill(-1),p=new Int32Array(f.length);for(let g=0;g<f.length;g++){let v=f[g],b=v.qe-v.qs;for(let E=g-1;E>=Math.max(0,g-Js);E--){if(c[E]+b<=c[g])continue;let M=f[E];if(M.flipped===v.flipped&&M.qs<v.qs&&(v.flipped?v.te<M.te:M.ts<v.ts)){let _=Math.max(0,M.qe-v.qs,v.flipped?v.te-M.ts:M.te-v.ts),T=v.qs+_-M.qe,P=v.flipped?M.ts-(v.te-_):v.ts+_-M.te;if(_<b&&T<=e&&P<=e){let G=c[E]+b-_-r(T,P);G>c[g]&&(c[g]=G,l[g]=E,p[g]=_)}}}}let h=0;for(let g=1;g<f.length;g++)c[g]>c[h]&&(h=g);let u=[];for(let g=h;g>=0;g=l[g])u.push({run:f[g],trim:p[g]});if(u.reverse(),u.reduce((g,{run:v,trim:b})=>g+v.qe-v.qs-b,0)<t)break;s.push(u);let m=u[0],y=u.at(-1),{flipped:S}=m.run,I=S?a.flipped:a.forward;I.query.push([m.run.qs+m.trim,y.run.qe]),I.target.push(S?[y.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,y.run.te]);for(let{run:g,trim:v}of u)i.query.push([g.qs+v,g.qe]),i.target.push(g.flipped?[g.ts,g.te-v]:[g.ts+v,g.te]);f=f.flatMap(g=>{let v=g.flipped?a.flipped:a.forward;return ri(g,[...i.query,...v.query],[...i.target,...v.target])}).sort((g,v)=>g.qs-v.qs||g.ts-v.ts)}return s}function qn(n,e){let t=new Map;for(let s=0;s+pe<=e.length;s++){let i=e.slice(s,s+pe),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+pe<=n.length;s++){let i=t.get(n.slice(s,s+pe));if(i&&i.length<=ei)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+pe,c.te=a+pe;else{let l={qs:s,qe:s+pe,ts:a,te:a+pe,flipped:!1};o.set(f,l),r.push(l)}}}return r}function oi(n,e){return[...qn(n,e),...qn(n,It(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Mt(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,p=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?It(p):p,r,s.qe,c)}$e(r,"=",i.qe-f),s=i}}function Dn(n,e,t){$e(t,"I",n.length),$e(t,"D",e.length)}function wo(n,e,t){n.length*e.length<=Hn?mo(n,e,t):Dn(n,e,t)}function zn(n,e,t,r=0){let[o]=n.length*e.length>Hn&&r<ti?Bn(qn(n,e),1/0,pe,go,1):[];if(!o){wo(n,e,t);return}let s=(f,c,l)=>{zn(f,c,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),Mt(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function si(n,e,t){zn(n,e,t)}function ii(n,e,t){let r=[];Mt(n,e,t,r,si);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 ai(n,e,t,r){let o=[];if(n.length*e.length<=Hn)mo(n,e,t);else{let s=Bn(oi(n,e),1/0,Math.max(r,pe),go),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>ii(a,n,e)),i){let a=(l,p,h,u,d)=>{o.some(y=>u<y.queryEnd&&y.queryStart<u+l.length||d<y.targetEnd&&y.targetStart<d+p.length)?wo(l,p,h):zn(l,p,h)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Mt(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else Dn(n,e,t)}return o}function jn(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 ao(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return jn(n,(i,a,f,c)=>{let l=e==="query"?f:c,p=h=>{let u=l+o*h;return u>=t&&u<r};if(i==="="||i==="X")for(let h=0;h<a;h++)p(h)&&(s+=i==="="?ho:Gn);else if(i==="I"==(e==="query"))for(let h=0;h<a;h++)p(h)&&(s+=h===0?fe:Ce);else p(0)&&(s+=fe+(a-1)*Ce)}),s}function fo(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function fi(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,f=new Uint8Array(n.queryEnd-n.queryStart);for(let[u,d]of n.shared)f.fill(1,u-n.queryStart,d-n.queryStart);let c=u=>f[u-n.queryStart]===1,l=()=>{$e(r,"I",o),$e(r,"D",s),o=0,s=0};jn(n,(u,d,m)=>{if(u==="I")o+=d;else if(u==="D")s+=d;else{for(let y=0;y<d;y++)e[i+y]?(o+=1,s+=1,c(t?m-y:m+y)&&(a+=1)):((o>0||s>0)&&l(),$e(r,u,1));i+=d}}),l();let p={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[u,d]=r.shift();p[u]+=d}let h={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[u,d]=r.pop();h[u]+=d}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?h.I:p.I),queryEnd:n.queryEnd-(t?p.I:h.I),targetStart:n.targetStart+p.D,targetEnd:n.targetEnd-h.D,edits:r,sharedBases:n.sharedBases-a}}function ci(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];jn(c,(p,h,u,d)=>{if(p==="="||p==="X")for(let m=0;m<h;m++)l.push([c.strand==="-"?u-m:u+m,d+m])});for(let[p,h]of l)o.query[p]=Math.min(255,o.query[p]+1),o.target[h]=Math.min(255,o.target[h]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[p,h]of c)for(let[u,d]of[["query",p],["target",h]])if(o[u][d]>1){let m=i[u].get(d);m?m.at(-1)!==l&&m.push(l):i[u].set(d,[l])}});let a=new Map,f=(c,l,p)=>{let h=`${p}:${c}:${l}`,u=a.get(h);if(u===void 0){let[d,m]=fo(n[c],p),[y,S]=fo(n[l],p),I=Math.max(d,y),g=Math.min(m,S),[v,b]=[n[c],n[l]];u=[ao(b,p,I,g)-ao(v,p,I,g),b.sharedBases-v.sharedBases,c-l].find(M=>M!==0)>0,a.set(h,u)}return u};return n.flatMap((c,l)=>{let p=s[l],h=new Uint8Array(p.length);if(p.forEach(([m,y],S)=>{for(let[I,g]of[["query",m],["target",y]])!h[S]&&i[I].get(g)?.some(v=>v!==l&&f(l,v,I))&&(h[S]=1)}),!h.includes(1))return[c];let u=fi(c,h),d=u?.edits.reduce((m,[y,S])=>m+(y==="="?S:0),0)??0;return u&&d>=r?[u]:[]})}function co(n,e){return n.map(t=>{let r=e(O(t));return B(t)?It(r):r}).join("")}function lo(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(O(r)).length);return t}function po(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=O(i);e.has(f)?t.set(f,a):e.set(f,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function li(n,e,t,r){let o=po(n),s=po(e),i=new Map;e.forEach((p,h)=>{s[h]||i.set(O(p),[h])});let a=2*e.length,f=(p,h,u)=>p*a+2*h+(u?1:0),c=new Set;n.forEach((p,h)=>{for(let u of o[h]?[]:i.get(O(p))??[])c.add(f(h,u,B(p)!==B(e[u])))});let l=[];return n.forEach((p,h)=>{for(let u of o[h]?[]:i.get(O(p))??[]){let d=B(p)!==B(e[u]),m=d?-1:1;if(!c.has(f(h-1,u-m,d))){let y=h,S=u;for(;y<n.length&&S>=0&&S<e.length&&c.has(f(y,S,d));)y+=1,S+=m;let I=S-m;l.push({qs:t[h],qe:t[y],ts:r[Math.min(u,I)],te:r[Math.max(u,I)+1],flipped:d})}}}),l}function yo(n,e,t,r={}){let o=co(n,t),s=co(e,t),i=li(n,e,lo(n,t),lo(e,t)),a=r.minMatch??Zs,f=r.bases??!0,c=[];for(let l of Bn(i,r.maxGap??1/0,a,ni)){let p=[],h=l[0],u=l.at(-1),{flipped:d}=h.run;Mt(l,o,s,p,f?(y,S,I,g,v)=>{for(let b of ai(y,S,I,a)){let E=v+S.length;c.push({...b,queryStart:g+b.queryStart,queryEnd:g+b.queryEnd,targetStart:d?E-b.targetEnd:v+b.targetStart,targetEnd:d?E-b.targetStart:v+b.targetEnd,strand:d?"+":"-",edits:d?b.edits.reverse():b.edits,shared:[]})}}:Dn),c.push({queryStart:h.run.qs+h.trim,queryEnd:u.run.qe,targetStart:d?u.run.ts:h.run.ts+h.trim,targetEnd:d?h.run.te-h.trim:u.run.te,strand:d?"-":"+",edits:d?p.reverse():p,sharedBases:l.reduce((y,{run:S,trim:I})=>y+S.qe-S.qs-I,0),shared:l.map(({run:y,trim:S})=>[y.qs+S,y.qe])})}return ci(c,o.length,s.length,a).map(({shared:l,...p})=>p).sort((l,p)=>l.queryStart-p.queryStart)}function xo(n){return n.map(([e,t])=>`${t}${e}`).join("")}var ke=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 Un(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var rt=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Un(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&&Un(e[s],e[a])&&(a=s),i<e.length&&Un(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 pi(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 hi(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function qe(n){return`${n.node}:${n.offset}`}function bo(n){return n.map(e=>K(e)).reverse()}function di(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 ui(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);vo(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=n.identity.walkForward,[a,f]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,pieces:[...a.pieces,...f.pieces],soloAligned:[...a.soloAligned,...f.soloAligned],identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function mi(n,e,t){if(n.some(i=>i.weight!==void 0))return n;let r=new Map;n.forEach((i,a)=>{if(i.identity){let f=r.get(i.identity.pathHandle);f?f.push(a):r.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of r.values()){i.sort((l,p)=>n[l].identity.hapStart-n[p].identity.hapStart);let a=i[0],f=n[a],c=[];for(let l of i.slice(1)){let p=n[l],h=c.length===0?di(f,p):void 0;if(h){f=ui(f,p,h),s.add(l);continue}if(!e(p)){c.push(l);continue}let u=e(f)?t([f,...c.map(d=>n[d]),p]):void 0;if(u){f=u;for(let d of[...c,l])s.add(d)}else o.set(a,f),a=l,f=p;c=[]}o.set(a,f)}return n.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function _t(n,e){return{node:n.path[e],offset:n.offsets[e]}}var gi=32768;function wi(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]<=gi?o[1]=r:t.push([r,r])}return t}var Lt=class{records=new Map;paths=[];twinStarts=new Set;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;stats={orderedAlignments:0,lcsAlignments:0,identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t={}){this.db=e,this.limit=t.limit,this.signal=t.signal}get nodeCount(){return this.records.size/2}get pathCount(){return this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(ye(e,"forward"))}hasHandle(e){return this.records.has(e)}record(e){let t=this.records.get(e);if(!t)throw new Error(`Subgraph has no record for handle ${e}`);return t}sortedHandles(){return[...this.records.keys()].sort((e,t)=>e-t)}async addNode(e){if(this.signal?.throwIfAborted(),this.limit!==void 0&&this.nodeCount>=this.limit)throw new ke(this.limit);let t=await this.db.getRecord(ye(e,"forward")),r=await this.db.getRecord(ye(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering ${xe(e,e.fragment)}`);if(!t.isIndexed)throw new Error(`Path ${xe(t.name,t.name.fragment)} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`Path ${xe(t.name,t.name.fragment)} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(O(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`Path ${xe(e.name,e.name.fragment)} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=O(e);await this.ensureNode(o);let s=this.record(e),i=Ue(e),a=new rt;return a.push(t,o,xt(i)),a.push(s.sequenceLen-t-1,o,bt(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords(Math.min(i,a),Math.max(i,a)+1)){let c=await this.db.indexedPositionsBetween(e,t,r),l=wi(c.map(p=>p.pos.node));await Promise.all(l.map(([p,h])=>this.db.prefetchRecords(p,h+2)))}}return o}async aroundInterval(e,t,r){if(t===0)throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof ke&&o.windowBp===void 0?new ke(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new rt;for(;;){let f=O(o.node),c=Ue(o.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,xt(c));let p=l.sequenceLen-s;if(i<=p){a.push(i===p?0:p-i-1,f,bt(c));break}a.push(0,f,bt(c));let h=l.gbwt().lf(o.offset);if(!h)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=h,s=0,i-=p}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new rt;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths();let r=new Set,o=new Set;for(let i of this.records.keys())o.add(O(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=qr(f);if(!r.has(`${a}:${l}`)){let u=this.record(ye(a,Hr(f))),d=i+u.sequenceLen-1;d<=t&&e.push(d,a,l)}let p=this.record(ye(a,Gr(f))),h=i+1;if(h<=t)for(let u of p.successors()){let d=O(u),m=xt(Ue(u));r.has(`${d}:${m}`)||e.push(h,d,m)}}for(let i of o)this.records.delete(ye(i,"forward")),this.records.delete(ye(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){this.clearPaths();let r=[e,K(t)],o=new Set([O(e),O(t)]),s=0;for(;r.length>0;){let i=r.pop(),a=O(i);this.hasNode(a)||(await this.addNode(a),s+=1);for(let f of this.record(i).successors()){let c=O(f);o.has(c)||(r.push(f,K(f)),o.add(c))}}return s}async extractSnarls(e){let t=0;for(let[r,o]of await this.overlappingSnarls(e))t+=await this.betweenNodes(r,o);return t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?We(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(K(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(K(l))).successors().length>1},r=async f=>{let c=await e(K(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[K(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=O(f);if(!this.hasHandle(f)&&!o.has(c)){o.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let p of["forward","reverse"])s.push(...(await e(ye(c,p))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((b,E)=>i.set(b,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let b=0;b<s;b++){let E=this.record(o[b]),M=E.gbwt().decompressArrays();f[b]=E.sequenceLen,c.push(M),a[b+1]=a[b]+M.nodes.length}let l=a[s],p=new Int32Array(l),h=new Int32Array(l),u=new Uint8Array(l);for(let b=0;b<s;b++){let E=c[b];p.set(E.nodes,a[b]),h.set(E.offsets,a[b])}c.length=0;for(let b=0;b<l;b++){let E=i.get(p[b]);E===void 0?p[b]=-1:(p[b]=E,u[a[E]+h[b]]=1)}let d=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,y,S=(b,E,M)=>{let L=[],_=0,T=0,P=-1,G=b,x=E;for(;;){G===d&&x===m&&(P=_),M&&(M.push(o[G]),L.push(x)),_+=1,T+=f[G];let C=a[G]+x,R=p[C];if(R<0)break;x=h[C],G=R}return{offsets:L,len:T,refAt:P,last:G}},I=(b,E,M,L)=>{L>=0&&(this.refId=this.paths.length,y=L),this.paths.push({path:b,offsets:E,len:M,weight:void 0,identity:void 0})},g=new Int32Array(s),v=d!==void 0&&B(o[d]);for(let b=0;b<s;b++){let E=o[b];if(!B(E)){let M=a[b],L=a[b+1]-M;for(let _=0;_<L;_++)if(u[M+_]===0){let T=[],{offsets:P,len:G,refAt:x,last:C}=S(b,_,T),R=o[C];if(x>=0||Ne(E,R)){if(I(T,P,G,x),!B(R)){let D=i.get(K(R));g[D]=g[D]+1}}else this.twinStarts.add(qe({node:E,offset:_}))}}}for(let b=0;b<s;b++){let E=o[b];if(B(E)){let M=a[b],L=a[b+1]-M,_=0;for(let P=0;P<L;P++)u[M+P]===0&&(_+=1);let T=!v&&_===g[b];for(let P=0;P<L;P++)if(u[M+P]===0){let G=T?void 0:S(b,P,void 0);if(G&&(G.refAt>=0||Ne(E,o[G.last]))){let x=[],{offsets:C,len:R,refAt:D}=S(b,P,x);I(x,C,R,D)}else this.twinStarts.add(qe({node:E,offset:P}))}}}if(r){if(y===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let b=this.paths[this.refId],E=r.nodeOffset;for(let L of b.path.slice(0,y))E+=this.record(L).sequenceLen;let M=r.seqOffset-E;this.refInterval=[M,M+b.len],b.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:M,hapEnd:M+b.len}}if(t==="distinct")this.distinctPaths();else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(){let e=this.refId===void 0?void 0:this.paths[this.refId].path;this.paths.sort((o,s)=>Wn(o.path,s.path)||o.len-s.len);let t=[],r;for(let o of this.paths){let s=t[t.length-1];s&&Wn(s.path,o.path)===0?s.weight=(s.weight??0)+1:(e&&Wn(o.path,e)===0&&(r=t.length),t.push({...o,weight:1}))}this.paths=t,this.refId=r}keepHaplotypes(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=this.paths.filter((s,i)=>i===this.refId||s.identity!==void 0&&e(s.identity.name)),o=new Set;for(let s of r)for(let i of s.path)o.add(O(i));for(let s of[...this.records.keys()])o.has(O(s))||this.records.delete(s);this.paths=r,this.refId=t===void 0?void 0:r.indexOf(t)}async extractChosenPaths(e,t,r){this.clearPaths();let o=e.position.seqOffset,s=await ro({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},keep:r,signal:this.signal,prefetchReferenceRange:(c,l,p)=>this.prefetchReferenceRange(c,l,p)});if(this.stats.keep=s.stats,s.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),a=c=>({path:c.handles,offsets:c.offsets,len:c.len,weight:void 0,identity:{pathHandle:c.pathHandle,name:c===s.reference?e.name:i.get(c.pathHandle).name,orientation:c.orientation,hapStart:c.hapStart,hapEnd:c.hapEnd}}),f=[s.reference,...s.pieces].sort(oo);return this.paths=f.map(a),this.refId=f.indexOf(s.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[s.reference.hapStart,s.reference.hapEnd],!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");let e=await this.db.haplotypeSampleInterval()??4096,t=Nn(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[d,m]of t)for(let y of await this.db.haplotypeSamplesInRange(d,m))r.set(qe(y),y);let o=d=>{let m=0,y=t.length-1;for(;m<y;){let I=m+y+1>>1;t[I][0]<=d?m=I:y=I-1}let S=t[m];return S[0]<=d&&d<=S[1]},s=new Map;this.paths.forEach((d,m)=>{d.path.length>0&&m!==this.refId&&s.set(qe(_t(d,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((d,m)=>{m!==this.refId&&i.fragmentLengths.push(d.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),f=d=>(i.graphLookups+=1,a(d)),c=async(d,m)=>{if(o(d.node))return r.get(qe(d));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let y=await this.db.haplotypeSampleAt(d.node,d.offset);return y||(i.companionMisses+=1),y},l=new Map,p=async d=>{let m=l.get(d);if(!m){let y=await this.db.getPath(d);if(!y)throw new Error(`Path ${d} is missing from the database`);m=y.name,l.set(d,m)}return m},h=(d,m,y)=>d.orientation==="forward"?{pathHandle:d.pathHandle,orientation:"forward",base:d.pathOffset-m}:{pathHandle:d.pathHandle,orientation:"reverse",base:d.pathOffset+m+y},u=(d,m)=>d.orientation==="forward"?{pathHandle:d.pathHandle,orientation:"forward",base:d.hapStart-m}:{pathHandle:d.pathHandle,orientation:"reverse",base:d.hapEnd+m};for(let d=0;d<this.paths.length;d++){let m=this.paths[d];if(d===this.refId||m.identity)continue;let y=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let g,v=0,b=d,E;for(;g===void 0;){if(this.signal?.throwIfAborted(),b!==void 0){if(S.has(b)){I.end="cycle";break}S.add(b);let P=this.paths[b];y.push({index:b,startBp:v}),I.fragments+=1;let G=v;for(let C=0;C<P.path.length;C++){let R=_t(P,C),D=r.get(qe(R)),V=this.record(R.node).sequenceLen;if(D){g=h(D,G,V);break}G+=V}if(v+=P.len,g){I.end="in-fragment sample";break}let x=_t(P,P.path.length-1);E=this.record(x.node).gbwt().lf(x.offset),b=void 0}if(E===void 0||E.node===0){I.end="endmarker";break}let M=qe(E),L=s.get(M);if(L!==void 0){let P=this.paths[L].identity;if(P){g=u(P,v),I.end="identified sibling";break}b=L;continue}this.records.has(E.node)&&(I.reentries+=1),this.twinStarts.has(M)&&(I.twinLandings+=1);let _=await c(E,I),T=await f(E.node);if(_){g=h(_,v,T.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,v-y[y.length-1].startBp>4*e+4*T.sequenceLen){I.end="bound";break}v+=T.sequenceLen,E=T.gbwt().lf(E.offset)}if(g){I.pathHandle=g.pathHandle;let M=await p(g.pathHandle);for(let{index:L,startBp:_}of y){let T=this.paths[L];T.identity=g.orientation==="forward"?{pathHandle:g.pathHandle,name:M,orientation:"forward",hapStart:g.base+_,hapEnd:g.base+_+T.len}:{pathHandle:g.pathHandle,name:M,orientation:"reverse",hapStart:g.base-_-T.len,hapEnd:g.base-_}}}}}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=hi(c,a);if(l===void 0)return;o[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[o]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[e.length-o-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),X(r,"M",i),vo(r,o-i-a,s-i-a),X(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??pi(so(e,t,p=>this.record(p).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(p,h,u,d)=>{p===h?X(s,"D",i[d]-i[u]):u===d?X(s,"I",this.pathLen(e.slice(p,h))):this.align(e.slice(p,h),t.slice(u,d),s)},f=0,c=0,l=0;for(let p=0;p<o.count;p++){let h=o.pathAt[p],u=o.refAt[p];(c!==h||l!==u)&&a(c,h,l,u);let d=this.record(e[h]).sequenceLen;X(s,"M",d),f+=d,c=h+1,l=u+1}return a(c,e.length,l,t.length),{edits:s,matched:f,matches:o}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(Br(r))o={...this.editsAgainst(t.path,r),flipped:!1};else{let s=bo(t.path),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={...this.editsAgainst(t.path,r),flipped:!1};else if(i===0)o={...this.editsAgainst(s,r),flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.alignment(e)?.edits.map(([t,r])=>`${r}${t}`).join("")}alignments(){let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,r=this.refPrefix(t)[t.length],o=(l,p,h,u)=>{let d=xi(l),m=this.paths[h[0]],y=this.paths[h[h.length-1]],S=m.identity,I=S?.orientation==="forward",[g,v]=I?[m,y]:[y,m];return{strand:p,refStart:e.start+d.leading,refEnd:e.start+r-d.trailing,edits:d.edits,weight:m.weight,path:h.flatMap(b=>this.paths[b].path),start:_t(m,0),pieces:h,soloAligned:u,identity:S===void 0?void 0:{pathHandle:S.pathHandle,name:S.name,hapStart:S.name.fragment+g.identity.hapStart,hapEnd:S.name.fragment+v.identity.hapEnd,walkForward:I}}},s=l=>l.soloAligned.reduce((p,h)=>p+h,0),i=l=>l.pieces.reduce((p,h)=>p+this.paths[h].len,0),a=l=>2*s(l)>=i(l),f=l=>{let p=l[0],h=l[l.length-1],u=p.identity.walkForward;if(l.some((x,C)=>x.strand!==p.strand||x.identity.walkForward!==u||C>0&&x.identity.hapStart<l[C-1].identity.hapEnd))return;let d=u?l:[...l].reverse(),m=d.flatMap(x=>x.pieces),y=d.flatMap(x=>x.soloAligned),S=p.strand==="+"!==u,I=m.map(x=>this.paths[x]),g=I.slice(1).map((x,C)=>{let R=I[C].identity;return u?x.identity.hapStart-R.hapEnd:R.hapStart-x.identity.hapEnd}),v=S?[...I].reverse():I,b=S?[...g].reverse():g,E=v.flatMap(x=>S?bo(x.path):x.path),{edits:M}=this.editsAgainst(E,t),L=So(M,v.map(x=>x.len)),_=new Map((S?[...m].reverse():m).map((x,C)=>[x,L[C]])),T=x=>2*x.pieces.reduce((C,R)=>C+_.get(R),0)>=s(x);if(!T(p)||!T(h))return;let P=[],G=0;return v.slice(0,-1).forEach((x,C)=>{G+=x.len,P.push([G,b[C]])}),o(bi(M,P),p.strand,m,y)},c=[];return this.paths.forEach((l,p)=>{if(p===this.refId)return;let{edits:h,flipped:u}=this.alignment(p),d=l.identity,m=d?d.orientation==="forward"!==u:!u;c.push(o(h,m?"+":"-",[p],So(h,[l.len])))}),mi(c,a,f).map(l=>{let{edits:p,identity:h,pieces:u,soloAligned:d,...m}=l,y={...m,cigar:Si(p)};return h?{...y,resolved:!0,name:h.name,label:xe({...h.name,fragment:h.hapStart},h.hapEnd),pathHandle:h.pathHandle,hapStart:h.hapStart,hapEnd:h.hapEnd}:{...y,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:p}=l;return p?[{name:p.name,start:p.name.fragment+p.hapStart,steps:Ot(l,p)}]:[]}),i=l=>p=>p.sample===l.sample&&p.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(ye(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(p=>f(p.name)).flatMap(p=>yo(p.steps,l.steps,c,o).map(h=>({query:p.name,queryStart:p.start+h.queryStart,queryEnd:p.start+h.queryEnd,strand:h.strand,target:l.name,targetStart:l.start+h.targetStart,targetEnd:l.start+h.targetEnd,cigar:xo(h.edits),matches:h.edits.reduce((u,[d,m])=>u+(d==="="?m:0),0),columns:h.edits.reduce((u,[,d])=>u+d,0),sharedBases:h.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=ye(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&We(o,s)&&t.push([r==="reverse"?1:0,O(s),B(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!B(r)){let o=O(r),s=`S ${o} ${this.record(r).sequence}
|
|
2
|
+
`;for(let[i,a,f]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${f?"-":"+"}
|
|
3
|
+
`;t.push(e.encode(s))}return Zr(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",...Kr(Xr(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)B(c)||r.push(`S ${O(c)} ${this.record(c).sequence}`);let s=c=>B(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&We(c,l)&&r.push(`L ${O(c)} ${s(c)} ${O(l)} ${s(l)} 0M`);let i=(c,l,p,h,u)=>{let d=Ot(c,l).map(S=>`${B(S)?"<":">"}${O(S)}`).join(""),m=c.weight===void 0?"":` WT:i:${c.weight}`,y=u===void 0?"":` CG:Z:${u}`;return`W ${p.sample} ${p.haplotype} ${p.contig} ${p.fragment} ${h} ${d}${m}${y}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&r.push(i(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let f=1;return this.paths.forEach((c,l)=>{if(l!==this.refId){let p=e.names==="resolved"?c.identity:void 0,h=t?this.alignToRef(l):void 0;r.push(p?i(c,p,{...p.name,fragment:p.name.fragment+p.hapStart},p.name.fragment+p.hapEnd,h):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,h)),f+=1}}),`${r.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`}outputPaths(e){let t=e.cigar??!1,r=[],o=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let i={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};r.push({info:this.paths[this.refId],identity:void 0,name:xe(i,this.refPath.fragment+this.refInterval[1]),cigar:void 0})}let s=1;return this.paths.forEach((i,a)=>{if(a===this.refId)return;let f=e.names==="resolved"?i.identity:void 0;r.push({info:i,identity:f,name:f?xe({...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd):xe({sample:"unknown",contig:o,haplotype:s,fragment:0},i.len),cigar:t?this.alignToRef(a):void 0}),s+=1}),r}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&We(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!B(s)).map(s=>({id:String(O(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(O(s)),from_is_reverse:B(s),to:String(O(i)),to_is_reverse:B(i)});let o=this.outputPaths(e).map(s=>yi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!B(i)),r=new Int32Array(t.length),o=[];t.forEach((i,a)=>{r[a]=O(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:r,nodeSequences:o,edges:Int32Array.from(s),paths:this.outputPaths(e).map(i=>({name:i.name,weight:i.info.weight,cigar:i.cigar,steps:Int32Array.from(Ot(i.info,i.identity))}))}}};function Ot(n,e){return e?.orientation==="reverse"?n.path.map(t=>K(t)).reverse():n.path}function yi(n,e,t,r){return{name:t,...n.weight===void 0?{}:{weight:n.weight},...r===void 0?{}:{cigar:r},path:Ot(n,e).map(o=>({id:String(O(o)),is_reverse:B(o)}))}}function Wn(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n[r],s=e[r];if(o!==s)return o<s?-1:1}return n.length-e.length}function X(n,e,t){if(t===0)return;let r=n[n.length-1];r?.[0]===e?r[1]+=t:n.push([e,t])}function kt(n){return n===0?0:6+(n-1)}function vo(n,e,t){if(e===0)X(n,"D",t);else if(t===0)X(n,"I",e);else{let r=Math.min(e,t),o=4*r+kt(e-r)+kt(t-r),s=kt(e)+kt(t);o<=s?(X(n,"M",r),X(n,"I",e-r),X(n,"D",t-r)):(X(n,"I",e),X(n,"D",t))}}function xi(n){let e=0;for(;e<n.length&&n[e][0]!=="M";)e+=1;if(e===n.length){let a=n.filter(([c])=>c==="I"),f=n.filter(([c])=>c==="D").reduce((c,[,l])=>c+l,0);return{edits:a.map(([c,l])=>[c,l]),leading:0,trailing:f}}let t=n.length;for(;n[t-1][0]!=="M";)t-=1;let r=a=>({inserted:a.reduce((f,[c,l])=>f+(c==="I"?l:0),0),deleted:a.reduce((f,[c,l])=>f+(c==="D"?l:0),0)}),o=r(n.slice(0,e)),s=r(n.slice(t)),i=[];X(i,"I",o.inserted);for(let[a,f]of n.slice(e,t))X(i,a,f);return X(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function So(n,e){let t=e.map(()=>0),r=e.length-1,o=0,s=e[0],i=0;for(let[a,f]of n){if(a==="D")continue;let c=f;for(;c>0;){for(;o<r&&i>=s;)o+=1,s+=e[o];let l=o<r?Math.min(c,s-i):c;a==="M"&&(t[o]+=l),i+=l,c-=l}}return t}function bi(n,e){let t=[],r=0,o=0;for(let[s,i]of n){if(s==="D"){X(t,s,i);continue}let a=r;for(;o<e.length&&e[o][0]<r+i;){let[f,c]=e[o];X(t,s,f-a),X(t,"I",c),a=f,o+=1}X(t,s,r+i-a),r+=i}for(;o<e.length;o++)X(t,"I",e[o][1]);return t}function Si(n){return n.map(([e,t])=>`${t}${e}`).join("")}async function Io(n,e,t,r,o){let s=new Lt(n,o);try{let i=await s.pathPosition(At(e,t));return await s.prefetchReferenceWalk(i,r-t),await s.aroundInterval(i.position,r-t,o.context??100),await s.extractSnarls(o.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof ke&&i.windowBp===void 0?new ke(i.limit,{windowBp:r-t,walkedBp:s.referenceWalkedBp??0}):i}}async function Ao(n,e,t,r,o={}){let{subgraph:s,reference:i}=await Io(n,e,t,r,o);return s.extractPaths(i,o.haplotypes??"all"),s}async function Eo(n,e,t,r,o){if(!n.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await Io(n,e,t,r,o),a=o.haplotypes??"all";return(a!=="all"||!await s.extractChosenPaths(i,r-t,o.keep))&&(s.extractPaths(i,a),await s.identifyPaths()),s.keepHaplotypes(o.keep),s}function Se(n,e){let t=0;for(let o=0;o<8;o++){let s=n[e+o];if(s===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(s&127),(s&128)===0)return[t,e+o+1]}let r=n[e+8];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+r,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function vi(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 Ii=new TextDecoder;function Tt(n){let[e,t]=Se(n,0),r=[],o=t;for(;o<e;){let[a,f]=Se(n,o);r.push(a),o=f}let s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=e;return r.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=vi(s,i,f);return i+=f,c}if(a===7){let f=s.getFloat64(i);return i+=8,f}if(a===8)return 0;if(a===9)return 1;if(a>=12){let f=a-12>>1,c=n.subarray(i,i+f);return i+=f,a%2===0?c:Ii.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var ot=2,Ft=5,Ro=10,Nt=13;function Po(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 Ai(n,e){let t=n[e];if(t!==ot&&t!==Ft&&t!==Ro&&t!==Nt)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===ot||t===Ft;return{type:t,cellCount:Po(n,e+3),rightChild:r?Oe(n,e+8):0,cellPointers:e+(r?12:8)}}function Re(n,e,t){return Po(n,e.cellPointers+2*t)}var Ei=4096,Ci=4096,$t=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let r=this.usable,o=t?Math.floor((r-12)*64/255)-23:r-35;if(e<=o)return e;let s=Math.floor((r-12)*32/255)-23,i=s+(e-s)%(r-4);return i<=o?i:s}async payload(e,t,r,o){let s=this.localPayloadSize(r,o);if(s===r)return e.subarray(t,t+r);let i=new Uint8Array(r);i.set(e.subarray(t,t+s),0);let a=s,f=Oe(e,t+s);for(;f!==0&&a<r;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,r-a));i.set(l,a),a+=l.length,f=Oe(c,0)}if(a!==r)throw new Error("SQLite overflow chain ended before the payload was complete");return i}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:Ai(t,e===1?100:0)}}tableDepth(e,t){let r=this.tableDepths.get(e);return r||(r=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Nt)return s;if(a.type!==Ft)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:Oe(i,Re(i,a,f))}})(),this.tableDepths.set(e,r),r.catch(()=>this.tableDepths.delete(e))),r}childIndexFor(e,t,r){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=Se(e,Re(e,t,i)+4);a<r?o=i+1:s=i}return o}async prefetchRowidRange(e,t,r){let o=await this.tableDepth(e,t),s=[e];for(let i=0;i<o;i++){let a=await Promise.all(s.map(c=>this.pageAt(c))),f=[];if(a.forEach(({page:c,header:l},p)=>{let h=p===0?this.childIndexFor(c,l,t):0,u=p===a.length-1?this.childIndexFor(c,l,r):l.cellCount;for(let d=h;d<=u;d++)f.push(d===l.cellCount?l.rightChild:Oe(c,Re(c,l,d)))}),f.length>Ci)return!1;this.pager.prefetch(f),s=f}return!0}async tableRowid(e,t){let r=e;for(;;){let{page:o,header:s}=await this.pageAt(r);if(s.type===Nt){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,p=Re(o,s,l),[h,u]=Se(o,p),[d,m]=Se(o,u);if(d===t)return Tt(await this.payload(o,m,h,!1));d<t?f=l+1:c=l}return}if(s.type!==Ft)throw new Error("SQLite table b-tree contains an index page");let i=0,a=s.cellCount;for(;i<a;){let f=i+a>>1,c=Re(o,s,f),[l]=Se(o,c+4);l<t?i=f+1:a=f}r=i===s.cellCount?s.rightChild:Oe(o,Re(o,s,i))}}async*tableScan(e){let{page:t,header:r}=await this.pageAt(e);if(r.type===Nt)for(let o=0;o<r.cellCount;o++){let s=Re(t,r,o),[i,a]=Se(t,s),[f,c]=Se(t,a);yield{rowid:f,values:Tt(await this.payload(t,c,i,!1))}}else{let o=[];for(let s=0;s<r.cellCount;s++)o.push(Oe(t,Re(t,r,s)));o.push(r.rightChild),this.pager.prefetch(o);for(let s of o)yield*this.tableScan(s)}}decodedCells(e,t){let r=this.decodedIndexPages.get(e);if(r)this.decodedIndexPages.delete(e);else if(r=new Array(t.cellCount),this.decodedIndexPages.size>=Ei){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,r),r}async indexCell(e,t,r,o){let s=this.decodedCells(e,r),i=s[o];if(!i){let a=Re(t,r,o),f=r.type===ot,[c,l]=Se(t,f?a+4:a);i={values:Tt(await this.payload(t,l,c,!0)),leftChild:f?Oe(t,a):0},s[o]=i}return i}async*indexScanFrom(e,t){let{page:r,header:o}=await this.pageAt(e),s=0,i=o.cellCount;for(;s<i;){let a=s+i>>1,f=await this.indexCell(e,r,o,a);Co(f.values,t)<0?s=a+1:i=a}for(let a=s;a<o.cellCount;a++){let f=await this.indexCell(e,r,o,a);o.type===ot&&(yield*this.indexScanFrom(f.leftChild,t)),yield f.values}o.type===ot&&(yield*this.indexScanFrom(o.rightChild,t))}async indexSeekLE(e,t){let r,o=e;for(;;){let{page:s,header:i}=await this.pageAt(o),a=0,f=i.cellCount,c=0;for(;a<f;){let l=a+f>>1,p=await this.indexCell(o,s,i,l);Co(p.values,t)<=0?(r=p.values,a=l+1):(c=p.leftChild,f=l)}if(i.type===Ro)return r;o=a===i.cellCount?i.rightChild:c}}};function Co(n,e){for(let t=0;t<e.length;t++){let r=n[t],o=e[t];if(typeof r!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(r!==o)return r<o?-1:1}return 0}var qt=class{blocks=new Map;blockSize;maxBlocks;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,r,o={}){this.source=e,this.pageSize=t,this.fileSize=r;let s=o.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(s/t)*t),this.maxBlocks=o.maxBlocks??256}async read(e,t){let r=0;for(;;)try{let o=await this.source.read(e,t);return this.bytesFetched+=o.length,o}catch(o){if(r+=1,r>=3)throw o;await new Promise(s=>setTimeout(s,200*r))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){let t=this.blocks.get(e);if(t)return this.blocks.delete(e),this.blocks.set(e,t),t;let r=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-r),s=this.read(o,r);return this.fetches+=1,this.blocks.set(e,s),this.forgetOnFailure(s,[e]),this.evict(),s}prefetch(e){let t=[...new Set(e.map(o=>Math.floor((o-1)*this.pageSize/this.blockSize)))].filter(o=>!this.blocks.has(o)).sort((o,s)=>o-s),r=0;for(;r<t.length;){let o=r+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[r],o-r),r=o}}fetchRun(e,t){let r=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-r),s=this.read(o,r);this.fetches+=1;let i=[];for(let a=0;a<t;a++){let f=a*this.blockSize;i.push(e+a),this.blocks.set(e+a,s.then(c=>c.subarray(f,f+this.blockSize)))}this.forgetOnFailure(s,i),this.evict()}forgetOnFailure(e,t){e.catch(()=>{for(let r of t)this.blocks.delete(r)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let r=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return r.subarray(o,o+this.pageSize)}};var st=class n{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){let{size:r}=await e.stat(),o=await e.read(Math.min(t.blockSize??65536,r),0),s=o.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3")throw new Error("Not a SQLite database");let a=new DataView(s.buffer,s.byteOffset,s.byteLength),f=a.getUint16(16),c=f===1?65536:f,l=s[20]??0,p=a.getUint32(56);if(p!==1)throw new Error(`SQLite text encoding ${p} is not UTF-8`);let h=new qt(e,c,r,t);h.seed(0,o),h.fetches+=1,h.bytesFetched+=o.length;let u=new $t(h,l),d=new Map;for await(let{values:m}of u.tableScan(1)){let[y,S,I,g,v]=m;typeof y=="string"&&typeof S=="string"&&typeof I=="string"&&typeof g=="number"&&d.set(S,{type:y,name:S,tableName:I,rootPage:g,sql:typeof v=="string"?v:""})}return new n(h,u,d)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}indexOn(e){let t=[...this.objects.values()].find(r=>r.type==="index"&&r.tableName===e);if(!t)throw new Error(`SQLite table ${e} has no index`);return t.rootPage}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,r){return this.btree.prefetchRowidRange(this.rootPage(e),t,r)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t){return this.btree.indexScanFrom(this.indexOn(e),t)}has(e){return this.objects.has(e)}};var Vn="GBZ-base version 4",Ht=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},Gt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: its Tags table has no version":`unsupported database schema "${e}"; this reader understands "${Vn}"`),this.found=e}},Bt=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,r,o,s){this.handle=e,this.edges=t,this.bwt=r,this.encodedSequence=o,this.next=s,this.sequenceLen=jr(o)}get id(){return O(this.handle)}get orientation(){return Ue(this.handle)}get sequence(){return this.decoded??=Ur(this.encodedSequence),this.decoded}successors(){return this.edges.filter(e=>e.node!==0).map(e=>e.node)}gbwt(){if(this.edges.length===0)throw new Error(`GBWT record for handle ${this.handle} is empty`);return new vt(this.edges,this.bwt)}};function Q(n,e){if(typeof n!="number")throw new Error(`${e} is not a number in the database`);return n}function Dt(n,e){if(typeof n!="string")throw new Error(`${e} is not text in the database`);return n}function Qn(n,e){if(!(n instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return n}function Mo(n,e){return{handle:n,fwStart:{node:Q(e[1],"Paths.fw_node"),offset:Q(e[2],"Paths.fw_offset")},revStart:{node:Q(e[3],"Paths.rev_node"),offset:Q(e[4],"Paths.rev_offset")},name:{sample:Dt(e[5],"Paths.sample"),contig:Dt(e[6],"Paths.contig"),haplotype:Q(e[7],"Paths.haplotype"),fragment:Q(e[8],"Paths.fragment")},isIndexed:Q(e[9],"Paths.is_indexed")!==0}}async function _o(n){let e=new Map;for await(let{values:t}of n.scan("Tags"))e.set(Dt(t[0],"Tags.key"),Dt(t[1],"Tags.value"));return e}var it=class n{tagCache;pathCache;pathMapCache;indexTags=new Map;sqlite;index;constructor(e,t){this.sqlite=e,this.index=t}static async open(e,t={}){let{haplotypeIndex:r,...o}=t,s=await st.open(e,o);for(let c of["Tags","Nodes","Paths","ReferenceIndex"])s.rootPage(c);let i=r?await st.open(r,o):void 0,a=new n(s,i),f=await a.tag("version");if(f!==Vn)throw new Gt(f);if(i){for(let u of["Tags","HaplotypeSamples","HaplotypeLengths"])i.rootPage(u);a.indexTags=await _o(i);let c=a.indexTags.get("haplotype_index_paths"),l=await a.tag("paths");if(c!==l)throw new Error(`haplotype index was built for ${c??"an unknown number of"} paths but the graph has ${l}`);let p=a.indexTags.get("haplotype_index_nodes"),h=await a.tag("nodes");if(p!==void 0&&p!==h)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${h}`);if(a.indexTags.get("haplotype_index_orientations")==="forward")throw new Ht}return a}tags(){return this.tagCache??=_o(this.sqlite),this.tagCache}async tag(e){return(await this.tags()).get(e)}prefetchRecords(e,t){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let r=t[4];return new Bt(e,zr(Qn(t[1],"Nodes.edges")),Qn(t[2],"Nodes.bwt"),Qn(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(Mo(t,r));return e})(),this.pathCache}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?Mo(e,t):void 0}pathsByHandle(){return this.pathMapCache??=this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),this.pathMapCache}async findPath(e){return(await this.paths()).filter(r=>r.name.sample===e.sample&&r.name.contig===e.contig&&r.name.haplotype===e.haplotype&&r.name.fragment<=e.fragment).sort((r,o)=>o.name.fragment-r.name.fragment)[0]}async pathsForSample(e){return(await this.paths()).filter(t=>t.name.sample===e)}async pathsNamed(e){let t=At(Jr(e),0);return(await this.paths()).filter(r=>r.name.sample===t.sample&&r.name.contig===t.contig&&r.name.haplotype===t.haplotype).sort((r,o)=>r.name.fragment-o.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let r=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!r){let i=await this.getPath(e);throw new Error(`Path ${i?xe(i.name,i.name.fragment):e} has not been indexed for random access`)}let o=r.pathOffset,s=r.pos;for(;;){let i=await this.getRecord(s.node);if(!i)throw new Error(`Node ${s.node} does not exist in the graph`);o+=i.sequenceLen;let a=i.gbwt().lf(s.offset);if(!a||a.node===0)return o;s=a}}return t}async pathFragmentsForRange(e,t,r){if(r<=t)return[];let o=await this.pathsNamed(e),s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<r);return(await Promise.all([...s,...i].map(async f=>({path:f,start:f.name.fragment,end:f.name.fragment+await this.pathLength(f.handle)})))).filter(f=>t<f.end)}async subgraphForFragment(e,t,r,o){let{keep:s,...i}=o;if(s!==void 0&&!this.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{sample:a,contig:f,haplotype:c}=e.path.name,l={sample:a,contig:f,haplotype:c},p=Math.max(t,e.start),h=Math.min(r,e.end),u=o.haplotypes??"all",d=u==="all"||u==="distinct",m;return s!==void 0&&u==="all"?m=await Eo(this,l,p,h,{...i,keep:s}):(m=await Ao(this,l,p,h,i),this.hasHaplotypeIndex&&d&&(await m.identifyPaths(),s!==void 0&&m.keepHaplotypes(s))),m}async getSubgraphForRange(e,t,r,o={}){let[s]=await this.pathFragmentsForRange(e,t,r);return s?this.subgraphForFragment(s,t,r,o):void 0}async getAlignmentsForRange(e,t,r,o={}){let s=[];for(let i of await this.pathFragmentsForRange(e,t,r)){let a=await this.subgraphForFragment(i,t,r,o);s.push(...a.alignments())}return s}async graphName(){let e=new Map;for(let[r,o]of await this.tags())r.startsWith("gbz_")&&e.set(r.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=Yr(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeAnchor(e,t){let r=await this.companion.indexSeekLE("HaplotypeAnchors",[e,t]),o=r?.[0]===e&&r[1]===t?await this.companion.byRowid("HaplotypeAnchors",Q(r[2],"HaplotypeAnchors rowid")):void 0;return o?{node:Q(o[2],"HaplotypeAnchors.node_handle"),pathOffset:Q(o[3],"HaplotypeAnchors.path_offset")}:void 0}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:Q(e[0],"HaplotypeSamples.node_handle"),offset:Q(e[1],"HaplotypeSamples.node_offset"),pathHandle:Q(e[2],"HaplotypeSamples.path_handle"),orientation:Q(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:Q(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let r=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0])){if(Q(o[0],"HaplotypeSamples.node_handle")>t)break;let i=await this.companion.byRowid("HaplotypeSamples",Q(o[2],"HaplotypeSamples rowid"));i&&r.push(this.sampleFromRow(i))}return r}async haplotypeSampleAt(e,t){let r=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);if(r?.[0]!==e||r[1]!==t)return;let o=await this.companion.byRowid("HaplotypeSamples",Q(r[2],"HaplotypeSamples rowid"));return o?this.sampleFromRow(o):void 0}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?Q(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:Q(t[1],"ReferenceIndex.path_offset"),pos:{node:Q(t[2],"ReferenceIndex.node_handle"),offset:Q(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let r=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return r?.[0]===e?Q(r[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let r=await this.indexedRowid(e,t);return r===void 0?void 0:this.indexedRow(r)}async indexedPositionsBetween(e,t,r){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,r)]),i=[];if(o!==void 0&&s!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",o,s+1);for(let a=o;a<=s;a++)i.push(await this.indexedRow(a))}return i}};var gr=le(On(),1),wr=le(et(),1),wn=le(_r(),1),Ps=le(Gs(),1);function Yn(n){let e=/\.gbz\.db$/i;return e.test(n)?n.replace(e,".haplotype-index.db"):void 0}var ko=le(_r(),1);function Ri(n){return Or(n)&&Yn(kr(n))?Lr(n,e=>Yn(e)):void 0}async function Oo(n,e){let t=Ri(n);if(t)try{return await(0,ko.openLocation)(t,e).stat(),t}catch{return}}var To=le(On(),1),Pi=5e3,Mi=50*2**20,Xn=class extends Error{constructor(t){super(`this GAF is ${(t/2**20).toFixed(0)} MB without an index; bgzip it and index it with tabix -p gaf`);this.name="UnindexedGafTooLargeError"}};function _i(n,e){if(n.length<=e)return n;let t=n.length/e;return Array.from({length:e},(r,o)=>n[Math.floor(o*t)])}var Lo=(n,e)=>n.path.some(t=>e.has(t.name)),zt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=(0,To.cachedSetup)({setup:async()=>{let{size:e}=await this.file.stat();if(e>Mi)throw new Xn(e);let t=await this.file.readFile(),r=new TextDecoder().decode(t[0]===31&&t[1]===139?await Tr(t):t);return Fr(r)}})}async readIndexed(e,t,r){let o=1/0,s=-1/0;for(let a of t){let f=Number(a);Number.isInteger(f)&&(o=Math.min(o,f),s=Math.max(s,f))}let i=[];return o<=s&&await e.getLines("{node}",o,s+1,{signal:r,lineCallback:a=>{let f=Nr(a);f&&Lo(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let r=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(o=>Lo(o,e));return{records:_i(r,Pi),total:r.length}}};var Es=le(On(),1),Cs=le(et(),1);var Kn=function(n,e){return Kn=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])},Kn(n,e)};function at(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Kn(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function No(n,e,t,r){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function a(l){try{c(r.next(l))}catch(p){i(p)}}function f(l){try{c(r.throw(l))}catch(p){i(p)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((r=r.apply(n,e||[])).next())})}function jt(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(l){return f([c,l])}}function f(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(r=1,o&&(s=c[0]&2?o.return:c[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,c[1])).done)return s;switch(o=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(l){c=[6,l],o=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function He(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ve(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return s}function Ye(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function Ge(n){return this instanceof Ge?(this.v=n,this):new Ge(n)}function Fo(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(u){return function(d){return Promise.resolve(d).then(u,p)}}function a(u,d){r[u]&&(o[u]=function(m){return new Promise(function(y,S){s.push([u,m,y,S])>1||f(u,m)})},d&&(o[u]=d(o[u])))}function f(u,d){try{c(r[u](d))}catch(m){h(s[0][3],m)}}function c(u){u.value instanceof Ge?Promise.resolve(u.value.v).then(l,p):h(s[0][2],u)}function l(u){f("next",u)}function p(u){f("throw",u)}function h(u,d){u(d),s.shift(),s.length&&f(s[0][0],s[0][1])}}function $o(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof He=="function"?He(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(i){return new Promise(function(a,f){i=n[s](i),o(a,f,i.done,i.value)})}}function o(s,i,a,f){Promise.resolve(f).then(function(c){s({value:c,done:a})},i)}}function H(n){return typeof n=="function"}function qo(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Ut=qo(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
6
|
+
`+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
7
|
+
`):"",this.name="UnsubscriptionError",this.errors=t}});function Zn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Wt=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=He(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(m){e={error:m}}finally{try{f&&!f.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(H(l))try{l()}catch(m){s=m instanceof Ut?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var h=He(p),u=h.next();!u.done;u=h.next()){var d=u.value;try{Ho(d)}catch(m){s=s??[],m instanceof Ut?s=Ye(Ye([],Ve(s)),Ve(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{u&&!u.done&&(o=h.return)&&o.call(h)}finally{if(r)throw r.error}}}if(s)throw new Ut(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Ho(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Zn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Zn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var Sf=Wt.EMPTY;function Qt(n){return n instanceof Wt||n&&"closed"in n&&H(n.remove)&&H(n.add)&&H(n.unsubscribe)}function Ho(n){H(n)?n():n.unsubscribe()}var be={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Xe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=Xe.delegate;return o?.setTimeout?o.setTimeout.apply(o,Ye([n,e],Ve(t))):setTimeout.apply(void 0,Ye([n,e],Ve(t)))},clearTimeout:function(n){var e=Xe.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function Vt(n){Xe.setTimeout(function(){var e=be.onUnhandledError;if(e)e(n);else throw n})}function Jn(){}var Go=(function(){return er("C",void 0,void 0)})();function Bo(n){return er("E",void 0,n)}function Do(n){return er("N",n,void 0)}function er(n,e,t){return{kind:n,value:e,error:t}}var Be=null;function zo(n){if(be.useDeprecatedSynchronousErrorHandling){var e=!Be;if(e&&(Be={errorThrown:!1,error:null}),n(),e){var t=Be,r=t.errorThrown,o=t.error;if(Be=null,r)throw o}}else n()}function jo(n){be.useDeprecatedSynchronousErrorHandling&&Be&&(Be.errorThrown=!0,Be.error=n)}var ft=(function(n){at(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Qt(t)&&t.add(r)):r.destination=Ti,r}return e.create=function(t,r,o){return new Xt(t,r,o)},e.prototype.next=function(t){this.isStopped?nr(Do(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?nr(Bo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?nr(Go,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Wt);var ki=Function.prototype.bind;function tr(n,e){return ki.call(n,e)}var Oi=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Yt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Yt(r)}else Yt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Yt(t)}},n})(),Xt=(function(n){at(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(H(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&be.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&tr(t.next,a),error:t.error&&tr(t.error,a),complete:t.complete&&tr(t.complete,a)}):i=t}return s.destination=new Oi(i),s}return e})(ft);function Yt(n){be.useDeprecatedSynchronousErrorHandling?jo(n):Vt(n)}function Li(n){throw n}function nr(n,e){var t=be.onStoppedNotification;t&&Xe.setTimeout(function(){return t(n,e)})}var Ti={closed:!0,next:Jn,error:Li,complete:Jn};var Ke=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Uo(n){return n}function Wo(n){return n.length===0?Uo:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var he=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Fi(e)?e:new Xt(e,t,r);return zo(function(){var i=o,a=i.operator,f=i.source;s.add(a?a.call(s,f):f?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Qo(t),new t(function(o,s){var i=new Xt({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Ke]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Wo(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Qo(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 Qo(n){var e;return(e=n??be.Promise)!==null&&e!==void 0?e:Promise}function Ni(n){return n&&H(n.next)&&H(n.error)&&H(n.complete)}function Fi(n){return n&&n instanceof ft||Ni(n)&&Qt(n)}function $i(n){return H(n?.lift)}function ge(n){return function(e){if($i(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Pe(n,e,t,r,o){return new qi(n,e,t,r,o)}var qi=(function(n){at(e,n);function e(t,r,o,s,i,a){var f=n.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=r?function(c){try{r(c)}catch(l){t.error(l)}}:n.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(ft);var Kt=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function Zt(n){return H(n?.then)}function Jt(n){return H(n[Ke])}function en(n){return Symbol.asyncIterator&&H(n?.[Symbol.asyncIterator])}function tn(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Hi(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var nn=Hi();function rn(n){return H(n?.[nn])}function on(n){return Fo(this,arguments,function(){var t,r,o,s;return jt(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Ge(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,Ge(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ge(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function sn(n){return H(n?.getReader)}function ve(n){if(n instanceof he)return n;if(n!=null){if(Jt(n))return Gi(n);if(Kt(n))return Bi(n);if(Zt(n))return Di(n);if(en(n))return Vo(n);if(rn(n))return zi(n);if(sn(n))return ji(n)}throw tn(n)}function Gi(n){return new he(function(e){var t=n[Ke]();if(H(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Bi(n){return new he(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Di(n){return new he(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Vt)})}function zi(n){return new he(function(e){var t,r;try{for(var o=He(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function Vo(n){return new he(function(e){Ui(n,e).catch(function(t){return e.error(t)})})}function ji(n){return Vo(on(n))}function Ui(n,e){var t,r,o,s;return No(this,void 0,void 0,function(){var i,a;return jt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=$o(n),f.label=1;case 1:return[4,t.next()];case 2:if(r=f.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];f.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=f.sent(),o={error:a},[3,11];case 6:return f.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function we(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function an(n,e){return e===void 0&&(e=0),ge(function(t,r){t.subscribe(Pe(r,function(o){return we(r,n,function(){return r.next(o)},e)},function(){return we(r,n,function(){return r.complete()},e)},function(o){return we(r,n,function(){return r.error(o)},e)}))})}function fn(n,e){return e===void 0&&(e=0),ge(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function Yo(n,e){return ve(n).pipe(fn(e),an(e))}function Xo(n,e){return ve(n).pipe(fn(e),an(e))}function Ko(n,e){return new he(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function Zo(n,e){return new he(function(t){var r;return we(t,e,function(){r=n[nn](),we(t,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return H(r?.return)&&r.return()}})}function cn(n,e){if(!n)throw new Error("Iterable cannot be null");return new he(function(t){we(t,e,function(){var r=n[Symbol.asyncIterator]();we(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function Jo(n,e){return cn(on(n),e)}function es(n,e){if(n!=null){if(Jt(n))return Yo(n,e);if(Kt(n))return Ko(n,e);if(Zt(n))return Xo(n,e);if(en(n))return cn(n,e);if(rn(n))return Zo(n,e);if(sn(n))return Jo(n,e)}throw tn(n)}function rr(n,e){return e?es(n,e):ve(n)}function ct(n,e){return ge(function(t,r){var o=0;t.subscribe(Pe(r,function(s){r.next(n.call(e,s,o++))}))})}function ts(n,e,t,r,o,s,i,a){var f=[],c=0,l=0,p=!1,h=function(){p&&!f.length&&!c&&e.complete()},u=function(m){return c<r?d(m):f.push(m)},d=function(m){s&&e.next(m),c++;var y=!1;ve(t(m,l++)).subscribe(Pe(e,function(S){o?.(S),s?u(S):e.next(S)},function(){y=!0},void 0,function(){if(y)try{c--;for(var S=function(){var I=f.shift();i?we(e,i,function(){return d(I)}):d(I)};f.length&&c<r;)S();h()}catch(I){e.error(I)}}))};return n.subscribe(Pe(e,u,function(){p=!0,h()})),function(){a?.()}}function Ze(n,e,t){return t===void 0&&(t=1/0),H(e)?Ze(function(r,o){return ct(function(s,i){return e(r,s,o,i)})(ve(n(r,o)))},t):(typeof e=="number"&&(t=e),ge(function(r,o){return ts(r,o,n,t)}))}function ns(n,e,t,r,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var p=c++;f=a?n(f,l,p):(a=!0,l),r&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function rs(n,e){return ge(ns(n,e,arguments.length>=2,!1,!0))}var Wi=function(n,e){return n.push(e),n};function ln(){return ge(function(n,e){rs(Wi,[])(n).subscribe(e)})}function os(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 ir(n){let e="";for(let{own:t,mate:r,op:o}of os(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var or=2**28-1;function sr(n,e,t){for(let r=e;r>0;r-=or)n.push((Math.min(r,or)<<4|t)>>>0)}function Qi(n,e,t){if(e===t)sr(n,e,0);else{let r=Math.ceil(Math.max(e,t)/or);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 ar(n){let e=[];for(let{own:t,mate:r,op:o}of os(n))o==="M"?Qi(e,t,r):o==="I"?sr(e,r,1):sr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function Vi(n){return n>=48&&n<=57}function Yi(n){return n!==void 0&&/[A-Za-z]/.test(n)}function ss(n,e){let t=e;for(;t<n.length&&Yi(n[t]);)t++;return t}function is(n,e){let t=e,r=0;for(;t<n.length&&Vi(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function ps(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=is(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=ss(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=ss(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}=is(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function fr(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;ps(n,(a,f,c,l,p)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,n[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let h=n.slice(l,p);e(73,i,c,h,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function hs(n,e,t,r){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=n.length;f<c;f++){let l=n[f],p=l>>>4,h=l&15;if(h===0||h===7){if(a)for(let u=0;u<p;u++)(e.charCodeAt(s+u)|32)!==(t.charCodeAt(o+u)|32)&&i.push({start:o+u,type:"mismatch",base:e[s+u],altbase:t[o+u],length:1});s+=p,o+=p}else if(h===1)i.push({start:o,type:"insertion",insertlen:p,insertedBases:e?.slice(s,s+p),length:0}),s+=p;else if(h===2)i.push({start:o,type:"deletion",length:p}),o+=p;else if(h===3)i.push({start:o,type:"skip",length:p}),o+=p;else if(h===8){for(let u=0;u<p;u++)i.push({start:o+u,type:"mismatch",base:e?.[s+u]||"X",qual:r?.[s+u],length:1});s+=p,o+=p}else h===5?i.push({start:o,type:"hardclip",cliplen:p,length:1}):h===4&&(i.push({start:o,type:"softclip",cliplen:p,length:1}),s+=p)}return i}function ds(n,e,t,r,o){if(!e)return[];let s=[],i=e.length,a=r.length,f=o!==void 0,c=t.length,l=!1;for(let I=0;I<c;I++)if(t[I].type==="skip"){l=!0;break}let p=0,h=0,u=0,d=0,m=0,y=0,S=n.length;for(;y<S;){let I=n.charCodeAt(y);if(I>=48&&I<=57){let g=0;for(;y<S;){let v=n.charCodeAt(y);if(v>=48&&v<=57)g=g*10+(v-48),y++;else break}p+=g}else if(I===94)for(y++;y<S&&n.charCodeAt(y)>=65;)y++,p++;else if(I>=65){let g=n[y];if(y++,l&&c>0)for(let L=m;L<c;L++){let _=t[L];_.type==="skip"&&p>=_.start&&(p+=_.length,m=L+1)}let v=u,b=d;for(let L=h;L<i&&b<=p;L++,h=L){let _=e[L],T=_>>>4,P=_&15;P===4||P===1?v+=T:P===2||P===6||P===3?b+=T:P!==5&&(v+=T,b+=T)}u=v,d=b;let E=v-(b-p),M=E<a?r[E]:"X";s.push({start:p,base:M,qual:f?o[E]:void 0,altbase:g,length:1,type:"mismatch"}),p++}else y++}return s}var us={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function ms(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=us[s];t.push(e<<4|i),e=0}}return t}function pr(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|us[a],r=0)}return t}function mn(n,e,t,r,o){let s=ms(n),i=n?hs(s,t,r,o):[];return e&&t?i.concat(ds(e,s,i,t,o)):i}var Zi=397,Ji=387,ea=385;function gs(n){return(1<<n&Zi)!==0}function ws(n){return(1<<n&Ji)!==0}function ys(n){return(1<<n&ea)!==0}function hr(n,e,t,r,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?r:t,l=[],p=1/0,h=-1/0,u=1/0,d=-1/0,m=(y,S)=>{u=Math.min(u,y,S),d=Math.max(d,y,S)};for(let y=0;y<n.length;y++){let S=n[y],I=S>>>4,g=S&15,v=g===9,b=v||gs(g)?I:0,E=v?n[++y]>>>4:ws(g)?I:0,M=f+b,L=c+E*a,_=f,T=M;if(T>=s&&_<=i)if(b>0){let P=Math.max(_,s),G=Math.min(T,i);if(G>P)if(p=Math.min(p,P),h=Math.max(h,G),v){let x=E/I,C=G-P,R=Math.round(C*x),D=Math.round(c+(P-f)*x*a);l.push(C<<4|9,R<<4|9),m(D,D+R*a)}else l.push(G-P<<4|g),ys(g)?m(c+(P-f)*a,c+(G-f)*a):m(c,c)}else E>0&&(v?l.push(S,n[y]):l.push(S),p=Math.min(p,f),h=Math.max(h,f),m(c,L));if(f=M,c=L,f>i)break}if(l.length!==0)return{start:p,end:h,mateStart:u,mateEnd:d,cigar:Uint32Array.from(l)}}function ta(n){return n===1||n===2||n===3}function dr(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?r:t,l,p=!1,h=()=>{l!==void 0&&p&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,p=!1};for(let u=0;u<n.length;u++){let d=n[u],m=d>>>4,y=d&15,S=y===9,I=S?n[++u]:void 0,g=S||gs(y)?m:0,v=I!==void 0?I>>>4:ws(y)?m:0,b=c+v*i;ta(y)&&m>=s?h():(g>0||v>0)&&(l===void 0&&(l={qLo:f,qHi:f,tLo:c,tHi:c,ops:[]}),l.qHi=f+g,l.tLo=Math.min(l.tLo,c,b),l.tHi=Math.max(l.tHi,c,b),l.ops.push(d),I!==void 0&&l.ops.push(I),p=p||S||ys(y)),f+=g,c=b}return h(),a}function xs(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function bs(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function ur(n){let e=xs(n),t=e===void 0?bs(n):void 0;return e!==void 0?pr(e):t!==void 0?ar(t):void 0}var na=le(et(),1),ra=le(vs(),1);var oa=le(et(),1);var sa=le(Bs(),1);var Is=le(et(),1),Le=class extends Is.SimpleFeature{get(e){return e==="mismatches"?mn(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?ir(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)fr(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of mn(this.walkableCigar))(c.type==="deletion"||c.type==="skip"?c.start<f&&c.start+c.length>a:c.start>=a&&c.start<=f)&&(c.type==="mismatch"?e(88,c.start,c.length,c.base,c.qual??-1,0,0):c.type==="insertion"?e(73,c.start,c.length,c.insertedBases??"",-1,0,c.insertlen):c.type==="deletion"?e(68,c.start,c.length,"",-1,0,0):c.type==="skip"&&e(78,c.start,c.length,"",-1,0,0))}}};var ia=["CIGAR","cs","coarseCigar","cg","cr"];function aa(n){return typeof n=="object"&&n!==null&&"refName"in n&&"start"in n&&"end"in n&&typeof n.refName=="string"&&typeof n.start=="number"&&typeof n.end=="number"}function fa(n){let e=n.get("mate");return aa(e)?e:void 0}function ca(n,e,t,r){let o=Math.max(n.start,r.start),s=Math.min(n.end,r.end),i=(e.end-e.start)/Math.max(n.end-n.start,1),a=l=>t===-1?e.end-(l-n.start)*i:e.start+(l-n.start)*i,f=Math.round(a(o)),c=Math.round(a(s));return s>o?{start:o,end:s,mateStart:Math.min(f,c),mateEnd:Math.max(f,c)}:void 0}function la(n,e,t,r,o){let s={start:n.get("start"),end:n.get("end")},i=n.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&r===void 0&&!o?void 0:ur(n);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ca(s,e,i,t);return c===void 0?[]:[c]}else return(r===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:dr(f,s.start,e.start,e.end,i,r)).flatMap(l=>{let p=hr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return p===void 0?[]:[p]})}function pa(n,e,t,r,o,s){let i=`:${r.start}-${r.end}${o}`,a=n.toJSON(),f={...a,uniqueId:`${n.id()}${i}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};a.syntenyId!==void 0&&(f.syntenyId=`${String(a.syntenyId)}${i}`);for(let c of ia)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Le(f)}function As(n,e,t,r=!1){let o=fa(n);if(o===void 0)return[n];{let s=la(n,o,e,t,r);return s.map((i,a)=>pa(n,o,i,e,s.length>1?`/${a}`:"",r))}}var gn=class extends Es.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=r,f=o&&this.recordsAreAlignments,c=(0,Cs.createStatusFanOut)(a.statusCallback);return rr(t).pipe(Ze((l,p)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(Ze(h=>f?As(h,h.get("assemblyName")===l.assemblyName?l:{start:h.get("start"),end:h.get("end")},s,i):[h]),ln(),ct(h=>({index:p,features:h})))),ln(),Ze(l=>l.sort((p,h)=>p.index-h.index).flatMap(p=>p.features)))}};var yr=class extends Error{constructor(){super("no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation");this.name="NoHaplotypeIndexError"}},xr=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}},br=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Rs(n,e){let t=Ee(e);return n[t]??n[e.sample]??t}function ha(n,e){return`${Ee(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function da({alignment:n,assemblyName:e,refName:t,lane:r}){let{refStart:o,refEnd:s,strand:i,cigar:a}=n;if(!(!n.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=n,p=ha(f,n),h={uniqueId:p,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:p,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new Le(h)}}function ua({pair:n,lane:e,mateLane:t}){let r=`${Ee(n.target)}#${n.target.contig}:${n.targetStart}-${n.targetEnd}|${Ee(n.query)}#${n.query.contig}:${n.queryStart}-${n.queryEnd}`;return new Le({uniqueId:r,assemblyName:e,refName:n.target.contig,start:n.targetStart,end:n.targetEnd,type:"match",strand:n.strand==="-"?-1:1,CIGAR:n.cigar,syntenyId:r,identity:n.matches/Math.max(n.columns,1),numMatches:n.matches,blockLen:n.columns,mate:{refName:n.query.contig,start:n.queryStart,end:n.queryEnd,assemblyName:t}})}var mr=n=>!("uri"in n)||n.uri!=="",Sr=class extends gn{constructor(){super(...arguments);this.graph=(0,gr.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),r=this.getConf("haplotypeIndexLocation"),o=mr(r)?r:await Oo(t,this.pluginManager),s=await it.open((0,wn.openLocation)(t,this.pluginManager),o?{haplotypeIndex:(0,wn.openLocation)(o,this.pluginManager)}:{}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let a=await Mn(s),f=wt({configured:this.getConf("referenceSample"),anchorPrefix:je(this,i),referenceSamples:a});return{db:s,anchor:i,referenceSample:f,referenceSamples:a}}});this.gaf=(0,gr.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),r=this.getConf(["readsIndex","location"]);return mr(t)?new zt((0,wn.openLocation)(t,this.pluginManager),mr(r)?$r(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r);return _n(o,s,t)}async getHaplotypes(t={}){let{db:r,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=Ee(i.name),f=s.get(a);f?f.contigs.includes(i.name.contig)||f.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:o.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Rn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:Rs(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:je(this,i),f=(await r.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:gt(Ee(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,r){let o=t===void 0||t.length===0?void 0:t.map(s=>je(this,s));return o===void 0&&r===void 0?void 0:s=>Pn(s,o)&&(r===void 0||gt(Ee(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s}=await this.graph(),{assemblyName:i,refName:a,start:f,end:c}=t;if(i!==s)throw new br(i,s);let l=await this.referenceQuery(a,{}),p=this.keepPredicate(r.haplotypes);return kn(o,l,f,c,{context:this.getConf("context"),snarls:r.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:r.signal,...p===void 0?{}:{keep:p}})}async getReads(t,r={}){let o=await this.gaf(r);return o?o.readsOver(new Set(t),r):{records:[],total:0}}async laneHaplotypes(t,r){let o=je(this,t);return(await this.getHaplotypes(r)).filter(s=>gt(s.prefix,o))}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:f}=t,c=je(this,r.targetAssemblyName),l=Rn(this),p=this.keepPredicate(r.haplotypes,c),h=await this.referenceQuery(i,r),u=this.getConf("nodeLimit");return(h?await(0,wr.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,r.statusCallback,()=>o.getAlignmentsForRange(h,a,f,{context:this.getConf("context"),haplotypes:"all",limit:u,signal:r.signal,...p===void 0?{}:{keep:p}}).catch(m=>{throw yt(m,u,f-a)??m})):[]).flatMap(m=>{let y=m.resolved?da({alignment:m,assemblyName:s,refName:i,lane:Rs(l,m.name)}):void 0;return y===void 0?[]:[y]})}async pairFeatures(t,r,o){let{targetAssemblyName:s}=o;if(s===void 0)throw new xr(r);let{db:i}=await this.graph(o),{refName:a,start:f,end:c}=t,l=await this.laneHaplotypes(r,o),p=await this.laneHaplotypes(s,o),h=[...l,...p],u=await this.referenceQuery(a,o),d=this.getConf("nodeLimit"),m=await i.haplotypeAnchorSpacing()!==void 0,y=(g,v)=>i.getSubgraphForRange(g,v.start,v.end,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:d,signal:o.signal,keep:b=>h.some(E=>E.sample===b.sample&&E.haplotype===b.haplotype)}).catch(b=>{throw yt(b,d,c-f)??b}),S=u&&m&&l.length>0&&p.length>0?(await(0,wr.updateStatus)(`Reading ${r} against ${s}`,o.statusCallback,async()=>Promise.all((await Mr(i,u,f,c)).map(g=>y(u,g))))).filter(g=>g!==void 0):[];return S.every(g=>{let v=g.stats.keep;return v!==void 0&&v.fallback===void 0})?S.flatMap(g=>l.flatMap(v=>p.flatMap(b=>g.pairAlignments({target:v,query:b,bases:!1}).map(E=>ua({pair:E,lane:r,mateLane:s}))))):[]}getFeatures(t,r={}){return(0,Ps.ObservableCreate)(async o=>{let{db:s,anchor:i}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new yr;if(t.assemblyName===i){let a=r.queryAssemblyName===void 0?await this.anchorFeatures(t,r):await this.pairFeatures(t,r.queryAssemblyName,r);for(let f of a)o.next(f)}o.complete()},r.signal)}};export{br as HaplotypeWindowError,yr as NoHaplotypeIndexError,qs as NoReferenceSampleError,Hs as NodeLimitError,xr as PairTargetError,Sr as default,da as fragmentFeature,Ee as haplotypePrefix,Rs as laneAssemblyName,yt as nodeLimitError,ua as pairFeature,wt as resolveReferenceSample};
|
|
8
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-FK6PVNBV.js.map
|