jbrowse-plugin-graphgenomeviewer 6.5.0 → 6.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +4 -3
  2. package/dist/chunks/AddTrackWorkflow-YGKG57NL.js +2 -0
  3. package/dist/chunks/AddTrackWorkflow-YGKG57NL.js.map +7 -0
  4. package/dist/chunks/ChooseSamplesDialog-GWMJ7B5D.js +2 -0
  5. package/dist/chunks/ChooseSamplesDialog-GWMJ7B5D.js.map +7 -0
  6. package/dist/chunks/ChooseWalksDialog-6HVVZMFD.js +2 -0
  7. package/dist/chunks/ChooseWalksDialog-6HVVZMFD.js.map +7 -0
  8. package/dist/chunks/{GbzBaseSyntenyAdapter-KVJKGGQ4.js → GbzBaseSyntenyAdapter-NULWNOBT.js} +5 -5
  9. package/dist/chunks/{GbzBaseSyntenyAdapter-KVJKGGQ4.js.map → GbzBaseSyntenyAdapter-NULWNOBT.js.map} +3 -3
  10. package/dist/chunks/GraphGenomeView-WGQL5W7H.js +10 -0
  11. package/dist/chunks/{GraphGenomeView-ZB4ED45M.js.map → GraphGenomeView-WGQL5W7H.js.map} +3 -3
  12. package/dist/chunks/GraphTrackSettingsDialog-SKB6RNCM.js +4 -0
  13. package/dist/chunks/GraphTrackSettingsDialog-SKB6RNCM.js.map +7 -0
  14. package/dist/chunks/HighlightColorDialog-QDR6WCJT.js +2 -0
  15. package/dist/chunks/{HighlightColorDialog-LXT72W7R.js.map → HighlightColorDialog-QDR6WCJT.js.map} +2 -2
  16. package/dist/chunks/LinearGraphDisplay-ZWVESHP5.js +2 -0
  17. package/dist/chunks/{LinearGraphDisplay-TQX7ZJZF.js.map → LinearGraphDisplay-ZWVESHP5.js.map} +1 -1
  18. package/dist/chunks/{MinigraphBubbleAdapter-CAXB5FGR.js → MinigraphBubbleAdapter-MF7DZTI5.js} +2 -2
  19. package/dist/chunks/RgfaTabixAdapter-YWXG65QG.js +3 -0
  20. package/dist/chunks/RgfaTabixAdapter-YWXG65QG.js.map +7 -0
  21. package/dist/chunks/chunk-564K5Z2F.js +2 -0
  22. package/dist/chunks/chunk-564K5Z2F.js.map +7 -0
  23. package/dist/chunks/{chunk-GB7CF6Z2.js → chunk-6U7XUPRS.js} +2 -2
  24. package/dist/chunks/{chunk-GB7CF6Z2.js.map → chunk-6U7XUPRS.js.map} +4 -4
  25. package/dist/chunks/chunk-K33IZSO2.js +2 -0
  26. package/dist/chunks/chunk-K33IZSO2.js.map +7 -0
  27. package/dist/chunks/{chunk-2SIR336R.js → chunk-KALP44OF.js} +2 -2
  28. package/dist/chunks/{chunk-2SIR336R.js.map → chunk-KALP44OF.js.map} +2 -2
  29. package/dist/chunks/chunk-PISV4EFU.js +2 -0
  30. package/dist/chunks/chunk-PISV4EFU.js.map +7 -0
  31. package/dist/chunks/chunk-QMUDCKOP.js +3 -0
  32. package/dist/chunks/chunk-QMUDCKOP.js.map +7 -0
  33. package/dist/chunks/chunk-SWAPOKBP.js +3 -0
  34. package/dist/chunks/chunk-SWAPOKBP.js.map +7 -0
  35. package/dist/chunks/chunk-TAE3AVU7.js +2 -0
  36. package/dist/chunks/chunk-TAE3AVU7.js.map +7 -0
  37. package/dist/chunks/chunk-TGP6EJGQ.js +2 -0
  38. package/dist/chunks/chunk-TGP6EJGQ.js.map +7 -0
  39. package/dist/chunks/renderSvg-6SX7U57L.js +2 -0
  40. package/dist/chunks/renderSvg-6SX7U57L.js.map +7 -0
  41. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +5 -6
  42. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
  43. package/package.json +1 -1
  44. package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.test.ts +7 -0
  45. package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.ts +14 -6
  46. package/src/GbzBaseSyntenyAdapter/companion.ts +1 -5
  47. package/src/GbzBaseSyntenyAdapter/configSchema.ts +11 -3
  48. package/src/GraphAddTrackWorkflow/AddTrackWorkflow.tsx +20 -2
  49. package/src/GraphAddTrackWorkflow/buildTrackConfig.test.ts +26 -0
  50. package/src/GraphAddTrackWorkflow/buildTrackConfig.ts +43 -37
  51. package/src/GraphGenomeView/components/BubbleHalos.tsx +18 -9
  52. package/src/GraphGenomeView/components/ChooseSamplesDialog.tsx +18 -61
  53. package/src/GraphGenomeView/components/ChooseWalksDialog.tsx +20 -63
  54. package/src/GraphGenomeView/components/ColorSchemeSelect.tsx +12 -28
  55. package/src/GraphGenomeView/components/FacetPanels.tsx +1 -1
  56. package/src/GraphGenomeView/components/GraphCanvas.tsx +3 -5
  57. package/src/GraphGenomeView/components/GraphSettingsDialog.tsx +73 -66
  58. package/src/GraphGenomeView/components/GraphToolbar.tsx +1 -1
  59. package/src/GraphGenomeView/components/HighlightColorDialog.tsx +8 -0
  60. package/src/GraphGenomeView/components/ImportForm.tsx +5 -2
  61. package/src/GraphGenomeView/components/LabelledSelect.tsx +83 -0
  62. package/src/GraphGenomeView/components/LayoutSelect.tsx +18 -38
  63. package/src/GraphGenomeView/components/PaneSvg.tsx +19 -27
  64. package/src/GraphGenomeView/components/PickNamesDialog.tsx +88 -0
  65. package/src/GraphGenomeView/components/RepeatSelect.tsx +21 -33
  66. package/src/GraphGenomeView/components/SettingsMenu.tsx +39 -26
  67. package/src/GraphGenomeView/components/WalkRowContextMenu.tsx +14 -1
  68. package/src/GraphGenomeView/components/WalkSelect.tsx +30 -2
  69. package/src/GraphGenomeView/components/legendStyles.ts +3 -0
  70. package/src/GraphGenomeView/components/usePaneGestures.ts +36 -11
  71. package/src/GraphGenomeView/host.ts +0 -6
  72. package/src/GraphGenomeView/model.test.ts +115 -0
  73. package/src/GraphGenomeView/model.ts +1 -0
  74. package/src/GraphGenomeView/pane/graphViews.ts +2 -2
  75. package/src/GraphGenomeView/pane/launchActions.ts +17 -11
  76. package/src/GraphGenomeView/pane/loadActions.ts +86 -25
  77. package/src/GraphGenomeView/pane/paneBase.ts +14 -1
  78. package/src/GraphGenomeView/pane/renderingActions.ts +1 -10
  79. package/src/GraphGenomeView/pane/settingActions.ts +4 -4
  80. package/src/GraphGenomeView/viewModel.ts +6 -14
  81. package/src/LinearGraphDisplay/components/SubgraphContextSelect.tsx +6 -3
  82. package/src/RgfaTabixAdapter/RgfaTabixAdapter.test.ts +219 -0
  83. package/src/RgfaTabixAdapter/RgfaTabixAdapter.ts +31 -4
  84. package/src/RgfaTabixAdapter/configSchema.ts +8 -7
  85. package/src/RgfaTabixAdapter/rgfaBed.ts +64 -6
  86. package/src/RgfaTabixAdapter/test_data/rgfa_ecoli_anchored.links.bed.gz +0 -0
  87. package/src/RgfaTabixAdapter/test_data/rgfa_ecoli_anchored.links.bed.gz.tbi +0 -0
  88. package/src/RgfaTabixAdapter/test_data/rgfa_ecoli_anchored.segs.bed.gz +0 -0
  89. package/src/RgfaTabixAdapter/test_data/rgfa_ecoli_anchored.segs.bed.gz.tbi +0 -0
  90. package/src/gaf/gafFile.ts +5 -5
  91. package/src/graphTrackDefaults/index.ts +1 -1
  92. package/src/launchFromGraph/launchTracks.test.ts +23 -0
  93. package/src/launchFromGraph/launchTracks.ts +8 -1
  94. package/src/locationName.ts +35 -0
  95. package/src/panSNTabix.ts +1 -1
  96. package/src/version.ts +1 -1
  97. package/dist/chunks/AddTrackWorkflow-ANWIWCO6.js +0 -2
  98. package/dist/chunks/AddTrackWorkflow-ANWIWCO6.js.map +0 -7
  99. package/dist/chunks/ChooseSamplesDialog-OYAB355I.js +0 -2
  100. package/dist/chunks/ChooseSamplesDialog-OYAB355I.js.map +0 -7
  101. package/dist/chunks/ChooseWalksDialog-HJE4CAKU.js +0 -2
  102. package/dist/chunks/ChooseWalksDialog-HJE4CAKU.js.map +0 -7
  103. package/dist/chunks/GraphGenomeView-ZB4ED45M.js +0 -10
  104. package/dist/chunks/GraphTrackSettingsDialog-UPAINCUZ.js +0 -4
  105. package/dist/chunks/GraphTrackSettingsDialog-UPAINCUZ.js.map +0 -7
  106. package/dist/chunks/HighlightColorDialog-LXT72W7R.js +0 -2
  107. package/dist/chunks/LinearGraphDisplay-TQX7ZJZF.js +0 -2
  108. package/dist/chunks/RgfaTabixAdapter-GYRNCGT2.js +0 -3
  109. package/dist/chunks/RgfaTabixAdapter-GYRNCGT2.js.map +0 -7
  110. package/dist/chunks/chunk-4T7DPQTR.js +0 -2
  111. package/dist/chunks/chunk-4T7DPQTR.js.map +0 -7
  112. package/dist/chunks/chunk-7KFSWOWX.js +0 -3
  113. package/dist/chunks/chunk-7KFSWOWX.js.map +0 -7
  114. package/dist/chunks/chunk-GXQ7NYB3.js +0 -2
  115. package/dist/chunks/chunk-GXQ7NYB3.js.map +0 -7
  116. package/dist/chunks/chunk-JC7I7V6M.js +0 -2
  117. package/dist/chunks/chunk-JC7I7V6M.js.map +0 -7
  118. package/dist/chunks/chunk-OU6VYHKB.js +0 -2
  119. package/dist/chunks/chunk-OU6VYHKB.js.map +0 -7
  120. package/dist/chunks/renderSvg-J7L374ND.js +0 -2
  121. package/dist/chunks/renderSvg-J7L374ND.js.map +0 -7
  122. /package/dist/chunks/{MinigraphBubbleAdapter-CAXB5FGR.js.map → MinigraphBubbleAdapter-MF7DZTI5.js.map} +0 -0
@@ -1,8 +1,8 @@
1
- import{a as Ln,b as Hs,c as Gr,d as zr}from"./chunk-2SIR336R.js";import{f as Bs,g as kn,h as me,i as _n,j as On,k as vt,l as Nn,m as It,o as Tn}from"./chunk-WUGRVNUJ.js";import{a as Fn,b as $n}from"./chunk-EHV7EUMI.js";import"./chunk-MYJYGSOH.js";import{a as qr}from"./chunk-KWAXLUPQ.js";import"./chunk-YBLNN5FU.js";import{e as St,f as ze,g as Pn}from"./chunk-DILFGQIL.js";import"./chunk-E7J6SB5P.js";import{a as Ds,d as Br,e as Hr,f as Dr}from"./chunk-4T7DPQTR.js";import{a as ot}from"./chunk-J4OLMLS5.js";import{a as qs,b as le}from"./chunk-FY3BTKY4.js";var Cs=qs((fd,As)=>{As.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function Se(r,e){return 2*r+(e==="reverse"?1:0)}function O(r){return Math.floor(r/2)}function je(r){return r%2===0?"forward":"reverse"}function j(r){return r%2===1}function re(r){return r%2===0?r+1:r-1}function jr(r){return r==="left"?"right":"left"}function Et(r){return r==="forward"?"left":"right"}function At(r){return r==="forward"?"right":"left"}function Ur(r){return r==="left"?"forward":"reverse"}function Wr(r){return r==="right"?"forward":"reverse"}function Ue(r,e){let t=O(r),n=O(e);return j(r)?n>t||n===t&&!j(e):n>=t}function st(r){return Fe(r[0],r[r.length-1])}function Fe(r,e){return r===void 0||e===void 0?!0:j(r)===j(e)?!j(r):Ue(r,e)}var it=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},Vr=255,Gs=256,Ct=class{source;sigma;threshold;constructor(e,t){this.source=new it(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<Vr?Math.floor(Gs/this.sigma):0}next(){if(this.sigma>=Vr){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let o=this.source.int();if(o===void 0)return;n+=o}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Qr(r){let e=new it(r),t=e.int();if(t===void 0||t===0)return[];let n=[],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,n.push({node:o,offset:a})}return n}var Mt=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Ct(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),n=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(n+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-n)};t[o.value]=i+o.len,n+=o.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let o=t+n>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:n=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(n+=s.len,n>e.offset))return o-(n-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:re(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 n=0;for(let o of t)if(n+=o.count,n>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 n=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++)n[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:n,offsets:o}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let o=this.edge(n.value);for(let s=0;s<n.len;s++)t.push({node:o.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var zs=["","A","C","G","T","N"];function Yr(r){let e=r[r.length-1];if(e===void 0)return 0;let t=e,n=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),n+=1;return 3*(r.length-1)+n}function Kr(r){let e="";for(let t of r){let n=t;for(let o=0;o<3;o++){let s=zs[n%6];if(s==="")return e;n=Math.floor(n/6),e+=s}}return e}var js={A:"T",C:"G",G:"C",T:"A",N:"N"};function Rt(r){let e="";for(let t=r.length-1;t>=0;t--)e+=js[r[t]]??"N";return e}var Us=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ee=(r,e)=>r>>>e|r<<32-e;function Xr(r){let e=Math.ceil((r.length+9)/64),t=new Uint8Array(e*64);t.set(r),t[r.length]=128;let n=new DataView(t.buffer),o=r.length*8;n.setUint32(t.length-8,Math.floor(o/2**32)),n.setUint32(t.length-4,o>>>0);let s=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let c=0;c<e;c++){for(let S=0;S<16;S++)i[S]=n.getUint32(c*64+S*4);for(let S=16;S<64;S++){let g=i[S-15],x=i[S-2],y=Ee(g,7)^Ee(g,18)^g>>>3,E=Ee(x,17)^Ee(x,19)^x>>>10;i[S]=i[S-16]+y+i[S-7]+E}let l=s[0],h=s[1],d=s[2],p=s[3],m=s[4],u=s[5],w=s[6],b=s[7];for(let S=0;S<64;S++){let g=Ee(m,6)^Ee(m,11)^Ee(m,25),x=m&u^~m&w,y=b+g+x+Us[S]+i[S]|0,E=Ee(l,2)^Ee(l,13)^Ee(l,22),A=l&h^l&d^h&d;b=w,w=u,u=m,m=p+y|0,p=d,d=h,h=l,l=y+E+A|0}[l,h,d,p,m,u,w,b].forEach((S,g)=>{s[g]=s[g]+S})}let a=new Uint8Array(32),f=new DataView(a.buffer);for(let c=0;c<8;c++)f.setUint32(c*4,s[c]);return a}function Zr(r,e){let t=new Map;if(r!==void 0)for(let n of r.split(";")){let o=n.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${n}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function to(r){return{name:r.get("pggname"),subgraph:Zr(r.get("subgraph"),"subgraph"),translation:Zr(r.get("translation"),"translation")}}function Jr(r,e){for(let[t,n]of e){let o=r.get(t);o||(o=new Set,r.set(t,o));for(let s of n)o.add(s)}}function no(r,e){let t={name:r,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(r,new Set([e.name])),Jr(t.subgraph,e.subgraph),Jr(t.translation,e.translation)),t}function eo(r){return[...r.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function ro(r){let e=[];r.name!==void 0&&e.push(`H NM:Z:${r.name}`);for(let[t,n]of eo(r.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of eo(r.translation))e.push(`H TL:Z:${t},${n}`);return e}async function oo(r){let e=r.reduce((i,a)=>i+a.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;let o=globalThis.crypto?.subtle;return[...o?new Uint8Array(await o.digest("SHA-256",t)):Xr(t)].map(i=>i.toString(16).padStart(2,"0")).join("")}var Ws="_gbwt_ref";function we(r){let e=`${r.sample}#${r.haplotype}#${r.contig}`;return r.end===void 0?e:`${e}[${r.fragment}-${r.end}]`}var Vs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Qs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ys(r){let e=Vs.exec(r);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Qs.exec(r);if(t)return{contig:t[1]};throw new Error(`"${r}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function We(r){return typeof r=="string"?Ys(r):r}function Ve(r,e){return{sample:r.sample??Ws,contig:r.contig,haplotype:r.haplotype??0,fragment:e}}var Ks=4096;function Bn(r){let e=[];for(let t of r){let n=e[e.length-1];n&&t-n[1]<=Ks?n[1]=t:e.push([t,t])}return e}var Xs=32768,so={mostChosenPaths:32},qn=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},ie=class extends Error{};function Pt(r,e,t,n){return r==="forward"?e+t:e-n}function io(r,e,t,n){return r==="forward"?e-n:e+t}function ao(r){return Fe(re(r.handles[r.handles.length-1]),re(r.handles[0]))}function at(r){return`${r.pathHandle}:${r.hapStart}:${r.hapEnd}`}async function fo(r){let{db:e,records:t,signal:n}=r,o=performance.now(),s=()=>{let I=performance.now(),M=I-o;return o=I,M},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},a=(I,M)=>{let _=`${I}: ${M}`;i.walks[_]=(i.walks[_]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async I=>{let M=t.get(I)??c.get(I);if(M)return M;let _=await e.getRecord(I);if(i.graphFetches+=1,!_)throw new Error(`Node record ${I} is missing from the database`);return c.set(I,_),_},h=I=>t.get(I).sequenceLen,d=await e.pathsByHandle(),p=I=>{let M=d.get(I);return M!==void 0&&r.keep(M.name)},m=[],u=new qn,w=new Map,b=new Set,S=new Set,g=async I=>{let M=(await l(I.node)).gbwt().lf(I.offset);return M===void 0||M.node===0?void 0:M},x=async(I,M)=>{let _=(await l(re(I.node))).gbwt().predecessorAt(I.offset);if(_===void 0||M!==void 0&&!M.has(_))return;let L=(await l(_)).gbwt().offsetTo(I);if(L===void 0)throw new Error(`No offset in ${_} leads to ${I.node}:${I.offset}`);return{node:_,offset:L}},y=(I,M,_,L)=>{let B=_.map(V=>V.pos.node),W=_.map(V=>V.pos.offset),J=0;for(let V of B)J+=h(V);let q=M==="forward"?_[0].left:_[_.length-1].left,$=m.length;m.push({pathHandle:I,orientation:M,handles:B,offsets:W,len:J,hapStart:q,hapEnd:q+J,canonical:Fe(B[0],B[B.length-1]),source:L});for(let V of _)u.set(V.pos,$);let K=w.get(I);return K?K.push($):w.set(I,[$]),$},E=async(I,M,_,L)=>{let B=[],W=I;for(;;){n?.throwIfAborted();let q=await x(W.pos,t);if(!q)break;W={pos:q,left:io(_,W.left,h(W.pos.node),h(q.node))},B.push(W)}B.reverse();let J=[I];for(W=I;;){n?.throwIfAborted();let q=await g(W.pos);if(!q||!t.has(q.node))break;W={pos:q,left:Pt(_,W.left,h(W.pos.node),h(q.node))},J.push(W)}return y(M,_,[...B,...J],L)},A=async(I,M,_,L)=>m[u.get(I.pos)??await E(I,M,_,L)],N=I=>{let M=I.handles[I.handles.length-1];return{pos:{node:M,offset:I.offsets[I.offsets.length-1]},left:I.orientation==="forward"?I.hapEnd-h(M):I.hapStart}},k=I=>{let M=I.handles[0];return{pos:{node:M,offset:I.offsets[0]},left:I.orientation==="forward"?I.hapStart:I.hapEnd-h(M)}},F=await E({pos:r.referencePos,left:r.referenceLeft},r.referenceHandle,"forward","reference"),R=m[F],T=()=>{if(i.fallback!==void 0)return{reference:R,pieces:[],stats:i};let I=new Map;m.forEach((_,L)=>{L!==F&&I.set(at(_),[...I.get(at(_))??[],_])});let M=[];for(let _ of I.values()){let L=new Set;for(let B of _)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),M.push(B),i.sources[B.source]+=1)}return i.sources.reference=1,i.pieces=M.length+1,{reference:R,pieces:M,stats:i}},C=async(I,M)=>{let _=M?b:S,L=M?S:b,B=I;for(;;){if(_.has(B))return;_.add(B);let W=m[B],J=M?N(W):k(W),q=0,$;for(;$===void 0;){n?.throwIfAborted();let K=M?await g(J.pos):await x(J.pos);if(!K){$="endmarker";break}let V=(await l(J.pos.node)).sequenceLen,Ie=(await l(K.node)).sequenceLen,oe=M?Pt(W.orientation,J.left,V,Ie):io(W.orientation,J.left,V,Ie);if(t.has(K.node)){let ee=u.get(K);ee===void 0?(B=await E({pos:K,left:oe},W.pathHandle,W.orientation,"chain"),L.add(B),$="landed"):(L.add(ee),$="merge")}else q>Xs?$="bound":(q+=Ie,J={pos:K,left:oe})}if(a("chain",$),$!=="landed")return}},D=async I=>{if(r.context>I.context)throw new ie(`the context of ${r.context} bp exceeds the ${I.context} bp the haplotype index's stray rows cover`);let M=i.spacing;if(M===void 0)throw new ie("the haplotype index has no anchors");let{bin:_,bound:L}=I,{fills:B,inserted:W}=r.snarls;if(r.snarls.mode==="overlapping"&&B.length>0)throw new ie("the haplotype index's stray rows cover contained snarls only");for(let v of B){if(v.inserted>0&&v.low===v.high)throw new ie(`the haplotype index's stray rows leave out the snarl bounded by node ${v.low} at both ends`);if(v.inserted>0&&(I.snarlNodes===void 0||v.nodes>I.snarlNodes))throw new ie(I.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${v.nodes} nodes exceeds the ${I.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(r.window.start/_),q=Math.floor((r.window.end-1)/_),$=J*_,K=(q+1)*_,V=new Map,Ie=async(v,P)=>{let U=await e.haplotypeAnchorsBetween(r.referenceHandle,v*M,P*M);for(let G of U)V.set(G.anchorOffset/M,G)},oe=Math.max(0,Math.floor(($-L)/M)-1),ee=Math.ceil((K+L)/M)+1,[{listed:yt,strays:ce}]=await Promise.all([e.haplotypeBinData(r.referenceHandle,J,q),Ie(oe,ee)]);for(let v of t.keys()){let P=O(v);if(!j(v)&&!yt(P)&&!W.has(P))throw new ie(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}i.scans=Bn([...t.keys()].sort((v,P)=>v-P));let pe=Promise.all(i.scans.map(([v,P])=>e.haplotypeSamplesInRange(v,P)));for(pe.catch(()=>{});oe>0&&(V.get(oe)?.pathOffset??Number.POSITIVE_INFINITY)>=$-L;)oe-=1,await Ie(oe,oe);for(;V.has(ee)&&V.get(ee).pathOffset<=K+L;)ee+=1,await Ie(ee,ee);let be=[...V.keys()].sort((v,P)=>v-P),ke=V.get(be[0]??-1);if(!ke)throw new ie("the haplotype index has no anchors on this path");let ue=v=>V.get(v).pathOffset,tt=new Map;for(let v of be){let P=O(V.get(v).node);tt.set(P,[...tt.get(P)??[],v])}let Cn=[...tt.keys()],Mr=Cn.map(v=>V.get(tt.get(v)[0]).visits);if(!Mr[Cn.indexOf(O(ke.node))].some(v=>v.pathHandle===r.referenceHandle&&v.orientation==="forward"&&v.pathOffset===ke.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${r.referenceHandle} at offset ${ke.pathOffset} (node ${O(ke.node)}); it does not match this graph`);let Rr=be.filter(v=>ue(v)<=r.window.start),Ts=be.filter(v=>ue(v)>=r.window.end);i.anchors=[ue(Rr[Rr.length-1]??be[0]),ue(Ts[0]??be[be.length-1])],i.anchorsRead=be.length;let Mn=new Map,Pr=new Set;if(Cn.forEach((v,P)=>{let U=tt.get(v),G=U.length===1?U[0]:void 0;for(let z of Mr[P])Pr.add(z.pathHandle),z.orientation==="forward"&&p(z.pathHandle)&&Mn.set(z.pathHandle,[...Mn.get(z.pathHandle)??[],{k:G,row:z}])}),i.chosenPaths=[...Pr].filter(p).length,i.chosenPaths>so.mostChosenPaths)throw new ie(`${i.chosenPaths} chosen paths pass the anchors, more than ${so.mostChosenPaths}`);let bt=[],Le=Number.POSITIVE_INFINITY,_e=0;for(let[v,P]of Mn){P.sort((U,G)=>U.row.pathOffset-G.row.pathOffset);for(let U=0;U+1<P.length;U++){let G=P[U],z=P[U+1];if(G.k===void 0||z.k===void 0||Math.abs(G.k-z.k)!==1)continue;let[Z,te]=ue(G.k)<=ue(z.k)?[G,z]:[z,G],ne=ue(Z.k),se=ue(te.k);ne<K&&se>=$?(bt.push({pathHandle:v,from:G.row,to:z.row}),Le=Math.min(Le,ne-L),_e=Math.max(_e,se+L)):ne>=K&&ne-K<=L?(bt.push({pathHandle:v,from:Z.row,to:void 0}),Le=Math.min(Le,ne-L),_e=Math.max(_e,ne+L)):se<$&&$-se<=L&&(bt.push({pathHandle:v,from:te.row,to:void 0}),Le=Math.min(Le,se-L),_e=Math.max(_e,se+L))}}let Ls=new Set(B.map(v=>`${v.low}:${v.high}`)),Fs=ce.filter(v=>p(v.pathHandle)&&(v.snarl===void 0||Ls.has(`${v.snarl[0]}:${v.snarl[1]}`))).sort((v,P)=>v.pathHandle-P.pathHandle||v.pathStart-P.pathStart);i.strays={bins:q-J+1,rows:ce.length,walked:0,outsideBp:0},_e>0&&await r.prefetchReferenceRange(r.referenceHandle,Math.max(0,Le),_e+1),i.ms.scan=s();let kr=8*M+2*(r.window.end-r.window.start),_r=i.strays,nt=0,Or=v=>{if(_r.outsideBp+=v,nt+=v,nt>kr)throw new ie(`a walk of a chosen path near the window went past its cap of ${kr} bp`)},Rn=new Map,Nr=(v,P,U)=>(Rn.get(v)??[]).some(([G,z])=>G<=P&&U<z),Tr=(v,P,U)=>{Rn.set(v,[...Rn.get(v)??[],[P,U]])},Lr=async(v,P,U,G,z)=>{let Z=P,te=U,ne=te;for(;Z&&te<=G;){n?.throwIfAborted();let se;if(t.has(Z.node)){let rt=await A({pos:Z,left:te},v,"forward",z),$r=N(rt);Z=$r.pos,te=$r.left,se=h(Z.node),ne=Math.max(ne,rt.hapEnd)}else se=(await l(Z.node)).sequenceLen,Or(se),ne=Math.max(ne,te+se);Z=await g(Z),te+=se}return ne},$s=async(v,P,U,G)=>{let z={pos:P,left:U},Z=U;for(;z.left>G;){n?.throwIfAborted();let te=await x(z.pos);if(!te)break;let ne=(await l(te.node)).sequenceLen,se=z.left-ne;if(t.has(te.node)){let rt=await A({pos:te,left:se},v,"forward","section");z=k(rt),Z=Math.min(Z,rt.hapStart)}else Or(ne),z={pos:te,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:v,from:P,to:U}of bt){let G=P.pathOffset,z=(U??P).pathOffset+L;if(Nr(v,G-L,z))continue;let Z={node:P.node,offset:P.offset};nt=0;let te=await Lr(v,Z,G,z,"section");nt=0;let ne=await $s(v,Z,G,G-L);Tr(v,Math.min(ne,G-L),Math.max(te,z+1)),a(U?"section":"visit",U?"past the far anchor":"bound")}for(let v of Fs){if(Nr(v.pathHandle,v.pathStart,v.pathEnd))continue;nt=0;let P=await Lr(v.pathHandle,{node:v.node,offset:v.offset},v.pathStart,v.pathEnd,"stray");Tr(v.pathHandle,v.pathStart,Math.max(P,v.pathEnd+1)),_r.walked+=1}i.ms.walks=s();let Fr=[];for(let v of await pe)for(let P of v)if(i.scanRows+=1,t.has(P.node)&&p(P.pathHandle)){if(!(w.get(P.pathHandle)??[]).some(U=>{let G=m[U];return G.hapStart<=P.pathOffset&&P.pathOffset<G.hapEnd}))throw new ie(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&Fr.push(P)}for(let v of Fr)await A({pos:{node:v.node,offset:v.offset},left:v.pathOffset},v.pathHandle,"reverse","twin");i.ms.check=s()},Y=async()=>{let I=new Map,M=q=>{let $=at(q),K=I.get($);K?K.add(q.orientation):I.set($,new Set([q.orientation]))},_=0,L=()=>{for(;_<m.length;_++)M(m[_])};L();let B=q=>(I.get(at(q))?.size??0)>1,W=2*f,J=(q,$)=>$===F?p(r.referenceHandle)&&ao(q):!q.canonical||ao(q);for(let q=0;q<m.length;q++){let $=m[q];if(B($)||!J($,q))continue;i.twins.tried+=1;let K=$.orientation==="forward"?"reverse":"forward",V=N($),Ie=0,oe;for(;!oe&&Ie<=W;){n?.throwIfAborted();let ce=await g(V.pos);if(!ce)break;let pe=(await l(ce.node)).sequenceLen,be=Pt($.orientation,V.left,(await l(V.pos.node)).sequenceLen,pe),ke=re(ce.node);oe=(await e.haplotypeSamplesInRange(ke,ke)).find(ue=>ue.pathHandle===$.pathHandle&&ue.orientation===K&&ue.pathOffset===be),Ie+=pe,V={pos:ce,left:be}}let ee=oe&&{pos:{node:oe.node,offset:oe.offset},left:oe.pathOffset},yt=0;for(;ee&&!B($)&&yt<=W+$.len;){if(n?.throwIfAborted(),t.has(ee.pos.node)){let ce=await A(ee,$.pathHandle,K,"twin"),pe=m.indexOf(ce);await C(pe,!0),await C(pe,!1),L(),ee=N(ce)}if(!B($)){let ce=(await l(ee.pos.node)).sequenceLen;yt+=ce;let pe=await g(ee.pos);ee=pe?{pos:pe,left:Pt(K,ee.left,ce,(await l(pe.node)).sequenceLen)}:void 0}}if(L(),!B($))throw new ie(`piece ${at($)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()};try{let I=await e.haplotypeStrayOptions();if(I===void 0)throw new ie("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await D(I),await Y()}catch(I){if(!(I instanceof ie))throw I;i.fallback=I.message}return T()}function co(r,e){return r.handles[0]-e.handles[0]||r.offsets[0]-e.offsets[0]}function kt(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>1;r[o]<e?t=o+1:n=o}return t}var _t=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 n=e;n>0;n-=n&-n){let o=this.tree[n];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let n=e+1;n<this.tree.length;n+=n&-n){let o=this.tree[n];(o===-1||t>this.ending[o])&&(this.tree[n]=e)}}},Hn=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,n){this.a=e,this.b=t,this.weight=n,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,n,o){let s=0;for(;e+s<t&&n+s<o&&this.a[e+s]===this.b[n+s];)this.match(e+s,n+s),s+=1;let i=0;for(;t-i>e+s&&o-i>n+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,n+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,n,o){if(e===t||n===o)return;let s=this.matchCount(e,t,n,o);if(s===0)return;if(s<=t-e+(o-n)){this.chain(e,t,n,o,s);return}let i=e+t>>1,a=this.split(e,i,t,n,o);this.solve(e,i,n,a),this.solve(i,t,a,o)}matchCount(e,t,n,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=kt(a,o)-kt(a,n))}return s}sweep(e,t,n,o,s,i,a){for(let f=e;f!==t;f+=n){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),h=kt(c,o),d=kt(c,s);for(let p=0;p<d-h;p++){let m=n===1?c[d-1-p]-o:s-1-c[h+p],u=i.bestBefore(m),w=(u===-1?0:i.ending[u])+l;if(w>i.ending[m]&&(i.raise(m,w),a)){let b=a.count++;a.row[b]=f,a.column[b]=m,a.previous[b]=u===-1?-1:a.endingMatch[u],a.endingMatch[m]=b}}}}chain(e,t,n,o,s){let i=new _t(o-n),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-n),count:0};this.sweep(e,t,1,n,o,i,a);let f=i.bestBefore(o-n);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],n+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,n,o,s){let i=new _t(s-o);this.sweep(e,t,n,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,n,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(n-1,t-1,-1,o,s),c=0,l=-1;for(let h=0;h<=i;h++){let d=a[h]+f[i-h];d>l&&(l=d,c=h)}return o+c}};function lo(r,e,t){let n=new Hn(r,e,t);return n.solve(0,r.length,0,e.length),[n.pairs,n.total]}var Zs=100,zn=4e6,Js=5e3,he=15,ei=64,ti=8,xo=1,jn=-4,ae=-6,Me=-1,Qe=-(2**30),Nt=0,Dn=1,yo=2;function $e(r,e,t){let n=r.at(-1);t>0&&(n?.[0]===e?n[1]+=t:r.push([e,t]))}function Ot(r,e,t){return r>=t&&r>=e?Nt:t>=e?yo:Dn}function bo(r,e,t){let n=r.length,o=e.length,s=o+1,i=new Uint8Array((n+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 m=1;m<=o;m++)c[m]=ae+(m-1)*Me,i[m]=(m===1?Nt:yo)<<4;for(let m=1;m<=n;m++){let u=new Int32Array(s).fill(Qe),w=new Int32Array(s).fill(Qe),b=new Int32Array(s).fill(Qe);w[0]=ae+(m-1)*Me,i[m*s]=(m===1?Nt:Dn)<<2;let S=r.charCodeAt(m-1);for(let g=1;g<=o;g++){let x=Ot(a[g-1],f[g-1],c[g-1]);u[g]=Math.max(a[g-1],f[g-1],c[g-1])+(S===e.charCodeAt(g-1)?xo:jn);let y=Ot(a[g]+ae,f[g]+Me,c[g]+ae);w[g]=Math.max(a[g]+ae,f[g]+Me,c[g]+ae);let E=Ot(u[g-1]+ae,w[g-1]+ae,b[g-1]+Me);b[g]=Math.max(u[g-1]+ae,w[g-1]+ae,b[g-1]+Me),i[m*s+g]=x|y<<2|E<<4}a=u,f=w,c=b}let l=[],h=n,d=o,p=Ot(a[o],f[o],c[o]);for(;h>0||d>0;){let m=i[h*s+d]>>2*p&3;p===Nt?(l.push(r[h-1]===e[d-1]?"=":"X"),h-=1,d-=1):p===Dn?(l.push("I"),h-=1):(l.push("D"),d-=1),p=m}for(let m of l.reverse())$e(t,m,1)}function ni(r,e){let t=Math.abs(r-e);return(t===0?0:Math.min(-ae-(t-1)*Me,-ae+10*Math.log2(t)))+(Math.min(r,e)>0?-jn:0)}function So(r,e){let t=Math.abs(r-e);return t===0?0:.01*he*t+.5*Math.log2(t)}function ho(r,e,t){return{qs:r.qs+e,qe:r.qs+t,ts:r.flipped?r.te-t:r.ts+e,te:r.flipped?r.te-e:r.ts+t,flipped:r.flipped}}function ri(r,e,t){let n=r.qe-r.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-r.qs),l=Math.min(n,f-r.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,r.flipped?r.te-f:a-r.ts),l=Math.min(n,r.flipped?r.te-a:f-r.ts);c<l&&o.push([c,l])}if(o.length===0)return[r];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=he&&s.push(ho(r,i,a)),i=Math.max(i,f);return n-i>=he&&s.push(ho(r,i,n)),s}function Un(r,e,t,n,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...r].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),h=new Int32Array(f.length);for(let g=0;g<f.length;g++){let x=f[g],y=x.qe-x.qs;for(let E=g-1;E>=Math.max(0,g-Js);E--){if(c[E]+y<=c[g])continue;let A=f[E];if(A.flipped===x.flipped&&A.qs<x.qs&&(x.flipped?x.te<A.te:A.ts<x.ts)){let k=Math.max(0,A.qe-x.qs,x.flipped?x.te-A.ts:A.te-x.ts),F=x.qs+k-A.qe,R=x.flipped?A.ts-(x.te-k):x.ts+k-A.te;if(k<y&&F<=e&&R<=e){let T=c[E]+y-k-n(F,R);T>c[g]&&(c[g]=T,l[g]=E,h[g]=k)}}}}let d=new Int32Array(f.length),p=-1;for(let g=0;g<f.length;g++){let x=f[g];d[g]=(d[l[g]]??0)+x.qe-x.qs-h[g],d[g]>=t&&(p<0||c[g]>c[p])&&(p=g)}if(p<0)break;let m=[];for(let g=p;g>=0;g=l[g])m.push({run:f[g],trim:h[g]});m.reverse(),s.push(m);let u=m[0],w=m.at(-1),{flipped:b}=u.run,S=b?a.flipped:a.forward;S.query.push([u.run.qs+u.trim,w.run.qe]),S.target.push(b?[w.run.ts,u.run.te-u.trim]:[u.run.ts+u.trim,w.run.te]);for(let{run:g,trim:x}of m)i.query.push([g.qs+x,g.qe]),i.target.push(g.flipped?[g.ts,g.te-x]:[g.ts+x,g.te]);f=f.flatMap(g=>{let x=g.flipped?a.flipped:a.forward;return ri(g,[...i.query,...x.query],[...i.target,...x.target])}).sort((g,x)=>g.qs-x.qs||g.ts-x.ts)}return s}function Gn(r,e){let t=new Map;for(let s=0;s+he<=e.length;s++){let i=e.slice(s,s+he),a=t.get(i);a?a.push(s):t.set(i,[s])}let n=[],o=new Map;for(let s=0;s+he<=r.length;s++){let i=t.get(r.slice(s,s+he));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+he,c.te=a+he;else{let l={qs:s,qe:s+he,ts:a,te:a+he,flipped:!1};o.set(f,l),n.push(l)}}}return n}function oi(r,e){return[...Gn(r,e),...Gn(r,Rt(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Tt(r,e,t,n,o){let s;for(let{run:i,trim:a}of r){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,h=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?Rt(h):h,n,s.qe,c)}$e(n,"=",i.qe-f),s=i}}function Wn(r,e,t){$e(t,"I",r.length),$e(t,"D",e.length)}function vo(r,e,t){r.length*e.length<=zn?bo(r,e,t):Wn(r,e,t)}function Vn(r,e,t,n=0){let[o]=r.length*e.length>zn&&n<ti?Un(Gn(r,e),1/0,he,So,1):[];if(!o){vo(r,e,t);return}let s=(f,c,l)=>{Vn(f,c,l,n+1)},i=o[0].run,a=o.at(-1).run;s(r.slice(0,i.qs),e.slice(0,i.ts),t),Tt(o,r,e,t,s),s(r.slice(a.qe),e.slice(a.te),t)}function si(r,e,t){Vn(r,e,t)}function ii(r,e,t){let n=[];Tt(r,e,t,n,si);let o=r[0],s=r.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?n.reverse():n,sharedBases:0}}function ai(r,e,t,n){let o=[];if(r.length*e.length<=zn)bo(r,e,t);else{let s=Un(oi(r,e),1/0,Math.max(n,he),So),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>ii(a,r,e)),i){let a=(l,h,d,p,m)=>{o.some(w=>p<w.queryEnd&&w.queryStart<p+l.length||m<w.targetEnd&&w.targetStart<m+h.length)?vo(l,h,d):Vn(l,h,d)},f=i[0].run,c=i.at(-1).run;a(r.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Tt(i,r,e,t,a),a(r.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else Wn(r,e,t)}return o}function Qn(r,e){let t=r.strand==="-",n=0,o=0;for(let[s,i]of r.edits)e(s,i,t?r.queryEnd-1-n:r.queryStart+n,r.targetStart+o),s!=="D"&&(n+=i),s!=="I"&&(o+=i)}function po(r,e,t,n){let o=e==="query"&&r.strand==="-"?-1:1,s=0;return Qn(r,(i,a,f,c)=>{let l=e==="query"?f:c,h=d=>{let p=l+o*d;return p>=t&&p<n};if(i==="="||i==="X")for(let d=0;d<a;d++)h(d)&&(s+=i==="="?xo:jn);else if(i==="I"==(e==="query"))for(let d=0;d<a;d++)h(d)&&(s+=d===0?ae:Me);else h(0)&&(s+=ae+(a-1)*Me)}),s}function uo(r,e){return e==="query"?[r.queryStart,r.queryEnd]:[r.targetStart,r.targetEnd]}function fi(r,e){let t=r.strand==="-",n=[],o=0,s=0,i=0,a=0,f=new Uint8Array(r.queryEnd-r.queryStart);for(let[p,m]of r.shared)f.fill(1,p-r.queryStart,m-r.queryStart);let c=p=>f[p-r.queryStart]===1,l=()=>{$e(n,"I",o),$e(n,"D",s),o=0,s=0};Qn(r,(p,m,u)=>{if(p==="I")o+=m;else if(p==="D")s+=m;else{for(let w=0;w<m;w++)e[i+w]?(o+=1,s+=1,c(t?u-w:u+w)&&(a+=1)):((o>0||s>0)&&l(),$e(n,p,1));i+=m}}),l();let h={I:0,D:0};for(;n[0]?.[0]==="I"||n[0]?.[0]==="D";){let[p,m]=n.shift();h[p]+=m}let d={I:0,D:0};for(;n.at(-1)?.[0]==="I"||n.at(-1)?.[0]==="D";){let[p,m]=n.pop();d[p]+=m}return n.length===0?void 0:{...r,queryStart:r.queryStart+(t?d.I:h.I),queryEnd:r.queryEnd-(t?h.I:d.I),targetStart:r.targetStart+h.D,targetEnd:r.targetEnd-d.D,edits:n,sharedBases:r.sharedBases-a}}function ci(r,e,t,n){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=r.map(c=>{let l=[];Qn(c,(h,d,p,m)=>{if(h==="="||h==="X")for(let u=0;u<d;u++)l.push([c.strand==="-"?p-u:p+u,m+u])});for(let[h,d]of l)o.query[h]=Math.min(255,o.query[h]+1),o.target[d]=Math.min(255,o.target[d]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[h,d]of c)for(let[p,m]of[["query",h],["target",d]])if(o[p][m]>1){let u=i[p].get(m);u?u.at(-1)!==l&&u.push(l):i[p].set(m,[l])}});let a=new Map,f=(c,l,h)=>{let d=`${h}:${c}:${l}`,p=a.get(d);if(p===void 0){let[m,u]=uo(r[c],h),[w,b]=uo(r[l],h),S=Math.max(m,w),g=Math.min(u,b),[x,y]=[r[c],r[l]];p=[po(y,h,S,g)-po(x,h,S,g),y.sharedBases-x.sharedBases,c-l].find(A=>A!==0)>0,a.set(d,p)}return p};return r.flatMap((c,l)=>{let h=s[l],d=new Uint8Array(h.length);if(h.forEach(([u,w],b)=>{for(let[S,g]of[["query",u],["target",w]])!d[b]&&i[S].get(g)?.some(x=>x!==l&&f(l,x,S))&&(d[b]=1)}),!d.includes(1))return[c];let p=fi(c,d),m=p?.edits.reduce((u,[w,b])=>u+(w==="="?b:0),0)??0;return p&&m>=n?[p]:[]})}function mo(r,e){return r.map(t=>{let n=e(O(t));return j(t)?Rt(n):n}).join("")}function go(r,e){let t=[0];for(let n of r)t.push(t.at(-1)+e(O(n)).length);return t}function wo(r){let e=new Map,t=new Map;r.forEach((i,a)=>{let f=O(i);e.has(f)?t.set(f,a):e.set(f,a)});let n=new Int32Array(r.length+1);for(let[i,a]of t)n[e.get(i)]+=1,n[a+1]-=1;let o=new Uint8Array(r.length),s=0;for(let i=0;i<r.length;i++)s+=n[i],o[i]=s>0?1:0;return o}function li(r,e,t,n){let o=wo(r),s=wo(e),i=new Map;e.forEach((h,d)=>{s[d]||i.set(O(h),[d])});let a=2*e.length,f=(h,d,p)=>h*a+2*d+(p?1:0),c=new Set;r.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[])c.add(f(d,p,j(h)!==j(e[p])))});let l=[];return r.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[]){let m=j(h)!==j(e[p]),u=m?-1:1,w=p-u;if(!(d>0&&w>=0&&w<e.length&&c.has(f(d-1,w,m)))){let S=d,g=p;for(;S<r.length&&g>=0&&g<e.length&&c.has(f(S,g,m));)S+=1,g+=u;let x=g-u;l.push({qs:t[d],qe:t[S],ts:n[Math.min(p,x)],te:n[Math.max(p,x)+1],flipped:m})}}}),l}function Io(r){let{query:e,target:t,sequenceOf:n}=r,o=mo(e,n),s=mo(t,n),i=li(e,t,go(e,n),go(t,n)),a=r.minMatch??Zs,f=r.bases??!0,c=[];for(let l of Un(i,r.maxGap??1/0,a,ni)){let h=[],d=l[0],p=l.at(-1),{flipped:m}=d.run;Tt(l,o,s,h,f?(w,b,S,g,x)=>{for(let y of ai(w,b,S,a)){let E=x+b.length;c.push({...y,queryStart:g+y.queryStart,queryEnd:g+y.queryEnd,targetStart:m?E-y.targetEnd:x+y.targetStart,targetEnd:m?E-y.targetStart:x+y.targetEnd,strand:m?"+":"-",edits:m?y.edits.reverse():y.edits,shared:[]})}}:Wn),c.push({queryStart:d.run.qs+d.trim,queryEnd:p.run.qe,targetStart:m?p.run.ts:d.run.ts+d.trim,targetEnd:m?d.run.te-d.trim:p.run.te,strand:m?"-":"+",edits:m?h.reverse():h,sharedBases:l.reduce((w,{run:b,trim:S})=>w+b.qe-b.qs-S,0),shared:l.map(({run:w,trim:b})=>[w.qs+b,w.qe])})}return ci(c,o.length,s.length,a).map(({shared:l,...h})=>h).sort((l,h)=>l.queryStart-h.queryStart)}function Eo(r){return r.map(([e,t])=>`${t}${e}`).join("")}var fe=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 Yn(r,e){return r[0]<e[0]||r[0]===e[0]&&(r[1]<e[1]||r[1]===e[1]&&r[2]<e[2])}var ct=class{heap=[];push(e,t,n){let o=this.heap;o.push([e,t,n]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Yn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Yn(e[s],e[a])&&(a=s),i<e.length&&Yn(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 hi(r){let e=new Int32Array(r.length),t=new Int32Array(r.length);return r.forEach(([n,o],s)=>{e[s]=n,t[s]=o}),{pathAt:e,refAt:t,count:r.length}}function di(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>1;r[o]>e?n=o:t=o+1}return r[t]}function qe(r){return`${r.node}:${r.offset}`}function ft(r){return r.map(e=>re(e)).reverse()}function pi(r,e){let t=e.identity.hapStart-r.identity.hapEnd,n=r.strand==="+"?e.refStart-r.refEnd:r.refStart-e.refEnd;return r.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function ui(r,e,t){let[n,o]=r.strand==="+"?[r,e]:[e,r],s=n.edits.map(([c,l])=>[c,l]);Co(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=r.identity.walkForward,[a,f]=i?[r,e]:[e,r];return{strand:r.strand,refStart:n.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:r.identity.pathHandle,name:r.identity.name,hapStart:r.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function mi(r,e,t){if(r.some(i=>i.weight!==void 0))return r;let n=new Map;r.forEach((i,a)=>{if(i.identity){let f=n.get(i.identity.pathHandle);f?f.push(a):n.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of n.values()){i.sort((l,h)=>r[l].identity.hapStart-r[h].identity.hapStart);let a=i[0],f=r[a],c=[];for(let l of i.slice(1)){let h=r[l],d=c.length===0?pi(f,h):void 0;if(d){f=ui(f,h,d),s.add(l);continue}if(!e(h)){c.push(l);continue}let p=e(f)?t([f,...c.map(m=>r[m]),h]):void 0;if(p){f=p;for(let m of[...c,l])s.add(m)}else o.set(a,f),a=l,f=h;c=[]}o.set(a,f)}return r.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function Lt(r,e){return{node:r.path[e],offset:r.offsets[e]}}var gi=32768;function wi(r){let e=[...r].sort((n,o)=>n-o),t=[];for(let n of e){let o=t[t.length-1];o&&n-o[1]<=gi?o[1]=n:t.push([n,n])}return t}var lt=class r{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new r(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(Se(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 fe(this.limit);let t=await this.db.getRecord(Se(e,"forward")),n=await this.db.getRecord(Se(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${we(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${we(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,n);if(!o)throw new Error(`The fragment of ${we(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,o.pathOffset,o.pos)}async findPathPosition(e,t,n,o){let s=n,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(`The fragment of ${we(e.name)} at ${e.name.fragment} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,n){let o=O(e);await this.ensureNode(o);let s=this.record(e),i=je(e),a=new ct;return a.push(t,o,Et(i)),a.push(s.sequenceLen-t-1,o,At(i)),this.insertContext(a,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);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,n);await this.db.prefetchRecords(wi(c.map(l=>l.pos.node)).map(([l,h])=>[l,h+2]),!0)}}return o}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(o){throw o instanceof fe&&o.windowBp===void 0?new fe(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new ct;for(;;){let f=O(o.node),c=je(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,Et(c));let h=l.sequenceLen-s;if(i<=h){a.push(i===h?0:h-i-1,f,At(c));break}a.push(0,f,At(c));let d=l.gbwt().lf(o.offset);if(!d)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=d,s=0,i-=h}return this.walkedBp=t,this.insertContext(a,n)}async aroundNodes(e,t){let n=new ct;for(let o of e)await this.ensureNode(o),n.push(0,o,"left"),n.push(0,o,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,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(n.has(c))continue;n.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=jr(f);if(!n.has(`${a}:${l}`)){let p=this.record(Se(a,Ur(f))),m=i+p.sequenceLen-1;m<=t&&e.push(m,a,l)}let h=this.record(Se(a,Wr(f))),d=i+1;if(d<=t)for(let p of h.successors()){let m=O(p),u=Et(je(p));n.has(`${m}:${u}`)||e.push(d,m,u)}}for(let i of o)this.records.delete(Se(i,"forward")),this.records.delete(Se(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,re(t)],o=new Set([O(e),O(t)]),s=[];for(;n.length>0;){let i=n.pop(),a=O(i);this.hasNode(a)||(await this.addNode(a),s.push(a));for(let f of this.record(i).successors()){let c=O(f);o.has(c)||(n.push(f,re(f)),o.add(c))}}return{inserted:s,nodes:o.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,o]of await this.overlappingSnarls(e)){let{inserted:s,nodes:i}=await this.fillBetween(n,o),a=O(n),f=O(o);this.snarlFills.push({low:Math.min(a,f),high:Math.max(a,f),nodes:i,inserted:s.length});for(let c of s)this.snarlNodes.add(c);t+=s.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(n=!0,this.hasHandle(i)?Ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(o=>this.hasHandle(o));return n===void 0?!1:t.length>1||this.record(re(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let o=this.records.get(n);if(o)return o;let s=t.get(n);if(!s){if(s=await this.db.getRecord(n),e?.(),!s)throw new Error(`Node record ${n} is missing from the database`);t.set(n,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(re(l))).successors().length>1},n=async f=>{let c=await e(re(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[re(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 n(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let h of["forward","reverse"])s.push(...(await e(Se(c,h))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((y,E)=>i.set(y,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let y=0;y<s;y++){let E=this.record(o[y]),A=E.gbwt().decompressArrays();f[y]=E.sequenceLen,c.push(A),a[y+1]=a[y]+A.nodes.length}let l=a[s],h=new Int32Array(l),d=new Int32Array(l),p=new Uint8Array(l);for(let y=0;y<s;y++){let E=c[y];h.set(E.nodes,a[y]),d.set(E.offsets,a[y])}c.length=0;for(let y=0;y<l;y++){let E=i.get(h[y]);E===void 0?h[y]=-1:(h[y]=E,p[a[E]+d[y]]=1)}let m=n===void 0?void 0:i.get(n.handle),u=n?.gbwtOffset,w,b=(y,E,A)=>{let N=[],k=0,F=0,R=-1,T=y,C=E;for(;;){T===m&&C===u&&(R=k),A&&(A.push(o[T]),N.push(C)),k+=1,F+=f[T];let D=a[T]+C,Y=h[D];if(Y<0)break;C=d[D],T=Y}return{offsets:N,len:F,refAt:R,last:T}},S=(y,E,A,N)=>{N>=0&&(this.refId=this.paths.length,w=N),this.paths.push({path:y,offsets:E,len:A,weight:void 0,identity:void 0})},g=new Int32Array(s);for(let y=0;y<s;y++){let E=o[y];if(!j(E)){let A=a[y],N=a[y+1]-A;for(let k=0;k<N;k++)if(p[A+k]===0){let F=[],{offsets:R,len:T,refAt:C,last:D}=b(y,k,F),Y=o[D];if(C>=0||Fe(E,Y)){if(S(F,R,T,C),!j(Y)){let I=i.get(re(Y));g[I]=g[I]+1}}else this.twinStarts.add(qe({node:E,offset:k}))}}}for(let y=0;y<s;y++){let E=o[y];if(j(E)){let A=a[y],N=a[y+1]-A,k=0;for(let R=0;R<N;R++)p[A+R]===0&&(k+=1);let F=(m===void 0||w!==void 0)&&k===g[y];for(let R=0;R<N;R++)if(p[A+R]===0){let T=F?void 0:b(y,R,void 0);if(T&&(T.refAt>=0||Fe(E,o[T.last]))){let C=[],{offsets:D,len:Y,refAt:I}=b(y,R,C);S(C,D,Y,I)}else this.twinStarts.add(qe({node:E,offset:R}))}}}let x=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),x&&(this.refId=this.paths.indexOf(x)),n){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let N of y.path.slice(0,w))E+=this.record(N).sequenceLen;let A=n.seqOffset-E;this.refInterval=[A,A+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:A,hapEnd:A+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,o=n&&!st(n)?ft(n):void 0,s=c=>o!==void 0&&Kn(c,o)===0||st(ft(c)),i=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,l)=>Kn(c.path,l.path)||c.len-l.len||(c===t?-1:l===t?1:0));let a=[],f;for(let c of this.paths){let l=a[a.length-1],h=i&&c!==t&&s(c.path);this.twinDeferred||=h,l&&Kn(l.path,c.path)===0&&!h?l.weight=(l.weight??1)+(c.weight??1):(c===t&&(f=a.length),a.push({...c,weight:c.weight??1}))}this.paths=a,this.refId=f}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=i=>`${i.pathHandle}:${i.hapStart}-${i.hapEnd}`,o=new Set;e?.identity&&t&&o.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let i of this.paths)i!==e&&i.identity?.orientation==="forward"&&o.add(n(i.identity));let s=this.paths.filter(i=>i===e||i.identity?.orientation!=="reverse"||!o.has(n(i.identity)));s.length<this.paths.length&&(this.paths=s,this.refId=e===void 0?void 0:s.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(i=>i.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((i,a)=>a!==this.refId&&i.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],o=this.paths.filter((i,a)=>a===this.refId||i.identity!==void 0&&e(i.identity.name)),s=new Set;for(let i of o)for(let a of i.path)s.add(O(a));for(let i of[...this.records.keys()])s.has(O(i))||this.records.delete(i);this.paths=o,this.refId=n===void 0?void 0:o.indexOf(n)}async extractChosenPaths(e,t,n,o){this.clearPaths();let s=e.position.seqOffset,i=await fo({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:s-e.position.nodeOffset,window:{start:s,end:s+t},context:o,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(l,h,d)=>this.prefetchReferenceRange(l,h,d)});if(this.stats.keep=i.stats,i.stats.fallback!==void 0)return!1;let a=await this.db.pathsByHandle(),f=l=>({path:l.handles,offsets:l.offsets,len:l.len,weight:void 0,identity:{pathHandle:l.pathHandle,name:l===i.reference?e.name:a.get(l.pathHandle).name,orientation:l.orientation,hapStart:l.hapStart,hapEnd:l.hapEnd}}),c=[i.reference,...i.pieces].sort(co);return this.paths=c.map(f),this.refId=c.indexOf(i.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[i.reference.hapStart,i.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Bn(this.sortedHandles());if(t.length===0)return;let n=new Map,o=await Promise.all(t.map(([u,w])=>this.db.haplotypeSamplesInRange(u,w)));for(let u of o.flat())n.set(qe(u),u);let s=u=>{let w=0,b=t.length-1;for(;w<b;){let g=w+b+1>>1;t[g][0]<=u?w=g:b=g-1}let S=t[w];return S[0]<=u&&u<=S[1]},i=new Map;this.paths.forEach((u,w)=>{u.path.length>0&&w!==this.refId&&i.set(qe(Lt(u,0)),w)});let a=this.stats.identification;a.interval=e,a.scans=t,a.windowSamples=n.size,this.paths.forEach((u,w)=>{w!==this.refId&&a.fragmentLengths.push(u.len)});let f=this.recordReader(()=>{this.stats.identificationFetches+=1,a.graphFetches+=1}),c=u=>(a.graphLookups+=1,f(u)),l=async(u,w)=>{if(s(u.node))return n.get(qe(u));this.stats.identificationFetches+=1,a.companionSeeks+=1,w.seeks+=1;let b=await this.db.haplotypeSampleAt(u.node,u.offset);return b||(a.companionMisses+=1),b},h=new Map,d=async u=>{let w=h.get(u);if(!w){let b=await this.db.getPath(u);if(!b)throw new Error(`Path ${u} is missing from the database`);w=b.name,h.set(u,w)}return w},p=(u,w,b)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.pathOffset-w}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.pathOffset+w+b},m=(u,w)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.hapStart-w}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.hapEnd+w};for(let u=0;u<this.paths.length;u++){let w=this.paths[u];if(u===this.refId||w.identity)continue;let b=[],S=new Set,g={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};a.chains.push(g);let x,y=0,E=u,A;for(;x===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){g.end="cycle";break}S.add(E);let T=this.paths[E];b.push({index:E,startBp:y}),g.fragments+=1;let C=y;for(let Y=0;Y<T.path.length;Y++){let I=Lt(T,Y),M=n.get(qe(I)),_=this.record(I.node).sequenceLen;if(M){x=p(M,C,_);break}C+=_}if(y+=T.len,x){g.end="in-fragment sample";break}let D=Lt(T,T.path.length-1);A=this.record(D.node).gbwt().lf(D.offset),E=void 0}if(A===void 0||A.node===0){g.end="endmarker";break}let N=qe(A),k=i.get(N);if(k!==void 0){let T=this.paths[k].identity;if(T){x=m(T,y),g.end="identified sibling";break}E=k;continue}this.records.has(A.node)&&(g.reentries+=1),this.twinStarts.has(N)&&(g.twinLandings+=1);let F=await l(A,g),R=await c(A.node);if(F){x=p(F,y,R.sequenceLen),g.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,g.steps+=1,y-b[b.length-1].startBp>4*e+4*R.sequenceLen){g.end="bound";break}y+=R.sequenceLen,A=R.gbwt().lf(A.offset)}if(x){g.pathHandle=x.pathHandle;let N=await d(x.pathHandle);for(let{index:k,startBp:F}of b){let R=this.paths[k];R.identity=x.orientation==="forward"?{pathHandle:x.pathHandle,name:N,orientation:"forward",hapStart:x.base+F,hapEnd:x.base+F+R.len}:{pathHandle:x.pathHandle,name:N,orientation:"reverse",hapStart:x.base-F-R.len,hapEnd:x.base-F}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,o)=>{let s=t.get(n);s?s.push(o):t.set(n,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,o)=>{t.push(t[o]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=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=n.get(e[f]);if(c){let l=di(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 n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=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 n;i+=1,a+=1,n+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return n}suffixMatches(e,t){let n=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 n;i+=1,a+=1,n+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return n}align(e,t,n){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(n,"M",i),Co(n,o-i-a,s-i-a),X(n,"M",a)}sharedWeight(e,t){let n=this.refIndex(t),o=0;for(let s of e)n.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=n??hi(lo(e,t,h=>this.record(h).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(h,d,p,m)=>{h===d?X(s,"D",i[m]-i[p]):p===m?X(s,"I",this.pathLen(e.slice(h,d))):this.align(e.slice(h,d),t.slice(p,m),s)},f=0,c=0,l=0;for(let h=0;h<o.count;h++){let d=o.pathAt[h],p=o.refAt[h];(c!==d||l!==p)&&a(c,d,l,p);let m=this.record(e[d]).sequenceLen;X(s,"M",m),f+=m,c=d+1,l=p+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 n=this.paths[this.refId].path,o;if(st(n)&&(t.identity===void 0||!st(ft(t.path))))o={...this.editsAgainst(t.path,n),flipped:!1};else{let s=ft(t.path),i=this.sharedWeight(t.path,n);if(this.sharedWeight(s,n)===0)o={...this.editsAgainst(t.path,n),flipped:!1};else if(i===0)o={...this.editsAgainst(s,n),flipped:!0};else{let f=this.editsAgainst(t.path,n),c=this.editsAgainst(s,n);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],o=(l,h,d,p)=>{let m=yi(l),u=this.paths[d[0]],w=this.paths[d[d.length-1]],b=u.identity,S=b?.orientation==="forward",[g,x]=S?[u,w]:[w,u];return{strand:h,refStart:e.start+m.leading,refEnd:e.start+n-m.trailing,edits:m.edits,weight:u.weight,path:d.flatMap(y=>this.paths[y].path),start:Lt(u,0),pieces:d,soloAligned:p,identity:b===void 0?void 0:{pathHandle:b.pathHandle,name:b.name,hapStart:b.name.fragment+g.identity.hapStart,hapEnd:b.name.fragment+x.identity.hapEnd,walkForward:S}}},s=l=>l.soloAligned.reduce((h,d)=>h+d,0),i=l=>l.pieces.reduce((h,d)=>h+this.paths[d].len,0),a=l=>2*s(l)>=i(l),f=l=>{let h=l[0],d=l[l.length-1],p=h.identity.walkForward;if(l.some((C,D)=>C.strand!==h.strand||C.identity.walkForward!==p||D>0&&C.identity.hapStart<l[D-1].identity.hapEnd))return;let m=p?l:[...l].reverse(),u=m.flatMap(C=>C.pieces),w=m.flatMap(C=>C.soloAligned),b=h.strand==="+"!==p,S=u.map(C=>this.paths[C]),g=S.slice(1).map((C,D)=>{let Y=S[D].identity;return p?C.identity.hapStart-Y.hapEnd:Y.hapStart-C.identity.hapEnd}),x=b?[...S].reverse():S,y=b?[...g].reverse():g,E=x.flatMap(C=>b?ft(C.path):C.path),{edits:A}=this.editsAgainst(E,t),N=Ao(A,x.map(C=>C.len)),k=new Map((b?[...u].reverse():u).map((C,D)=>[C,N[D]])),F=C=>2*C.pieces.reduce((D,Y)=>D+k.get(Y),0)>=s(C);if(!F(h)||!F(d))return;let R=[],T=0;return x.slice(0,-1).forEach((C,D)=>{T+=C.len,R.push([T,y[D]])}),o(bi(A,R),h.strand,u,w)},c=[];return this.paths.forEach((l,h)=>{if(h===this.refId)return;let{edits:d,flipped:p}=this.alignment(h),m=l.identity,u=m?m.orientation==="forward"!==p:!p;c.push(o(d,u?"+":"-",[h],Ao(d,[l.len])))}),mi(c,a,f).map(l=>{let{edits:h,identity:d,pieces:p,soloAligned:m,...u}=l,w={...u,cigar:Si(h)};return d?{...w,resolved:!0,name:d.name,label:we({...d.name,fragment:d.hapStart,end:d.hapEnd}),pathHandle:d.pathHandle,hapStart:d.hapStart,hapEnd:d.hapEnd}:{...w,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...o}=e,s=this.paths.flatMap(l=>{let{identity:h}=l;return h?[{name:h.name,start:h.name.fragment+h.hapStart,steps:$t(l,h)}]:[]}),i=l=>h=>h.sample===l.sample&&h.haplotype===l.haplotype,a=i(t),f=n?i(n):l=>!a(l),c=l=>this.record(Se(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(h=>f(h.name)).flatMap(h=>Io({...o,query:h.steps,target:l.steps,sequenceOf:c}).map(d=>({query:h.name,queryStart:h.start+d.queryStart,queryEnd:h.start+d.queryEnd,strand:d.strand,target:l.name,targetStart:l.start+d.targetStart,targetEnd:l.start+d.targetEnd,cigar:Eo(d.edits),matches:d.edits.reduce((p,[m,u])=>p+(m==="="?u:0),0),columns:d.edits.reduce((p,[,m])=>p+m,0),sharedBases:d.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let o=Se(e,n);for(let s of this.record(o).successors())this.hasHandle(s)&&Ue(o,s)&&t.push([n==="reverse"?1:0,O(s),j(s)?1:0])}return t.sort((n,o)=>n[0]-o[0]||n[1]-o[1]||n[2]-o[2]),t.filter((n,o)=>o===0||n[0]!==t[o-1][0]||n[1]!==t[o-1][1]||n[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!j(n)){let o=O(n),s=`S ${o} ${this.record(n).sequence}
1
+ import{a as Tn,b as Hs,c as zr,d as jr}from"./chunk-KALP44OF.js";import{f as Bs,g as qr,h as be,i as Pn,j as kn,k as vt,l as _n,m as On,o as Nn}from"./chunk-WUGRVNUJ.js";import{a as Ln,b as Fn}from"./chunk-EHV7EUMI.js";import"./chunk-MYJYGSOH.js";import{a as Gr}from"./chunk-KWAXLUPQ.js";import"./chunk-YBLNN5FU.js";import{e as St,f as ze,g as Rn}from"./chunk-DILFGQIL.js";import"./chunk-E7J6SB5P.js";import{b as Br,c as Hr,d as Dr,e as Ds}from"./chunk-K33IZSO2.js";import{a as ot}from"./chunk-J4OLMLS5.js";import{a as qs,b as le}from"./chunk-FY3BTKY4.js";var Ms=qs((fd,Cs)=>{Cs.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function Se(r,e){return 2*r+(e==="reverse"?1:0)}function O(r){return Math.floor(r/2)}function je(r){return r%2===0?"forward":"reverse"}function j(r){return r%2===1}function re(r){return r%2===0?r+1:r-1}function Ur(r){return r==="left"?"right":"left"}function It(r){return r==="forward"?"left":"right"}function Et(r){return r==="forward"?"right":"left"}function Wr(r){return r==="left"?"forward":"reverse"}function Vr(r){return r==="right"?"forward":"reverse"}function Ue(r,e){let t=O(r),n=O(e);return j(r)?n>t||n===t&&!j(e):n>=t}function st(r){return Fe(r[0],r[r.length-1])}function Fe(r,e){return r===void 0||e===void 0?!0:j(r)===j(e)?!j(r):Ue(r,e)}var it=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},Qr=255,Gs=256,At=class{source;sigma;threshold;constructor(e,t){this.source=new it(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<Qr?Math.floor(Gs/this.sigma):0}next(){if(this.sigma>=Qr){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,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let o=this.source.int();if(o===void 0)return;n+=o}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Yr(r){let e=new it(r),t=e.int();if(t===void 0||t===0)return[];let n=[],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,n.push({node:o,offset:a})}return n}var Ct=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new At(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),n=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(n+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-n)};t[o.value]=i+o.len,n+=o.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let o=t+n>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:n=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(n+=s.len,n>e.offset))return o-(n-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:re(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 n=0;for(let o of t)if(n+=o.count,n>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 n=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++)n[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:n,offsets:o}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let o=this.edge(n.value);for(let s=0;s<n.len;s++)t.push({node:o.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var zs=["","A","C","G","T","N"];function Kr(r){let e=r[r.length-1];if(e===void 0)return 0;let t=e,n=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),n+=1;return 3*(r.length-1)+n}function Xr(r){let e="";for(let t of r){let n=t;for(let o=0;o<3;o++){let s=zs[n%6];if(s==="")return e;n=Math.floor(n/6),e+=s}}return e}var js={A:"T",C:"G",G:"C",T:"A",N:"N"};function Mt(r){let e="";for(let t=r.length-1;t>=0;t--)e+=js[r[t]]??"N";return e}var Us=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ee=(r,e)=>r>>>e|r<<32-e;function Zr(r){let e=Math.ceil((r.length+9)/64),t=new Uint8Array(e*64);t.set(r),t[r.length]=128;let n=new DataView(t.buffer),o=r.length*8;n.setUint32(t.length-8,Math.floor(o/2**32)),n.setUint32(t.length-4,o>>>0);let s=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let c=0;c<e;c++){for(let S=0;S<16;S++)i[S]=n.getUint32(c*64+S*4);for(let S=16;S<64;S++){let g=i[S-15],x=i[S-2],y=Ee(g,7)^Ee(g,18)^g>>>3,E=Ee(x,17)^Ee(x,19)^x>>>10;i[S]=i[S-16]+y+i[S-7]+E}let l=s[0],h=s[1],d=s[2],p=s[3],m=s[4],u=s[5],w=s[6],b=s[7];for(let S=0;S<64;S++){let g=Ee(m,6)^Ee(m,11)^Ee(m,25),x=m&u^~m&w,y=b+g+x+Us[S]+i[S]|0,E=Ee(l,2)^Ee(l,13)^Ee(l,22),A=l&h^l&d^h&d;b=w,w=u,u=m,m=p+y|0,p=d,d=h,h=l,l=y+E+A|0}[l,h,d,p,m,u,w,b].forEach((S,g)=>{s[g]=s[g]+S})}let a=new Uint8Array(32),f=new DataView(a.buffer);for(let c=0;c<8;c++)f.setUint32(c*4,s[c]);return a}function Jr(r,e){let t=new Map;if(r!==void 0)for(let n of r.split(";")){let o=n.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${n}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function no(r){return{name:r.get("pggname"),subgraph:Jr(r.get("subgraph"),"subgraph"),translation:Jr(r.get("translation"),"translation")}}function eo(r,e){for(let[t,n]of e){let o=r.get(t);o||(o=new Set,r.set(t,o));for(let s of n)o.add(s)}}function ro(r,e){let t={name:r,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(r,new Set([e.name])),eo(t.subgraph,e.subgraph),eo(t.translation,e.translation)),t}function to(r){return[...r.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function oo(r){let e=[];r.name!==void 0&&e.push(`H NM:Z:${r.name}`);for(let[t,n]of to(r.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of to(r.translation))e.push(`H TL:Z:${t},${n}`);return e}async function so(r){let e=r.reduce((i,a)=>i+a.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;let o=globalThis.crypto?.subtle;return[...o?new Uint8Array(await o.digest("SHA-256",t)):Zr(t)].map(i=>i.toString(16).padStart(2,"0")).join("")}var Ws="_gbwt_ref";function ge(r){let e=`${r.sample}#${r.haplotype}#${r.contig}`;return r.end===void 0?e:`${e}[${r.fragment}-${r.end}]`}var Vs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Qs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ys(r){let e=Vs.exec(r);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Qs.exec(r);if(t)return{contig:t[1]};throw new Error(`"${r}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function We(r){return typeof r=="string"?Ys(r):r}function Ve(r,e){return{sample:r.sample??Ws,contig:r.contig,haplotype:r.haplotype??0,fragment:e}}var Ks=4096;function qn(r){let e=[];for(let t of r){let n=e[e.length-1];n&&t-n[1]<=Ks?n[1]=t:e.push([t,t])}return e}var Xs=32768,io={mostChosenPaths:32},$n=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},ie=class extends Error{};function Rt(r,e,t,n){return r==="forward"?e+t:e-n}function ao(r,e,t,n){return r==="forward"?e-n:e+t}function fo(r){return Fe(re(r.handles[r.handles.length-1]),re(r.handles[0]))}function at(r){return`${r.pathHandle}:${r.hapStart}:${r.hapEnd}`}async function co(r){let{db:e,records:t,signal:n}=r,o=performance.now(),s=()=>{let I=performance.now(),M=I-o;return o=I,M},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},a=(I,M)=>{let _=`${I}: ${M}`;i.walks[_]=(i.walks[_]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async I=>{let M=t.get(I)??c.get(I);if(M)return M;let _=await e.getRecord(I);if(i.graphFetches+=1,!_)throw new Error(`Node record ${I} is missing from the database`);return c.set(I,_),_},h=I=>t.get(I).sequenceLen,d=await e.pathsByHandle(),p=I=>{let M=d.get(I);return M!==void 0&&r.keep(M.name)},m=[],u=new $n,w=new Map,b=new Set,S=new Set,g=async I=>{let M=(await l(I.node)).gbwt().lf(I.offset);return M===void 0||M.node===0?void 0:M},x=async(I,M)=>{let _=(await l(re(I.node))).gbwt().predecessorAt(I.offset);if(_===void 0||M!==void 0&&!M.has(_))return;let L=(await l(_)).gbwt().offsetTo(I);if(L===void 0)throw new Error(`No offset in ${_} leads to ${I.node}:${I.offset}`);return{node:_,offset:L}},y=(I,M,_,L)=>{let B=_.map(V=>V.pos.node),W=_.map(V=>V.pos.offset),J=0;for(let V of B)J+=h(V);let q=M==="forward"?_[0].left:_[_.length-1].left,$=m.length;m.push({pathHandle:I,orientation:M,handles:B,offsets:W,len:J,hapStart:q,hapEnd:q+J,canonical:Fe(B[0],B[B.length-1]),source:L});for(let V of _)u.set(V.pos,$);let K=w.get(I);return K?K.push($):w.set(I,[$]),$},E=async(I,M,_,L)=>{let B=[],W=I;for(;;){n?.throwIfAborted();let q=await x(W.pos,t);if(!q)break;W={pos:q,left:ao(_,W.left,h(W.pos.node),h(q.node))},B.push(W)}B.reverse();let J=[I];for(W=I;;){n?.throwIfAborted();let q=await g(W.pos);if(!q||!t.has(q.node))break;W={pos:q,left:Rt(_,W.left,h(W.pos.node),h(q.node))},J.push(W)}return y(M,_,[...B,...J],L)},A=async(I,M,_,L)=>m[u.get(I.pos)??await E(I,M,_,L)],N=I=>{let M=I.handles[I.handles.length-1];return{pos:{node:M,offset:I.offsets[I.offsets.length-1]},left:I.orientation==="forward"?I.hapEnd-h(M):I.hapStart}},k=I=>{let M=I.handles[0];return{pos:{node:M,offset:I.offsets[0]},left:I.orientation==="forward"?I.hapStart:I.hapEnd-h(M)}},F=await E({pos:r.referencePos,left:r.referenceLeft},r.referenceHandle,"forward","reference"),R=m[F],T=()=>{if(i.fallback!==void 0)return{reference:R,pieces:[],stats:i};let I=new Map;m.forEach((_,L)=>{L!==F&&I.set(at(_),[...I.get(at(_))??[],_])});let M=[];for(let _ of I.values()){let L=new Set;for(let B of _)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),M.push(B),i.sources[B.source]+=1)}return i.sources.reference=1,i.pieces=M.length+1,{reference:R,pieces:M,stats:i}},C=async(I,M)=>{let _=M?b:S,L=M?S:b,B=I;for(;;){if(_.has(B))return;_.add(B);let W=m[B],J=M?N(W):k(W),q=0,$;for(;$===void 0;){n?.throwIfAborted();let K=M?await g(J.pos):await x(J.pos);if(!K){$="endmarker";break}let V=(await l(J.pos.node)).sequenceLen,Ie=(await l(K.node)).sequenceLen,oe=M?Rt(W.orientation,J.left,V,Ie):ao(W.orientation,J.left,V,Ie);if(t.has(K.node)){let ee=u.get(K);ee===void 0?(B=await E({pos:K,left:oe},W.pathHandle,W.orientation,"chain"),L.add(B),$="landed"):(L.add(ee),$="merge")}else q>Xs?$="bound":(q+=Ie,J={pos:K,left:oe})}if(a("chain",$),$!=="landed")return}},D=async I=>{if(r.context>I.context)throw new ie(`the context of ${r.context} bp exceeds the ${I.context} bp the haplotype index's stray rows cover`);let M=i.spacing;if(M===void 0)throw new ie("the haplotype index has no anchors");let{bin:_,bound:L}=I,{fills:B,inserted:W}=r.snarls;if(r.snarls.mode==="overlapping"&&B.length>0)throw new ie("the haplotype index's stray rows cover contained snarls only");for(let v of B){if(v.inserted>0&&v.low===v.high)throw new ie(`the haplotype index's stray rows leave out the snarl bounded by node ${v.low} at both ends`);if(v.inserted>0&&(I.snarlNodes===void 0||v.nodes>I.snarlNodes))throw new ie(I.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${v.nodes} nodes exceeds the ${I.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(r.window.start/_),q=Math.floor((r.window.end-1)/_),$=J*_,K=(q+1)*_,V=new Map,Ie=async(v,P)=>{let U=await e.haplotypeAnchorsBetween(r.referenceHandle,v*M,P*M);for(let G of U)V.set(G.anchorOffset/M,G)},oe=Math.max(0,Math.floor(($-L)/M)-1),ee=Math.ceil((K+L)/M)+1,[{listed:yt,strays:ce}]=await Promise.all([e.haplotypeBinData(r.referenceHandle,J,q),Ie(oe,ee)]);for(let v of t.keys()){let P=O(v);if(!j(v)&&!yt(P)&&!W.has(P))throw new ie(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}i.scans=qn([...t.keys()].sort((v,P)=>v-P));let pe=Promise.all(i.scans.map(([v,P])=>e.haplotypeSamplesInRange(v,P)));for(pe.catch(()=>{});oe>0&&(V.get(oe)?.pathOffset??Number.POSITIVE_INFINITY)>=$-L;)oe-=1,await Ie(oe,oe);for(;V.has(ee)&&V.get(ee).pathOffset<=K+L;)ee+=1,await Ie(ee,ee);let ye=[...V.keys()].sort((v,P)=>v-P),ke=V.get(ye[0]??-1);if(!ke)throw new ie("the haplotype index has no anchors on this path");let ue=v=>V.get(v).pathOffset,tt=new Map;for(let v of ye){let P=O(V.get(v).node);tt.set(P,[...tt.get(P)??[],v])}let An=[...tt.keys()],Mr=An.map(v=>V.get(tt.get(v)[0]).visits);if(!Mr[An.indexOf(O(ke.node))].some(v=>v.pathHandle===r.referenceHandle&&v.orientation==="forward"&&v.pathOffset===ke.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${r.referenceHandle} at offset ${ke.pathOffset} (node ${O(ke.node)}); it does not match this graph`);let Rr=ye.filter(v=>ue(v)<=r.window.start),Ts=ye.filter(v=>ue(v)>=r.window.end);i.anchors=[ue(Rr[Rr.length-1]??ye[0]),ue(Ts[0]??ye[ye.length-1])],i.anchorsRead=ye.length;let Cn=new Map,Pr=new Set;if(An.forEach((v,P)=>{let U=tt.get(v),G=U.length===1?U[0]:void 0;for(let z of Mr[P])Pr.add(z.pathHandle),z.orientation==="forward"&&p(z.pathHandle)&&Cn.set(z.pathHandle,[...Cn.get(z.pathHandle)??[],{k:G,row:z}])}),i.chosenPaths=[...Pr].filter(p).length,i.chosenPaths>io.mostChosenPaths)throw new ie(`${i.chosenPaths} chosen paths pass the anchors, more than ${io.mostChosenPaths}`);let bt=[],Le=Number.POSITIVE_INFINITY,_e=0;for(let[v,P]of Cn){P.sort((U,G)=>U.row.pathOffset-G.row.pathOffset);for(let U=0;U+1<P.length;U++){let G=P[U],z=P[U+1];if(G.k===void 0||z.k===void 0||Math.abs(G.k-z.k)!==1)continue;let[Z,te]=ue(G.k)<=ue(z.k)?[G,z]:[z,G],ne=ue(Z.k),se=ue(te.k);ne<K&&se>=$?(bt.push({pathHandle:v,from:G.row,to:z.row}),Le=Math.min(Le,ne-L),_e=Math.max(_e,se+L)):ne>=K&&ne-K<=L?(bt.push({pathHandle:v,from:Z.row,to:void 0}),Le=Math.min(Le,ne-L),_e=Math.max(_e,ne+L)):se<$&&$-se<=L&&(bt.push({pathHandle:v,from:te.row,to:void 0}),Le=Math.min(Le,se-L),_e=Math.max(_e,se+L))}}let Ls=new Set(B.map(v=>`${v.low}:${v.high}`)),Fs=ce.filter(v=>p(v.pathHandle)&&(v.snarl===void 0||Ls.has(`${v.snarl[0]}:${v.snarl[1]}`))).sort((v,P)=>v.pathHandle-P.pathHandle||v.pathStart-P.pathStart);i.strays={bins:q-J+1,rows:ce.length,walked:0,outsideBp:0},_e>0&&await r.prefetchReferenceRange(r.referenceHandle,Math.max(0,Le),_e+1),i.ms.scan=s();let kr=8*M+2*(r.window.end-r.window.start),_r=i.strays,nt=0,Or=v=>{if(_r.outsideBp+=v,nt+=v,nt>kr)throw new ie(`a walk of a chosen path near the window went past its cap of ${kr} bp`)},Mn=new Map,Nr=(v,P,U)=>(Mn.get(v)??[]).some(([G,z])=>G<=P&&U<z),Tr=(v,P,U)=>{Mn.set(v,[...Mn.get(v)??[],[P,U]])},Lr=async(v,P,U,G,z)=>{let Z=P,te=U,ne=te;for(;Z&&te<=G;){n?.throwIfAborted();let se;if(t.has(Z.node)){let rt=await A({pos:Z,left:te},v,"forward",z),$r=N(rt);Z=$r.pos,te=$r.left,se=h(Z.node),ne=Math.max(ne,rt.hapEnd)}else se=(await l(Z.node)).sequenceLen,Or(se),ne=Math.max(ne,te+se);Z=await g(Z),te+=se}return ne},$s=async(v,P,U,G)=>{let z={pos:P,left:U},Z=U;for(;z.left>G;){n?.throwIfAborted();let te=await x(z.pos);if(!te)break;let ne=(await l(te.node)).sequenceLen,se=z.left-ne;if(t.has(te.node)){let rt=await A({pos:te,left:se},v,"forward","section");z=k(rt),Z=Math.min(Z,rt.hapStart)}else Or(ne),z={pos:te,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:v,from:P,to:U}of bt){let G=P.pathOffset,z=(U??P).pathOffset+L;if(Nr(v,G-L,z))continue;let Z={node:P.node,offset:P.offset};nt=0;let te=await Lr(v,Z,G,z,"section");nt=0;let ne=await $s(v,Z,G,G-L);Tr(v,Math.min(ne,G-L),Math.max(te,z+1)),a(U?"section":"visit",U?"past the far anchor":"bound")}for(let v of Fs){if(Nr(v.pathHandle,v.pathStart,v.pathEnd))continue;nt=0;let P=await Lr(v.pathHandle,{node:v.node,offset:v.offset},v.pathStart,v.pathEnd,"stray");Tr(v.pathHandle,v.pathStart,Math.max(P,v.pathEnd+1)),_r.walked+=1}i.ms.walks=s();let Fr=[];for(let v of await pe)for(let P of v)if(i.scanRows+=1,t.has(P.node)&&p(P.pathHandle)){if(!(w.get(P.pathHandle)??[]).some(U=>{let G=m[U];return G.hapStart<=P.pathOffset&&P.pathOffset<G.hapEnd}))throw new ie(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&Fr.push(P)}for(let v of Fr)await A({pos:{node:v.node,offset:v.offset},left:v.pathOffset},v.pathHandle,"reverse","twin");i.ms.check=s()},Y=async()=>{let I=new Map,M=q=>{let $=at(q),K=I.get($);K?K.add(q.orientation):I.set($,new Set([q.orientation]))},_=0,L=()=>{for(;_<m.length;_++)M(m[_])};L();let B=q=>(I.get(at(q))?.size??0)>1,W=2*f,J=(q,$)=>$===F?p(r.referenceHandle)&&fo(q):!q.canonical||fo(q);for(let q=0;q<m.length;q++){let $=m[q];if(B($)||!J($,q))continue;i.twins.tried+=1;let K=$.orientation==="forward"?"reverse":"forward",V=N($),Ie=0,oe;for(;!oe&&Ie<=W;){n?.throwIfAborted();let ce=await g(V.pos);if(!ce)break;let pe=(await l(ce.node)).sequenceLen,ye=Rt($.orientation,V.left,(await l(V.pos.node)).sequenceLen,pe),ke=re(ce.node);oe=(await e.haplotypeSamplesInRange(ke,ke)).find(ue=>ue.pathHandle===$.pathHandle&&ue.orientation===K&&ue.pathOffset===ye),Ie+=pe,V={pos:ce,left:ye}}let ee=oe&&{pos:{node:oe.node,offset:oe.offset},left:oe.pathOffset},yt=0;for(;ee&&!B($)&&yt<=W+$.len;){if(n?.throwIfAborted(),t.has(ee.pos.node)){let ce=await A(ee,$.pathHandle,K,"twin"),pe=m.indexOf(ce);await C(pe,!0),await C(pe,!1),L(),ee=N(ce)}if(!B($)){let ce=(await l(ee.pos.node)).sequenceLen;yt+=ce;let pe=await g(ee.pos);ee=pe?{pos:pe,left:Rt(K,ee.left,ce,(await l(pe.node)).sequenceLen)}:void 0}}if(L(),!B($))throw new ie(`piece ${at($)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()};try{let I=await e.haplotypeStrayOptions();if(I===void 0)throw new ie("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await D(I),await Y()}catch(I){if(!(I instanceof ie))throw I;i.fallback=I.message}return T()}function lo(r,e){return r.handles[0]-e.handles[0]||r.offsets[0]-e.offsets[0]}function Pt(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>1;r[o]<e?t=o+1:n=o}return t}var kt=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 n=e;n>0;n-=n&-n){let o=this.tree[n];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let n=e+1;n<this.tree.length;n+=n&-n){let o=this.tree[n];(o===-1||t>this.ending[o])&&(this.tree[n]=e)}}},Bn=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,n){this.a=e,this.b=t,this.weight=n,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,n,o){let s=0;for(;e+s<t&&n+s<o&&this.a[e+s]===this.b[n+s];)this.match(e+s,n+s),s+=1;let i=0;for(;t-i>e+s&&o-i>n+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,n+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,n,o){if(e===t||n===o)return;let s=this.matchCount(e,t,n,o);if(s===0)return;if(s<=t-e+(o-n)){this.chain(e,t,n,o,s);return}let i=e+t>>1,a=this.split(e,i,t,n,o);this.solve(e,i,n,a),this.solve(i,t,a,o)}matchCount(e,t,n,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Pt(a,o)-Pt(a,n))}return s}sweep(e,t,n,o,s,i,a){for(let f=e;f!==t;f+=n){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),h=Pt(c,o),d=Pt(c,s);for(let p=0;p<d-h;p++){let m=n===1?c[d-1-p]-o:s-1-c[h+p],u=i.bestBefore(m),w=(u===-1?0:i.ending[u])+l;if(w>i.ending[m]&&(i.raise(m,w),a)){let b=a.count++;a.row[b]=f,a.column[b]=m,a.previous[b]=u===-1?-1:a.endingMatch[u],a.endingMatch[m]=b}}}}chain(e,t,n,o,s){let i=new kt(o-n),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-n),count:0};this.sweep(e,t,1,n,o,i,a);let f=i.bestBefore(o-n);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],n+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,n,o,s){let i=new kt(s-o);this.sweep(e,t,n,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,n,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(n-1,t-1,-1,o,s),c=0,l=-1;for(let h=0;h<=i;h++){let d=a[h]+f[i-h];d>l&&(l=d,c=h)}return o+c}};function ho(r,e,t){let n=new Bn(r,e,t);return n.solve(0,r.length,0,e.length),[n.pairs,n.total]}var Zs=100,Gn=4e6,Js=5e3,he=15,ei=64,ti=8,yo=1,zn=-4,ae=-6,Me=-1,Qe=-(2**30),Ot=0,Hn=1,bo=2;function $e(r,e,t){let n=r.at(-1);t>0&&(n?.[0]===e?n[1]+=t:r.push([e,t]))}function _t(r,e,t){return r>=t&&r>=e?Ot:t>=e?bo:Hn}function So(r,e,t){let n=r.length,o=e.length,s=o+1,i=new Uint8Array((n+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 m=1;m<=o;m++)c[m]=ae+(m-1)*Me,i[m]=(m===1?Ot:bo)<<4;for(let m=1;m<=n;m++){let u=new Int32Array(s).fill(Qe),w=new Int32Array(s).fill(Qe),b=new Int32Array(s).fill(Qe);w[0]=ae+(m-1)*Me,i[m*s]=(m===1?Ot:Hn)<<2;let S=r.charCodeAt(m-1);for(let g=1;g<=o;g++){let x=_t(a[g-1],f[g-1],c[g-1]);u[g]=Math.max(a[g-1],f[g-1],c[g-1])+(S===e.charCodeAt(g-1)?yo:zn);let y=_t(a[g]+ae,f[g]+Me,c[g]+ae);w[g]=Math.max(a[g]+ae,f[g]+Me,c[g]+ae);let E=_t(u[g-1]+ae,w[g-1]+ae,b[g-1]+Me);b[g]=Math.max(u[g-1]+ae,w[g-1]+ae,b[g-1]+Me),i[m*s+g]=x|y<<2|E<<4}a=u,f=w,c=b}let l=[],h=n,d=o,p=_t(a[o],f[o],c[o]);for(;h>0||d>0;){let m=i[h*s+d]>>2*p&3;p===Ot?(l.push(r[h-1]===e[d-1]?"=":"X"),h-=1,d-=1):p===Hn?(l.push("I"),h-=1):(l.push("D"),d-=1),p=m}for(let m of l.reverse())$e(t,m,1)}function ni(r,e){let t=Math.abs(r-e);return(t===0?0:Math.min(-ae-(t-1)*Me,-ae+10*Math.log2(t)))+(Math.min(r,e)>0?-zn:0)}function vo(r,e){let t=Math.abs(r-e);return t===0?0:.01*he*t+.5*Math.log2(t)}function po(r,e,t){return{qs:r.qs+e,qe:r.qs+t,ts:r.flipped?r.te-t:r.ts+e,te:r.flipped?r.te-e:r.ts+t,flipped:r.flipped}}function ri(r,e,t){let n=r.qe-r.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-r.qs),l=Math.min(n,f-r.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,r.flipped?r.te-f:a-r.ts),l=Math.min(n,r.flipped?r.te-a:f-r.ts);c<l&&o.push([c,l])}if(o.length===0)return[r];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=he&&s.push(po(r,i,a)),i=Math.max(i,f);return n-i>=he&&s.push(po(r,i,n)),s}function jn(r,e,t,n,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...r].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),h=new Int32Array(f.length);for(let g=0;g<f.length;g++){let x=f[g],y=x.qe-x.qs;for(let E=g-1;E>=Math.max(0,g-Js);E--){if(c[E]+y<=c[g])continue;let A=f[E];if(A.flipped===x.flipped&&A.qs<x.qs&&(x.flipped?x.te<A.te:A.ts<x.ts)){let k=Math.max(0,A.qe-x.qs,x.flipped?x.te-A.ts:A.te-x.ts),F=x.qs+k-A.qe,R=x.flipped?A.ts-(x.te-k):x.ts+k-A.te;if(k<y&&F<=e&&R<=e){let T=c[E]+y-k-n(F,R);T>c[g]&&(c[g]=T,l[g]=E,h[g]=k)}}}}let d=new Int32Array(f.length),p=-1;for(let g=0;g<f.length;g++){let x=f[g];d[g]=(d[l[g]]??0)+x.qe-x.qs-h[g],d[g]>=t&&(p<0||c[g]>c[p])&&(p=g)}if(p<0)break;let m=[];for(let g=p;g>=0;g=l[g])m.push({run:f[g],trim:h[g]});m.reverse(),s.push(m);let u=m[0],w=m.at(-1),{flipped:b}=u.run,S=b?a.flipped:a.forward;S.query.push([u.run.qs+u.trim,w.run.qe]),S.target.push(b?[w.run.ts,u.run.te-u.trim]:[u.run.ts+u.trim,w.run.te]);for(let{run:g,trim:x}of m)i.query.push([g.qs+x,g.qe]),i.target.push(g.flipped?[g.ts,g.te-x]:[g.ts+x,g.te]);f=f.flatMap(g=>{let x=g.flipped?a.flipped:a.forward;return ri(g,[...i.query,...x.query],[...i.target,...x.target])}).sort((g,x)=>g.qs-x.qs||g.ts-x.ts)}return s}function Dn(r,e){let t=new Map;for(let s=0;s+he<=e.length;s++){let i=e.slice(s,s+he),a=t.get(i);a?a.push(s):t.set(i,[s])}let n=[],o=new Map;for(let s=0;s+he<=r.length;s++){let i=t.get(r.slice(s,s+he));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+he,c.te=a+he;else{let l={qs:s,qe:s+he,ts:a,te:a+he,flipped:!1};o.set(f,l),n.push(l)}}}return n}function oi(r,e){return[...Dn(r,e),...Dn(r,Mt(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Nt(r,e,t,n,o){let s;for(let{run:i,trim:a}of r){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,h=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?Mt(h):h,n,s.qe,c)}$e(n,"=",i.qe-f),s=i}}function Un(r,e,t){$e(t,"I",r.length),$e(t,"D",e.length)}function Io(r,e,t){r.length*e.length<=Gn?So(r,e,t):Un(r,e,t)}function Wn(r,e,t,n=0){let[o]=r.length*e.length>Gn&&n<ti?jn(Dn(r,e),1/0,he,vo,1):[];if(!o){Io(r,e,t);return}let s=(f,c,l)=>{Wn(f,c,l,n+1)},i=o[0].run,a=o.at(-1).run;s(r.slice(0,i.qs),e.slice(0,i.ts),t),Nt(o,r,e,t,s),s(r.slice(a.qe),e.slice(a.te),t)}function si(r,e,t){Wn(r,e,t)}function ii(r,e,t){let n=[];Nt(r,e,t,n,si);let o=r[0],s=r.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?n.reverse():n,sharedBases:0}}function ai(r,e,t,n){let o=[];if(r.length*e.length<=Gn)So(r,e,t);else{let s=jn(oi(r,e),1/0,Math.max(n,he),vo),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>ii(a,r,e)),i){let a=(l,h,d,p,m)=>{o.some(w=>p<w.queryEnd&&w.queryStart<p+l.length||m<w.targetEnd&&w.targetStart<m+h.length)?Io(l,h,d):Wn(l,h,d)},f=i[0].run,c=i.at(-1).run;a(r.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Nt(i,r,e,t,a),a(r.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else Un(r,e,t)}return o}function Vn(r,e){let t=r.strand==="-",n=0,o=0;for(let[s,i]of r.edits)e(s,i,t?r.queryEnd-1-n:r.queryStart+n,r.targetStart+o),s!=="D"&&(n+=i),s!=="I"&&(o+=i)}function uo(r,e,t,n){let o=e==="query"&&r.strand==="-"?-1:1,s=0;return Vn(r,(i,a,f,c)=>{let l=e==="query"?f:c,h=d=>{let p=l+o*d;return p>=t&&p<n};if(i==="="||i==="X")for(let d=0;d<a;d++)h(d)&&(s+=i==="="?yo:zn);else if(i==="I"==(e==="query"))for(let d=0;d<a;d++)h(d)&&(s+=d===0?ae:Me);else h(0)&&(s+=ae+(a-1)*Me)}),s}function mo(r,e){return e==="query"?[r.queryStart,r.queryEnd]:[r.targetStart,r.targetEnd]}function fi(r,e){let t=r.strand==="-",n=[],o=0,s=0,i=0,a=0,f=new Uint8Array(r.queryEnd-r.queryStart);for(let[p,m]of r.shared)f.fill(1,p-r.queryStart,m-r.queryStart);let c=p=>f[p-r.queryStart]===1,l=()=>{$e(n,"I",o),$e(n,"D",s),o=0,s=0};Vn(r,(p,m,u)=>{if(p==="I")o+=m;else if(p==="D")s+=m;else{for(let w=0;w<m;w++)e[i+w]?(o+=1,s+=1,c(t?u-w:u+w)&&(a+=1)):((o>0||s>0)&&l(),$e(n,p,1));i+=m}}),l();let h={I:0,D:0};for(;n[0]?.[0]==="I"||n[0]?.[0]==="D";){let[p,m]=n.shift();h[p]+=m}let d={I:0,D:0};for(;n.at(-1)?.[0]==="I"||n.at(-1)?.[0]==="D";){let[p,m]=n.pop();d[p]+=m}return n.length===0?void 0:{...r,queryStart:r.queryStart+(t?d.I:h.I),queryEnd:r.queryEnd-(t?h.I:d.I),targetStart:r.targetStart+h.D,targetEnd:r.targetEnd-d.D,edits:n,sharedBases:r.sharedBases-a}}function ci(r,e,t,n){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=r.map(c=>{let l=[];Vn(c,(h,d,p,m)=>{if(h==="="||h==="X")for(let u=0;u<d;u++)l.push([c.strand==="-"?p-u:p+u,m+u])});for(let[h,d]of l)o.query[h]=Math.min(255,o.query[h]+1),o.target[d]=Math.min(255,o.target[d]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[h,d]of c)for(let[p,m]of[["query",h],["target",d]])if(o[p][m]>1){let u=i[p].get(m);u?u.at(-1)!==l&&u.push(l):i[p].set(m,[l])}});let a=new Map,f=(c,l,h)=>{let d=`${h}:${c}:${l}`,p=a.get(d);if(p===void 0){let[m,u]=mo(r[c],h),[w,b]=mo(r[l],h),S=Math.max(m,w),g=Math.min(u,b),[x,y]=[r[c],r[l]];p=[uo(y,h,S,g)-uo(x,h,S,g),y.sharedBases-x.sharedBases,c-l].find(A=>A!==0)>0,a.set(d,p)}return p};return r.flatMap((c,l)=>{let h=s[l],d=new Uint8Array(h.length);if(h.forEach(([u,w],b)=>{for(let[S,g]of[["query",u],["target",w]])!d[b]&&i[S].get(g)?.some(x=>x!==l&&f(l,x,S))&&(d[b]=1)}),!d.includes(1))return[c];let p=fi(c,d),m=p?.edits.reduce((u,[w,b])=>u+(w==="="?b:0),0)??0;return p&&m>=n?[p]:[]})}function go(r,e){return r.map(t=>{let n=e(O(t));return j(t)?Mt(n):n}).join("")}function wo(r,e){let t=[0];for(let n of r)t.push(t.at(-1)+e(O(n)).length);return t}function xo(r){let e=new Map,t=new Map;r.forEach((i,a)=>{let f=O(i);e.has(f)?t.set(f,a):e.set(f,a)});let n=new Int32Array(r.length+1);for(let[i,a]of t)n[e.get(i)]+=1,n[a+1]-=1;let o=new Uint8Array(r.length),s=0;for(let i=0;i<r.length;i++)s+=n[i],o[i]=s>0?1:0;return o}function li(r,e,t,n){let o=xo(r),s=xo(e),i=new Map;e.forEach((h,d)=>{s[d]||i.set(O(h),[d])});let a=2*e.length,f=(h,d,p)=>h*a+2*d+(p?1:0),c=new Set;r.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[])c.add(f(d,p,j(h)!==j(e[p])))});let l=[];return r.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[]){let m=j(h)!==j(e[p]),u=m?-1:1,w=p-u;if(!(d>0&&w>=0&&w<e.length&&c.has(f(d-1,w,m)))){let S=d,g=p;for(;S<r.length&&g>=0&&g<e.length&&c.has(f(S,g,m));)S+=1,g+=u;let x=g-u;l.push({qs:t[d],qe:t[S],ts:n[Math.min(p,x)],te:n[Math.max(p,x)+1],flipped:m})}}}),l}function Eo(r){let{query:e,target:t,sequenceOf:n}=r,o=go(e,n),s=go(t,n),i=li(e,t,wo(e,n),wo(t,n)),a=r.minMatch??Zs,f=r.bases??!0,c=[];for(let l of jn(i,r.maxGap??1/0,a,ni)){let h=[],d=l[0],p=l.at(-1),{flipped:m}=d.run;Nt(l,o,s,h,f?(w,b,S,g,x)=>{for(let y of ai(w,b,S,a)){let E=x+b.length;c.push({...y,queryStart:g+y.queryStart,queryEnd:g+y.queryEnd,targetStart:m?E-y.targetEnd:x+y.targetStart,targetEnd:m?E-y.targetStart:x+y.targetEnd,strand:m?"+":"-",edits:m?y.edits.reverse():y.edits,shared:[]})}}:Un),c.push({queryStart:d.run.qs+d.trim,queryEnd:p.run.qe,targetStart:m?p.run.ts:d.run.ts+d.trim,targetEnd:m?d.run.te-d.trim:p.run.te,strand:m?"-":"+",edits:m?h.reverse():h,sharedBases:l.reduce((w,{run:b,trim:S})=>w+b.qe-b.qs-S,0),shared:l.map(({run:w,trim:b})=>[w.qs+b,w.qe])})}return ci(c,o.length,s.length,a).map(({shared:l,...h})=>h).sort((l,h)=>l.queryStart-h.queryStart)}function Ao(r){return r.map(([e,t])=>`${t}${e}`).join("")}var fe=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 Qn(r,e){return r[0]<e[0]||r[0]===e[0]&&(r[1]<e[1]||r[1]===e[1]&&r[2]<e[2])}var ct=class{heap=[];push(e,t,n){let o=this.heap;o.push([e,t,n]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Qn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Qn(e[s],e[a])&&(a=s),i<e.length&&Qn(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 hi(r){let e=new Int32Array(r.length),t=new Int32Array(r.length);return r.forEach(([n,o],s)=>{e[s]=n,t[s]=o}),{pathAt:e,refAt:t,count:r.length}}function di(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>1;r[o]>e?n=o:t=o+1}return r[t]}function qe(r){return`${r.node}:${r.offset}`}function ft(r){return r.map(e=>re(e)).reverse()}function pi(r,e){let t=e.identity.hapStart-r.identity.hapEnd,n=r.strand==="+"?e.refStart-r.refEnd:r.refStart-e.refEnd;return r.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function ui(r,e,t){let[n,o]=r.strand==="+"?[r,e]:[e,r],s=n.edits.map(([c,l])=>[c,l]);Mo(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=r.identity.walkForward,[a,f]=i?[r,e]:[e,r];return{strand:r.strand,refStart:n.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:r.identity.pathHandle,name:r.identity.name,hapStart:r.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function mi(r,e,t){if(r.some(i=>i.weight!==void 0))return r;let n=new Map;r.forEach((i,a)=>{if(i.identity){let f=n.get(i.identity.pathHandle);f?f.push(a):n.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of n.values()){i.sort((l,h)=>r[l].identity.hapStart-r[h].identity.hapStart);let a=i[0],f=r[a],c=[];for(let l of i.slice(1)){let h=r[l],d=c.length===0?pi(f,h):void 0;if(d){f=ui(f,h,d),s.add(l);continue}if(!e(h)){c.push(l);continue}let p=e(f)?t([f,...c.map(m=>r[m]),h]):void 0;if(p){f=p;for(let m of[...c,l])s.add(m)}else o.set(a,f),a=l,f=h;c=[]}o.set(a,f)}return r.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function Tt(r,e){return{node:r.path[e],offset:r.offsets[e]}}var gi=32768;function wi(r){let e=[...r].sort((n,o)=>n-o),t=[];for(let n of e){let o=t[t.length-1];o&&n-o[1]<=gi?o[1]=n:t.push([n,n])}return t}var lt=class r{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new r(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(Se(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 fe(this.limit);let t=await this.db.getRecord(Se(e,"forward")),n=await this.db.getRecord(Se(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${ge(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${ge(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,n);if(!o)throw new Error(`The fragment of ${ge(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,o.pathOffset,o.pos)}async findPathPosition(e,t,n,o){let s=n,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(`The fragment of ${ge(e.name)} at ${e.name.fragment} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,n){let o=O(e);await this.ensureNode(o);let s=this.record(e),i=je(e),a=new ct;return a.push(t,o,It(i)),a.push(s.sequenceLen-t-1,o,Et(i)),this.insertContext(a,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);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,n);await this.db.prefetchRecords(wi(c.map(l=>l.pos.node)).map(([l,h])=>[l,h+2]),!0)}}return o}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(o){throw o instanceof fe&&o.windowBp===void 0?new fe(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new ct;for(;;){let f=O(o.node),c=je(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,It(c));let h=l.sequenceLen-s;if(i<=h){a.push(i===h?0:h-i-1,f,Et(c));break}a.push(0,f,Et(c));let d=l.gbwt().lf(o.offset);if(!d)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=d,s=0,i-=h}return this.walkedBp=t,this.insertContext(a,n)}async aroundNodes(e,t){let n=new ct;for(let o of e)await this.ensureNode(o),n.push(0,o,"left"),n.push(0,o,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,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(n.has(c))continue;n.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=Ur(f);if(!n.has(`${a}:${l}`)){let p=this.record(Se(a,Wr(f))),m=i+p.sequenceLen-1;m<=t&&e.push(m,a,l)}let h=this.record(Se(a,Vr(f))),d=i+1;if(d<=t)for(let p of h.successors()){let m=O(p),u=It(je(p));n.has(`${m}:${u}`)||e.push(d,m,u)}}for(let i of o)this.records.delete(Se(i,"forward")),this.records.delete(Se(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,re(t)],o=new Set([O(e),O(t)]),s=[];for(;n.length>0;){let i=n.pop(),a=O(i);this.hasNode(a)||(await this.addNode(a),s.push(a));for(let f of this.record(i).successors()){let c=O(f);o.has(c)||(n.push(f,re(f)),o.add(c))}}return{inserted:s,nodes:o.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,o]of await this.overlappingSnarls(e)){let{inserted:s,nodes:i}=await this.fillBetween(n,o),a=O(n),f=O(o);this.snarlFills.push({low:Math.min(a,f),high:Math.max(a,f),nodes:i,inserted:s.length});for(let c of s)this.snarlNodes.add(c);t+=s.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(n=!0,this.hasHandle(i)?Ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(o=>this.hasHandle(o));return n===void 0?!1:t.length>1||this.record(re(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let o=this.records.get(n);if(o)return o;let s=t.get(n);if(!s){if(s=await this.db.getRecord(n),e?.(),!s)throw new Error(`Node record ${n} is missing from the database`);t.set(n,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(re(l))).successors().length>1},n=async f=>{let c=await e(re(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[re(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 n(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let h of["forward","reverse"])s.push(...(await e(Se(c,h))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((y,E)=>i.set(y,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let y=0;y<s;y++){let E=this.record(o[y]),A=E.gbwt().decompressArrays();f[y]=E.sequenceLen,c.push(A),a[y+1]=a[y]+A.nodes.length}let l=a[s],h=new Int32Array(l),d=new Int32Array(l),p=new Uint8Array(l);for(let y=0;y<s;y++){let E=c[y];h.set(E.nodes,a[y]),d.set(E.offsets,a[y])}c.length=0;for(let y=0;y<l;y++){let E=i.get(h[y]);E===void 0?h[y]=-1:(h[y]=E,p[a[E]+d[y]]=1)}let m=n===void 0?void 0:i.get(n.handle),u=n?.gbwtOffset,w,b=(y,E,A)=>{let N=[],k=0,F=0,R=-1,T=y,C=E;for(;;){T===m&&C===u&&(R=k),A&&(A.push(o[T]),N.push(C)),k+=1,F+=f[T];let D=a[T]+C,Y=h[D];if(Y<0)break;C=d[D],T=Y}return{offsets:N,len:F,refAt:R,last:T}},S=(y,E,A,N)=>{N>=0&&(this.refId=this.paths.length,w=N),this.paths.push({path:y,offsets:E,len:A,weight:void 0,identity:void 0})},g=new Int32Array(s);for(let y=0;y<s;y++){let E=o[y];if(!j(E)){let A=a[y],N=a[y+1]-A;for(let k=0;k<N;k++)if(p[A+k]===0){let F=[],{offsets:R,len:T,refAt:C,last:D}=b(y,k,F),Y=o[D];if(C>=0||Fe(E,Y)){if(S(F,R,T,C),!j(Y)){let I=i.get(re(Y));g[I]=g[I]+1}}else this.twinStarts.add(qe({node:E,offset:k}))}}}for(let y=0;y<s;y++){let E=o[y];if(j(E)){let A=a[y],N=a[y+1]-A,k=0;for(let R=0;R<N;R++)p[A+R]===0&&(k+=1);let F=(m===void 0||w!==void 0)&&k===g[y];for(let R=0;R<N;R++)if(p[A+R]===0){let T=F?void 0:b(y,R,void 0);if(T&&(T.refAt>=0||Fe(E,o[T.last]))){let C=[],{offsets:D,len:Y,refAt:I}=b(y,R,C);S(C,D,Y,I)}else this.twinStarts.add(qe({node:E,offset:R}))}}}let x=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),x&&(this.refId=this.paths.indexOf(x)),n){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let N of y.path.slice(0,w))E+=this.record(N).sequenceLen;let A=n.seqOffset-E;this.refInterval=[A,A+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:A,hapEnd:A+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,o=n&&!st(n)?ft(n):void 0,s=c=>o!==void 0&&Yn(c,o)===0||st(ft(c)),i=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,l)=>Yn(c.path,l.path)||c.len-l.len||(c===t?-1:l===t?1:0));let a=[],f;for(let c of this.paths){let l=a[a.length-1],h=i&&c!==t&&s(c.path);this.twinDeferred||=h,l&&Yn(l.path,c.path)===0&&!h?l.weight=(l.weight??1)+(c.weight??1):(c===t&&(f=a.length),a.push({...c,weight:c.weight??1}))}this.paths=a,this.refId=f}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=i=>`${i.pathHandle}:${i.hapStart}-${i.hapEnd}`,o=new Set;e?.identity&&t&&o.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let i of this.paths)i!==e&&i.identity?.orientation==="forward"&&o.add(n(i.identity));let s=this.paths.filter(i=>i===e||i.identity?.orientation!=="reverse"||!o.has(n(i.identity)));s.length<this.paths.length&&(this.paths=s,this.refId=e===void 0?void 0:s.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(i=>i.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((i,a)=>a!==this.refId&&i.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],o=this.paths.filter((i,a)=>a===this.refId||i.identity!==void 0&&e(i.identity.name)),s=new Set;for(let i of o)for(let a of i.path)s.add(O(a));for(let i of[...this.records.keys()])s.has(O(i))||this.records.delete(i);this.paths=o,this.refId=n===void 0?void 0:o.indexOf(n)}async extractChosenPaths(e,t,n,o){this.clearPaths();let s=e.position.seqOffset,i=await co({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:s-e.position.nodeOffset,window:{start:s,end:s+t},context:o,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(l,h,d)=>this.prefetchReferenceRange(l,h,d)});if(this.stats.keep=i.stats,i.stats.fallback!==void 0)return!1;let a=await this.db.pathsByHandle(),f=l=>({path:l.handles,offsets:l.offsets,len:l.len,weight:void 0,identity:{pathHandle:l.pathHandle,name:l===i.reference?e.name:a.get(l.pathHandle).name,orientation:l.orientation,hapStart:l.hapStart,hapEnd:l.hapEnd}}),c=[i.reference,...i.pieces].sort(lo);return this.paths=c.map(f),this.refId=c.indexOf(i.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[i.reference.hapStart,i.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=qn(this.sortedHandles());if(t.length===0)return;let n=new Map,o=await Promise.all(t.map(([u,w])=>this.db.haplotypeSamplesInRange(u,w)));for(let u of o.flat())n.set(qe(u),u);let s=u=>{let w=0,b=t.length-1;for(;w<b;){let g=w+b+1>>1;t[g][0]<=u?w=g:b=g-1}let S=t[w];return S[0]<=u&&u<=S[1]},i=new Map;this.paths.forEach((u,w)=>{u.path.length>0&&w!==this.refId&&i.set(qe(Tt(u,0)),w)});let a=this.stats.identification;a.interval=e,a.scans=t,a.windowSamples=n.size,this.paths.forEach((u,w)=>{w!==this.refId&&a.fragmentLengths.push(u.len)});let f=this.recordReader(()=>{this.stats.identificationFetches+=1,a.graphFetches+=1}),c=u=>(a.graphLookups+=1,f(u)),l=async(u,w)=>{if(s(u.node))return n.get(qe(u));this.stats.identificationFetches+=1,a.companionSeeks+=1,w.seeks+=1;let b=await this.db.haplotypeSampleAt(u.node,u.offset);return b||(a.companionMisses+=1),b},h=new Map,d=async u=>{let w=h.get(u);if(!w){let b=await this.db.getPath(u);if(!b)throw new Error(`Path ${u} is missing from the database`);w=b.name,h.set(u,w)}return w},p=(u,w,b)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.pathOffset-w}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.pathOffset+w+b},m=(u,w)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.hapStart-w}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.hapEnd+w};for(let u=0;u<this.paths.length;u++){let w=this.paths[u];if(u===this.refId||w.identity)continue;let b=[],S=new Set,g={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};a.chains.push(g);let x,y=0,E=u,A;for(;x===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){g.end="cycle";break}S.add(E);let T=this.paths[E];b.push({index:E,startBp:y}),g.fragments+=1;let C=y;for(let Y=0;Y<T.path.length;Y++){let I=Tt(T,Y),M=n.get(qe(I)),_=this.record(I.node).sequenceLen;if(M){x=p(M,C,_);break}C+=_}if(y+=T.len,x){g.end="in-fragment sample";break}let D=Tt(T,T.path.length-1);A=this.record(D.node).gbwt().lf(D.offset),E=void 0}if(A===void 0||A.node===0){g.end="endmarker";break}let N=qe(A),k=i.get(N);if(k!==void 0){let T=this.paths[k].identity;if(T){x=m(T,y),g.end="identified sibling";break}E=k;continue}this.records.has(A.node)&&(g.reentries+=1),this.twinStarts.has(N)&&(g.twinLandings+=1);let F=await l(A,g),R=await c(A.node);if(F){x=p(F,y,R.sequenceLen),g.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,g.steps+=1,y-b[b.length-1].startBp>4*e+4*R.sequenceLen){g.end="bound";break}y+=R.sequenceLen,A=R.gbwt().lf(A.offset)}if(x){g.pathHandle=x.pathHandle;let N=await d(x.pathHandle);for(let{index:k,startBp:F}of b){let R=this.paths[k];R.identity=x.orientation==="forward"?{pathHandle:x.pathHandle,name:N,orientation:"forward",hapStart:x.base+F,hapEnd:x.base+F+R.len}:{pathHandle:x.pathHandle,name:N,orientation:"reverse",hapStart:x.base-F-R.len,hapEnd:x.base-F}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,o)=>{let s=t.get(n);s?s.push(o):t.set(n,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,o)=>{t.push(t[o]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=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=n.get(e[f]);if(c){let l=di(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 n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=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 n;i+=1,a+=1,n+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return n}suffixMatches(e,t){let n=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 n;i+=1,a+=1,n+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return n}align(e,t,n){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(n,"M",i),Mo(n,o-i-a,s-i-a),X(n,"M",a)}sharedWeight(e,t){let n=this.refIndex(t),o=0;for(let s of e)n.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=n??hi(ho(e,t,h=>this.record(h).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(h,d,p,m)=>{h===d?X(s,"D",i[m]-i[p]):p===m?X(s,"I",this.pathLen(e.slice(h,d))):this.align(e.slice(h,d),t.slice(p,m),s)},f=0,c=0,l=0;for(let h=0;h<o.count;h++){let d=o.pathAt[h],p=o.refAt[h];(c!==d||l!==p)&&a(c,d,l,p);let m=this.record(e[d]).sequenceLen;X(s,"M",m),f+=m,c=d+1,l=p+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 n=this.paths[this.refId].path,o;if(st(n)&&(t.identity===void 0||!st(ft(t.path))))o={...this.editsAgainst(t.path,n),flipped:!1};else{let s=ft(t.path),i=this.sharedWeight(t.path,n);if(this.sharedWeight(s,n)===0)o={...this.editsAgainst(t.path,n),flipped:!1};else if(i===0)o={...this.editsAgainst(s,n),flipped:!0};else{let f=this.editsAgainst(t.path,n),c=this.editsAgainst(s,n);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],o=(l,h,d,p)=>{let m=yi(l),u=this.paths[d[0]],w=this.paths[d[d.length-1]],b=u.identity,S=b?.orientation==="forward",[g,x]=S?[u,w]:[w,u];return{strand:h,refStart:e.start+m.leading,refEnd:e.start+n-m.trailing,edits:m.edits,weight:u.weight,path:d.flatMap(y=>this.paths[y].path),start:Tt(u,0),pieces:d,soloAligned:p,identity:b===void 0?void 0:{pathHandle:b.pathHandle,name:b.name,hapStart:b.name.fragment+g.identity.hapStart,hapEnd:b.name.fragment+x.identity.hapEnd,walkForward:S}}},s=l=>l.soloAligned.reduce((h,d)=>h+d,0),i=l=>l.pieces.reduce((h,d)=>h+this.paths[d].len,0),a=l=>2*s(l)>=i(l),f=l=>{let h=l[0],d=l[l.length-1],p=h.identity.walkForward;if(l.some((C,D)=>C.strand!==h.strand||C.identity.walkForward!==p||D>0&&C.identity.hapStart<l[D-1].identity.hapEnd))return;let m=p?l:[...l].reverse(),u=m.flatMap(C=>C.pieces),w=m.flatMap(C=>C.soloAligned),b=h.strand==="+"!==p,S=u.map(C=>this.paths[C]),g=S.slice(1).map((C,D)=>{let Y=S[D].identity;return p?C.identity.hapStart-Y.hapEnd:Y.hapStart-C.identity.hapEnd}),x=b?[...S].reverse():S,y=b?[...g].reverse():g,E=x.flatMap(C=>b?ft(C.path):C.path),{edits:A}=this.editsAgainst(E,t),N=Co(A,x.map(C=>C.len)),k=new Map((b?[...u].reverse():u).map((C,D)=>[C,N[D]])),F=C=>2*C.pieces.reduce((D,Y)=>D+k.get(Y),0)>=s(C);if(!F(h)||!F(d))return;let R=[],T=0;return x.slice(0,-1).forEach((C,D)=>{T+=C.len,R.push([T,y[D]])}),o(bi(A,R),h.strand,u,w)},c=[];return this.paths.forEach((l,h)=>{if(h===this.refId)return;let{edits:d,flipped:p}=this.alignment(h),m=l.identity,u=m?m.orientation==="forward"!==p:!p;c.push(o(d,u?"+":"-",[h],Co(d,[l.len])))}),mi(c,a,f).map(l=>{let{edits:h,identity:d,pieces:p,soloAligned:m,...u}=l,w={...u,cigar:Si(h)};return d?{...w,resolved:!0,name:d.name,label:ge({...d.name,fragment:d.hapStart,end:d.hapEnd}),pathHandle:d.pathHandle,hapStart:d.hapStart,hapEnd:d.hapEnd}:{...w,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...o}=e,s=this.paths.flatMap(l=>{let{identity:h}=l;return h?[{name:h.name,start:h.name.fragment+h.hapStart,steps:Ft(l,h)}]:[]}),i=l=>h=>h.sample===l.sample&&h.haplotype===l.haplotype,a=i(t),f=n?i(n):l=>!a(l),c=l=>this.record(Se(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(h=>f(h.name)).flatMap(h=>Eo({...o,query:h.steps,target:l.steps,sequenceOf:c}).map(d=>({query:h.name,queryStart:h.start+d.queryStart,queryEnd:h.start+d.queryEnd,strand:d.strand,target:l.name,targetStart:l.start+d.targetStart,targetEnd:l.start+d.targetEnd,cigar:Ao(d.edits),matches:d.edits.reduce((p,[m,u])=>p+(m==="="?u:0),0),columns:d.edits.reduce((p,[,m])=>p+m,0),sharedBases:d.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let o=Se(e,n);for(let s of this.record(o).successors())this.hasHandle(s)&&Ue(o,s)&&t.push([n==="reverse"?1:0,O(s),j(s)?1:0])}return t.sort((n,o)=>n[0]-o[0]||n[1]-o[1]||n[2]-o[2]),t.filter((n,o)=>o===0||n[0]!==t[o-1][0]||n[1]!==t[o-1][1]||n[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!j(n)){let o=O(n),s=`S ${o} ${this.record(n).sequence}
2
2
  `;for(let[i,a,f]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${f?"-":"+"}
3
- `;t.push(e.encode(s))}return oo(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...ro(no(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)j(c)||n.push(`S ${O(c)} ${this.record(c).sequence}`);let s=c=>j(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&Ue(c,l)&&n.push(`L ${O(c)} ${s(c)} ${O(l)} ${s(l)} 0M`);let i=(c,l,h,d,p)=>{let m=$t(c,l).map(b=>`${j(b)?"<":">"}${O(b)}`).join(""),u=c.weight===void 0?"":` WT:i:${c.weight}`,w=p===void 0?"":` CG:Z:${p}`;return`W ${h.sample} ${h.haplotype} ${h.contig} ${h.fragment} ${d} ${m}${u}${w}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.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 h=e.names!=="anonymous"?c.identity:void 0,d=t?this.alignToRef(l):void 0;n.push(h?i(c,h,{...h.name,fragment:h.name.fragment+h.hapStart},h.name.fragment+h.hapEnd,d):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,d)),f+=1}}),`${n.join(`
3
+ `;t.push(e.encode(s))}return so(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...oo(ro(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)j(c)||n.push(`S ${O(c)} ${this.record(c).sequence}`);let s=c=>j(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&Ue(c,l)&&n.push(`L ${O(c)} ${s(c)} ${O(l)} ${s(l)} 0M`);let i=(c,l,h,d,p)=>{let m=Ft(c,l).map(b=>`${j(b)?"<":">"}${O(b)}`).join(""),u=c.weight===void 0?"":` WT:i:${c.weight}`,w=p===void 0?"":` CG:Z:${p}`;return`W ${h.sample} ${h.haplotype} ${h.contig} ${h.fragment} ${d} ${m}${u}${w}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.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 h=e.names!=="anonymous"?c.identity:void 0,d=t?this.alignToRef(l):void 0;n.push(h?i(c,h,{...h.name,fragment:h.name.fragment+h.hapStart},h.name.fragment+h.hapEnd,d):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,d)),f+=1}}),`${n.join(`
4
4
  `)}
5
- `}outputPaths(e){this.settleDeferred();let t=e.cigar??!1,n=[],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]};n.push({info:this.paths[this.refId],identity:void 0,name:we({...i,end: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!=="anonymous"?i.identity:void 0;n.push({info:i,identity:f,name:f?we({...f.name,fragment:f.name.fragment+f.hapStart,end:f.name.fragment+f.hapEnd}):we({sample:"unknown",contig:o,haplotype:s,fragment:0,end:i.len}),cigar:t?this.alignToRef(a):void 0}),s+=1}),n}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Ue(e,t)&&(yield[e,t])}walkSpans(){return this.settleDeferred(),this.paths.flatMap((e,t)=>{let n=t===this.refId?void 0:e.identity;return n?[{name:n.name,start:n.name.fragment+n.hapStart,end:n.name.fragment+n.hapEnd}]:[]})}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!j(s)).map(s=>({id:String(O(s)),sequence:this.record(s).sequence})),n=[];for(let[s,i]of this.outputEdges())n.push({from:String(O(s)),from_is_reverse:j(s),to:String(O(i)),to_is_reverse:j(i)});let o=this.outputPaths(e).map(s=>xi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:n,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!j(i)),n=new Int32Array(t.length),o=[];t.forEach((i,a)=>{n[a]=O(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:n,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($t(i.info,i.identity))}))}}};function $t(r,e){return e?.orientation==="reverse"?r.path.map(t=>re(t)).reverse():r.path}function xi(r,e,t,n){return{name:t,...r.weight===void 0?{}:{weight:r.weight},...n===void 0?{}:{cigar:n},path:$t(r,e).map(o=>({id:String(O(o)),is_reverse:j(o)}))}}function Kn(r,e){let t=Math.min(r.length,e.length);for(let n=0;n<t;n++){let o=r[n],s=e[n];if(o!==s)return o<s?-1:1}return r.length-e.length}function X(r,e,t){if(t===0)return;let n=r[r.length-1];n?.[0]===e?n[1]+=t:r.push([e,t])}function Ft(r){return r===0?0:6+(r-1)}function Co(r,e,t){if(e===0)X(r,"D",t);else if(t===0)X(r,"I",e);else{let n=Math.min(e,t),o=4*n+Ft(e-n)+Ft(t-n),s=Ft(e)+Ft(t);o<=s?(X(r,"M",n),X(r,"I",e-n),X(r,"D",t-n)):(X(r,"I",e),X(r,"D",t))}}function yi(r){let e=0;for(;e<r.length&&r[e][0]!=="M";)e+=1;if(e===r.length){let a=r.filter(([c])=>c==="I"),f=r.filter(([c])=>c==="D").reduce((c,[,l])=>c+l,0);return{edits:a.map(([c,l])=>[c,l]),leading:0,trailing:f}}let t=r.length;for(;r[t-1][0]!=="M";)t-=1;let n=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=n(r.slice(0,e)),s=n(r.slice(t)),i=[];X(i,"I",o.inserted);for(let[a,f]of r.slice(e,t))X(i,a,f);return X(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function Ao(r,e){let t=e.map(()=>0),n=e.length-1,o=0,s=e[0],i=0;for(let[a,f]of r){if(a==="D")continue;let c=f;for(;c>0;){for(;o<n&&i>=s;)o+=1,s+=e[o];let l=o<n?Math.min(c,s-i):c;a==="M"&&(t[o]+=l),i+=l,c-=l}}return t}function bi(r,e){let t=[],n=0,o=0;for(let[s,i]of r){if(s==="D"){X(t,s,i);continue}let a=n;for(;o<e.length&&e[o][0]<n+i;){let[f,c]=e[o];X(t,s,f-a),X(t,"I",c),a=f,o+=1}X(t,s,n+i-a),n+=i}for(;o<e.length;o++)X(t,"I",e[o][1]);return t}function Si(r){return r.map(([e,t])=>`${t}${e}`).join("")}function Oe(r,e,t=0){if(!Number.isSafeInteger(e)||e<t)throw new Error(`${r} must be a whole number${t>0?` of at least ${t}`:""}, not ${e}`);return e}function qt(r){return Oe("context",r.context??100)}function Bt(r,e){return e.limit!==void 0&&Oe("limit",e.limit),lt.create(r,e)}async function Mo(r,e){let t=qt(e),n=Bt(r,e),o=await n.pathPosition(Ve(We(e.path),Oe("offset",e.offset)));return await n.aroundPosition(o.position.handle,o.position.nodeOffset,t),await n.extractSnarls(e.snarls??"none"),n.extractPaths(o,e.haplotypes??"all"),n}async function vi(r,e){let t=Oe("start",e.start),n=Oe("end",e.end),o=qt(e),s=Bt(r,e);try{let i=await s.pathPosition(Ve(We(e.path),t));return await s.prefetchReferenceWalk(i,n-t),await s.aroundInterval(i.position,n-t,o),await s.extractSnarls(e.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof fe&&i.windowBp===void 0?new fe(i.limit,{windowBp:n-t,walkedBp:s.referenceWalkedBp??0}):i}}async function Xn(r,e){let{keep:t}=e,n=e.haplotypes??"all",o=n==="all"||n==="distinct";if(t!==void 0&&o&&!r.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await vi(r,e);return t===void 0||!o?(s.extractPaths(i,n),s):(await s.extractChosenPaths(i,e.end-e.start,t,qt(e))||(s.extractPaths(i,"all"),await s.identifyPaths()),s.keepHaplotypes(t),n==="distinct"&&s.mergeDistinct(),s)}async function Ro(r,e){let t=e.haplotypes??"all",n=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(n==="overlapping"&&new Set(e.nodeIds).size>1)throw new Error("Overlapping snarls cannot be extracted for a node-based query with multiple nodes");let o=qt(e);for(let i of e.nodeIds)Oe("node id",i,1);let s=Bt(r,e);return await s.aroundNodes(e.nodeIds,o),await s.extractSnarls(n),s.extractPaths(void 0,t),s}async function Po(r,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let n=Bt(r,e);return await n.betweenNodes(Oe("startHandle",e.startHandle,2),Oe("endHandle",e.endHandle,2)),n.extractPaths(void 0,t),n}function Ae(r,e){let t=0;for(let o=0;o<8;o++){let s=r[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){if(o===7&&!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+o+1]}}let n=r[e+8];if(n===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+n,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function Ii(r,e,t){switch(t){case 1:return r.getInt8(e);case 2:return r.getInt16(e);case 3:return r.getInt8(e)<<16|r.getUint16(e+1);case 4:return r.getInt32(e);case 6:return r.getInt16(e)*4294967296+r.getUint32(e+2);default:{let n=r.getBigInt64(e);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${n} exceeds the safe integer range`);return Number(n)}}}var Ei=new TextDecoder;function Ht(r){let[e,t]=Ae(r,0),n=[],o=t;for(;o<e;){let[a,f]=Ae(r,o);n.push(a),o=f}let s=new DataView(r.buffer,r.byteOffset,r.byteLength),i=e;return n.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=Ii(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=r.subarray(i,i+f);return i+=f,a%2===0?c:Ei.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var Gt=2,zt=5,ko=10,Dt=13;function _o(r,e){return r[e]*256+r[e+1]}function Ne(r,e){return r[e]*16777216+r[e+1]*65536+r[e+2]*256+r[e+3]}function Ai(r,e){let t=r[e];if(t!==Gt&&t!==zt&&t!==ko&&t!==Dt)throw new Error(`SQLite page has unknown b-tree type ${t}`);let n=t===Gt||t===zt;return{type:t,cellCount:_o(r,e+3),rightChild:n?Ne(r,e+8):0,cellPointers:e+(n?12:8)}}function Re(r,e,t){return _o(r,e.cellPointers+2*t)}var Ci=4096,jt=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let n=this.usable,o=t?Math.floor((n-12)*64/255)-23:n-35;if(e<=o)return e;let s=Math.floor((n-12)*32/255)-23,i=s+(e-s)%(n-4);return i<=o?i:s}async payload(e,t,n,o){let s=this.localPayloadSize(n,o);if(s===n)return e.subarray(t,t+n);let i=new Uint8Array(n);i.set(e.subarray(t,t+s),0);let a=s,f=Ne(e,t+s);for(;f!==0&&a<n;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,n-a));i.set(l,a),a+=l.length,f=Ne(c,0)}if(a!==n)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 n=this.tableDepths.get(e);return n||(n=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Dt)return s;if(a.type!==zt)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:Ne(i,Re(i,a,f))}})(),this.tableDepths.set(e,n),n.catch(()=>this.tableDepths.delete(e))),n}childIndexFor(e,t,n){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=Ae(e,Re(e,t,i)+4);a<n?o=i+1:s=i}return o}async prefetchRowidRanges(e,t,n=!1){if(t.length===0)return!0;let o=await this.tableDepth(e,t[0][0]),s=t.map(()=>[e]);for(let i=0;i<o;i++){s=await Promise.all(s.map((f,c)=>this.childrenInRange(f,...t[c])));let a=s.flat();if(n)this.pager.prefetchLeading(a);else if(!this.pager.prefetch(a))return!1}return!0}async childrenInRange(e,t,n){let o=await Promise.all(e.map(i=>this.pageAt(i))),s=[];return o.forEach(({page:i,header:a},f)=>{let c=f===0?this.childIndexFor(i,a,t):0,l=f===o.length-1?this.childIndexFor(i,a,n):a.cellCount;for(let h=c;h<=l;h++)s.push(h===a.cellCount?a.rightChild:Ne(i,Re(i,a,h)))}),s}async tableRowid(e,t){let n=e;for(;;){let{page:o,header:s}=await this.pageAt(n);if(s.type===Dt){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,h=Re(o,s,l),[d,p]=Ae(o,h),[m,u]=Ae(o,p);if(m===t)return Ht(await this.payload(o,u,d,!1));m<t?f=l+1:c=l}return}if(s.type!==zt)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]=Ae(o,c+4);l<t?i=f+1:a=f}n=i===s.cellCount?s.rightChild:Ne(o,Re(o,s,i))}}async*tableScan(e){yield*this.scanPage(e,await this.tableDepth(e,0))}async*scanPage(e,t){let{page:n,header:o}=await this.pageAt(e);if(o.type===Dt)for(let s=0;s<o.cellCount;s++){let i=Re(n,o,s),[a,f]=Ae(n,i),[c,l]=Ae(n,f);yield{rowid:c,values:Ht(await this.payload(n,l,a,!1))}}else{let s=[];for(let i=0;i<o.cellCount;i++)s.push(Ne(n,Re(n,o,i)));s.push(o.rightChild),t===1&&this.pager.prefetchLeading(s);for(let i of s)yield*this.scanPage(i,t-1)}}decodedCells(e,t){let n=this.decodedIndexPages.get(e);if(n)this.decodedIndexPages.delete(e);else if(n=new Array(t.cellCount),this.decodedIndexPages.size>=Ci){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,n),n}async indexCell(e,t,n,o){let s=this.decodedCells(e,n),i=s[o];if(!i){let a=Re(t,n,o),f=n.type===Gt,[c,l]=Ae(t,f?a+4:a);i={values:Ht(await this.payload(t,l,c,!0)),leftChild:f?Ne(t,a):0},s[o]=i}return i}async lowerBound(e,t,n,o,s,i){let a=s,f=n.cellCount;for(;a<f;){let c=a+f>>1,l=await this.indexCell(e,t,n,c),h=Zn(l.values,o);h<0||i&&h===0?a=c+1:f=c}return a}async*indexScanFrom(e,t,n){let{page:o,header:s}=await this.pageAt(e),i=await this.lowerBound(e,o,s,t,0,!1),a=s.type===Gt;if(a&&n){let f=await this.lowerBound(e,o,s,n,i,!0),c=[];for(let l=i;l<=f;l++)c.push(l===s.cellCount?s.rightChild:(await this.indexCell(e,o,s,l)).leftChild);this.pager.prefetchLeading(c)}for(let f=i;f<s.cellCount;f++){let c=await this.indexCell(e,o,s,f);if(a&&(yield*this.indexScanFrom(c.leftChild,t,n)),n&&Zn(c.values,n)>0)return;yield c.values}a&&(yield*this.indexScanFrom(s.rightChild,t,n))}async indexSeekLE(e,t){let n,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,h=await this.indexCell(o,s,i,l);Zn(h.values,t)<=0?(n=h.values,a=l+1):(c=h.leftChild,f=l)}if(i.type===ko)return n;o=a===i.cellCount?i.rightChild:c}}};function Zn(r,e){for(let t=0;t<e.length;t++){let n=r[t],o=e[t];if(typeof n!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(n!==o)return n<o?-1:1}return 0}function Oo({blockSize:r,maxBlocks:e}){if(r!==void 0&&!(Number.isSafeInteger(r)&&r>0))throw new Error(`blockSize must be a positive integer, not ${r}`);if(e!==void 0&&!(Number.isSafeInteger(e)&&e>0))throw new Error(`maxBlocks must be a positive integer, not ${e}`)}var Ut=class{blocks=new Map;blockSize;maxBlocks;plan;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,n,o={}){this.source=e,this.pageSize=t,this.fileSize=n;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 n=await this.readRetrying(e,t);if(this.bytesFetched+=n.length,n.length<e)throw new Error(`the file ends at byte ${t+n.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return n}async readRetrying(e,t){let n=0;for(;;)try{return await this.source.read(e,t)}catch(o){if(n+=1,n>=3)throw o;await new Promise(s=>setTimeout(s,200*n))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){this.follow(e);let t=this.touch(e);if(t)return t;let n=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-n),s=this.read(o,n);return this.fetches+=1,this.store(e,s),this.evict(),s}touch(e){let t=this.blocks.get(e);return t&&(this.blocks.delete(e),this.blocks.set(e,t)),t}blockOf(e){return Math.floor((e-1)*this.pageSize/this.blockSize)}get prefetchBudget(){return Math.max(1,Math.floor(this.maxBlocks/2))}get chunk(){return Math.max(1,Math.floor(this.prefetchBudget/2))}prefetch(e){let t=new Set(e.map(n=>this.blockOf(n)));return t.size>this.prefetchBudget?!1:(this.fetchBlocks(t),!0)}prefetchLeading(e){let t=[],n=new Map;for(let o of e){let s=this.blockOf(o);n.has(s)||(n.set(s,t.length),t.push(s))}this.plan={blocks:t,position:n,next:0},this.advance(this.prefetchBudget)}advance(e){let t=this.plan;if(!t)return;let n=t.blocks.slice(t.next,t.next+e);t.next+=n.length,t.next>=t.blocks.length&&(this.plan=void 0),this.fetchBlocks(new Set(n))}follow(e){let t=this.plan,n=t?.position.get(e);t&&n!==void 0&&n>=t.next-Math.ceil(this.chunk/2)&&this.advance(this.chunk)}fetchBlocks(e){let t=[...e].filter(o=>!this.touch(o)).sort((o,s)=>o-s),n=0;for(;n<t.length;){let o=n+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[n],o-n),n=o}}fetchRun(e,t){let n=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-n),s=this.read(o,n);this.fetches+=1;for(let i=0;i<t;i++){let a=i*this.blockSize;this.store(e+i,s.then(f=>f.subarray(a,a+this.blockSize)))}this.evict()}store(e,t){this.blocks.set(e,t),t.catch(()=>{this.blocks.get(e)===t&&this.blocks.delete(e)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let n=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return n.subarray(o,o+this.pageSize)}};var ht=class r{pager;btree;objects;constructor(e,t,n){this.pager=e,this.btree=t,this.objects=n}static async open(e,t={}){Oo(t);let n=await e.read(Math.max(512,t.blockSize??65536),0),o=n.subarray(0,100);if(new TextDecoder().decode(o.subarray(0,15))!=="SQLite format 3"||o.length<100)throw new Error("Not a SQLite database");let i=new DataView(o.buffer,o.byteOffset,o.byteLength),a=i.getUint16(16),f=a===1?65536:a,c=o[20]??0,l=i.getUint32(56);if(l!==1)throw new Error(`SQLite text encoding ${l} is not UTF-8`);let h=i.getUint32(28);if(h===0||i.getUint32(24)!==i.getUint32(92))throw new Error("SQLite header has no valid database size; the file was written by SQLite older than 3.7.0");let d=h*f,p=new Ut(e,f,d,t);p.seed(0,n),p.fetches+=1,p.bytesFetched+=n.length;let m=new jt(p,c),u=new Map;for await(let{values:w}of m.tableScan(1)){let[b,S,g,x,y]=w;typeof b=="string"&&typeof S=="string"&&typeof g=="string"&&typeof x=="number"&&u.set(S,{type:b,name:S,tableName:g,rootPage:x,sql:typeof y=="string"?y:""})}return new r(p,m,u)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}withoutRowid(e){let t=this.objects.get(e);return t?.type==="table"&&/without\s+rowid/i.test(t.sql)}indexOn(e){let t=[...this.objects.values()].find(n=>n.type==="index"&&n.tableName===e);if(t)return t.rootPage;if(this.withoutRowid(e))return this.rootPage(e);throw new Error(`SQLite table ${e} has no index`)}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,n=!1){return this.btree.prefetchRowidRanges(this.rootPage(e),t,n)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t,n){return this.btree.indexScanFrom(this.indexOn(e),t,n)}has(e){return this.objects.has(e)}};var nr="GBZ-base version 4",Wt=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${we(e)}`),this.path=e}},Vt=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")}},Qt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: it has no version tag":`unsupported database schema "${e}"; this reader understands "${nr}"`),this.found=e}};function Mi(r){if(r.length===1)return r[0];let e=new Uint8Array(r.reduce((n,o)=>n+o.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}var Jn=3,Ye=class{at=0;bytes;constructor(e){this.bytes=e}get done(){return this.at>=this.bytes.length}next(){let e=0,t=1;for(;;){let n=this.bytes[this.at++];if(n===void 0)throw new Error("a haplotype index blob ends inside a number");if(e+=(n&127)*t,t*=128,(n&128)===0)return e}}};function Ri(r,e){let t=new Ye(r),n=0;for(;!t.done;){let o=n+t.next();n=o+t.next(),e.push([o,n])}}function Pi(r){r.sort((n,o)=>n[0]-o[0]);let e=[],t=[];for(let[n,o]of r){let s=t.length-1;s>=0&&n<=t[s]+1?t[s]=Math.max(t[s],o):(e.push(n),t.push(o))}return n=>{let o=0,s=e.length;for(;o<s;){let i=o+s>>1;e[i]<=n?o=i+1:s=i}return o>0&&n<=t[o-1]}}function ki(r,e,t){let n=new Ye(e);for(;!n.done;){let o=n.next(),s=n.next(),i=n.next(),a=n.next(),f=n.next();t.push({bin:r,pathHandle:o,pathStart:s,pathEnd:i,snarl:f>0?[a,f]:void 0,node:n.next(),offset:n.next()})}}function _i(r,e,t){let n=O(r);for(let o of e){let s=new Ye(o);for(;!s.done;){let i=s.next(),a=i%2;t.push({node:2*n+a,offset:s.next(),pathHandle:(i-a)/2,orientation:"forward",pathOffset:s.next()})}}}var tr=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,n,o,s){this.handle=e,this.edges=t,this.bwt=n,this.encodedSequence=o,this.next=s,this.sequenceLen=Yr(o)}get id(){return O(this.handle)}get orientation(){return je(this.handle)}get sequence(){return this.decoded??=Kr(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 Mt(this.edges,this.bwt)}};function Q(r,e){if(typeof r!="number")throw new Error(`${e} is not a number in the database`);return r}function dt(r,e){if(typeof r!="string")throw new Error(`${e} is not text in the database`);return r}function Be(r,e){if(!(r instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return r}function No(r,e){return{handle:r,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}}function er(r,e){return r.catch(e),r}async function To(r){let e=new Map;for await(let{values:t}of r.scan("Tags"))e.set(dt(t[0],"Tags.key"),dt(t[1],"Tags.value"));return e}var pt=class r{pathCache;pathMapCache;indexTags=new Map;overviewRowsCache;sqlite;index;tagMap;constructor(e,t,n){this.sqlite=e,this.index=t,this.tagMap=n}static async open(e){let{source:t,haplotypeIndex:n}=e,o={blockSize:e.blockSize,maxBlocks:e.maxBlocks},s=await ht.open(t,o),i=s.objects.has("Tags")?await To(s):new Map,a=i.get("version");if(a!==nr)throw new Qt(a);for(let l of["Nodes","Paths","ReferenceIndex"])s.rootPage(l);let f=n?await ht.open(n,o):void 0,c=new r(s,f,i);if(f){for(let u of["Tags","HaplotypeSamples","HaplotypeLengths"])if(!f.objects.has(u))throw new Error(`haplotypeIndex is not a gbz-base haplotype index: it has no ${u} table`);c.indexTags=await To(f);let l=c.indexTags.get("haplotype_index_paths"),h=await c.tag("paths");if(l!==h)throw new Error(`haplotype index was built for ${l??"an unknown number of"} paths but the graph has ${h}`);let d=c.indexTags.get("haplotype_index_nodes"),p=await c.tag("nodes");if(d!==void 0&&d!==p)throw new Error(`haplotype index was built for a graph with ${d} nodes but this one has ${p}`);if(c.indexTags.get("haplotype_index_orientations")==="forward")throw new Vt;let m=c.indexTags.get("haplotype_index_format");if(Number(m)!==Jn)throw new Error(m===void 0?`the haplotype index predates format ${Jn}; rebuild it with gbz-haplotype-index 0.3`:`the haplotype index has format ${m}; this version of @gmod/gbz-base reads format ${Jn}`)}return c}async tags(){return this.tagMap}async tag(e){return this.tagMap.get(e)}prefetchRecords(e,t=!1){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let n=t[4];return new tr(e,Qr(Be(t[1],"Nodes.edges")),Be(t[2],"Nodes.bwt"),Be(t[3],"Nodes.sequence"),typeof n=="number"?n:void 0)}paths(){return this.pathCache??=er(this.scanPaths(),()=>{this.pathCache=void 0}),this.pathCache}async scanPaths(){let e=[];for await(let{rowid:t,values:n}of this.sqlite.scan("Paths"))e.push(No(t,n));return e}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?No(e,t):void 0}pathsByHandle(){return this.pathMapCache??=er(this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),()=>{this.pathMapCache=void 0}),this.pathMapCache}async findPath(e){return(await this.paths()).filter(n=>n.name.sample===e.sample&&n.name.contig===e.contig&&n.name.haplotype===e.haplotype&&n.name.fragment<=e.fragment).sort((n,o)=>o.name.fragment-n.name.fragment)[0]}async pathsNamed(e){let t=Ve(We(e),0);return(await this.paths()).filter(n=>n.name.sample===t.sample&&n.name.contig===t.contig&&n.name.haplotype===t.haplotype).sort((n,o)=>n.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 n=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!n){let i=await this.getPath(e);throw new Error(`${i?`The fragment of ${we(i.name)} at ${i.name.fragment}`:`Path ${e}`} has not been indexed for random access`)}let o=n.pathOffset,s=n.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 getPathFragments(e){let{start:t,end:n}=e;if(Number.isNaN(t)||Number.isNaN(n))throw new Error(`The window ${t}..${n} is not a number range`);let o=await this.pathsNamed(e.path);if(o.length===0)throw new Wt(Ve(We(e.path),0));if(n<=t)return[];let s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<n);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){let{sample:n,contig:o,haplotype:s}=e.path.name,i=Math.max(t.start,e.start),a=t.haplotypes??"all";try{let f=await Xn(this,{...t,path:{sample:n,contig:o,haplotype:s},start:i,end:Math.min(t.end,e.end)});return t.keep===void 0&&this.hasHaplotypeIndex&&(a==="all"||a==="distinct")&&await f.identifyPaths(),f}catch(f){throw f instanceof fe&&f.walkedBp!==void 0?new fe(f.limit,{windowBp:t.end-t.start,walkedBp:i-t.start+f.walkedBp}):f}}async getSubgraphs(e){let t=await this.getPathFragments(e);return(await Promise.allSettled(t.map(o=>this.subgraphForFragment(o,e)))).map(o=>{if(o.status==="rejected")throw o.reason;return o.value})}async getAlignments(e){return(await this.getSubgraphs(e)).flatMap(t=>t.alignments())}subgraphInInterval(e){return Xn(this,e)}subgraphAtOffset(e){return Mo(this,e)}subgraphAroundNodes(e){return Ro(this,e)}subgraphBetween(e){return Po(this,e)}fetchStats(){let e=({pager:t})=>({fetches:t.fetches,bytesFetched:t.bytesFetched});return{graph:e(this.sqlite),haplotypeIndex:this.index?e(this.index):void 0}}async graphName(){let e=new Map;for(let[n,o]of await this.tags())n.startsWith("gbz_")&&e.set(n.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=to(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeSampleGap(){let e=await this.haplotypeSampleInterval(),t=this.indexTags.get("haplotype_index_reference_interval");return e===void 0?void 0:Math.max(e,t===void 0?0:Number(t))}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeStrayOptions(){let e=n=>this.indexTags.get(`haplotype_index_stray_${n}`);if(!this.index?.has("HaplotypeBins")||e("format")!=="2")return;let t=e("snarls")==="modeled"&&e("chain_links")===(await this.tag("chain_links")??"0");return{context:Number(e("context")),bin:Number(e("bin")),bound:Number(e("bound")),snarlNodes:t?Number(e("snarl_nodes")):void 0}}async blobRows(e,t,n){let o=[],s=[];for await(let i of this.companion.indexScanFrom(e,t,n))s.push(Q(i[i.length-1],`${e} rowid`));s.length>1&&await this.companion.prefetchRows(e,[[Math.min(...s),Math.max(...s)+1]],!0);for(let i of s){let a=await this.companion.byRowid(e,i);a&&o.push(a)}return o}async haplotypeBinData(e,t,n){let o=[],s=[];for(let i of await this.blobRows("HaplotypeBins",[e,t],[e,n])){let a=Q(i[1],"HaplotypeBins.bin");Ri(Be(i[3],"HaplotypeBins.nodes"),o),ki(a,Be(i[4],"HaplotypeBins.strays"),s)}return{listed:Pi(o),strays:s}}async haplotypeAnchorsBetween(e,t,n){let o=[],s=[],i=()=>{let a=o[o.length-1];a&&_i(a.node,s,a.visits),s=[]};for(let a of await this.blobRows("HaplotypeAnchors",[e,t],[e,n])){let f=Q(a[1],"HaplotypeAnchors.anchor_offset");o[o.length-1]?.anchorOffset!==f&&(i(),o.push({anchorOffset:f,node:Q(a[3],"HaplotypeAnchors.node_handle"),pathOffset:Q(a[4],"HaplotypeAnchors.path_offset"),visits:[]})),s.push(Be(a[5],"HaplotypeAnchors.visits"))}return i(),o}async haplotypeAnchor(e,t){let[n]=await this.haplotypeAnchorsBetween(e,t,t);return n&&{node:n.node,pathOffset:n.pathOffset}}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:Q(e[0],"HaplotypeSamples.node_handle"),offset:Q(e[1],"HaplotypeSamples.node_offset"),pathHandle:Q(e[2],"HaplotypeSamples.path_handle"),orientation:Q(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:Q(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let n=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0],[t,Number.MAX_SAFE_INTEGER]))n.push(this.sampleFromRow(o));return n}async haplotypeSampleAt(e,t){let n=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);return n?.[0]===e&&n[1]===t?this.sampleFromRow(n):void 0}overviewRows(){return this.overviewRowsCache??=er((async()=>{let e=[];for await(let{rowid:t,values:n}of this.companion.scan("HaplotypeOverviewRows"))e[t]={sample:dt(n[1],"HaplotypeOverviewRows.sample"),haplotype:Q(n[2],"HaplotypeOverviewRows.haplotype")};return e})(),()=>{this.overviewRowsCache=void 0}),this.overviewRowsCache}async overviewChunks(e,t,n,o,s){let i=new Map;for(let a of await this.blobRows(e,[t,n,o],[t,n,s])){let f=Q(a[2],`${e}.chunk`),c=i.get(f)??[];c.push(Be(a[4],`${e} blob`)),i.set(f,c)}return new Map([...i].map(([a,f])=>[a,Mi(f)]))}async haplotypeOverview(e){let{signal:t}=e;t?.throwIfAborted();let n=u=>this.indexTags.get(`haplotype_index_overview_${u}`);if(!this.index?.has("HaplotypeOverviewClasses")||n("format")!=="1")return;let o=Number(n("bin")),s=Number(n("chunk")),i=Number(n("levels")),a=Math.max(0,Math.min(Math.floor(e.level??0)||0,i-1));if(e.level===void 0&&e.bpPerPixel!==void 0)for(;a+1<i&&o*4**(a+1)<=e.bpPerPixel;)a+=1;let f=o*4**a,[c,l]=await Promise.all([this.getPathFragments(e),this.overviewRows()]);t?.throwIfAborted();let h=Math.ceil(l.length/2),d=[],p=[];for(let u of c){let w=u.end-u.start,b=Math.max(e.start,u.start)-u.start,S=Math.min(e.end,u.end)-u.start,g=Math.floor(b/f),x=Math.floor((S-1)/f),y=Math.floor(g/s),E=Math.floor(x/s),[A,N]=await Promise.all([this.overviewChunks("HaplotypeOverviewBins",u.path.handle,a,y,E),this.overviewChunks("HaplotypeOverviewClasses",u.path.handle,a,y,E)]);t?.throwIfAborted();for(let k=y;k<=E;k++){let F=new Ye(A.get(k)??new Uint8Array),R=N.get(k)??new Uint8Array;for(let T=k*s;!F.done;T++){let C=Array.from({length:7},()=>F.next());if(T<g||T>x)continue;d.push({start:u.start+T*f,end:u.start+Math.min((T+1)*f,w),classes:[C[0],C[1],C[2],C[3]],excursions:C[4],variants:C[5],longestExcursion:C[6]});let D=(T-k*s)*h;p.push(R.subarray(D,D+h))}}}if(d.length===0)return;let m=new Uint8Array(d.length*l.length);return p.forEach((u,w)=>{for(let b=0;b<l.length;b++)m[w*l.length+b]=(u[b>>1]??0)>>4*(b%2)&15}),{level:a,bin:f,haplotypes:l,bins:d,cells:m}}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?Q(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:Q(t[1],"ReferenceIndex.path_offset"),pos:{node:Q(t[2],"ReferenceIndex.node_handle"),offset:Q(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let n=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return n?.[0]===e?Q(n[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let n=await this.indexedRowid(e,t);return n===void 0?void 0:this.indexedRow(n)}async indexedPositionsBetween(e,t,n){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,n)]),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 Ir=le(Ln(),1),xt=le(ot(),1),En=le(qr(),1),Ns=le(Hs(),1);function Yt(r){let e=/\.gbz\.db$/i;return e.test(r)?r.replace(e,".haplotype-index.db"):void 0}var Lo=le(qr(),1);function Oi(r){return Hr(r)&&Yt(Br(r))?Dr(r,e=>Yt(e)):void 0}function Ni(r){return r instanceof Error&&(/\bHTTP 40[34]\b/.test(r.message)||r.code==="ENOENT")}async function Fo(r,e){let t=Oi(r);if(!t)return{};try{return await(0,Lo.openLocation)(t,e).stat(),{location:t}}catch(n){return Ni(n)?{}:{unreadable:String(n)}}}var qo=le(Ln(),1),Ti=5e3,Li=50*2**20,rr=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 Fi(r,e){if(r.length<=e)return r;let t=r.length/e;return Array.from({length:e},(n,o)=>r[Math.floor(o*t)])}var $o=(r,e)=>r.path.some(t=>e.has(t.name)),Kt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=(0,qo.cachedSetup)({setup:async()=>{let{size:e}=await this.file.stat();if(e>Li)throw new rr(e);let t=await this.file.readFile(),n=new TextDecoder().decode(t[0]===31&&t[1]===139?await Gr(t):t);return $n(n)}})}async readIndexed(e,t,n){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:n,lineCallback:a=>{let f=Fn(a);f&&$o(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(o=>$o(o,e));return{records:Fi(n,Ti),total:n.length}}};var Ps=le(Ln(),1),ks=le(ot(),1);var or=function(r,e){return or=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},or(r,e)};function ut(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");or(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Bo(r,e,t,n){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(n.next(l))}catch(h){i(h)}}function f(l){try{c(n.throw(l))}catch(h){i(h)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((n=n.apply(r,e||[])).next())})}function Xt(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,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(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(n=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(r,t)}catch(l){c=[6,l],o=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function He(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ke(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function Xe(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function De(r){return this instanceof De?(this.v=r,this):new De(r)}function Ho(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,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(p){return function(m){return Promise.resolve(m).then(p,h)}}function a(p,m){n[p]&&(o[p]=function(u){return new Promise(function(w,b){s.push([p,u,w,b])>1||f(p,u)})},m&&(o[p]=m(o[p])))}function f(p,m){try{c(n[p](m))}catch(u){d(s[0][3],u)}}function c(p){p.value instanceof De?Promise.resolve(p.value.v).then(l,h):d(s[0][2],p)}function l(p){f("next",p)}function h(p){f("throw",p)}function d(p,m){p(m),s.shift(),s.length&&f(s[0][0],s[0][1])}}function Do(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof He=="function"?He(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(a,f){i=r[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(r){return typeof r=="function"}function Go(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Zt=Go(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
5
+ `}outputPaths(e){this.settleDeferred();let t=e.cigar??!1,n=[],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]};n.push({info:this.paths[this.refId],identity:void 0,name:ge({...i,end: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!=="anonymous"?i.identity:void 0;n.push({info:i,identity:f,name:f?ge({...f.name,fragment:f.name.fragment+f.hapStart,end:f.name.fragment+f.hapEnd}):ge({sample:"unknown",contig:o,haplotype:s,fragment:0,end:i.len}),cigar:t?this.alignToRef(a):void 0}),s+=1}),n}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Ue(e,t)&&(yield[e,t])}walkSpans(){return this.settleDeferred(),this.paths.flatMap((e,t)=>{let n=t===this.refId?void 0:e.identity;return n?[{name:n.name,start:n.name.fragment+n.hapStart,end:n.name.fragment+n.hapEnd}]:[]})}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!j(s)).map(s=>({id:String(O(s)),sequence:this.record(s).sequence})),n=[];for(let[s,i]of this.outputEdges())n.push({from:String(O(s)),from_is_reverse:j(s),to:String(O(i)),to_is_reverse:j(i)});let o=this.outputPaths(e).map(s=>xi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:n,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!j(i)),n=new Int32Array(t.length),o=[];t.forEach((i,a)=>{n[a]=O(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:n,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(Ft(i.info,i.identity))}))}}};function Ft(r,e){return e?.orientation==="reverse"?r.path.map(t=>re(t)).reverse():r.path}function xi(r,e,t,n){return{name:t,...r.weight===void 0?{}:{weight:r.weight},...n===void 0?{}:{cigar:n},path:Ft(r,e).map(o=>({id:String(O(o)),is_reverse:j(o)}))}}function Yn(r,e){let t=Math.min(r.length,e.length);for(let n=0;n<t;n++){let o=r[n],s=e[n];if(o!==s)return o<s?-1:1}return r.length-e.length}function X(r,e,t){if(t===0)return;let n=r[r.length-1];n?.[0]===e?n[1]+=t:r.push([e,t])}function Lt(r){return r===0?0:6+(r-1)}function Mo(r,e,t){if(e===0)X(r,"D",t);else if(t===0)X(r,"I",e);else{let n=Math.min(e,t),o=4*n+Lt(e-n)+Lt(t-n),s=Lt(e)+Lt(t);o<=s?(X(r,"M",n),X(r,"I",e-n),X(r,"D",t-n)):(X(r,"I",e),X(r,"D",t))}}function yi(r){let e=0;for(;e<r.length&&r[e][0]!=="M";)e+=1;if(e===r.length){let a=r.filter(([c])=>c==="I"),f=r.filter(([c])=>c==="D").reduce((c,[,l])=>c+l,0);return{edits:a.map(([c,l])=>[c,l]),leading:0,trailing:f}}let t=r.length;for(;r[t-1][0]!=="M";)t-=1;let n=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=n(r.slice(0,e)),s=n(r.slice(t)),i=[];X(i,"I",o.inserted);for(let[a,f]of r.slice(e,t))X(i,a,f);return X(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function Co(r,e){let t=e.map(()=>0),n=e.length-1,o=0,s=e[0],i=0;for(let[a,f]of r){if(a==="D")continue;let c=f;for(;c>0;){for(;o<n&&i>=s;)o+=1,s+=e[o];let l=o<n?Math.min(c,s-i):c;a==="M"&&(t[o]+=l),i+=l,c-=l}}return t}function bi(r,e){let t=[],n=0,o=0;for(let[s,i]of r){if(s==="D"){X(t,s,i);continue}let a=n;for(;o<e.length&&e[o][0]<n+i;){let[f,c]=e[o];X(t,s,f-a),X(t,"I",c),a=f,o+=1}X(t,s,n+i-a),n+=i}for(;o<e.length;o++)X(t,"I",e[o][1]);return t}function Si(r){return r.map(([e,t])=>`${t}${e}`).join("")}function Oe(r,e,t=0){if(!Number.isSafeInteger(e)||e<t)throw new Error(`${r} must be a whole number${t>0?` of at least ${t}`:""}, not ${e}`);return e}function $t(r){return Oe("context",r.context??100)}function qt(r,e){return e.limit!==void 0&&Oe("limit",e.limit),lt.create(r,e)}async function Ro(r,e){let t=$t(e),n=qt(r,e),o=await n.pathPosition(Ve(We(e.path),Oe("offset",e.offset)));return await n.aroundPosition(o.position.handle,o.position.nodeOffset,t),await n.extractSnarls(e.snarls??"none"),n.extractPaths(o,e.haplotypes??"all"),n}async function vi(r,e){let t=Oe("start",e.start),n=Oe("end",e.end),o=$t(e),s=qt(r,e);try{let i=await s.pathPosition(Ve(We(e.path),t));return await s.prefetchReferenceWalk(i,n-t),await s.aroundInterval(i.position,n-t,o),await s.extractSnarls(e.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof fe&&i.windowBp===void 0?new fe(i.limit,{windowBp:n-t,walkedBp:s.referenceWalkedBp??0}):i}}async function Kn(r,e){let{keep:t}=e,n=e.haplotypes??"all",o=n==="all"||n==="distinct";if(t!==void 0&&o&&!r.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await vi(r,e);return t===void 0||!o?(s.extractPaths(i,n),s):(await s.extractChosenPaths(i,e.end-e.start,t,$t(e))||(s.extractPaths(i,"all"),await s.identifyPaths()),s.keepHaplotypes(t),n==="distinct"&&s.mergeDistinct(),s)}async function Po(r,e){let t=e.haplotypes??"all",n=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(n==="overlapping"&&new Set(e.nodeIds).size>1)throw new Error("Overlapping snarls cannot be extracted for a node-based query with multiple nodes");let o=$t(e);for(let i of e.nodeIds)Oe("node id",i,1);let s=qt(r,e);return await s.aroundNodes(e.nodeIds,o),await s.extractSnarls(n),s.extractPaths(void 0,t),s}async function ko(r,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let n=qt(r,e);return await n.betweenNodes(Oe("startHandle",e.startHandle,2),Oe("endHandle",e.endHandle,2)),n.extractPaths(void 0,t),n}function Ae(r,e){let t=0;for(let o=0;o<8;o++){let s=r[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){if(o===7&&!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+o+1]}}let n=r[e+8];if(n===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+n,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function Ii(r,e,t){switch(t){case 1:return r.getInt8(e);case 2:return r.getInt16(e);case 3:return r.getInt8(e)<<16|r.getUint16(e+1);case 4:return r.getInt32(e);case 6:return r.getInt16(e)*4294967296+r.getUint32(e+2);default:{let n=r.getBigInt64(e);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${n} exceeds the safe integer range`);return Number(n)}}}var Ei=new TextDecoder;function Bt(r){let[e,t]=Ae(r,0),n=[],o=t;for(;o<e;){let[a,f]=Ae(r,o);n.push(a),o=f}let s=new DataView(r.buffer,r.byteOffset,r.byteLength),i=e;return n.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=Ii(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=r.subarray(i,i+f);return i+=f,a%2===0?c:Ei.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var Dt=2,Gt=5,_o=10,Ht=13;function Oo(r,e){return r[e]*256+r[e+1]}function Ne(r,e){return r[e]*16777216+r[e+1]*65536+r[e+2]*256+r[e+3]}function Ai(r,e){let t=r[e];if(t!==Dt&&t!==Gt&&t!==_o&&t!==Ht)throw new Error(`SQLite page has unknown b-tree type ${t}`);let n=t===Dt||t===Gt;return{type:t,cellCount:Oo(r,e+3),rightChild:n?Ne(r,e+8):0,cellPointers:e+(n?12:8)}}function Re(r,e,t){return Oo(r,e.cellPointers+2*t)}var Ci=4096,zt=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let n=this.usable,o=t?Math.floor((n-12)*64/255)-23:n-35;if(e<=o)return e;let s=Math.floor((n-12)*32/255)-23,i=s+(e-s)%(n-4);return i<=o?i:s}async payload(e,t,n,o){let s=this.localPayloadSize(n,o);if(s===n)return e.subarray(t,t+n);let i=new Uint8Array(n);i.set(e.subarray(t,t+s),0);let a=s,f=Ne(e,t+s);for(;f!==0&&a<n;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,n-a));i.set(l,a),a+=l.length,f=Ne(c,0)}if(a!==n)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 n=this.tableDepths.get(e);return n||(n=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Ht)return s;if(a.type!==Gt)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:Ne(i,Re(i,a,f))}})(),this.tableDepths.set(e,n),n.catch(()=>this.tableDepths.delete(e))),n}childIndexFor(e,t,n){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=Ae(e,Re(e,t,i)+4);a<n?o=i+1:s=i}return o}async prefetchRowidRanges(e,t,n=!1){if(t.length===0)return!0;let o=await this.tableDepth(e,t[0][0]),s=t.map(()=>[e]);for(let i=0;i<o;i++){s=await Promise.all(s.map((f,c)=>this.childrenInRange(f,...t[c])));let a=s.flat();if(n)this.pager.prefetchLeading(a);else if(!this.pager.prefetch(a))return!1}return!0}async childrenInRange(e,t,n){let o=await Promise.all(e.map(i=>this.pageAt(i))),s=[];return o.forEach(({page:i,header:a},f)=>{let c=f===0?this.childIndexFor(i,a,t):0,l=f===o.length-1?this.childIndexFor(i,a,n):a.cellCount;for(let h=c;h<=l;h++)s.push(h===a.cellCount?a.rightChild:Ne(i,Re(i,a,h)))}),s}async tableRowid(e,t){let n=e;for(;;){let{page:o,header:s}=await this.pageAt(n);if(s.type===Ht){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,h=Re(o,s,l),[d,p]=Ae(o,h),[m,u]=Ae(o,p);if(m===t)return Bt(await this.payload(o,u,d,!1));m<t?f=l+1:c=l}return}if(s.type!==Gt)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]=Ae(o,c+4);l<t?i=f+1:a=f}n=i===s.cellCount?s.rightChild:Ne(o,Re(o,s,i))}}async*tableScan(e){yield*this.scanPage(e,await this.tableDepth(e,0))}async*scanPage(e,t){let{page:n,header:o}=await this.pageAt(e);if(o.type===Ht)for(let s=0;s<o.cellCount;s++){let i=Re(n,o,s),[a,f]=Ae(n,i),[c,l]=Ae(n,f);yield{rowid:c,values:Bt(await this.payload(n,l,a,!1))}}else{let s=[];for(let i=0;i<o.cellCount;i++)s.push(Ne(n,Re(n,o,i)));s.push(o.rightChild),t===1&&this.pager.prefetchLeading(s);for(let i of s)yield*this.scanPage(i,t-1)}}decodedCells(e,t){let n=this.decodedIndexPages.get(e);if(n)this.decodedIndexPages.delete(e);else if(n=new Array(t.cellCount),this.decodedIndexPages.size>=Ci){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,n),n}async indexCell(e,t,n,o){let s=this.decodedCells(e,n),i=s[o];if(!i){let a=Re(t,n,o),f=n.type===Dt,[c,l]=Ae(t,f?a+4:a);i={values:Bt(await this.payload(t,l,c,!0)),leftChild:f?Ne(t,a):0},s[o]=i}return i}async lowerBound(e,t,n,o,s,i){let a=s,f=n.cellCount;for(;a<f;){let c=a+f>>1,l=await this.indexCell(e,t,n,c),h=Xn(l.values,o);h<0||i&&h===0?a=c+1:f=c}return a}async*indexScanFrom(e,t,n){let{page:o,header:s}=await this.pageAt(e),i=await this.lowerBound(e,o,s,t,0,!1),a=s.type===Dt;if(a&&n){let f=await this.lowerBound(e,o,s,n,i,!0),c=[];for(let l=i;l<=f;l++)c.push(l===s.cellCount?s.rightChild:(await this.indexCell(e,o,s,l)).leftChild);this.pager.prefetchLeading(c)}for(let f=i;f<s.cellCount;f++){let c=await this.indexCell(e,o,s,f);if(a&&(yield*this.indexScanFrom(c.leftChild,t,n)),n&&Xn(c.values,n)>0)return;yield c.values}a&&(yield*this.indexScanFrom(s.rightChild,t,n))}async indexSeekLE(e,t){let n,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,h=await this.indexCell(o,s,i,l);Xn(h.values,t)<=0?(n=h.values,a=l+1):(c=h.leftChild,f=l)}if(i.type===_o)return n;o=a===i.cellCount?i.rightChild:c}}};function Xn(r,e){for(let t=0;t<e.length;t++){let n=r[t],o=e[t];if(typeof n!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(n!==o)return n<o?-1:1}return 0}function No({blockSize:r,maxBlocks:e}){if(r!==void 0&&!(Number.isSafeInteger(r)&&r>0))throw new Error(`blockSize must be a positive integer, not ${r}`);if(e!==void 0&&!(Number.isSafeInteger(e)&&e>0))throw new Error(`maxBlocks must be a positive integer, not ${e}`)}var jt=class{blocks=new Map;blockSize;maxBlocks;plan;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,n,o={}){this.source=e,this.pageSize=t,this.fileSize=n;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 n=await this.readRetrying(e,t);if(this.bytesFetched+=n.length,n.length<e)throw new Error(`the file ends at byte ${t+n.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return n}async readRetrying(e,t){let n=0;for(;;)try{return await this.source.read(e,t)}catch(o){if(n+=1,n>=3)throw o;await new Promise(s=>setTimeout(s,200*n))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){this.follow(e);let t=this.touch(e);if(t)return t;let n=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-n),s=this.read(o,n);return this.fetches+=1,this.store(e,s),this.evict(),s}touch(e){let t=this.blocks.get(e);return t&&(this.blocks.delete(e),this.blocks.set(e,t)),t}blockOf(e){return Math.floor((e-1)*this.pageSize/this.blockSize)}get prefetchBudget(){return Math.max(1,Math.floor(this.maxBlocks/2))}get chunk(){return Math.max(1,Math.floor(this.prefetchBudget/2))}prefetch(e){let t=new Set(e.map(n=>this.blockOf(n)));return t.size>this.prefetchBudget?!1:(this.fetchBlocks(t),!0)}prefetchLeading(e){let t=[],n=new Map;for(let o of e){let s=this.blockOf(o);n.has(s)||(n.set(s,t.length),t.push(s))}this.plan={blocks:t,position:n,next:0},this.advance(this.prefetchBudget)}advance(e){let t=this.plan;if(!t)return;let n=t.blocks.slice(t.next,t.next+e);t.next+=n.length,t.next>=t.blocks.length&&(this.plan=void 0),this.fetchBlocks(new Set(n))}follow(e){let t=this.plan,n=t?.position.get(e);t&&n!==void 0&&n>=t.next-Math.ceil(this.chunk/2)&&this.advance(this.chunk)}fetchBlocks(e){let t=[...e].filter(o=>!this.touch(o)).sort((o,s)=>o-s),n=0;for(;n<t.length;){let o=n+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[n],o-n),n=o}}fetchRun(e,t){let n=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-n),s=this.read(o,n);this.fetches+=1;for(let i=0;i<t;i++){let a=i*this.blockSize;this.store(e+i,s.then(f=>f.subarray(a,a+this.blockSize)))}this.evict()}store(e,t){this.blocks.set(e,t),t.catch(()=>{this.blocks.get(e)===t&&this.blocks.delete(e)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let n=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return n.subarray(o,o+this.pageSize)}};var ht=class r{pager;btree;objects;constructor(e,t,n){this.pager=e,this.btree=t,this.objects=n}static async open(e,t={}){No(t);let n=await e.read(Math.max(512,t.blockSize??65536),0),o=n.subarray(0,100);if(new TextDecoder().decode(o.subarray(0,15))!=="SQLite format 3"||o.length<100)throw new Error("Not a SQLite database");let i=new DataView(o.buffer,o.byteOffset,o.byteLength),a=i.getUint16(16),f=a===1?65536:a,c=o[20]??0,l=i.getUint32(56);if(l!==1)throw new Error(`SQLite text encoding ${l} is not UTF-8`);let h=i.getUint32(28);if(h===0||i.getUint32(24)!==i.getUint32(92))throw new Error("SQLite header has no valid database size; the file was written by SQLite older than 3.7.0");let d=h*f,p=new jt(e,f,d,t);p.seed(0,n),p.fetches+=1,p.bytesFetched+=n.length;let m=new zt(p,c),u=new Map;for await(let{values:w}of m.tableScan(1)){let[b,S,g,x,y]=w;typeof b=="string"&&typeof S=="string"&&typeof g=="string"&&typeof x=="number"&&u.set(S,{type:b,name:S,tableName:g,rootPage:x,sql:typeof y=="string"?y:""})}return new r(p,m,u)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}withoutRowid(e){let t=this.objects.get(e);return t?.type==="table"&&/without\s+rowid/i.test(t.sql)}indexOn(e){let t=[...this.objects.values()].find(n=>n.type==="index"&&n.tableName===e);if(t)return t.rootPage;if(this.withoutRowid(e))return this.rootPage(e);throw new Error(`SQLite table ${e} has no index`)}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,n=!1){return this.btree.prefetchRowidRanges(this.rootPage(e),t,n)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t,n){return this.btree.indexScanFrom(this.indexOn(e),t,n)}has(e){return this.objects.has(e)}};var tr="GBZ-base version 4",Ut=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${ge(e)}`),this.path=e}},Wt=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")}},Vt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: it has no version tag":`unsupported database schema "${e}"; this reader understands "${tr}"`),this.found=e}};function Mi(r){if(r.length===1)return r[0];let e=new Uint8Array(r.reduce((n,o)=>n+o.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}var Zn=3,Ye=class{at=0;bytes;constructor(e){this.bytes=e}get done(){return this.at>=this.bytes.length}next(){let e=0,t=1;for(;;){let n=this.bytes[this.at++];if(n===void 0)throw new Error("a haplotype index blob ends inside a number");if(e+=(n&127)*t,t*=128,(n&128)===0)return e}}};function Ri(r,e){let t=new Ye(r),n=0;for(;!t.done;){let o=n+t.next();n=o+t.next(),e.push([o,n])}}function Pi(r){r.sort((n,o)=>n[0]-o[0]);let e=[],t=[];for(let[n,o]of r){let s=t.length-1;s>=0&&n<=t[s]+1?t[s]=Math.max(t[s],o):(e.push(n),t.push(o))}return n=>{let o=0,s=e.length;for(;o<s;){let i=o+s>>1;e[i]<=n?o=i+1:s=i}return o>0&&n<=t[o-1]}}function ki(r,e,t){let n=new Ye(e);for(;!n.done;){let o=n.next(),s=n.next(),i=n.next(),a=n.next(),f=n.next();t.push({bin:r,pathHandle:o,pathStart:s,pathEnd:i,snarl:f>0?[a,f]:void 0,node:n.next(),offset:n.next()})}}function _i(r,e,t){let n=O(r);for(let o of e){let s=new Ye(o);for(;!s.done;){let i=s.next(),a=i%2;t.push({node:2*n+a,offset:s.next(),pathHandle:(i-a)/2,orientation:"forward",pathOffset:s.next()})}}}var er=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,n,o,s){this.handle=e,this.edges=t,this.bwt=n,this.encodedSequence=o,this.next=s,this.sequenceLen=Kr(o)}get id(){return O(this.handle)}get orientation(){return je(this.handle)}get sequence(){return this.decoded??=Xr(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 Ct(this.edges,this.bwt)}};function Q(r,e){if(typeof r!="number")throw new Error(`${e} is not a number in the database`);return r}function dt(r,e){if(typeof r!="string")throw new Error(`${e} is not text in the database`);return r}function Be(r,e){if(!(r instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return r}function To(r,e){return{handle:r,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}}function Jn(r,e){return r.catch(e),r}async function Lo(r){let e=new Map;for await(let{values:t}of r.scan("Tags"))e.set(dt(t[0],"Tags.key"),dt(t[1],"Tags.value"));return e}var pt=class r{pathCache;pathMapCache;indexTags=new Map;overviewRowsCache;sqlite;index;tagMap;constructor(e,t,n){this.sqlite=e,this.index=t,this.tagMap=n}static async open(e){let{source:t,haplotypeIndex:n}=e,o={blockSize:e.blockSize,maxBlocks:e.maxBlocks},s=await ht.open(t,o),i=s.objects.has("Tags")?await Lo(s):new Map,a=i.get("version");if(a!==tr)throw new Vt(a);for(let l of["Nodes","Paths","ReferenceIndex"])s.rootPage(l);let f=n?await ht.open(n,o):void 0,c=new r(s,f,i);if(f){for(let u of["Tags","HaplotypeSamples","HaplotypeLengths"])if(!f.objects.has(u))throw new Error(`haplotypeIndex is not a gbz-base haplotype index: it has no ${u} table`);c.indexTags=await Lo(f);let l=c.indexTags.get("haplotype_index_paths"),h=await c.tag("paths");if(l!==h)throw new Error(`haplotype index was built for ${l??"an unknown number of"} paths but the graph has ${h}`);let d=c.indexTags.get("haplotype_index_nodes"),p=await c.tag("nodes");if(d!==void 0&&d!==p)throw new Error(`haplotype index was built for a graph with ${d} nodes but this one has ${p}`);if(c.indexTags.get("haplotype_index_orientations")==="forward")throw new Wt;let m=c.indexTags.get("haplotype_index_format");if(Number(m)!==Zn)throw new Error(m===void 0?`the haplotype index predates format ${Zn}; rebuild it with gbz-haplotype-index 0.3`:`the haplotype index has format ${m}; this version of @gmod/gbz-base reads format ${Zn}`)}return c}async tags(){return this.tagMap}async tag(e){return this.tagMap.get(e)}prefetchRecords(e,t=!1){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let n=t[4];return new er(e,Yr(Be(t[1],"Nodes.edges")),Be(t[2],"Nodes.bwt"),Be(t[3],"Nodes.sequence"),typeof n=="number"?n:void 0)}paths(){return this.pathCache??=Jn(this.scanPaths(),()=>{this.pathCache=void 0}),this.pathCache}async scanPaths(){let e=[];for await(let{rowid:t,values:n}of this.sqlite.scan("Paths"))e.push(To(t,n));return e}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?To(e,t):void 0}pathsByHandle(){return this.pathMapCache??=Jn(this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),()=>{this.pathMapCache=void 0}),this.pathMapCache}async findPath(e){return(await this.paths()).filter(n=>n.name.sample===e.sample&&n.name.contig===e.contig&&n.name.haplotype===e.haplotype&&n.name.fragment<=e.fragment).sort((n,o)=>o.name.fragment-n.name.fragment)[0]}async pathsNamed(e){let t=Ve(We(e),0);return(await this.paths()).filter(n=>n.name.sample===t.sample&&n.name.contig===t.contig&&n.name.haplotype===t.haplotype).sort((n,o)=>n.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 n=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!n){let i=await this.getPath(e);throw new Error(`${i?`The fragment of ${ge(i.name)} at ${i.name.fragment}`:`Path ${e}`} has not been indexed for random access`)}let o=n.pathOffset,s=n.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 getPathFragments(e){let{start:t,end:n}=e;if(Number.isNaN(t)||Number.isNaN(n))throw new Error(`The window ${t}..${n} is not a number range`);let o=await this.pathsNamed(e.path);if(o.length===0)throw new Ut(Ve(We(e.path),0));if(n<=t)return[];let s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<n);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){let{sample:n,contig:o,haplotype:s}=e.path.name,i=Math.max(t.start,e.start),a=t.haplotypes??"all";try{let f=await Kn(this,{...t,path:{sample:n,contig:o,haplotype:s},start:i,end:Math.min(t.end,e.end)});return t.keep===void 0&&this.hasHaplotypeIndex&&(a==="all"||a==="distinct")&&await f.identifyPaths(),f}catch(f){throw f instanceof fe&&f.walkedBp!==void 0?new fe(f.limit,{windowBp:t.end-t.start,walkedBp:i-t.start+f.walkedBp}):f}}async getSubgraphs(e){let t=await this.getPathFragments(e);return(await Promise.allSettled(t.map(o=>this.subgraphForFragment(o,e)))).map(o=>{if(o.status==="rejected")throw o.reason;return o.value})}async getAlignments(e){return(await this.getSubgraphs(e)).flatMap(t=>t.alignments())}subgraphInInterval(e){return Kn(this,e)}subgraphAtOffset(e){return Ro(this,e)}subgraphAroundNodes(e){return Po(this,e)}subgraphBetween(e){return ko(this,e)}fetchStats(){let e=({pager:t})=>({fetches:t.fetches,bytesFetched:t.bytesFetched});return{graph:e(this.sqlite),haplotypeIndex:this.index?e(this.index):void 0}}async graphName(){let e=new Map;for(let[n,o]of await this.tags())n.startsWith("gbz_")&&e.set(n.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=no(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeSampleGap(){let e=await this.haplotypeSampleInterval(),t=this.indexTags.get("haplotype_index_reference_interval");return e===void 0?void 0:Math.max(e,t===void 0?0:Number(t))}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeStrayOptions(){let e=n=>this.indexTags.get(`haplotype_index_stray_${n}`);if(!this.index?.has("HaplotypeBins")||e("format")!=="2")return;let t=e("snarls")==="modeled"&&e("chain_links")===(await this.tag("chain_links")??"0");return{context:Number(e("context")),bin:Number(e("bin")),bound:Number(e("bound")),snarlNodes:t?Number(e("snarl_nodes")):void 0}}async blobRows(e,t,n){let o=[],s=[];for await(let i of this.companion.indexScanFrom(e,t,n))s.push(Q(i[i.length-1],`${e} rowid`));s.length>1&&await this.companion.prefetchRows(e,[[Math.min(...s),Math.max(...s)+1]],!0);for(let i of s){let a=await this.companion.byRowid(e,i);a&&o.push(a)}return o}async haplotypeBinData(e,t,n){let o=[],s=[];for(let i of await this.blobRows("HaplotypeBins",[e,t],[e,n])){let a=Q(i[1],"HaplotypeBins.bin");Ri(Be(i[3],"HaplotypeBins.nodes"),o),ki(a,Be(i[4],"HaplotypeBins.strays"),s)}return{listed:Pi(o),strays:s}}async haplotypeAnchorsBetween(e,t,n){let o=[],s=[],i=()=>{let a=o[o.length-1];a&&_i(a.node,s,a.visits),s=[]};for(let a of await this.blobRows("HaplotypeAnchors",[e,t],[e,n])){let f=Q(a[1],"HaplotypeAnchors.anchor_offset");o[o.length-1]?.anchorOffset!==f&&(i(),o.push({anchorOffset:f,node:Q(a[3],"HaplotypeAnchors.node_handle"),pathOffset:Q(a[4],"HaplotypeAnchors.path_offset"),visits:[]})),s.push(Be(a[5],"HaplotypeAnchors.visits"))}return i(),o}async haplotypeAnchor(e,t){let[n]=await this.haplotypeAnchorsBetween(e,t,t);return n&&{node:n.node,pathOffset:n.pathOffset}}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:Q(e[0],"HaplotypeSamples.node_handle"),offset:Q(e[1],"HaplotypeSamples.node_offset"),pathHandle:Q(e[2],"HaplotypeSamples.path_handle"),orientation:Q(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:Q(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let n=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0],[t,Number.MAX_SAFE_INTEGER]))n.push(this.sampleFromRow(o));return n}async haplotypeSampleAt(e,t){let n=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);return n?.[0]===e&&n[1]===t?this.sampleFromRow(n):void 0}overviewRows(){return this.overviewRowsCache??=Jn((async()=>{let e=[];for await(let{rowid:t,values:n}of this.companion.scan("HaplotypeOverviewRows"))e[t]={sample:dt(n[1],"HaplotypeOverviewRows.sample"),haplotype:Q(n[2],"HaplotypeOverviewRows.haplotype")};return e})(),()=>{this.overviewRowsCache=void 0}),this.overviewRowsCache}async overviewChunks(e,t,n,o,s){let i=new Map;for(let a of await this.blobRows(e,[t,n,o],[t,n,s])){let f=Q(a[2],`${e}.chunk`),c=i.get(f)??[];c.push(Be(a[4],`${e} blob`)),i.set(f,c)}return new Map([...i].map(([a,f])=>[a,Mi(f)]))}async haplotypeOverview(e){let{signal:t}=e;t?.throwIfAborted();let n=u=>this.indexTags.get(`haplotype_index_overview_${u}`);if(!this.index?.has("HaplotypeOverviewClasses")||n("format")!=="1")return;let o=Number(n("bin")),s=Number(n("chunk")),i=Number(n("levels")),a=Math.max(0,Math.min(Math.floor(e.level??0)||0,i-1));if(e.level===void 0&&e.bpPerPixel!==void 0)for(;a+1<i&&o*4**(a+1)<=e.bpPerPixel;)a+=1;let f=o*4**a,[c,l]=await Promise.all([this.getPathFragments(e),this.overviewRows()]);t?.throwIfAborted();let h=Math.ceil(l.length/2),d=[],p=[];for(let u of c){let w=u.end-u.start,b=Math.max(e.start,u.start)-u.start,S=Math.min(e.end,u.end)-u.start,g=Math.floor(b/f),x=Math.floor((S-1)/f),y=Math.floor(g/s),E=Math.floor(x/s),[A,N]=await Promise.all([this.overviewChunks("HaplotypeOverviewBins",u.path.handle,a,y,E),this.overviewChunks("HaplotypeOverviewClasses",u.path.handle,a,y,E)]);t?.throwIfAborted();for(let k=y;k<=E;k++){let F=new Ye(A.get(k)??new Uint8Array),R=N.get(k)??new Uint8Array;for(let T=k*s;!F.done;T++){let C=Array.from({length:7},()=>F.next());if(T<g||T>x)continue;d.push({start:u.start+T*f,end:u.start+Math.min((T+1)*f,w),classes:[C[0],C[1],C[2],C[3]],excursions:C[4],variants:C[5],longestExcursion:C[6]});let D=(T-k*s)*h;p.push(R.subarray(D,D+h))}}}if(d.length===0)return;let m=new Uint8Array(d.length*l.length);return p.forEach((u,w)=>{for(let b=0;b<l.length;b++)m[w*l.length+b]=(u[b>>1]??0)>>4*(b%2)&15}),{level:a,bin:f,haplotypes:l,bins:d,cells:m}}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?Q(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:Q(t[1],"ReferenceIndex.path_offset"),pos:{node:Q(t[2],"ReferenceIndex.node_handle"),offset:Q(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let n=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return n?.[0]===e?Q(n[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let n=await this.indexedRowid(e,t);return n===void 0?void 0:this.indexedRow(n)}async indexedPositionsBetween(e,t,n){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,n)]),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 Ir=le(Tn(),1),xt=le(ot(),1),In=le(Gr(),1),Ns=le(Hs(),1);function Qt(r){let e=/\.gbz\.db$/i;return e.test(r)?r.replace(e,".haplotype-index.db"):void 0}var Fo=le(Gr(),1);function Oi(r){return Hr(r)&&Qt(Br(r))?Dr(r,e=>Qt(e)):void 0}function Ni(r){return r instanceof Error&&(/\bHTTP 40[34]\b/.test(r.message)||r.code==="ENOENT")}async function $o(r,e){let t=Oi(r);if(!t)return{};try{return await(0,Fo.openLocation)(t,e).stat(),{location:t}}catch(n){return Ni(n)?{}:{unreadable:String(n)}}}var Bo=le(Tn(),1),Ti=5e3,Li=50*2**20,nr=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 Fi(r,e){if(r.length<=e)return r;let t=r.length/e;return Array.from({length:e},(n,o)=>r[Math.floor(o*t)])}var qo=(r,e)=>r.path.some(t=>e.has(t.name)),Yt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=(0,Bo.cachedSetup)({setup:async({signal:e})=>{let{size:t}=await this.file.stat();if(t>Li)throw new nr(t);let n=await this.file.readFile({signal:e}),o=new TextDecoder().decode(n[0]===31&&n[1]===139?await zr(n):n);return Fn(o)}})}async readIndexed(e,t,n){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:n,lineCallback:a=>{let f=Ln(a);f&&qo(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(o=>qo(o,e));return{records:Fi(n,Ti),total:n.length}}};var ks=le(Tn(),1),_s=le(ot(),1);var rr=function(r,e){return rr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},rr(r,e)};function ut(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");rr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ho(r,e,t,n){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(n.next(l))}catch(h){i(h)}}function f(l){try{c(n.throw(l))}catch(h){i(h)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((n=n.apply(r,e||[])).next())})}function Kt(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,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(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(n=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(r,t)}catch(l){c=[6,l],o=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function He(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ke(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function Xe(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function De(r){return this instanceof De?(this.v=r,this):new De(r)}function Do(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,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(p){return function(m){return Promise.resolve(m).then(p,h)}}function a(p,m){n[p]&&(o[p]=function(u){return new Promise(function(w,b){s.push([p,u,w,b])>1||f(p,u)})},m&&(o[p]=m(o[p])))}function f(p,m){try{c(n[p](m))}catch(u){d(s[0][3],u)}}function c(p){p.value instanceof De?Promise.resolve(p.value.v).then(l,h):d(s[0][2],p)}function l(p){f("next",p)}function h(p){f("throw",p)}function d(p,m){p(m),s.shift(),s.length&&f(s[0][0],s[0][1])}}function Go(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof He=="function"?He(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(a,f){i=r[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(r){return typeof r=="function"}function zo(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Xt=zo(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
6
6
  `+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
7
- `):"",this.name="UnsubscriptionError",this.errors=t}});function sr(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Jt=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,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(u){e={error:u}}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(u){s=u instanceof Zt?u.errors:[u]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var d=He(h),p=d.next();!p.done;p=d.next()){var m=p.value;try{zo(m)}catch(u){s=s??[],u instanceof Zt?s=Xe(Xe([],Ke(s)),Ke(u.errors)):s.push(u)}}}catch(u){n={error:u}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(n)throw n.error}}}if(s)throw new Zt(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)zo(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&sr(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&sr(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var tc=Jt.EMPTY;function en(r){return r instanceof Jt||r&&"closed"in r&&H(r.remove)&&H(r.add)&&H(r.unsubscribe)}function zo(r){H(r)?r():r.unsubscribe()}var ve={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ze={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];var o=Ze.delegate;return o?.setTimeout?o.setTimeout.apply(o,Xe([r,e],Ke(t))):setTimeout.apply(void 0,Xe([r,e],Ke(t)))},clearTimeout:function(r){var e=Ze.delegate;return(e?.clearTimeout||clearTimeout)(r)},delegate:void 0};function tn(r){Ze.setTimeout(function(){var e=ve.onUnhandledError;if(e)e(r);else throw r})}function ir(){}var jo=(function(){return ar("C",void 0,void 0)})();function Uo(r){return ar("E",void 0,r)}function Wo(r){return ar("N",r,void 0)}function ar(r,e,t){return{kind:r,value:e,error:t}}var Ge=null;function Vo(r){if(ve.useDeprecatedSynchronousErrorHandling){var e=!Ge;if(e&&(Ge={errorThrown:!1,error:null}),r(),e){var t=Ge,n=t.errorThrown,o=t.error;if(Ge=null,n)throw o}}else r()}function Qo(r){ve.useDeprecatedSynchronousErrorHandling&&Ge&&(Ge.errorThrown=!0,Ge.error=r)}var mt=(function(r){ut(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,en(t)&&t.add(n)):n.destination=Hi,n}return e.create=function(t,n,o){return new rn(t,n,o)},e.prototype.next=function(t){this.isStopped?cr(Wo(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?cr(Uo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?cr(jo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.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})(Jt);var $i=Function.prototype.bind;function fr(r,e){return $i.call(r,e)}var qi=(function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){nn(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){nn(n)}else nn(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){nn(t)}},r})(),rn=(function(r){ut(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(H(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var a;s&&ve.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&fr(t.next,a),error:t.error&&fr(t.error,a),complete:t.complete&&fr(t.complete,a)}):i=t}return s.destination=new qi(i),s}return e})(mt);function nn(r){ve.useDeprecatedSynchronousErrorHandling?Qo(r):tn(r)}function Bi(r){throw r}function cr(r,e){var t=ve.onStoppedNotification;t&&Ze.setTimeout(function(){return t(r,e)})}var Hi={closed:!0,next:ir,error:Bi,complete:ir};var Je=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Yo(r){return r}function Ko(r){return r.length===0?Yo:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var de=(function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=Gi(e)?e:new rn(e,t,n);return Vo(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},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Xo(t),new t(function(o,s){var i=new rn({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Je]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ko(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Xo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r})();function Xo(r){var e;return(e=r??ve.Promise)!==null&&e!==void 0?e:Promise}function Di(r){return r&&H(r.next)&&H(r.error)&&H(r.complete)}function Gi(r){return r&&r instanceof mt||Di(r)&&en(r)}function zi(r){return H(r?.lift)}function xe(r){return function(e){if(zi(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function Pe(r,e,t,n,o){return new ji(r,e,t,n,o)}var ji=(function(r){ut(e,r);function e(t,n,o,s,i,a){var f=r.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=n?function(c){try{n(c)}catch(l){t.error(l)}}:r.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:r.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(mt);var on=(function(r){return r&&typeof r.length=="number"&&typeof r!="function"});function sn(r){return H(r?.then)}function an(r){return H(r[Je])}function fn(r){return Symbol.asyncIterator&&H(r?.[Symbol.asyncIterator])}function cn(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ui(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ln=Ui();function hn(r){return H(r?.[ln])}function dn(r){return Ho(this,arguments,function(){var t,n,o,s;return Xt(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,De(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,De(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,De(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 pn(r){return H(r?.getReader)}function Ce(r){if(r instanceof de)return r;if(r!=null){if(an(r))return Wi(r);if(on(r))return Vi(r);if(sn(r))return Qi(r);if(fn(r))return Zo(r);if(hn(r))return Yi(r);if(pn(r))return Ki(r)}throw cn(r)}function Wi(r){return new de(function(e){var t=r[Je]();if(H(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vi(r){return new de(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Qi(r){return new de(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,tn)})}function Yi(r){return new de(function(e){var t,n;try{for(var o=He(r),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&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function Zo(r){return new de(function(e){Xi(r,e).catch(function(t){return e.error(t)})})}function Ki(r){return Zo(dn(r))}function Xi(r,e){var t,n,o,s;return Bo(this,void 0,void 0,function(){var i,a;return Xt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Do(r),f.label=1;case 1:return[4,t.next()];case 2:if(n=f.sent(),!!n.done)return[3,4];if(i=n.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]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function ye(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function un(r,e){return e===void 0&&(e=0),xe(function(t,n){t.subscribe(Pe(n,function(o){return ye(n,r,function(){return n.next(o)},e)},function(){return ye(n,r,function(){return n.complete()},e)},function(o){return ye(n,r,function(){return n.error(o)},e)}))})}function mn(r,e){return e===void 0&&(e=0),xe(function(t,n){n.add(r.schedule(function(){return t.subscribe(n)},e))})}function Jo(r,e){return Ce(r).pipe(mn(e),un(e))}function es(r,e){return Ce(r).pipe(mn(e),un(e))}function ts(r,e){return new de(function(t){var n=0;return e.schedule(function(){n===r.length?t.complete():(t.next(r[n++]),t.closed||this.schedule())})})}function ns(r,e){return new de(function(t){var n;return ye(t,e,function(){n=r[ln](),ye(t,e,function(){var o,s,i;try{o=n.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return H(n?.return)&&n.return()}})}function gn(r,e){if(!r)throw new Error("Iterable cannot be null");return new de(function(t){ye(t,e,function(){var n=r[Symbol.asyncIterator]();ye(t,e,function(){n.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function rs(r,e){return gn(dn(r),e)}function os(r,e){if(r!=null){if(an(r))return Jo(r,e);if(on(r))return ts(r,e);if(sn(r))return es(r,e);if(fn(r))return gn(r,e);if(hn(r))return ns(r,e);if(pn(r))return rs(r,e)}throw cn(r)}function lr(r,e){return e?os(r,e):Ce(r)}function gt(r,e){return xe(function(t,n){var o=0;t.subscribe(Pe(n,function(s){n.next(r.call(e,s,o++))}))})}function ss(r,e,t,n,o,s,i,a){var f=[],c=0,l=0,h=!1,d=function(){h&&!f.length&&!c&&e.complete()},p=function(u){return c<n?m(u):f.push(u)},m=function(u){s&&e.next(u),c++;var w=!1;Ce(t(u,l++)).subscribe(Pe(e,function(b){o?.(b),s?p(b):e.next(b)},function(){w=!0},void 0,function(){if(w)try{c--;for(var b=function(){var S=f.shift();i?ye(e,i,function(){return m(S)}):m(S)};f.length&&c<n;)b();d()}catch(S){e.error(S)}}))};return r.subscribe(Pe(e,p,function(){h=!0,d()})),function(){a?.()}}function et(r,e,t){return t===void 0&&(t=1/0),H(e)?et(function(n,o){return gt(function(s,i){return e(n,s,o,i)})(Ce(r(n,o)))},t):(typeof e=="number"&&(t=e),xe(function(n,o){return ss(n,o,r,t)}))}function is(r,e,t,n,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var h=c++;f=a?r(f,l,h):(a=!0,l),n&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function as(r,e){return xe(is(r,e,arguments.length>=2,!1,!0))}var Zi=function(r,e){return r.push(e),r};function wn(){return xe(function(r,e){as(Zi,[])(r).subscribe(e)})}function fs(r){let e=[],t=0,n;for(let o=0,s=r.length;o<s;o++){let i=r.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)n=t,t=0;else{let a=r[o];a==="M"||a==="="||a==="X"?e.push({own:n===void 0?t:n,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}),n=void 0,t=0}}return e}function pr(r){let e="";for(let{own:t,mate:n,op:o}of fs(r))e+=o==="M"?t===0?`${n}I`:n===0?`${t}D`:`${t}M`:`${o==="I"?n:t}${o}`;return e}var hr=2**28-1;function dr(r,e,t){for(let n=e;n>0;n-=hr)r.push((Math.min(n,hr)<<4|t)>>>0)}function Ji(r,e,t){if(e===t)dr(r,e,0);else{let n=Math.ceil(Math.max(e,t)/hr);for(let o=0;o<n;o++){let s=Math.floor(e*(o+1)/n)-Math.floor(e*o/n),i=Math.floor(t*(o+1)/n)-Math.floor(t*o/n);r.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function ur(r){let e=[];for(let{own:t,mate:n,op:o}of fs(r))o==="M"?Ji(e,t,n):o==="I"?dr(e,n,1):dr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function ea(r){return r>=48&&r<=57}function ta(r){return r!==void 0&&/[A-Za-z]/.test(r)}function cs(r,e){let t=e;for(;t<r.length&&ta(r[t]);)t++;return t}function ls(r,e){let t=e,n=0;for(;t<r.length&&ea(r.charCodeAt(t));)n=n*10+(r.charCodeAt(t)-48),t++;return{value:n,next:t}}function ms(r,e){let t=0;for(;t<r.length;){let n=r[t];if(n===":"){let{value:o,next:s}=ls(r,t+1);e(":",o,o,t+1,s),t=s}else if(n==="="){let o=cs(r,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(n==="*")e("*",1,1,t+1,Math.min(t+3,r.length)),t+=3;else if(n==="+"||n==="-"){let o=cs(r,t+1),s=o-t-1;e(n,n==="-"?s:0,n==="+"?s:0,t+1,o),t=o}else if(n==="~"){let{value:o,next:s}=ls(r,t+3),i=Math.min(s+2,r.length);e("~",o,0,t+1,i),t=i}else t++}}function mr(r,e,t,n){let o=t??Number.NEGATIVE_INFINITY,s=n??Number.POSITIVE_INFINITY,i=0;ms(r,(a,f,c,l,h)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,r[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let d=r.slice(l,h);e(73,i,c,d,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function gs(r,e,t,n){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=r.length;f<c;f++){let l=r[f],h=l>>>4,d=l&15;if(d===0||d===7){if(a)for(let p=0;p<h;p++)(e.charCodeAt(s+p)|32)!==(t.charCodeAt(o+p)|32)&&i.push({start:o+p,type:"mismatch",base:e[s+p],altbase:t[o+p],length:1});s+=h,o+=h}else if(d===1)i.push({start:o,type:"insertion",insertlen:h,insertedBases:e?.slice(s,s+h),length:0}),s+=h;else if(d===2)i.push({start:o,type:"deletion",length:h}),o+=h;else if(d===3)i.push({start:o,type:"skip",length:h}),o+=h;else if(d===8){for(let p=0;p<h;p++)i.push({start:o+p,type:"mismatch",base:e?.[s+p]||"X",qual:n?.[s+p],length:1});s+=h,o+=h}else d===5?i.push({start:o,type:"hardclip",cliplen:h,length:1}):d===4&&(i.push({start:o,type:"softclip",cliplen:h,length:1}),s+=h)}return i}function ws(r,e,t,n,o){if(!e)return[];let s=[],i=e.length,a=n.length,f=o!==void 0,c=t.length,l=!1;for(let S=0;S<c;S++)if(t[S].type==="skip"){l=!0;break}let h=0,d=0,p=0,m=0,u=0,w=0,b=r.length;for(;w<b;){let S=r.charCodeAt(w);if(S>=48&&S<=57){let g=0;for(;w<b;){let x=r.charCodeAt(w);if(x>=48&&x<=57)g=g*10+(x-48),w++;else break}h+=g}else if(S===94)for(w++;w<b&&r.charCodeAt(w)>=65;)w++,h++;else if(S>=65){let g=r[w];if(w++,l&&c>0)for(let N=u;N<c;N++){let k=t[N];k.type==="skip"&&h>=k.start&&(h+=k.length,u=N+1)}let x=p,y=m;for(let N=d;N<i&&y<=h;N++,d=N){let k=e[N],F=k>>>4,R=k&15;R===4||R===1?x+=F:R===2||R===6||R===3?y+=F:R!==5&&(x+=F,y+=F)}p=x,m=y;let E=x-(y-h),A=E<a?n[E]:"X";s.push({start:h,base:A,qual:f?o[E]:void 0,altbase:g,length:1,type:"mismatch"}),h++}else w++}return s}var xs={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function ys(r=""){let e=0,t=[];for(let n=0,o=r.length;n<o;n++){let s=r.charCodeAt(n);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=xs[s];t.push(e<<4|i),e=0}}return t}function xr(r=""){let e=0;for(let s=0,i=r.length;s<i;s++){let a=r.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),n=0,o=0;for(let s=0,i=r.length;s<i;s++){let a=r.charCodeAt(s);a>=48&&a<=57?n=n*10+(a-48):(t[o++]=n<<4|xs[a],n=0)}return t}function vn(r,e,t,n,o){let s=ys(r),i=r?gs(s,t,n,o):[];return e&&t?i.concat(ws(e,s,i,t,o)):i}var oa=397,sa=387,ia=385;function bs(r){return(1<<r&oa)!==0}function Ss(r){return(1<<r&sa)!==0}function vs(r){return(1<<r&ia)!==0}function yr(r,e,t,n,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?n:t,l=[],h=1/0,d=-1/0,p=1/0,m=-1/0,u=(w,b)=>{p=Math.min(p,w,b),m=Math.max(m,w,b)};for(let w=0;w<r.length;w++){let b=r[w],S=b>>>4,g=b&15,x=g===9,y=x||bs(g)?S:0,E=x?r[++w]>>>4:Ss(g)?S:0,A=f+y,N=c+E*a,k=f,F=A;if(F>=s&&k<=i)if(y>0){let R=Math.max(k,s),T=Math.min(F,i);if(T>R)if(h=Math.min(h,R),d=Math.max(d,T),x){let C=E/S,D=T-R,Y=Math.round(D*C),I=Math.round(c+(R-f)*C*a);l.push(D<<4|9,Y<<4|9),u(I,I+Y*a)}else l.push(T-R<<4|g),vs(g)?u(c+(R-f)*a,c+(T-f)*a):u(c,c)}else E>0&&(x?l.push(b,r[w]):l.push(b),h=Math.min(h,f),d=Math.max(d,f),u(c,N));if(f=A,c=N,f>i)break}if(l.length!==0)return{start:h,end:d,mateStart:p,mateEnd:m,cigar:Uint32Array.from(l)}}function aa(r){return r===1||r===2||r===3}function br(r,e,t,n,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?n:t,l,h=!1,d=()=>{l!==void 0&&h&&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,h=!1};for(let p=0;p<r.length;p++){let m=r[p],u=m>>>4,w=m&15,b=w===9,S=b?r[++p]:void 0,g=b||bs(w)?u:0,x=S!==void 0?S>>>4:Ss(w)?u:0,y=c+x*i;aa(w)&&u>=s?d():(g>0||x>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,y),l.tHi=Math.max(l.tHi,c,y),l.ops.push(m),S!==void 0&&l.ops.push(S),h=h||b||vs(w)),f+=g,c=y}return d(),a}function Is(r){let e=r.get("CIGAR");return typeof e=="string"?e:void 0}function Es(r){let e=r.get("coarseCigar");return typeof e=="string"?e:void 0}function Sr(r){let e=Is(r),t=e===void 0?Es(r):void 0;return e!==void 0?xr(e):t!==void 0?ur(t):void 0}var fa=le(ot(),1),ca=le(Cs(),1);var la=le(ot(),1);var ha=le(Ds(),1);var Ms=le(ot(),1),Te=class extends Ms.SimpleFeature{get(e){return e==="mismatches"?vn(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"?pr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let n=this.get("start"),o=t?.start===void 0?void 0:t.start-n,s=t?.end===void 0?void 0:t.end-n,i=this.get("cs");if(i)mr(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of vn(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 da=["CIGAR","cs","coarseCigar","cg","cr"];function pa(r){return typeof r=="object"&&r!==null&&"refName"in r&&"start"in r&&"end"in r&&typeof r.refName=="string"&&typeof r.start=="number"&&typeof r.end=="number"}function ua(r){let e=r.get("mate");return pa(e)?e:void 0}function ma(r,e,t,n){let o=Math.max(r.start,n.start),s=Math.min(r.end,n.end),i=(e.end-e.start)/Math.max(r.end-r.start,1),a=l=>t===-1?e.end-(l-r.start)*i:e.start+(l-r.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 ga(r,e,t,n,o){let s={start:r.get("start"),end:r.get("end")},i=r.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&n===void 0&&!o?void 0:Sr(r);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ma(s,e,i,t);return c===void 0?[]:[c]}else return(n===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:br(f,s.start,e.start,e.end,i,n)).flatMap(l=>{let h=yr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return h===void 0?[]:[h]})}function wa(r,e,t,n,o,s){let i=`:${n.start}-${n.end}${o}`,a=r.toJSON(),f={...a,uniqueId:`${r.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 da)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Te(f)}function Rs(r,e,t,n=!1){let o=ua(r);if(o===void 0)return[r];{let s=ga(r,o,e,t,n);return s.map((i,a)=>wa(r,o,i,e,s.length>1?`/${a}`:"",n))}}var In=class extends Ps.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,n={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=n,f=o&&this.recordsAreAlignments,c=(0,ks.createStatusFanOut)(a.statusCallback);return lr(t).pipe(et((l,h)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(et(d=>f?Rs(d,d.get("assemblyName")===l.assemblyName?l:{start:d.get("start"),end:d.get("end")},s,i):[d]),wn(),gt(d=>({index:h,features:d})))),wn(),et(l=>l.sort((h,d)=>h.index-d.index).flatMap(h=>h.features)))}};var An=class extends Error{constructor(t){super(t===void 0?"no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation":`the haplotype index beside the graph database could not be checked (${t}), so the walks cannot be named; if it is there, reload to try again, or set haplotypeIndexLocation`);this.name="NoHaplotypeIndexError"}},Er=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}};function xa(r,e){if(e===void 0)throw new Er(r);return{queryAssemblyName:r,targetAssemblyName:e}}var Ar=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function _s(r,e){let t=me(e);return r[t]??r[e.sample]??t}function ya(r,e){return`${me(r)}#${r.contig}@${e.start.node}.${e.start.offset}`}function ba({alignment:r,assemblyName:e,refName:t,lane:n}){let{refStart:o,refEnd:s,strand:i,cigar:a}=r;if(!(!r.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=r,h=ya(f,r),d={uniqueId:h,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:h,mate:{refName:f.contig,start:c,end:l,assemblyName:n}};return new Te(d)}}function Sa({pair:r,lane:e,mateLane:t}){let n=`${me(r.target)}#${r.target.contig}:${r.targetStart}-${r.targetEnd}|${me(r.query)}#${r.query.contig}:${r.queryStart}-${r.queryEnd}`;return new Te({uniqueId:n,assemblyName:e,refName:r.target.contig,start:r.targetStart,end:r.targetEnd,type:"match",strand:r.strand==="-"?-1:1,CIGAR:r.cigar,syntenyId:n,identity:r.matches/Math.max(r.columns,1),numMatches:r.matches,blockLen:r.columns,mate:{refName:r.query.contig,start:r.queryStart,end:r.queryEnd,assemblyName:t}})}var va=12e4;function Ia(r,e){let t=new Map;for(let o of r)for(let{name:s,start:i,end:a}of o.walkSpans()){let f=me(s);if(e.has(f)){let c=`${f}#${s.contig}`;t.set(c,[...t.get(c)??[],[i,a]])}}let n=0;for(let o of t.values()){o.sort((s,i)=>s[0]-i[0]);for(let s=1;s<o.length;s++){let i=o[s][0]-o[s-1][1];i>0&&i<=va&&(n=Math.max(n,i))}}return n}function Os(r,e){return r instanceof kn&&(r.message=`Zoom in to about ${(0,xt.getBpDisplayStr)(r.fitsBp)} to see ${e}`),r}var vr=r=>!("uri"in r)||r.uri!=="",Cr=class extends In{constructor(){super(...arguments);this.graph=(0,Ir.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),o=vr(n)?{location:n}:await Fo(t,this.pluginManager),s=o.location,i=await pt.open({source:(0,En.openLocation)(t,this.pluginManager),haplotypeIndex:s?(0,En.openLocation)(s,this.pluginManager):void 0}),a=this.getConf("assemblyNames")[0];if(a===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let f=await On(i),c=vt({configured:this.getConf("referenceSample"),anchorPrefix:ze(this,a),referenceSamples:f});return{db:i,anchor:a,referenceSample:c,referenceSamples:f,unreadableIndex:o.unreadable}}});this.gaf=(0,Ir.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return vr(t)?new Kt((0,En.openLocation)(t,this.pluginManager),vr(n)?zr(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:o,referenceSample:s}=await this.graph(n);return Nn(o,s,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await n.paths()){let a=me(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:n,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Pn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:_s(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:n,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:ze(this,i),f=(await n.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:St(me(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,n){let o=t===void 0||t.length===0?void 0:t.map(s=>ze(this,s));return o===void 0&&n===void 0?void 0:s=>_n(s,o)&&(n===void 0||St(me(s),n))}async getSubgraph(t,n={}){let{db:o,anchor:s,unreadableIndex:i}=await this.graph(),{assemblyName:a,refName:f,start:c,end:l}=t;if(a!==s)throw new Ar(a,s);let h=await this.referenceQuery(f,{}),d=this.keepPredicate(n.haplotypes);if(d!==void 0&&!o.hasHaplotypeIndex)throw new An(i);return Tn(o,h,c,l,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:d}).catch(p=>{throw Os(p,"the graph")})}async getReads(t,n={}){let o=await this.gaf(n);return o?o.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let o=ze(this,t);return(await this.getHaplotypes(n)).filter(s=>St(s.prefix,o))}async anchorFeatures(t,n){let{db:o}=await this.graph(n),{assemblyName:s,refName:i,start:a,end:f}=t,c=ze(this,n.targetAssemblyName),l=Pn(this),h=this.keepPredicate(n.haplotypes,c),d=await this.referenceQuery(i,n),p=this.getConf("nodeLimit");return(d?await(0,xt.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,n.statusCallback,()=>o.getAlignments({path:d,start:a,end:f,context:this.getConf("context"),haplotypes:"all",limit:p,signal:n.signal,keep:h}).catch(u=>{throw Os(It(u,p,f-a)??u,"lanes")})):[]).flatMap(u=>{let w=u.resolved?ba({alignment:u,assemblyName:s,refName:i,lane:_s(l,u.name)}):void 0;return w===void 0?[]:[w]})}async pairFeatures(t,n,o){let{db:s}=await this.graph(o),{refName:i,start:a,end:f}=t,l=(await Promise.all(n.map(async g=>({pair:g,featureSide:await this.laneHaplotypes(g.queryAssemblyName,o),mateSide:await this.laneHaplotypes(g.targetAssemblyName,o)})))).filter(({featureSide:g,mateSide:x})=>g.length>0&&x.length>0),h=new Set(l.flatMap(({featureSide:g,mateSide:x})=>[...g,...x].map(me))),d=await this.referenceQuery(i,o),p=this.getConf("nodeLimit"),m=this.getConf("context"),[u]=n,w=(g,x)=>s.getSubgraphs({path:g,start:a,end:f,context:x,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:p,signal:o.signal,keep:y=>h.has(me(y))}),b=async g=>{let x=await w(g,m).catch(A=>{throw It(A,p,f-a)??A}),y=Ia(x,h),E=Math.ceil(y/2)+2e3;return y>0&&E>m?w(g,E).catch(A=>{if(A instanceof fe)return x;throw A}):x};return(d&&u&&l.length>0?await(0,xt.updateStatus)(n.length===1?`Reading ${u.queryAssemblyName} against ${u.targetAssemblyName}`:`Reading ${n.length} lane pairs`,o.statusCallback,()=>b(d)):[]).flatMap(g=>l.flatMap(({pair:x,featureSide:y,mateSide:E})=>y.flatMap(A=>E.flatMap(N=>g.pairAlignments({target:A,query:N,bases:!1}).map(k=>Sa({pair:k,lane:x.queryAssemblyName,mateLane:x.targetAssemblyName}))))))}getFeatures(t,n={}){return(0,Ns.ObservableCreate)(async o=>{let{db:s,anchor:i,unreadableIndex:a}=await this.graph(n);if(!s.hasHaplotypeIndex)throw new An(a);if(t.assemblyName===i){let f=n.lanePairs?.length?await this.pairFeatures(t,n.lanePairs,n):n.queryAssemblyName===void 0?await this.anchorFeatures(t,n):await this.pairFeatures(t,[xa(n.queryAssemblyName,n.targetAssemblyName)],n);for(let c of f)o.next(c)}o.complete()},n.signal)}};export{Ar as HaplotypeWindowError,An as NoHaplotypeIndexError,Bs as NoReferenceSampleError,kn as NodeLimitError,Er as PairTargetError,Cr as default,ba as fragmentFeature,me as haplotypePrefix,_s as laneAssemblyName,It as nodeLimitError,Sa as pairFeature,vt as resolveReferenceSample,Ia as widestWalkGap};
8
- //# sourceMappingURL=GbzBaseSyntenyAdapter-KVJKGGQ4.js.map
7
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function or(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Zt=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,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(u){e={error:u}}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(u){s=u instanceof Xt?u.errors:[u]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var d=He(h),p=d.next();!p.done;p=d.next()){var m=p.value;try{jo(m)}catch(u){s=s??[],u instanceof Xt?s=Xe(Xe([],Ke(s)),Ke(u.errors)):s.push(u)}}}catch(u){n={error:u}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(n)throw n.error}}}if(s)throw new Xt(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)jo(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&or(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&or(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var tc=Zt.EMPTY;function Jt(r){return r instanceof Zt||r&&"closed"in r&&H(r.remove)&&H(r.add)&&H(r.unsubscribe)}function jo(r){H(r)?r():r.unsubscribe()}var ve={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ze={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];var o=Ze.delegate;return o?.setTimeout?o.setTimeout.apply(o,Xe([r,e],Ke(t))):setTimeout.apply(void 0,Xe([r,e],Ke(t)))},clearTimeout:function(r){var e=Ze.delegate;return(e?.clearTimeout||clearTimeout)(r)},delegate:void 0};function en(r){Ze.setTimeout(function(){var e=ve.onUnhandledError;if(e)e(r);else throw r})}function sr(){}var Uo=(function(){return ir("C",void 0,void 0)})();function Wo(r){return ir("E",void 0,r)}function Vo(r){return ir("N",r,void 0)}function ir(r,e,t){return{kind:r,value:e,error:t}}var Ge=null;function Qo(r){if(ve.useDeprecatedSynchronousErrorHandling){var e=!Ge;if(e&&(Ge={errorThrown:!1,error:null}),r(),e){var t=Ge,n=t.errorThrown,o=t.error;if(Ge=null,n)throw o}}else r()}function Yo(r){ve.useDeprecatedSynchronousErrorHandling&&Ge&&(Ge.errorThrown=!0,Ge.error=r)}var mt=(function(r){ut(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Jt(t)&&t.add(n)):n.destination=Hi,n}return e.create=function(t,n,o){return new nn(t,n,o)},e.prototype.next=function(t){this.isStopped?fr(Vo(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?fr(Wo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?fr(Uo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.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})(Zt);var $i=Function.prototype.bind;function ar(r,e){return $i.call(r,e)}var qi=(function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){tn(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){tn(n)}else tn(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){tn(t)}},r})(),nn=(function(r){ut(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(H(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var a;s&&ve.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&ar(t.next,a),error:t.error&&ar(t.error,a),complete:t.complete&&ar(t.complete,a)}):i=t}return s.destination=new qi(i),s}return e})(mt);function tn(r){ve.useDeprecatedSynchronousErrorHandling?Yo(r):en(r)}function Bi(r){throw r}function fr(r,e){var t=ve.onStoppedNotification;t&&Ze.setTimeout(function(){return t(r,e)})}var Hi={closed:!0,next:sr,error:Bi,complete:sr};var Je=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Ko(r){return r}function Xo(r){return r.length===0?Ko:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var de=(function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=Gi(e)?e:new nn(e,t,n);return Qo(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},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Zo(t),new t(function(o,s){var i=new nn({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Je]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Xo(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Zo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r})();function Zo(r){var e;return(e=r??ve.Promise)!==null&&e!==void 0?e:Promise}function Di(r){return r&&H(r.next)&&H(r.error)&&H(r.complete)}function Gi(r){return r&&r instanceof mt||Di(r)&&Jt(r)}function zi(r){return H(r?.lift)}function we(r){return function(e){if(zi(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function Pe(r,e,t,n,o){return new ji(r,e,t,n,o)}var ji=(function(r){ut(e,r);function e(t,n,o,s,i,a){var f=r.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=n?function(c){try{n(c)}catch(l){t.error(l)}}:r.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:r.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(mt);var rn=(function(r){return r&&typeof r.length=="number"&&typeof r!="function"});function on(r){return H(r?.then)}function sn(r){return H(r[Je])}function an(r){return Symbol.asyncIterator&&H(r?.[Symbol.asyncIterator])}function fn(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ui(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var cn=Ui();function ln(r){return H(r?.[cn])}function hn(r){return Do(this,arguments,function(){var t,n,o,s;return Kt(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,De(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,De(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,De(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 dn(r){return H(r?.getReader)}function Ce(r){if(r instanceof de)return r;if(r!=null){if(sn(r))return Wi(r);if(rn(r))return Vi(r);if(on(r))return Qi(r);if(an(r))return Jo(r);if(ln(r))return Yi(r);if(dn(r))return Ki(r)}throw fn(r)}function Wi(r){return new de(function(e){var t=r[Je]();if(H(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vi(r){return new de(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Qi(r){return new de(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,en)})}function Yi(r){return new de(function(e){var t,n;try{for(var o=He(r),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&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function Jo(r){return new de(function(e){Xi(r,e).catch(function(t){return e.error(t)})})}function Ki(r){return Jo(hn(r))}function Xi(r,e){var t,n,o,s;return Ho(this,void 0,void 0,function(){var i,a;return Kt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Go(r),f.label=1;case 1:return[4,t.next()];case 2:if(n=f.sent(),!!n.done)return[3,4];if(i=n.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]),n&&!n.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 xe(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function pn(r,e){return e===void 0&&(e=0),we(function(t,n){t.subscribe(Pe(n,function(o){return xe(n,r,function(){return n.next(o)},e)},function(){return xe(n,r,function(){return n.complete()},e)},function(o){return xe(n,r,function(){return n.error(o)},e)}))})}function un(r,e){return e===void 0&&(e=0),we(function(t,n){n.add(r.schedule(function(){return t.subscribe(n)},e))})}function es(r,e){return Ce(r).pipe(un(e),pn(e))}function ts(r,e){return Ce(r).pipe(un(e),pn(e))}function ns(r,e){return new de(function(t){var n=0;return e.schedule(function(){n===r.length?t.complete():(t.next(r[n++]),t.closed||this.schedule())})})}function rs(r,e){return new de(function(t){var n;return xe(t,e,function(){n=r[cn](),xe(t,e,function(){var o,s,i;try{o=n.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return H(n?.return)&&n.return()}})}function mn(r,e){if(!r)throw new Error("Iterable cannot be null");return new de(function(t){xe(t,e,function(){var n=r[Symbol.asyncIterator]();xe(t,e,function(){n.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function os(r,e){return mn(hn(r),e)}function ss(r,e){if(r!=null){if(sn(r))return es(r,e);if(rn(r))return ns(r,e);if(on(r))return ts(r,e);if(an(r))return mn(r,e);if(ln(r))return rs(r,e);if(dn(r))return os(r,e)}throw fn(r)}function cr(r,e){return e?ss(r,e):Ce(r)}function gt(r,e){return we(function(t,n){var o=0;t.subscribe(Pe(n,function(s){n.next(r.call(e,s,o++))}))})}function is(r,e,t,n,o,s,i,a){var f=[],c=0,l=0,h=!1,d=function(){h&&!f.length&&!c&&e.complete()},p=function(u){return c<n?m(u):f.push(u)},m=function(u){s&&e.next(u),c++;var w=!1;Ce(t(u,l++)).subscribe(Pe(e,function(b){o?.(b),s?p(b):e.next(b)},function(){w=!0},void 0,function(){if(w)try{c--;for(var b=function(){var S=f.shift();i?xe(e,i,function(){return m(S)}):m(S)};f.length&&c<n;)b();d()}catch(S){e.error(S)}}))};return r.subscribe(Pe(e,p,function(){h=!0,d()})),function(){a?.()}}function et(r,e,t){return t===void 0&&(t=1/0),H(e)?et(function(n,o){return gt(function(s,i){return e(n,s,o,i)})(Ce(r(n,o)))},t):(typeof e=="number"&&(t=e),we(function(n,o){return is(n,o,r,t)}))}function as(r,e,t,n,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var h=c++;f=a?r(f,l,h):(a=!0,l),n&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function fs(r,e){return we(as(r,e,arguments.length>=2,!1,!0))}var Zi=function(r,e){return r.push(e),r};function gn(){return we(function(r,e){fs(Zi,[])(r).subscribe(e)})}function cs(r){let e=[],t=0,n;for(let o=0,s=r.length;o<s;o++){let i=r.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)n=t,t=0;else{let a=r[o];a==="M"||a==="="||a==="X"?e.push({own:n===void 0?t:n,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}),n=void 0,t=0}}return e}function dr(r){let e="";for(let{own:t,mate:n,op:o}of cs(r))e+=o==="M"?t===0?`${n}I`:n===0?`${t}D`:`${t}M`:`${o==="I"?n:t}${o}`;return e}var lr=2**28-1;function hr(r,e,t){for(let n=e;n>0;n-=lr)r.push((Math.min(n,lr)<<4|t)>>>0)}function Ji(r,e,t){if(e===t)hr(r,e,0);else{let n=Math.ceil(Math.max(e,t)/lr);for(let o=0;o<n;o++){let s=Math.floor(e*(o+1)/n)-Math.floor(e*o/n),i=Math.floor(t*(o+1)/n)-Math.floor(t*o/n);r.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function pr(r){let e=[];for(let{own:t,mate:n,op:o}of cs(r))o==="M"?Ji(e,t,n):o==="I"?hr(e,n,1):hr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function ea(r){return r>=48&&r<=57}function ta(r){return r!==void 0&&/[A-Za-z]/.test(r)}function ls(r,e){let t=e;for(;t<r.length&&ta(r[t]);)t++;return t}function hs(r,e){let t=e,n=0;for(;t<r.length&&ea(r.charCodeAt(t));)n=n*10+(r.charCodeAt(t)-48),t++;return{value:n,next:t}}function gs(r,e){let t=0;for(;t<r.length;){let n=r[t];if(n===":"){let{value:o,next:s}=hs(r,t+1);e(":",o,o,t+1,s),t=s}else if(n==="="){let o=ls(r,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(n==="*")e("*",1,1,t+1,Math.min(t+3,r.length)),t+=3;else if(n==="+"||n==="-"){let o=ls(r,t+1),s=o-t-1;e(n,n==="-"?s:0,n==="+"?s:0,t+1,o),t=o}else if(n==="~"){let{value:o,next:s}=hs(r,t+3),i=Math.min(s+2,r.length);e("~",o,0,t+1,i),t=i}else t++}}function ur(r,e,t,n){let o=t??Number.NEGATIVE_INFINITY,s=n??Number.POSITIVE_INFINITY,i=0;gs(r,(a,f,c,l,h)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,r[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let d=r.slice(l,h);e(73,i,c,d,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function ws(r,e,t,n){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=r.length;f<c;f++){let l=r[f],h=l>>>4,d=l&15;if(d===0||d===7){if(a)for(let p=0;p<h;p++)(e.charCodeAt(s+p)|32)!==(t.charCodeAt(o+p)|32)&&i.push({start:o+p,type:"mismatch",base:e[s+p],altbase:t[o+p],length:1});s+=h,o+=h}else if(d===1)i.push({start:o,type:"insertion",insertlen:h,insertedBases:e?.slice(s,s+h),length:0}),s+=h;else if(d===2)i.push({start:o,type:"deletion",length:h}),o+=h;else if(d===3)i.push({start:o,type:"skip",length:h}),o+=h;else if(d===8){for(let p=0;p<h;p++)i.push({start:o+p,type:"mismatch",base:e?.[s+p]||"X",qual:n?.[s+p],length:1});s+=h,o+=h}else d===5?i.push({start:o,type:"hardclip",cliplen:h,length:1}):d===4&&(i.push({start:o,type:"softclip",cliplen:h,length:1}),s+=h)}return i}function xs(r,e,t,n,o){if(!e)return[];let s=[],i=e.length,a=n.length,f=o!==void 0,c=t.length,l=!1;for(let S=0;S<c;S++)if(t[S].type==="skip"){l=!0;break}let h=0,d=0,p=0,m=0,u=0,w=0,b=r.length;for(;w<b;){let S=r.charCodeAt(w);if(S>=48&&S<=57){let g=0;for(;w<b;){let x=r.charCodeAt(w);if(x>=48&&x<=57)g=g*10+(x-48),w++;else break}h+=g}else if(S===94)for(w++;w<b&&r.charCodeAt(w)>=65;)w++,h++;else if(S>=65){let g=r[w];if(w++,l&&c>0)for(let N=u;N<c;N++){let k=t[N];k.type==="skip"&&h>=k.start&&(h+=k.length,u=N+1)}let x=p,y=m;for(let N=d;N<i&&y<=h;N++,d=N){let k=e[N],F=k>>>4,R=k&15;R===4||R===1?x+=F:R===2||R===6||R===3?y+=F:R!==5&&(x+=F,y+=F)}p=x,m=y;let E=x-(y-h),A=E<a?n[E]:"X";s.push({start:h,base:A,qual:f?o[E]:void 0,altbase:g,length:1,type:"mismatch"}),h++}else w++}return s}var ys={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function bs(r=""){let e=0,t=[];for(let n=0,o=r.length;n<o;n++){let s=r.charCodeAt(n);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=ys[s];t.push(e<<4|i),e=0}}return t}function wr(r=""){let e=0;for(let s=0,i=r.length;s<i;s++){let a=r.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),n=0,o=0;for(let s=0,i=r.length;s<i;s++){let a=r.charCodeAt(s);a>=48&&a<=57?n=n*10+(a-48):(t[o++]=n<<4|ys[a],n=0)}return t}function Sn(r,e,t,n,o){let s=bs(r),i=r?ws(s,t,n,o):[];return e&&t?i.concat(xs(e,s,i,t,o)):i}var oa=397,sa=387,ia=385;function Ss(r){return(1<<r&oa)!==0}function vs(r){return(1<<r&sa)!==0}function Is(r){return(1<<r&ia)!==0}function xr(r,e,t,n,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?n:t,l=[],h=1/0,d=-1/0,p=1/0,m=-1/0,u=(w,b)=>{p=Math.min(p,w,b),m=Math.max(m,w,b)};for(let w=0;w<r.length;w++){let b=r[w],S=b>>>4,g=b&15,x=g===9,y=x||Ss(g)?S:0,E=x?r[++w]>>>4:vs(g)?S:0,A=f+y,N=c+E*a,k=f,F=A;if(F>=s&&k<=i)if(y>0){let R=Math.max(k,s),T=Math.min(F,i);if(T>R)if(h=Math.min(h,R),d=Math.max(d,T),x){let C=E/S,D=T-R,Y=Math.round(D*C),I=Math.round(c+(R-f)*C*a);l.push(D<<4|9,Y<<4|9),u(I,I+Y*a)}else l.push(T-R<<4|g),Is(g)?u(c+(R-f)*a,c+(T-f)*a):u(c,c)}else E>0&&(x?l.push(b,r[w]):l.push(b),h=Math.min(h,f),d=Math.max(d,f),u(c,N));if(f=A,c=N,f>i)break}if(l.length!==0)return{start:h,end:d,mateStart:p,mateEnd:m,cigar:Uint32Array.from(l)}}function aa(r){return r===1||r===2||r===3}function yr(r,e,t,n,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?n:t,l,h=!1,d=()=>{l!==void 0&&h&&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,h=!1};for(let p=0;p<r.length;p++){let m=r[p],u=m>>>4,w=m&15,b=w===9,S=b?r[++p]:void 0,g=b||Ss(w)?u:0,x=S!==void 0?S>>>4:vs(w)?u:0,y=c+x*i;aa(w)&&u>=s?d():(g>0||x>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,y),l.tHi=Math.max(l.tHi,c,y),l.ops.push(m),S!==void 0&&l.ops.push(S),h=h||b||Is(w)),f+=g,c=y}return d(),a}function Es(r){let e=r.get("CIGAR");return typeof e=="string"?e:void 0}function As(r){let e=r.get("coarseCigar");return typeof e=="string"?e:void 0}function br(r){let e=Es(r),t=e===void 0?As(r):void 0;return e!==void 0?wr(e):t!==void 0?pr(t):void 0}var fa=le(ot(),1),ca=le(Ms(),1);var la=le(ot(),1);var ha=le(Ds(),1);var Rs=le(ot(),1),Te=class extends Rs.SimpleFeature{get(e){return e==="mismatches"?Sn(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"?dr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let n=this.get("start"),o=t?.start===void 0?void 0:t.start-n,s=t?.end===void 0?void 0:t.end-n,i=this.get("cs");if(i)ur(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of Sn(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 da=["CIGAR","cs","coarseCigar","cg","cr"];function pa(r){return typeof r=="object"&&r!==null&&"refName"in r&&"start"in r&&"end"in r&&typeof r.refName=="string"&&typeof r.start=="number"&&typeof r.end=="number"}function ua(r){let e=r.get("mate");return pa(e)?e:void 0}function ma(r,e,t,n){let o=Math.max(r.start,n.start),s=Math.min(r.end,n.end),i=(e.end-e.start)/Math.max(r.end-r.start,1),a=l=>t===-1?e.end-(l-r.start)*i:e.start+(l-r.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 ga(r,e,t,n,o){let s={start:r.get("start"),end:r.get("end")},i=r.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&n===void 0&&!o?void 0:br(r);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ma(s,e,i,t);return c===void 0?[]:[c]}else return(n===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:yr(f,s.start,e.start,e.end,i,n)).flatMap(l=>{let h=xr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return h===void 0?[]:[h]})}function wa(r,e,t,n,o,s){let i=`:${n.start}-${n.end}${o}`,a=r.toJSON(),f={...a,uniqueId:`${r.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 da)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Te(f)}function Ps(r,e,t,n=!1){let o=ua(r);if(o===void 0)return[r];{let s=ga(r,o,e,t,n);return s.map((i,a)=>wa(r,o,i,e,s.length>1?`/${a}`:"",n))}}var vn=class extends ks.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,n={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=n,f=o&&this.recordsAreAlignments,c=(0,_s.createStatusFanOut)(a.statusCallback);return cr(t).pipe(et((l,h)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(et(d=>f?Ps(d,d.get("assemblyName")===l.assemblyName?l:{start:d.get("start"),end:d.get("end")},s,i):[d]),gn(),gt(d=>({index:h,features:d})))),gn(),et(l=>l.sort((h,d)=>h.index-d.index).flatMap(h=>h.features)))}};var En=class extends Error{constructor(t){super(t===void 0?"no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation":`the haplotype index beside the graph database could not be checked (${t}), so the walks cannot be named; if it is there, reload to try again, or set haplotypeIndexLocation`);this.name="NoHaplotypeIndexError"}},Er=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}};function xa(r,e){if(e===void 0)throw new Er(r);return{queryAssemblyName:r,targetAssemblyName:e}}var Ar=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Os(r,e){let t=be(e);return r[t]??r[e.sample]??t}function ya(r,e){return`${be(r)}#${r.contig}@${e.start.node}.${e.start.offset}`}function ba({alignment:r,assemblyName:e,refName:t,lane:n}){let{refStart:o,refEnd:s,strand:i,cigar:a}=r;if(!(!r.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=r,h=ya(f,r),d={uniqueId:h,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:h,mate:{refName:f.contig,start:c,end:l,assemblyName:n}};return new Te(d)}}function Sa({pair:r,lane:e,mateLane:t}){let n=`${be(r.target)}#${r.target.contig}:${r.targetStart}-${r.targetEnd}|${be(r.query)}#${r.query.contig}:${r.queryStart}-${r.queryEnd}`;return new Te({uniqueId:n,assemblyName:e,refName:r.target.contig,start:r.targetStart,end:r.targetEnd,type:"match",strand:r.strand==="-"?-1:1,CIGAR:r.cigar,syntenyId:n,identity:r.matches/Math.max(r.columns,1),numMatches:r.matches,blockLen:r.columns,mate:{refName:r.query.contig,start:r.queryStart,end:r.queryEnd,assemblyName:t}})}var va=12e4;function Ia(r,e){let t=new Map;for(let o of r)for(let{name:s,start:i,end:a}of o.walkSpans()){let f=be(s);if(e.has(f)){let c=`${f}#${s.contig}`;t.set(c,[...t.get(c)??[],[i,a]])}}let n=0;for(let o of t.values()){o.sort((s,i)=>s[0]-i[0]);for(let s=1;s<o.length;s++){let i=o[s][0]-o[s-1][1];i>0&&i<=va&&(n=Math.max(n,i))}}return n}function Sr(r,e){return r instanceof qr&&(r.message=`Zoom in to about ${(0,xt.getBpDisplayStr)(r.fitsBp)} to see ${e}`),r}var vr=r=>!("uri"in r)||r.uri!=="",Cr=class extends vn{constructor(){super(...arguments);this.graph=(0,Ir.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),o=vr(n)?{location:n}:await $o(t,this.pluginManager),s=o.location,i=await pt.open({source:(0,In.openLocation)(t,this.pluginManager),haplotypeIndex:s?(0,In.openLocation)(s,this.pluginManager):void 0}),a=this.getConf("assemblyNames")[0];if(a===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let f=await kn(i),c=vt({configured:this.getConf("referenceSample"),anchorPrefix:ze(this,a),referenceSamples:f});return{db:i,anchor:a,referenceSample:c,referenceSamples:f,unreadableIndex:o.unreadable}}});this.gaf=(0,Ir.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return vr(t)?new Yt((0,In.openLocation)(t,this.pluginManager),vr(n)?jr(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:o,referenceSample:s}=await this.graph(n);return _n(o,s,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await n.paths()){let a=be(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:n,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:Os(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:n,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:ze(this,i),f=(await n.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:St(be(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,n){let o=t===void 0||t.length===0?void 0:t.map(s=>ze(this,s));return o===void 0&&n===void 0?void 0:s=>Pn(s,o)&&(n===void 0||St(be(s),n))}async getSubgraph(t,n={}){let{signal:o}=n,{db:s,anchor:i,referenceSample:a,unreadableIndex:f}=await this.graph({signal:o}),{assemblyName:c,refName:l,start:h,end:d}=t;if(c!==i)throw new Ar(c,i);let p=await this.referenceQuery(l,{signal:o});if(!p)throw new Error(`${a} has no indexed path ${l} in this graph`);let m=this.keepPredicate(n.haplotypes);if(m!==void 0&&!s.hasHaplotypeIndex)throw new En(f);return Nn(s,p,h,d,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:m}).catch(u=>{throw Sr(u,"the graph")})}async getReads(t,n={}){let o=await this.gaf(n);return o?o.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let o=ze(this,t);return(await this.getHaplotypes(n)).filter(s=>St(s.prefix,o))}async anchorFeatures(t,n){let{db:o}=await this.graph(n),{assemblyName:s,refName:i,start:a,end:f}=t,c=ze(this,n.targetAssemblyName),l=Rn(this),h=this.keepPredicate(n.haplotypes,c),d=await this.referenceQuery(i,n),p=this.getConf("nodeLimit");return(d?await(0,xt.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,n.statusCallback,()=>o.getAlignments({path:d,start:a,end:f,context:this.getConf("context"),haplotypes:"all",limit:p,signal:n.signal,keep:h}).catch(u=>{throw Sr(On(u,p,f-a)??u,"lanes")})):[]).flatMap(u=>{let w=u.resolved?ba({alignment:u,assemblyName:s,refName:i,lane:Os(l,u.name)}):void 0;return w===void 0?[]:[w]})}async pairFeatures(t,n,o){let{db:s}=await this.graph(o),{refName:i,start:a,end:f}=t,l=(await Promise.all(n.map(async g=>({pair:g,featureSide:await this.laneHaplotypes(g.queryAssemblyName,o),mateSide:await this.laneHaplotypes(g.targetAssemblyName,o)})))).filter(({featureSide:g,mateSide:x})=>g.length>0&&x.length>0),h=new Set(l.flatMap(({featureSide:g,mateSide:x})=>[...g,...x].map(be))),d=await this.referenceQuery(i,o),p=this.getConf("nodeLimit"),m=this.getConf("context"),[u]=n,w=(g,x)=>s.getSubgraphs({path:g,start:a,end:f,context:x,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:p,signal:o.signal,keep:y=>h.has(be(y))}),b=async g=>{let x=await w(g,m).catch(A=>{throw Sr(On(A,p,f-a)??A,"lanes")}),y=Ia(x,h),E=Math.ceil(y/2)+2e3;return y>0&&E>m?w(g,E).catch(A=>{if(A instanceof fe)return x;throw A}):x};return(d&&u&&l.length>0?await(0,xt.updateStatus)(n.length===1?`Reading ${u.queryAssemblyName} against ${u.targetAssemblyName}`:`Reading ${n.length} lane pairs`,o.statusCallback,()=>b(d)):[]).flatMap(g=>l.flatMap(({pair:x,featureSide:y,mateSide:E})=>y.flatMap(A=>E.flatMap(N=>g.pairAlignments({target:A,query:N,bases:!1}).map(k=>Sa({pair:k,lane:x.queryAssemblyName,mateLane:x.targetAssemblyName}))))))}getFeatures(t,n={}){return(0,Ns.ObservableCreate)(async o=>{let{db:s,anchor:i,unreadableIndex:a}=await this.graph(n);if(!s.hasHaplotypeIndex)throw new En(a);if(t.assemblyName===i){let f=n.lanePairs?.length?await this.pairFeatures(t,n.lanePairs,n):n.queryAssemblyName===void 0?await this.anchorFeatures(t,n):await this.pairFeatures(t,[xa(n.queryAssemblyName,n.targetAssemblyName)],n);for(let c of f)o.next(c)}o.complete()},n.signal)}};export{Ar as HaplotypeWindowError,En as NoHaplotypeIndexError,Bs as NoReferenceSampleError,Er as PairTargetError,Cr as default,ba as fragmentFeature,Os as laneAssemblyName,Sa as pairFeature,vt as resolveReferenceSample,Ia as widestWalkGap};
8
+ //# sourceMappingURL=GbzBaseSyntenyAdapter-NULWNOBT.js.map