jbrowse-plugin-graphgenomeviewer 8.3.3 → 8.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/chunks/GbzBaseSyntenyAdapter-RRLBONL5.js +2 -0
- package/dist/chunks/GbzBaseSyntenyAdapter-RRLBONL5.js.map +7 -0
- package/dist/chunks/{GraphGenomeView-TC3UNRFN.js → GraphGenomeView-JJNU2432.js} +2 -2
- package/dist/chunks/{GraphTrackSettingsDialog-JZBOLXZW.js → GraphTrackSettingsDialog-7NGUPDUJ.js} +2 -2
- package/dist/chunks/{HighlightColorDialog-4VGVC7SN.js → HighlightColorDialog-KFXSZXTC.js} +2 -2
- package/dist/chunks/{LinearGraphDisplay-6IO5ADGB.js → LinearGraphDisplay-K3AT3S7J.js} +2 -2
- package/dist/chunks/{MinigraphBubbleAdapter-X4VJ3AEX.js → MinigraphBubbleAdapter-P66QLENP.js} +2 -2
- package/dist/chunks/{RgfaTabixAdapter-535GN32R.js → RgfaTabixAdapter-CQJROUIP.js} +2 -2
- package/dist/chunks/{WalkFormsAdapter-DAGNKDXV.js → WalkFormsAdapter-YSYANJD5.js} +2 -2
- package/dist/chunks/WalkTabixSyntenyAdapter-4I32E62Y.js +2 -0
- package/dist/chunks/WalkTabixSyntenyAdapter-4I32E62Y.js.map +7 -0
- package/dist/chunks/{chunk-QCEM5AXZ.js → chunk-3HS6N7WB.js} +2 -2
- package/dist/chunks/{chunk-QCEM5AXZ.js.map → chunk-3HS6N7WB.js.map} +1 -1
- package/dist/chunks/{chunk-MBGXXS3Z.js → chunk-3S33TTXF.js} +2 -2
- package/dist/chunks/{chunk-MBGXXS3Z.js.map → chunk-3S33TTXF.js.map} +1 -1
- package/dist/chunks/{chunk-37XRCKBJ.js → chunk-4B3GQTHX.js} +2 -2
- package/dist/chunks/{chunk-37XRCKBJ.js.map → chunk-4B3GQTHX.js.map} +1 -1
- package/dist/chunks/chunk-C5YAQNOO.js +4 -0
- package/dist/chunks/chunk-C5YAQNOO.js.map +7 -0
- package/dist/chunks/chunk-CNFMSSE2.js +3 -0
- package/dist/chunks/chunk-CNFMSSE2.js.map +7 -0
- package/dist/chunks/chunk-DAF7EWRF.js +3 -0
- package/dist/chunks/{chunk-UMCYJHEB.js.map → chunk-DAF7EWRF.js.map} +4 -4
- package/dist/chunks/chunk-DKQFTMWL.js +2 -0
- package/dist/chunks/chunk-DKQFTMWL.js.map +7 -0
- package/dist/chunks/{chunk-YUA46UN2.js → chunk-EVKN4Y3R.js} +2 -2
- package/dist/chunks/{chunk-YUA46UN2.js.map → chunk-EVKN4Y3R.js.map} +1 -1
- package/dist/chunks/{chunk-ELO4G2TG.js → chunk-HICKAMKK.js} +2 -2
- package/dist/chunks/{chunk-ELO4G2TG.js.map → chunk-HICKAMKK.js.map} +1 -1
- package/dist/chunks/{chunk-SZZZD7I3.js → chunk-HMIJBEUE.js} +3 -3
- package/dist/chunks/{chunk-SZZZD7I3.js.map → chunk-HMIJBEUE.js.map} +2 -2
- package/dist/chunks/{chunk-B6YUND32.js → chunk-HQ7FQACT.js} +2 -2
- package/dist/chunks/{chunk-B6YUND32.js.map → chunk-HQ7FQACT.js.map} +1 -1
- package/dist/chunks/{chunk-UZYU3HDD.js → chunk-KVZIGTH3.js} +2 -2
- package/dist/chunks/{chunk-CCPRHM4X.js → chunk-L372SDUG.js} +1 -1
- package/dist/chunks/{chunk-CCPRHM4X.js.map → chunk-L372SDUG.js.map} +1 -1
- package/dist/chunks/{chunk-YVRZM7FP.js → chunk-LD6RX4AZ.js} +1 -1
- package/dist/chunks/{chunk-YVRZM7FP.js.map → chunk-LD6RX4AZ.js.map} +1 -1
- package/dist/chunks/chunk-NBS4FGQ6.js +4 -0
- package/dist/chunks/{chunk-QY2UJ4TX.js.map → chunk-NBS4FGQ6.js.map} +3 -3
- package/dist/chunks/{chunk-DXJSOZY2.js → chunk-NFPLX56S.js} +1 -1
- package/dist/chunks/{chunk-DXJSOZY2.js.map → chunk-NFPLX56S.js.map} +1 -1
- package/dist/chunks/{chunk-JBQSIRNH.js → chunk-QB5JERW4.js} +1 -1
- package/dist/chunks/{chunk-JBQSIRNH.js.map → chunk-QB5JERW4.js.map} +1 -1
- package/dist/chunks/{chunk-4CP5H6LQ.js → chunk-RCJQCBBI.js} +2 -2
- package/dist/chunks/chunk-SYKOZDP6.js +2 -0
- package/dist/chunks/{chunk-NLMAQYCK.js → chunk-YS3R3J2I.js} +2 -2
- package/dist/chunks/{chunk-NLMAQYCK.js.map → chunk-YS3R3J2I.js.map} +2 -2
- package/dist/chunks/{renderSvg-MNRHFE4C.js → renderSvg-2YULK24A.js} +2 -2
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +2 -2
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +2 -2
- package/package.json +10 -10
- package/src/GraphGenomeView/components/LabelLayer.tsx +9 -4
- package/src/RgfaTabixAdapter/test_data/walks5_skippair.GRCh38.walks.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/walks5_skippair.GRCh38.walks.bed.gz.tbi +0 -0
- package/src/WalkTabixSyntenyAdapter/WalkTabixSyntenyAdapter.test.ts +127 -0
- package/src/WalkTabixSyntenyAdapter/WalkTabixSyntenyAdapter.ts +163 -46
- package/src/WalkTabixSyntenyAdapter/walkLanes.ts +88 -1
- package/src/readinessConformance.test.ts +66 -0
- package/src/synteny/matchFeature.ts +3 -2
- package/src/version.ts +1 -1
- package/dist/chunks/GbzBaseSyntenyAdapter-OLFYIFN4.js +0 -2
- package/dist/chunks/GbzBaseSyntenyAdapter-OLFYIFN4.js.map +0 -7
- package/dist/chunks/WalkTabixSyntenyAdapter-M453NH3L.js +0 -2
- package/dist/chunks/WalkTabixSyntenyAdapter-M453NH3L.js.map +0 -7
- package/dist/chunks/chunk-2EDOJEF3.js +0 -4
- package/dist/chunks/chunk-2EDOJEF3.js.map +0 -7
- package/dist/chunks/chunk-52L7CQAG.js +0 -3
- package/dist/chunks/chunk-52L7CQAG.js.map +0 -7
- package/dist/chunks/chunk-A4YJFEBE.js +0 -2
- package/dist/chunks/chunk-BI2RYKPA.js +0 -2
- package/dist/chunks/chunk-BI2RYKPA.js.map +0 -7
- package/dist/chunks/chunk-QY2UJ4TX.js +0 -4
- package/dist/chunks/chunk-UMCYJHEB.js +0 -3
- /package/dist/chunks/{GraphGenomeView-TC3UNRFN.js.map → GraphGenomeView-JJNU2432.js.map} +0 -0
- /package/dist/chunks/{GraphTrackSettingsDialog-JZBOLXZW.js.map → GraphTrackSettingsDialog-7NGUPDUJ.js.map} +0 -0
- /package/dist/chunks/{HighlightColorDialog-4VGVC7SN.js.map → HighlightColorDialog-KFXSZXTC.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-6IO5ADGB.js.map → LinearGraphDisplay-K3AT3S7J.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-X4VJ3AEX.js.map → MinigraphBubbleAdapter-P66QLENP.js.map} +0 -0
- /package/dist/chunks/{RgfaTabixAdapter-535GN32R.js.map → RgfaTabixAdapter-CQJROUIP.js.map} +0 -0
- /package/dist/chunks/{WalkFormsAdapter-DAGNKDXV.js.map → WalkFormsAdapter-YSYANJD5.js.map} +0 -0
- /package/dist/chunks/{chunk-UZYU3HDD.js.map → chunk-KVZIGTH3.js.map} +0 -0
- /package/dist/chunks/{chunk-4CP5H6LQ.js.map → chunk-RCJQCBBI.js.map} +0 -0
- /package/dist/chunks/{chunk-A4YJFEBE.js.map → chunk-SYKOZDP6.js.map} +0 -0
- /package/dist/chunks/{renderSvg-MNRHFE4C.js.map → renderSvg-2YULK24A.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as dt,c as ht,d as yt,g as C,j as K,l as xt,q as Mt,r as $,w as bt,x as vt}from"./chunk-HICKAMKK.js";import{b as pt,c as mt}from"./chunk-L372SDUG.js";var gt=20;function be(t){let n=e=>Math.round(e*100)/100;return t.map((e,o)=>`${o?"L":"M"}${n(e.x)},${n(e.y)}`).join("")}function wt(t,n,e,o,r){let s=Math.hypot(o-n,e-t);if(s===0)return[e,o];let a=(e-t)/s,c=(o-n)/s;return[e+r*a,o+r*c]}function Y(t,n){let e=1-n,o=e*e*e,r=3*e*e*n,s=3*e*n*n,a=n*n*n;return{x:o*t.x0+r*t.cx0+s*t.cx1+a*t.x1,y:o*t.y0+r*t.cy0+s*t.cy1+a*t.y1}}function Pt(t){let n=t[Math.floor(t.length/2)];return n?Y(n,.5):void 0}function Nt(t){let n=1/0,e=1/0,o=-1/0,r=-1/0;for(let s of t)n=Math.min(n,s.x0,s.cx0,s.cx1,s.x1),o=Math.max(o,s.x0,s.cx0,s.cx1,s.x1),e=Math.min(e,s.y0,s.cy0,s.cy1,s.y1),r=Math.max(r,s.y0,s.cy0,s.cy1,s.y1);return{minX:n,minY:e,maxX:o,maxY:r}}function tn(t,n,e){let o=Y(t,n),r=Y(t,e),s=(e-n)/3,a=At(t,n),c=At(t,e);return{x0:o.x,y0:o.y,cx0:o.x+a.x*s,cy0:o.y+a.y*s,cx1:r.x-c.x*s,cy1:r.y-c.y*s,x1:r.x,y1:r.y}}function At(t,n){let e=1-n,o=3*e*e,r=6*e*n,s=3*n*n;return{x:o*(t.cx0-t.x0)+r*(t.cx1-t.cx0)+s*(t.x1-t.cx1),y:o*(t.cy0-t.y0)+r*(t.cy1-t.cy0)+s*(t.y1-t.cy1)}}var H=32;function nn(t,n,e,o){let r=[],s=0;return t.forEach((a,c)=>{let i=n[c],l=i/H,d=Y(a,0);for(let u=1;u<=H;u++){let y=Y(a,u/H);if(Math.max(d.x,y.x)+l>=e.minX&&Math.min(d.x,y.x)-l<=e.maxX&&Math.max(d.y,y.y)+l/o>=e.minY&&Math.min(d.y,y.y)-l/o<=e.maxY){let f=s+i*(u-1)/H,h=s+i*u/H,x=r.at(-1);x&&x[1]>=f?x[1]=h:r.push([f,h])}d=y}s+=i}),r}function ve(t,n,e=1,o){let r=t.map(u=>Math.hypot(u.cx0-u.x0,(u.cy0-u.y0)*e)+Math.hypot(u.cx1-u.cx0,(u.cy1-u.cy0)*e)+Math.hypot(u.x1-u.cx1,(u.y1-u.cy1)*e)),s=r.reduce((u,y)=>u+y,0),a=Math.round(s/n),c=Math.max(3,a%2?a:a+1),i=o?nn(t,r,o,e):void 0,l=0,d=[];for(let u=0;u<c;u+=2){let y=u/c*s,f=(u+1)/c*s;if(i){for(;l<i.length&&i[l][1]<y;)l++;if(l===i.length)break;if(i[l][0]>f)continue}let h=[],x=[],p=0;t.forEach((b,m)=>{let M=r[m],g=p+M;if(M>0&&g>y&&p<f){let v=Math.max(0,(y-p)/M),w=Math.min(1,(f-p)/M);h.push(tn(b,v,w)),x.push((m+v)/t.length,(m+w)/t.length)}p=g}),h.length&&d.push({curves:h,startAlong:x[0],endAlong:x.at(-1)})}return d}function ge(t,n,e,o,r){let s=t.length,a=new Array(s);for(let c=0;c<s;c++){let i=t[c],l=c/s,d=(c+1)/s,u=n+(o-n)*l,y=e+(r-e)*l,f=n+(o-n)*d,h=e+(r-e)*d;a[c]={x0:i.x0+u,y0:i.y0+y,cx0:i.cx0+u,cy0:i.cy0+y,cx1:i.cx1+f,cy1:i.cy1+h,x1:i.x1+f,y1:i.y1+h}}return a}function we(t,n,e){let o=new Array(t.length);for(let r=0;r<t.length;r++){let s=t[r];o[r]={x0:s.x0+n,y0:s.y0+e,cx0:s.cx0+n,cy0:s.cy0+e,cx1:s.cx1+n,cy1:s.cy1+e,x1:s.x1+n,y1:s.y1+e}}return o}function W(t,n){let e=t.length-1;return n==="end"?{at:t[e],inward:t[e-1]}:{at:t[0],inward:t[1]}}var en=.5,on=80;function F(t){return t.endsWith("-")?"-":"+"}function q(t){let n=(e,o)=>(o??F(e))===F(e);return{from:n(t.from,t.fromStrand)?"end":"start",to:n(t.to,t.toStrand)?"start":"end"}}function _t(t){let n=1/0,e=-1/0;for(let o of t)n=Math.min(n,o.x),e=Math.max(e,o.x);return{min:n,max:e}}function Et(t,n){return Math.max(0,n.min-t,t-n.max)}function It(t,n,e){let o=Et(t[0].x,n),r=Et(t[t.length-1].x,n);return o===r?e:o<r?"start":"end"}function rn(t,n){return{from:It(t,_t(n),"end"),to:It(n,_t(t),"start")}}var Lt=new WeakMap;function sn(t,n){let e=Lt.get(t);e||(e=new WeakMap,Lt.set(t,e));let o=e.get(n);return o||(o=rn(t,n),e.set(n,o)),o}var cn=.75,an=1.15,fn=.35,un=3*gt;function ln(t,n,e,o,r,s){let a=Math.hypot(e-t,o-n),c=a===0?1:(e-t)/a,i=a===0?0:(o-n)/a,l=0,d=1/0,u=-1/0;for(let x of r){let p=x.x-t,b=x.y-n,m=p*-i+b*c;Math.abs(m)>Math.abs(l)&&(l=m);let M=p*c+b*i;d=Math.min(d,M),u=Math.max(u,M)}let y=r.length?u-d:0,f=Math.max(Math.abs(l)*an/cn,y*fn),h=s===void 0?f:Math.min(f,s);return l<0?-h:h}function Xt({scaleX:t,scaleY:n}){return n/t}var dn=3;function J(t,n,e){let o=n.x-t.x,r=(n.y-t.y)*e,s=Math.hypot(o,r);return s===0?void 0:{x:o/s,y:r/s}}function Ae(t,n,e,o){let r=Xt(o),s=dn/Math.max(o.scaleX,1e-6),a=J(t[t.length-1],n[0],r)??J(t[0],t.at(-1),r)??J(n[0],n.at(-1),r)??{x:1,y:0},c=[];for(let i=0;i<e;i++){let l=(i-(e-1)/2)*s;c.push({x:-a.y*l,y:a.x*l/r})}return c}function Q(t,n){return t.map(e=>({x:e.x,y:e.y*n}))}function hn(t,n){for(let e of t)e.y0/=n,e.cy0/=n,e.cy1/=n,e.y1/=n;return t}function Z(t,n,e){let o=0;for(let r=1;r<t.length;r++){let s=t[r-1],a=t[r];o+=Math.hypot((a.x-s.x)*n,(a.y-s.y)*e)}return o}var yn=12,xn=40;function Ot(t,n){let e=Z(t,n,n);return Math.min(xn,Math.max(yn,e/2))/Math.max(n,Number.EPSILON)}function pn(t){return t.from!==t.to?!1:t.fromStrand&&t.toStrand&&t.fromStrand!==t.toStrand?t.fromStrand==="+"?"end":"start":!0}function Ct(t,n=!1){let e=pn(t);if(!n)return e;let o=q(t);return e===!1?o:o.from===o.to?o.from:!0}function mn(t,n){let{at:e,inward:o}=t,r=o?e.x-o.x:1,s=o?e.y-o.y:0,a=Math.hypot(r,s)||1,c=r/a,i=s/a,l=e.x,d=e.y,u=l+c*n/3,y=d+i*n/3,f=l+c*n,h=d+i*n,x=-i*n/2,p=c*n/2;return[{x0:l,y0:d,cx0:u,cy0:y,cx1:f+x,cy1:h+p,x1:f,y1:h},{x0:f,y0:h,cx0:f-x,cy0:h-p,cx1:u,cy1:y,x1:l,y1:d}]}function tt(t,n,e,o,r=[],s){let a=o.scaleX,c=Xt(o),i=s??(o.pixelRows?un:void 0);if(e===!1&&(e=sn(t,n)),c!==1)return hn(tt(Q(t,c),Q(n,c),e,{scaleX:a,scaleY:a},Q(r,c),i===void 0?void 0:i*c),c);if(typeof e=="string")return mn(W(t,e),Ot(t,a));let l=e===!0,d=e===!0?{from:"end",to:"start"}:e,u=W(t,d.from),y=W(n,d.to),f=u.at,h=y.at,x=f.x,p=f.y,b=h.x,m=h.y;if(l){let M=1,g=0;if(u.inward){let S=f.x-u.inward.x,P=f.y-u.inward.y,X=Math.hypot(S,P);X>0&&(M=S/X,g=P/X)}let v=Ot(t,a),w=-g,_=M,I=(f.x+h.x)/2+w*v,E=(f.y+h.y)/2+_*v,A=x+M*v,N=p+g*v,O=b-M*v,L=m-g*v;return[{x0:x,y0:p,cx0:A,cy0:N,cx1:A+w*v,cy1:N+_*v,x1:I,y1:E},{x0:I,y0:E,cx0:O+w*v,cy0:L+_*v,cx1:O,cy1:L,x1:b,y1:m}]}else{let M=u.inward??{x:f.x-(h.x-f.x),y:f.y-(h.y-f.y)},g=y.inward??{x:h.x-(f.x-h.x),y:h.y-(f.y-h.y)},v=Math.hypot(b-x,m-p),w=(at,it,Jt,Qt)=>{let ft=it.x-at.x,ut=it.y-at.y,lt=Math.hypot(ft,ut),Zt=lt===0?0:(Jt*ft+Qt*ut)/lt;return Math.max(0,Math.min(v*en,on,Zt*.5))},_=h.x-f.x,I=h.y-f.y,[E,A]=wt(M.x,M.y,f.x,f.y,w(M,f,_,I)),[N,O]=wt(g.x,g.y,h.x,h.y,w(g,h,-_,-I)),L=r.length?ln(x,p,b,m,r,i):0,S=v===0?1:v,P=(b-x)/S,X=(m-p)/S,T=-X*L,B=P*L,R=P*Math.abs(L),ct=X*Math.abs(L);return[{x0:x,y0:p,cx0:E+T-R,cy0:A+B-ct,cx1:N+T+R,cy1:O+B+ct,x1:b,y1:m}]}}function St(t,n){let e=t[0],o=t.at(-1);return Math.hypot(e.x-n.x,e.y-n.y)<Math.hypot(o.x-n.x,o.y-n.y)?"start":"end"}function kt(t,n,e,o){let r=W(t,o?.from??St(t,e[0])),s=W(n,o?.to??St(n,e.at(-1))),a=[r.at,...e,s.at],c=l=>{let d=a[l],u=f=>Math.hypot(f.x-d.x,f.y-d.y),y=(f,h)=>{let x=f?u(f):0,p=u(h);return x===0?{x:h.x-d.x,y:h.y-d.y}:{x:(d.x-f.x)/x*p,y:(d.y-f.y)/x*p}};if(l===0)return y(r.inward,a[1]);if(l===a.length-1){let f=y(s.inward,a[l-1]);return{x:-f.x,y:-f.y}}return{x:(a[l+1].x-a[l-1].x)/2,y:(a[l+1].y-a[l-1].y)/2}},i=[];for(let l=0;l<a.length-1;l++){let d=a[l],u=a[l+1],y=c(l),f=c(l+1);i.push({x0:d.x,y0:d.y,cx0:d.x+y.x/3,cy0:d.y+y.y/3,cx1:u.x-f.x/3,cy1:u.y-f.y/3,x1:u.x,y1:u.y})}return i}function nt(){let t=new WeakMap;return(n,e,o)=>{let r=t.get(n);if(r?.deps.length===e.length&&r.deps.every((a,c)=>Object.is(a,e[c])))return r.value;let s=o();return t.set(n,{deps:e,value:s}),s}}var Bt=11,Mn=6.2,D=4;function et(t){return t.length*Mn+D*2}function bn(t,n){return t.x0<n.x1&&t.x1>n.x0&&t.y0<n.y1&&t.y1>n.y0}function Tt(t,n){return t.x1<=0||t.x0>=n.width||t.y1<=0||t.y0>=n.height}function vn(t,n){return t.x0>=0&&t.x1<=n.width&&t.y0>=0&&t.y1<=n.height}function Rt(t,n=[]){let e=[...n];return o=>Tt(o,t)||e.some(r=>bn(r,o))?!1:(e.push(o),!0)}function Ie(t,n,e){let o=[],r=Bt+D*2,s=(c,i,l,d)=>{let u=et(i),y=!1;for(let f=0;f<=(c.stack??0);f++){let h=l+d*f*r,x={x0:c.x-u/2,x1:c.x+u/2,y0:h-Bt-D,y1:h+D};if(Tt(x,n))break;if(vn(x,n)&&(c.fits?.(x)??!0)){if(e(x))return{placed:{...c,text:i,y:h,w:u},crowded:y};y=!0}}return{placed:void 0,crowded:y}},a=(c,i)=>{let l=s(c,i,c.y,c.y>n.height/2?-1:1);return l.placed??(c.flipY===void 0||l.crowded?void 0:s(c,i,c.flipY,c.flipY<c.y?-1:1).placed)};for(let c of t){let i=a(c,c.text)??(c.fallback===void 0?void 0:a(c,c.fallback));i&&o.push(i)}return o}function $t(t){return t==="+"?"-":"+"}function Ne(t,n=new Set){let e=t.edges.map(q),o=new Map,r=(f,h,x)=>{dt(o,`${f}|${h}`,x)};t.edges.forEach((f,h)=>{r(f.from,e[h].from,h),r(f.to,e[h].to,h)});let s=f=>{let h=o.get(`${f}|end`);if(h?.length!==1)return;let x=h[0],p=t.edges[x];return p.from===f&&p.to!==f&&!n.has(f)&&!n.has(p.to)&&e[x].from==="end"&&e[x].to==="start"&&o.get(`${p.to}|start`)?.length===1?x:void 0},a=new Set,c=new Map,i=new Map;for(let f of t.nodes){let h=o.get(`${f.id}|start`),x=h?.length===1?t.edges[h[0]].from:void 0;if(c.has(f.id)||x!==void 0&&s(x)===h[0])continue;let p=[f.id];for(;;){let b=s(p.at(-1)),m=b===void 0?void 0:t.edges[b].to;if(m===void 0||c.has(m))break;a.add(b),p.push(m)}for(let b of p)c.set(b,f.id);p.length>1&&i.set(f.id,p)}for(let f of t.nodes)c.has(f.id)||c.set(f.id,f.id);let l=new Map(t.nodes.map(f=>[f.id,f])),d=[];for(let f of t.nodes){if(c.get(f.id)!==f.id)continue;let h=i.get(f.id);if(!h){d.push(f);continue}let x=h.map(m=>l.get(m)),p=x.filter(C),b=p.length?p.reduce((m,M)=>m.stable.start<=M.stable.start?m:M):x[0];d.push({id:f.id,name:f.name,length:x.reduce((m,M)=>m+M.length,0),depth:f.depth,stable:b.stable})}let u=new Set,y=[];return t.edges.forEach((f,h)=>{let x=c.get(f.from),p=c.get(f.to),b=e[h],m=`${x}|${b.from}>${p}|${b.to}`;a.has(h)||u.has(m)||(u.add(m),y.push({from:x,to:p,...b.from==="start"?{fromStrand:$t(F(x))}:{},...b.to==="end"?{toStrand:$t(F(p))}:{}}))}),{graph:{...t,nodes:d,edges:y,paths:void 0,pathVisits:void 0},runs:i}}function Xe(t,n,e){let o={...t};for(let[r,s]of n){let a=t[r];if(!a?.length)continue;delete o[r];let c=rt(a),i=c.at(-1),l=s.map(y=>Math.max(e(y),0)),d=l.reduce((y,f)=>y+f,0),u=0;s.forEach((y,f)=>{let h=d?l[f]/d*i:i/s.length,x=f===s.length-1?i:u+h;o[y]=Yt(a,c,u,x),u=x})}return o}function Ce(t,n,e){if(t.length===0)return[];let o=rt(t),r=o.at(-1);return Yt(t,o,n*r,e*r)}function Ht(t){let n=rt(t);return ot(t,n,n.at(-1)/2)}function rt(t){let n=[0];for(let e=1;e<t.length;e++)n.push(n[e-1]+Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y));return n}function Wt(t,n){let e=0,o=t.length;for(;e<o;){let r=e+o>>1;t[r]<n?e=r+1:o=r}return e}function ot(t,n,e){if(e<=0)return{...t[0]};let o=Wt(n,e);if(o>=n.length)return{...t.at(-1)};let r=n[o]-n[o-1],s=r>0?(e-n[o-1])/r:0,a=t[o-1],c=t[o];return{x:a.x+(c.x-a.x)*s,y:a.y+(c.y-a.y)*s}}function Yt(t,n,e,o){let r=[ot(t,n,e)];for(let s=Wt(n,e);s<t.length&&n[s]<o;s++)n[s]>e&&r.push({...t[s]});return r.push(ot(t,n,o)),r}function $e(t,n){let e=new Set(t.nodes.filter(i=>C(i)&&K(i,n)).map(i=>i.id)),o=t.paths??[];if(e.size===0||o.length===0)return t;let r=o.map(i=>{let l=-1,d=-1;return i.nodeIds.forEach((u,y)=>{e.has(u)&&(l<0&&(l=y),d=y)}),l<0?void 0:{first:l,last:d}});if(r.every((i,l)=>i?.first===0&&i.last===o[l].nodeIds.length-1))return t;let s=new Set,a=[],c=new Map;return o.forEach((i,l)=>{let d=r[l];if(d){let u=i.nodeIds.slice(d.first,d.last+1);for(let y of u)s.add(y);a.push({...i,nodeIds:u}),c.set(i.name,{first:d.first,nodeIds:u})}}),{...t,nodes:t.nodes.filter(i=>s.has(i.id)),edges:t.edges.filter(i=>s.has(i.from)&&s.has(i.to)),paths:a,pathVisits:t.pathVisits&&gn(t.pathVisits,o,r,new Map(t.nodes.map(i=>[i.id,i.name]))),anchorPaths:bt(t,c)}}function gn(t,n,e,o){let r=t.replay(),s=new Mt;return n.forEach((a,c)=>{let i=t.pathIndex($(a.name).name),l=e[c];a.nodeIds.forEach((d,u)=>{let y=o.get(d)??d,f=r(t.slot(y),i);f>=0&&l&&u>=l.first&&u<=l.last&&s.add(y,t.paths[i],t.samples[i],t.start[f],t.reversed[f]===1)})}),s.build()}function He(t,n,e){let o=t.nodes.map(r=>{if(!C(r))return r;let s=r.stable.start,a=s+r.length,[c,i]=K(r,n)?[Math.max(s,n.start),Math.min(a,n.end)]:a<=n.start?[Math.max(s,a-e),a]:[s,Math.min(a,s+e)];return c===s&&i===a?r:{...r,length:i-c,stable:{...r.stable,start:c},unclipped:{start:s,length:r.length}}});return o.some((r,s)=>r!==t.nodes[s])?{...t,nodes:o}:t}function Ft(t){return t.nodes.some(n=>n.unclipped)?{...t,nodes:t.nodes.map(({unclipped:n,...e})=>n&&e.stable?{...e,length:n.length,stable:{...e.stable,start:n.start}}:e)}:t}var wn=1,ze=t=>`skips ${t??"the reference"} sequence (a deletion)`;function An(t,n){return n.flatMap(e=>t[e]??[])}function Gt(t,n,e,o,r,s){let a=t[n.from],c=t[n.to];if(!(!a?.length||!c?.length))return r?kt(a,c,r,s?q(n):void 0):tt(a,c,Ct(n,s),e,o?An(t,o):[])}function _n(t){let n=ht(t.nodes.filter(C),e=>e.stable.refName);for(let e of n.values())e.sort((o,r)=>o.stable.start-r.stable.start);return n}function En(t,n,e){let o=[];if(t)for(let r=xt(t,n);r<t.length;r++){let s=t[r];if(s.stable.start>=e)break;s.stable.start+s.length<=e&&o.push(s.id)}return o}function In(t,n,e,o){let{fromStrand:r,toStrand:s}=t;if(r===void 0||s===void 0)return!0;let a=r===(n.stable.strand??"+"),c=s===(e.stable.strand??"+");return o?a&&c:!a&&!c}function Ln(t,n,e,o){let r;for(let s of o(n))for(let a of o(e)){let c=s<=a,i=c?{start:s+n.length,end:a}:{start:a+e.length,end:s};In(t,n,e,c)&&(!r||Math.abs(i.end-i.start)<Math.abs(r.end-r.start))&&(r=i)}return r}var On=.01;function Sn(t,n){let e=new Map;for(let[o,r]of t){let s=r.flatMap(a=>{let c=n(a);return c.slice(1).map((i,l)=>({at:c[l],copy:i-c[l]}))});s.length&&e.set(o,s.sort((a,c)=>a.at-c.at))}return e}function Pn(t,n,e){if(!t)return!1;let o=yt(t.length,s=>t[s].at<n),r=[t[o-1],t[o]].filter(s=>s!==void 0).sort((s,a)=>Math.abs(s.at-n)-Math.abs(a.at-n))[0];return r!==void 0&&Math.abs(r.at-n)<=r.copy&&Math.abs(e-r.copy)<=r.copy*On}function je(t){let n=Ft(t),e=new Map(n.nodes.map(c=>[c.id,c])),o=_n(n),r=vt(n),s=Sn(o,r),a=[];for(let c=0;c<n.edges.length;c++){let i=n.edges[c],l=e.get(i.from),d=e.get(i.to);if(!i.foldBridge&&l!==void 0&&d!==void 0&&C(l)&&C(d)&&l.stable.refName===d.stable.refName){let u=Ln(i,l,d,r),y=l.stable.refName,f=u?u.end-u.start:0;if(u&&f>=wn&&!Pn(s.get(y),u.start,f)){let{start:h,end:x}=u;a.push({edgeIndex:c,from:i.from,to:i.to,...i.fromStrand?{fromStrand:i.fromStrand}:{},...i.toStrand?{toStrand:i.toStrand}:{},refName:y,start:h,end:x,bp:f,bypassed:En(o.get(y),h,x)})}}}return a}function Nn(t,n){let e=new Map,o=a=>{let c=a;for(;e.has(c);)c=e.get(c);return c!==a&&e.set(a,c),c},r=(a,c)=>{let[i,l]=[o(a),o(c)];return i!==l&&e.set(i,l),i!==l},s=new Set(n.map(a=>a.edgeIndex));return t.edges.forEach((a,c)=>{s.has(c)||r(a.from,a.to)}),new Set(n.filter(a=>!r(a.from,a.to)).map(a=>a.edgeIndex))}function Ue(t,n){return n?.walks.length?t.filter(e=>!n.edgeIndexes.has(e.edgeIndex)):t}var qt=new WeakMap;function Ke(t,n,e=!0){let o=qt.get(n);o||(o=new Map,qt.set(n,o));let r=o.get(e);if(!r){let s=e?new Set:Nn(t,n);r={shown:n.filter(a=>!s.has(a.edgeIndex)),bypassed:new Map(n.map(a=>[a.edgeIndex,a.bypassed])),hidden:s},o.set(e,r)}return r}var Xn=26,Cn=4e4,kn=8,Bn=8,Tn=5.7,Rn=6,$n=13,G=3,V=2;function U(t){return(t.length*Tn+Rn+G)/2}var k=($n+G)/2,Hn=U("1 bp");function z(t,n,e){return{x0:n-t,x1:n+t,y0:e-k,y1:e+k}}function oo(t,n){return{x0:6,x1:6+et(t)+G,y0:n-8-G/2,y1:n+8+G/2}}function j(t,n,e){return e<n?t:Math.min(Math.max(t,n),e)}function zt(t){return String(t).replace(/\B(?=(\d{3})+$)/g,",")}function jt(t){let[n,e]=t>=999500?[t/1e6,"Mb"]:t>=1e3?[t/1e3,"kb"]:[];return n===void 0?`${t} bp`:`${+n.toFixed(n>=100?0:1)} ${e}`}function Dt(t){return`${jt(t)} del`}function Wn(t,n,e,o){let r=t[0],s=t[t.length-1],a=(n.x-(r.x0+s.x1)/2)*e,c=(n.y-(r.y0+s.y1)/2)*o,i=Math.hypot(a,c);return i===0?{x:0,y:-1}:{x:a/i,y:c/i}}function Yn(t,n){return Math.abs(n.x)*(t.x1-t.x0)/2+Math.abs(n.y)*(t.y1-t.y0)/2}function Fn(t,n){let e=(t.x1-t.x0)/2,o=(t.y1-t.y0)/2;return Math.min(n.x===0?1/0:e/Math.abs(n.x),n.y===0?1/0:o/Math.abs(n.y))}function qn(t,n){let e=1/0,o=1/0,r=-1/0,s=-1/0;for(let a of t)for(let c of n[a]??[])e=Math.min(e,c.x),r=Math.max(r,c.x),o=Math.min(o,c.y),s=Math.max(s,c.y);return e===1/0?void 0:{minX:e,minY:o,maxX:r,maxY:s}}var Gn=nt();function Dn(t,n){return Gn(t,[n],()=>Object.entries(t).filter(([e,o])=>o.length>0&&n.has(e)).sort(([e],[o])=>n.get(o)-n.get(e)))}var Vn=nt();function zn(t,n,e,o,r,s){let{scaleX:a,scaleY:c}=e;return Vn(t,[n,r,s,a,c,o],()=>{let i=[];for(let l of[...n].sort((d,u)=>u.bp-d.bp)){let d=Gt(t,l,e,l.bypassed,r?.[l.edgeIndex],s),u=d?Pt(d):void 0;if(d&&u){let{minX:y,minY:f,maxX:h,maxY:x}=Nt(d);i.push({deletion:l,curves:d,apex:u,extent:Math.max((h-y)*a,(x-f)*c)})}}return i})}function jn({nodePositions:t,nodeLengths:n,deletions:e,deletionRoutes:o,stranded:r=!1,alleleDeletions:s,axis:a,translateX:c,translateY:i,width:l,height:d,version:u=0}){let{scaleX:y,scaleY:f}=a,h=[],x=[];for(let{deletion:m,curves:M,apex:g,extent:v}of zn(t,e,a,u,o,r))if(v>=Xn){let w=Dt(m.bp),_=U(w),I=z(_,0,0),E=g.x*y+c,A=g.y*f+i;if(E<0||E>l||A<0||A>d)continue;let N=v>=_*2/V,O=Wn(M,g,y,f),L=Yn(I,O)+Bn,S=N?E:j(E+O.x*L,_,l-_),P=N?A:j(A+O.y*L,k,d-k),X=Math.hypot(S-E,P-A),T;if(X>0){let B={x:(S-E)/X,y:(P-A)/X},R=Fn(I,B);T={arcX:E,arcY:A,labelX:S-B.x*R,labelY:P-B.y*R}}h.push({label:{key:`del:${m.edgeIndex}`,text:w,x:S,y:P,kind:"deletion",leader:T},box:z(_,S,P)})}let p=new Set,b=[...s??[]].sort((m,M)=>M.bp-m.bp);for(let m of b){let M=qn(m.nodeIds,t);if(!M)continue;let g=Math.max(M.minX*y+c,0),v=Math.min(M.maxX*y+c,l),w=Math.max(M.minY*f+i,0),_=Math.min(M.maxY*f+i,d);if(v<g||_<w)continue;let I=Math.max(v-g,_-w),E=Dt(m.bp),A=U(E);if(I>=A*2/V){for(let L of m.nodeIds)p.add(L);let N=j((g+v)/2,A,l-A),O=j((w+_)/2,k,d-k);h.push({label:{key:`alleledel:${m.nodeIds.join(",")}`,text:E,x:N,y:O,kind:"deletion"},box:z(A,N,O)})}}for(let[m,M]of Dn(t,n)){if(p.has(m))continue;let{x:g,y:v}=Ht(M),w=v*f+i;if(w+k<=0||w-k>=d)continue;let _=Z(M,y,f);if(_<Hn*2/V)continue;let I=jt(n.get(m)),E=U(I);if(_>=E*2/V){let A=g*y+c;x.push({label:{key:`node:${m}`,text:I,x:A,y:w,kind:"node"},box:z(E,A,w)})}}return{deletions:h,nodes:x}}function Un(t,n){return Math.max(kn,Math.floor(t*n/Cn))}function Vt(t,n,e=1/0){let o=[];for(let{label:r,box:s}of t){if(o.length>=e)break;n(s)&&o.push(r)}return o}function ro({reserved:t,take:n,...e}){n??=Rt(e,t);let{deletions:o,nodes:r}=jn(e);return[...Vt(o,n),...Vt(r,n,Un(e.width,e.height))]}function fo(t){let n=0;for(let e=0;e<t.length;e++)n=t.charCodeAt(e)+((n<<5)-n);return Math.abs(n%360)}function Kn(t,n){return t*360/n}var Jn=.7,Qn=.5,Zn=16;function uo(t){return t>0&&t<=Zn}function te(t,n){return`hsl(${Kn(t,n)}, ${Jn*100}%, ${Qn*100}%)`}function lo(t,n){return`hsl(0, 0%, ${n>1?25+45*t/(n-1):45}%)`}function ne(t){let n=$(t).name.split("#"),e=n.join("#");if(n.length>=3&&pt(n[0])){let o=n.slice(2).join("#");return[o,o,e]}return[n[0],n.slice(0,2).join("#"),e]}function ee(t,n){let{start:e}=$(t);return n.map(o=>`${o} @${zt(e)}`)}function ho(t,n){let e=new Map;t.forEach((d,u)=>{e.has(d.name)||e.set(d.name,u)});let o=[...e].map(([d,u])=>({name:d,i:u})),r=o.map(d=>ne(d.name)),s=d=>o.map((u,y)=>r[y][d]),a=d=>o.map((u,y)=>ee(u.name,r[y])[d]),c=[s(0),s(1),a(0),s(2),a(1),a(2)],l=c.find(d=>new Set(d).size===o.length)??c.at(-1);return o.map(({name:d,i:u},y)=>({name:d,label:l[y],color:n?.[u]??te(u,t.length)}))}function yo(t){let n=new Map;return new Map([...t].sort((e,o)=>e.label.localeCompare(o.label)).map(e=>{let o=(n.get(e.label)??0)+1;return n.set(e.label,o),[e.name,o>1?`${e.label} (${o})`:e.label]}))}var mo=[{value:"depth",label:"By depth",description:"Thicker the more paths carry a node, on the square root of its depth against the mean. A graph with one depth everywhere draws uniform."},{value:"frequency",label:"By frequency",description:"As wide as the share of haplotypes that pass a node, or its AF tag: full width at 100%, half at 50%, and wider where a haplotype passes it more than once."},{value:"uniform",label:"Uniform",description:"Every node the same thickness."}],oe=.3,st=3,re=.05;function se(t){let n=0,e=0;for(let o of t.nodes)n+=o.depth*o.length,e+=o.length;return e>0?n/e:0}function ce(t){return t.sample===void 0?mt(t.name)??t.name:`${t.sample}#${t.haplotype??0}`}function ae(t){return new Set((t.paths??[]).map(ce)).size}function ie(t,n){return t.frequency??(n>0?t.depth/n:void 0)}function fe(t,n){return n==="depth"?se(t):n==="frequency"?ae(t):0}function Ut(t){return Math.min(st,Math.max(re,t))}function ue(t,n){let e=ie(t,n);return e===void 0?1:Ut(e)}function Mo(t){return[1,.5,.1].map(n=>({label:`${n*100}%`,widthPx:t*Ut(n)}))}function le(t,n){return!(n>0)||!(t.depth>0)?1:Math.min(st,Math.max(oe,Math.sqrt(t.depth/n)))}function de(t,n,e,o){return n*(e==="depth"?le(t,o):e==="frequency"?ue(t,o):1)}function he(t,n){return t*(n==="uniform"?1:st)}var ye=4;function xe(t,n){return Math.max(t/n,ye)}function bo(t,n,e,o,r=0){let s=t?fe(t,o):0,a=c=>r>0?xe(c,r)*r/2:c/2;return{maxHalfWidthPx:a(he(e,o)),halfWidthPx:c=>{let i=n?.get(c);return a(i?de(i,e,o,s):e)}}}var go=[{value:"uniform",label:"Uniform",description:"Every link the same thickness."},{value:"walks",label:"By walks",description:"Thicker the more walks take a link, on the square root of its count against the busiest link in the cut. A graph without walks draws uniform."}],Kt=.5,pe=4;function wo(t){let n=0;for(let e of t.edges)n=Math.max(n,e.pathIds?.length??0);return n}function Ao(t,n,e){return e==="uniform"||n===0?1:Kt+(pe-Kt)*Math.sqrt(t/n)}export{gt as a,be as b,Nt as c,ve as d,ge as e,we as f,F as g,q as h,Xt as i,Ae as j,Z as k,nt as l,Bt as m,Mn as n,D as o,et as p,Rt as q,Ie as r,Ne as s,Xe as t,Ce as u,$e as v,He as w,ze as x,Gt as y,je as z,Ue as A,Ke as B,oo as C,zt as D,jt as E,ro as F,fo as G,Kn as H,Jn as I,Qn as J,Zn as K,uo as L,te as M,lo as N,ho as O,yo as P,mo as Q,se as R,fe as S,Mo as T,de as U,xe as V,bo as W,go as X,wo as Y,Ao as Z};
|
|
2
|
+
//# sourceMappingURL=chunk-DKQFTMWL.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-CPMHA4W5.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-JJV2GT2Z.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-HMXCN6PG.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-S43IBA5Y.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-HNNP5QUN.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-H4UHV22B.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-ALGYCMMH.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-OPTHW6IZ.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-ZULVAGVE.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-XWH4LB56.js", "../../node_modules/.pnpm/@jbrowse+bandage-core@12.3.0/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-DAEEMZ74.js"],
|
|
4
|
+
"sourcesContent": ["// src/layout/rowSpacing.ts\nvar ROW_HEIGHT_PX = 20;\n\nexport {\n ROW_HEIGHT_PX\n};\n", "import {\n ROW_HEIGHT_PX\n} from \"./chunk-CPMHA4W5.js\";\n\n// src/util/geometry.ts\nfunction svgPath(points) {\n const round = (v) => Math.round(v * 100) / 100;\n return points.map((p, i) => `${i ? \"L\" : \"M\"}${round(p.x)},${round(p.y)}`).join(\"\");\n}\nfunction projectLine(x1, y1, x2, y2, distance) {\n const d = Math.hypot(y2 - y1, x2 - x1);\n if (d === 0) {\n return [x2, y2];\n }\n const vx = (x2 - x1) / d;\n const vy = (y2 - y1) / d;\n return [x2 + distance * vx, y2 + distance * vy];\n}\nfunction curvePointAt(c, t) {\n const u = 1 - t;\n const a = u * u * u;\n const b = 3 * u * u * t;\n const d = 3 * u * t * t;\n const e = t * t * t;\n return {\n x: a * c.x0 + b * c.cx0 + d * c.cx1 + e * c.x1,\n y: a * c.y0 + b * c.cy0 + d * c.cy1 + e * c.y1\n };\n}\nfunction curveMidpoint(curves) {\n const mid = curves[Math.floor(curves.length / 2)];\n return mid ? curvePointAt(mid, 0.5) : void 0;\n}\nfunction curveBounds(curves) {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const c of curves) {\n minX = Math.min(minX, c.x0, c.cx0, c.cx1, c.x1);\n maxX = Math.max(maxX, c.x0, c.cx0, c.cx1, c.x1);\n minY = Math.min(minY, c.y0, c.cy0, c.cy1, c.y1);\n maxY = Math.max(maxY, c.y0, c.cy0, c.cy1, c.y1);\n }\n return { minX, minY, maxX, maxY };\n}\nfunction subCurve(c, t0, t1) {\n const p0 = curvePointAt(c, t0);\n const p1 = curvePointAt(c, t1);\n const dt = (t1 - t0) / 3;\n const d0 = curveTangentAt(c, t0);\n const d1 = curveTangentAt(c, t1);\n return {\n x0: p0.x,\n y0: p0.y,\n cx0: p0.x + d0.x * dt,\n cy0: p0.y + d0.y * dt,\n cx1: p1.x - d1.x * dt,\n cy1: p1.y - d1.y * dt,\n x1: p1.x,\n y1: p1.y\n };\n}\nfunction curveTangentAt(c, t) {\n const u = 1 - t;\n const a = 3 * u * u;\n const b = 6 * u * t;\n const d = 3 * t * t;\n return {\n x: a * (c.cx0 - c.x0) + b * (c.cx1 - c.cx0) + d * (c.x1 - c.cx1),\n y: a * (c.cy0 - c.y0) + b * (c.cy1 - c.cy0) + d * (c.y1 - c.cy1)\n };\n}\nvar VISIBLE_SAMPLES = 32;\nfunction visibleStretches(curves, lengths, bounds, yToX) {\n const stretches = [];\n let start = 0;\n curves.forEach((c, k) => {\n const length = lengths[k];\n const pad = length / VISIBLE_SAMPLES;\n let last = curvePointAt(c, 0);\n for (let i = 1; i <= VISIBLE_SAMPLES; i++) {\n const next = curvePointAt(c, i / VISIBLE_SAMPLES);\n if (Math.max(last.x, next.x) + pad >= bounds.minX && Math.min(last.x, next.x) - pad <= bounds.maxX && Math.max(last.y, next.y) + pad / yToX >= bounds.minY && Math.min(last.y, next.y) - pad / yToX <= bounds.maxY) {\n const from = start + length * (i - 1) / VISIBLE_SAMPLES;\n const to = start + length * i / VISIBLE_SAMPLES;\n const prev = stretches.at(-1);\n if (prev && prev[1] >= from) {\n prev[1] = to;\n } else {\n stretches.push([from, to]);\n }\n }\n last = next;\n }\n start += length;\n });\n return stretches;\n}\nvar dashCurves = (curves, dashWorld, yToX = 1, bounds) => dashSpans(curves, dashWorld, yToX, bounds).map((d) => d.curves);\nfunction dashSpans(curves, dashWorld, yToX = 1, bounds) {\n const lengths = curves.map(\n (c) => Math.hypot(c.cx0 - c.x0, (c.cy0 - c.y0) * yToX) + Math.hypot(c.cx1 - c.cx0, (c.cy1 - c.cy0) * yToX) + Math.hypot(c.x1 - c.cx1, (c.y1 - c.cy1) * yToX)\n );\n const total = lengths.reduce((a, b) => a + b, 0);\n const periods = Math.round(total / dashWorld);\n const spans = Math.max(3, periods % 2 ? periods : periods + 1);\n const stretches = bounds ? visibleStretches(curves, lengths, bounds, yToX) : void 0;\n let seen = 0;\n const out = [];\n for (let i = 0; i < spans; i += 2) {\n const from = i / spans * total;\n const to = (i + 1) / spans * total;\n if (stretches) {\n while (seen < stretches.length && stretches[seen][1] < from) {\n seen++;\n }\n if (seen === stretches.length) {\n break;\n }\n if (stretches[seen][0] > to) {\n continue;\n }\n }\n const dash = [];\n const along = [];\n let start = 0;\n curves.forEach((c, k) => {\n const length = lengths[k];\n const end = start + length;\n if (length > 0 && end > from && start < to) {\n const t0 = Math.max(0, (from - start) / length);\n const t1 = Math.min(1, (to - start) / length);\n dash.push(subCurve(c, t0, t1));\n along.push((k + t0) / curves.length, (k + t1) / curves.length);\n }\n start = end;\n });\n if (dash.length) {\n out.push({\n curves: dash,\n startAlong: along[0],\n endAlong: along.at(-1)\n });\n }\n }\n return out;\n}\nvar slideAt = (from, to, along) => ({\n dx: from.dx + (to.dx - from.dx) * along,\n dy: from.dy + (to.dy - from.dy) * along\n});\nfunction slideCurves(curves, fromDx, fromDy, toDx, toDy) {\n const n = curves.length;\n const out = new Array(n);\n for (let i = 0; i < n; i++) {\n const c = curves[i];\n const a = i / n;\n const b = (i + 1) / n;\n const adx = fromDx + (toDx - fromDx) * a;\n const ady = fromDy + (toDy - fromDy) * a;\n const bdx = fromDx + (toDx - fromDx) * b;\n const bdy = fromDy + (toDy - fromDy) * b;\n out[i] = {\n x0: c.x0 + adx,\n y0: c.y0 + ady,\n cx0: c.cx0 + adx,\n cy0: c.cy0 + ady,\n cx1: c.cx1 + bdx,\n cy1: c.cy1 + bdy,\n x1: c.x1 + bdx,\n y1: c.y1 + bdy\n };\n }\n return out;\n}\nfunction translateCurves(curves, dx, dy) {\n const out = new Array(curves.length);\n for (let i = 0; i < curves.length; i++) {\n const c = curves[i];\n out[i] = {\n x0: c.x0 + dx,\n y0: c.y0 + dy,\n cx0: c.cx0 + dx,\n cy0: c.cy0 + dy,\n cx1: c.cx1 + dx,\n cy1: c.cy1 + dy,\n x1: c.x1 + dx,\n y1: c.y1 + dy\n };\n }\n return out;\n}\nfunction attachment(segments, side) {\n const last = segments.length - 1;\n return side === \"end\" ? { at: segments[last], inward: segments[last - 1] } : { at: segments[0], inward: segments[1] };\n}\nvar TANGENT_SPAN_FACTOR = 0.5;\nvar MAX_TANGENT = 80;\nfunction ownStrand(id) {\n return id.endsWith(\"-\") ? \"-\" : \"+\";\n}\nfunction strandSides(edge) {\n const own = (id, strand) => (strand ?? ownStrand(id)) === ownStrand(id);\n return {\n from: own(edge.from, edge.fromStrand) ? \"end\" : \"start\",\n to: own(edge.to, edge.toStrand) ? \"start\" : \"end\"\n };\n}\nfunction spanOf(segments) {\n let min = Infinity;\n let max = -Infinity;\n for (const s of segments) {\n min = Math.min(min, s.x);\n max = Math.max(max, s.x);\n }\n return { min, max };\n}\nfunction distanceToSpan(x, span) {\n return Math.max(0, span.min - x, x - span.max);\n}\nfunction facingSide(segments, other, tieBreak) {\n const startGap = distanceToSpan(segments[0].x, other);\n const endGap = distanceToSpan(segments[segments.length - 1].x, other);\n return startGap === endGap ? tieBreak : startGap < endGap ? \"start\" : \"end\";\n}\nfunction facingSides(fromSegments, toSegments) {\n return {\n from: facingSide(fromSegments, spanOf(toSegments), \"end\"),\n to: facingSide(toSegments, spanOf(fromSegments), \"start\")\n };\n}\nvar laidSides = /* @__PURE__ */ new WeakMap();\nfunction heldFacingSides(fromSegments, toSegments) {\n let byTo = laidSides.get(fromSegments);\n if (!byTo) {\n byTo = /* @__PURE__ */ new WeakMap();\n laidSides.set(fromSegments, byTo);\n }\n let sides = byTo.get(toSegments);\n if (!sides) {\n sides = facingSides(fromSegments, toSegments);\n byTo.set(toSegments, sides);\n }\n return sides;\n}\nvar APEX_FRACTION = 0.75;\nvar BOW_CLEARANCE = 1.15;\nvar ALONG_FRACTION = 0.35;\nvar MAX_ROW_BOW_PX = 3 * ROW_HEIGHT_PX;\nfunction bowAround(p1x, p1y, p2x, p2y, toward, maxBow) {\n const chord = Math.hypot(p2x - p1x, p2y - p1y);\n const ux = chord === 0 ? 1 : (p2x - p1x) / chord;\n const uy = chord === 0 ? 0 : (p2y - p1y) / chord;\n let reach = 0;\n let minAlong = Infinity;\n let maxAlong = -Infinity;\n for (const p of toward) {\n const dx = p.x - p1x;\n const dy = p.y - p1y;\n const perp = dx * -uy + dy * ux;\n if (Math.abs(perp) > Math.abs(reach)) {\n reach = perp;\n }\n const along = dx * ux + dy * uy;\n minAlong = Math.min(minAlong, along);\n maxAlong = Math.max(maxAlong, along);\n }\n const span = toward.length ? maxAlong - minAlong : 0;\n const uncapped = Math.max(\n Math.abs(reach) * BOW_CLEARANCE / APEX_FRACTION,\n span * ALONG_FRACTION\n );\n const size = maxBow === void 0 ? uncapped : Math.min(uncapped, maxBow);\n return reach < 0 ? -size : size;\n}\nfunction yToXOf({ scaleX, scaleY }) {\n return scaleY / scaleX;\n}\nvar PATH_RIBBON_SPACING_PX = 3;\nfunction drawnDirection(a, b, yToX) {\n const dx = b.x - a.x;\n const dy = (b.y - a.y) * yToX;\n const len = Math.hypot(dx, dy);\n return len === 0 ? void 0 : { x: dx / len, y: dy / len };\n}\nfunction pathRibbonOffsets(fromSegments, toSegments, count, axis) {\n const yToX = yToXOf(axis);\n const spacing = PATH_RIBBON_SPACING_PX / Math.max(axis.scaleX, 1e-6);\n const dir = drawnDirection(\n fromSegments[fromSegments.length - 1],\n toSegments[0],\n yToX\n ) ?? drawnDirection(fromSegments[0], fromSegments.at(-1), yToX) ?? drawnDirection(toSegments[0], toSegments.at(-1), yToX) ?? { x: 1, y: 0 };\n const offsets = [];\n for (let i = 0; i < count; i++) {\n const distance = (i - (count - 1) / 2) * spacing;\n offsets.push({ x: -dir.y * distance, y: dir.x * distance / yToX });\n }\n return offsets;\n}\nfunction scaleYOf(points, yToX) {\n return points.map((p) => ({ x: p.x, y: p.y * yToX }));\n}\nfunction unscaleYOf(curves, yToX) {\n for (const c of curves) {\n c.y0 /= yToX;\n c.cy0 /= yToX;\n c.cy1 /= yToX;\n c.y1 /= yToX;\n }\n return curves;\n}\nfunction polylinePx(points, scaleX, scaleY) {\n let total = 0;\n for (let i = 1; i < points.length; i++) {\n const a = points[i - 1];\n const b = points[i];\n total += Math.hypot((b.x - a.x) * scaleX, (b.y - a.y) * scaleY);\n }\n return total;\n}\nvar SELF_LOOP_MIN_PX = 12;\nvar SELF_LOOP_MAX_PX = 40;\nfunction selfLoopReach(segments, scale) {\n const nodePx = polylinePx(segments, scale, scale);\n const reachPx = Math.min(\n SELF_LOOP_MAX_PX,\n Math.max(SELF_LOOP_MIN_PX, nodePx / 2)\n );\n return reachPx / Math.max(scale, Number.EPSILON);\n}\nfunction selfLinkOf(edge) {\n if (edge.from !== edge.to) {\n return false;\n }\n return edge.fromStrand && edge.toStrand && edge.fromStrand !== edge.toStrand ? edge.fromStrand === \"+\" ? \"end\" : \"start\" : true;\n}\nfunction edgeJoinOf(edge, stranded = false) {\n const self = selfLinkOf(edge);\n if (!stranded) {\n return self;\n }\n const sides = strandSides(edge);\n return self === false ? sides : sides.from === sides.to ? sides.from : true;\n}\nfunction hairpinCurves(attach, reach) {\n const { at, inward } = attach;\n const dx = inward ? at.x - inward.x : 1;\n const dy = inward ? at.y - inward.y : 0;\n const len = Math.hypot(dx, dy) || 1;\n const ux = dx / len;\n const uy = dy / len;\n const px = at.x;\n const py = at.y;\n const nearX = px + ux * reach / 3;\n const nearY = py + uy * reach / 3;\n const apexX = px + ux * reach;\n const apexY = py + uy * reach;\n const sideX = -uy * reach / 2;\n const sideY = ux * reach / 2;\n return [\n {\n x0: px,\n y0: py,\n cx0: nearX,\n cy0: nearY,\n cx1: apexX + sideX,\n cy1: apexY + sideY,\n x1: apexX,\n y1: apexY\n },\n {\n x0: apexX,\n y0: apexY,\n cx0: apexX - sideX,\n cy0: apexY - sideY,\n cx1: nearX,\n cy1: nearY,\n x1: px,\n y1: py\n }\n ];\n}\nfunction computeEdgeCurves(fromSegments, toSegments, join, axis, bypassed = [], maxBowIn) {\n const scale = axis.scaleX;\n const yToX = yToXOf(axis);\n const maxBow = maxBowIn ?? (axis.pixelRows ? MAX_ROW_BOW_PX : void 0);\n if (join === false) {\n join = heldFacingSides(fromSegments, toSegments);\n }\n if (yToX !== 1) {\n return unscaleYOf(\n computeEdgeCurves(\n scaleYOf(fromSegments, yToX),\n scaleYOf(toSegments, yToX),\n join,\n { scaleX: scale, scaleY: scale },\n scaleYOf(bypassed, yToX),\n // the cap is a y measure and the body works in x units, so it converts\n // with everything else that crosses this boundary\n maxBow === void 0 ? void 0 : maxBow * yToX\n ),\n yToX\n );\n }\n if (typeof join === \"string\") {\n return hairpinCurves(\n attachment(fromSegments, join),\n selfLoopReach(fromSegments, scale)\n );\n }\n const loop = join === true;\n const sides = join === true ? { from: \"end\", to: \"start\" } : join;\n const fromAttach = attachment(fromSegments, sides.from);\n const toAttach = attachment(toSegments, sides.to);\n const fromEnd = fromAttach.at;\n const toStart = toAttach.at;\n const p1x = fromEnd.x;\n const p1y = fromEnd.y;\n const p2x = toStart.x;\n const p2y = toStart.y;\n if (loop) {\n let segDirX = 1;\n let segDirY = 0;\n if (fromAttach.inward) {\n const dx = fromEnd.x - fromAttach.inward.x;\n const dy = fromEnd.y - fromAttach.inward.y;\n const len = Math.hypot(dx, dy);\n if (len > 0) {\n segDirX = dx / len;\n segDirY = dy / len;\n }\n }\n const ext = selfLoopReach(fromSegments, scale);\n const perpX = -segDirY;\n const perpY = segDirX;\n const midX = (fromEnd.x + toStart.x) / 2 + perpX * ext;\n const midY = (fromEnd.y + toStart.y) / 2 + perpY * ext;\n const cp1x = p1x + segDirX * ext;\n const cp1y = p1y + segDirY * ext;\n const cp2x = p2x - segDirX * ext;\n const cp2y = p2y - segDirY * ext;\n return [\n {\n x0: p1x,\n y0: p1y,\n cx0: cp1x,\n cy0: cp1y,\n cx1: cp1x + perpX * ext,\n cy1: cp1y + perpY * ext,\n x1: midX,\n y1: midY\n },\n {\n x0: midX,\n y0: midY,\n cx0: cp2x + perpX * ext,\n cy0: cp2y + perpY * ext,\n cx1: cp2x,\n cy1: cp2y,\n x1: p2x,\n y1: p2y\n }\n ];\n } else {\n const fromPrev = fromAttach.inward ?? {\n x: fromEnd.x - (toStart.x - fromEnd.x),\n y: fromEnd.y - (toStart.y - fromEnd.y)\n };\n const toNext = toAttach.inward ?? {\n x: toStart.x - (fromEnd.x - toStart.x),\n y: toStart.y - (fromEnd.y - toStart.y)\n };\n const dist = Math.hypot(p2x - p1x, p2y - p1y);\n const tangentProj = (prev, at, towardX, towardY) => {\n const dx = at.x - prev.x;\n const dy = at.y - prev.y;\n const len = Math.hypot(dx, dy);\n const along = len === 0 ? 0 : (towardX * dx + towardY * dy) / len;\n return Math.max(\n 0,\n Math.min(dist * TANGENT_SPAN_FACTOR, MAX_TANGENT, along * 0.5)\n );\n };\n const towardToX = toStart.x - fromEnd.x;\n const towardToY = toStart.y - fromEnd.y;\n const [cx1, cy1] = projectLine(\n fromPrev.x,\n fromPrev.y,\n fromEnd.x,\n fromEnd.y,\n tangentProj(fromPrev, fromEnd, towardToX, towardToY)\n );\n const [cx2, cy2] = projectLine(\n toNext.x,\n toNext.y,\n toStart.x,\n toStart.y,\n tangentProj(toNext, toStart, -towardToX, -towardToY)\n );\n const bulge = bypassed.length ? bowAround(p1x, p1y, p2x, p2y, bypassed, maxBow) : 0;\n const chordLen = dist === 0 ? 1 : dist;\n const ux = (p2x - p1x) / chordLen;\n const uy = (p2y - p1y) / chordLen;\n const bulgeX = -uy * bulge;\n const bulgeY = ux * bulge;\n const spreadX = ux * Math.abs(bulge);\n const spreadY = uy * Math.abs(bulge);\n return [\n {\n x0: p1x,\n y0: p1y,\n cx0: cx1 + bulgeX - spreadX,\n cy0: cy1 + bulgeY - spreadY,\n cx1: cx2 + bulgeX + spreadX,\n cy1: cy2 + bulgeY + spreadY,\n x1: p2x,\n y1: p2y\n }\n ];\n }\n}\nfunction nearerEnd(segments, to) {\n const start = segments[0];\n const end = segments.at(-1);\n return Math.hypot(start.x - to.x, start.y - to.y) < Math.hypot(end.x - to.x, end.y - to.y) ? \"start\" : \"end\";\n}\nfunction routedEdgeCurves(fromSegments, toSegments, route, sides) {\n const fromAttach = attachment(\n fromSegments,\n sides?.from ?? nearerEnd(fromSegments, route[0])\n );\n const toAttach = attachment(\n toSegments,\n sides?.to ?? nearerEnd(toSegments, route.at(-1))\n );\n const points = [fromAttach.at, ...route, toAttach.at];\n const tangent = (i) => {\n const p = points[i];\n const span = (q) => Math.hypot(q.x - p.x, q.y - p.y);\n const along = (inward, next) => {\n const len = inward ? span(inward) : 0;\n const reach = span(next);\n return len === 0 ? { x: next.x - p.x, y: next.y - p.y } : {\n x: (p.x - inward.x) / len * reach,\n y: (p.y - inward.y) / len * reach\n };\n };\n if (i === 0) {\n return along(fromAttach.inward, points[1]);\n }\n if (i === points.length - 1) {\n const out = along(toAttach.inward, points[i - 1]);\n return { x: -out.x, y: -out.y };\n }\n return {\n x: (points[i + 1].x - points[i - 1].x) / 2,\n y: (points[i + 1].y - points[i - 1].y) / 2\n };\n };\n const curves = [];\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i];\n const b = points[i + 1];\n const ta = tangent(i);\n const tb = tangent(i + 1);\n curves.push({\n x0: a.x,\n y0: a.y,\n cx0: a.x + ta.x / 3,\n cy0: a.y + ta.y / 3,\n cx1: b.x - tb.x / 3,\n cy1: b.y - tb.y / 3,\n x1: b.x,\n y1: b.y\n });\n }\n return curves;\n}\n\nexport {\n svgPath,\n projectLine,\n curvePointAt,\n curveMidpoint,\n curveBounds,\n dashCurves,\n dashSpans,\n slideAt,\n slideCurves,\n translateCurves,\n ownStrand,\n strandSides,\n bowAround,\n yToXOf,\n PATH_RIBBON_SPACING_PX,\n pathRibbonOffsets,\n polylinePx,\n selfLinkOf,\n edgeJoinOf,\n computeEdgeCurves,\n routedEdgeCurves\n};\n", "// src/util/weakMemo.ts\nfunction weakMemo() {\n const cache = /* @__PURE__ */ new WeakMap();\n return (key, deps, compute) => {\n const hit = cache.get(key);\n if (hit?.deps.length === deps.length && hit.deps.every((d, i) => Object.is(d, deps[i]))) {\n return hit.value;\n }\n const value = compute();\n cache.set(key, { deps, value });\n return value;\n };\n}\n\nexport {\n weakMemo\n};\n", "// src/overlayLabels.ts\nvar LABEL_PX = 11;\nvar LABEL_CHAR_PX = 6.2;\nvar LABEL_PAD = 4;\nfunction labelWidth(text) {\n return text.length * LABEL_CHAR_PX + LABEL_PAD * 2;\n}\nfunction overlaps(a, b) {\n return a.x0 < b.x1 && a.x1 > b.x0 && a.y0 < b.y1 && a.y1 > b.y0;\n}\nfunction offFrame(box, frame) {\n return box.x1 <= 0 || box.x0 >= frame.width || box.y1 <= 0 || box.y0 >= frame.height;\n}\nfunction insideFrame(box, frame) {\n return box.x0 >= 0 && box.x1 <= frame.width && box.y0 >= 0 && box.y1 <= frame.height;\n}\nfunction occupancy(frame, reserved = []) {\n const placed = [...reserved];\n return (box) => {\n if (offFrame(box, frame) || placed.some((p) => overlaps(p, box))) {\n return false;\n }\n placed.push(box);\n return true;\n };\n}\nfunction placeLabels(candidates, frame, take) {\n const out = [];\n const row = LABEL_PX + LABEL_PAD * 2;\n const stackFrom = (c, text, from, direction) => {\n const w = labelWidth(text);\n let crowded = false;\n for (let tries = 0; tries <= (c.stack ?? 0); tries++) {\n const y = from + direction * tries * row;\n const box = {\n x0: c.x - w / 2,\n x1: c.x + w / 2,\n y0: y - LABEL_PX - LABEL_PAD,\n y1: y + LABEL_PAD\n };\n if (offFrame(box, frame)) {\n break;\n }\n if (insideFrame(box, frame) && (c.fits?.(box) ?? true)) {\n if (take(box)) {\n return { placed: { ...c, text, y, w }, crowded };\n }\n crowded = true;\n }\n }\n return { placed: void 0, crowded };\n };\n const place = (c, text) => {\n const first = stackFrom(c, text, c.y, c.y > frame.height / 2 ? -1 : 1);\n return first.placed ?? (c.flipY === void 0 || first.crowded ? void 0 : stackFrom(c, text, c.flipY, c.flipY < c.y ? -1 : 1).placed);\n };\n for (const c of candidates) {\n const placed = place(c, c.text) ?? (c.fallback === void 0 ? void 0 : place(c, c.fallback));\n if (placed) {\n out.push(placed);\n }\n }\n return out;\n}\n\nexport {\n LABEL_PX,\n LABEL_CHAR_PX,\n LABEL_PAD,\n labelWidth,\n overlaps,\n occupancy,\n placeLabels\n};\n", "import {\n ownStrand,\n strandSides\n} from \"./chunk-JJV2GT2Z.js\";\nimport {\n pushTo\n} from \"./chunk-BSOZW3FC.js\";\nimport {\n isBackbone\n} from \"./chunk-RJWPJCIB.js\";\n\n// src/layout/mergeRuns.ts\nfunction flip(strand) {\n return strand === \"+\" ? \"-\" : \"+\";\n}\nfunction mergeRuns(graph, alone = /* @__PURE__ */ new Set()) {\n const sides = graph.edges.map(strandSides);\n const at = /* @__PURE__ */ new Map();\n const attach = (id, side, ei) => {\n pushTo(at, `${id}|${side}`, ei);\n };\n graph.edges.forEach((edge, ei) => {\n attach(edge.from, sides[ei].from, ei);\n attach(edge.to, sides[ei].to, ei);\n });\n const joinAfter = (a) => {\n const out = at.get(`${a}|end`);\n if (out?.length !== 1) {\n return void 0;\n }\n const ei = out[0];\n const edge = graph.edges[ei];\n return edge.from === a && edge.to !== a && !alone.has(a) && !alone.has(edge.to) && sides[ei].from === \"end\" && sides[ei].to === \"start\" && at.get(`${edge.to}|start`)?.length === 1 ? ei : void 0;\n };\n const joined = /* @__PURE__ */ new Set();\n const runOf = /* @__PURE__ */ new Map();\n const runs = /* @__PURE__ */ new Map();\n for (const node of graph.nodes) {\n const into = at.get(`${node.id}|start`);\n const pred = into?.length === 1 ? graph.edges[into[0]].from : void 0;\n if (runOf.has(node.id) || pred !== void 0 && joinAfter(pred) === into[0]) {\n continue;\n }\n const run = [node.id];\n for (; ; ) {\n const ei = joinAfter(run.at(-1));\n const next = ei === void 0 ? void 0 : graph.edges[ei].to;\n if (next === void 0 || runOf.has(next)) {\n break;\n }\n joined.add(ei);\n run.push(next);\n }\n for (const id of run) {\n runOf.set(id, node.id);\n }\n if (run.length > 1) {\n runs.set(node.id, run);\n }\n }\n for (const node of graph.nodes) {\n if (!runOf.has(node.id)) {\n runOf.set(node.id, node.id);\n }\n }\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const nodes = [];\n for (const node of graph.nodes) {\n if (runOf.get(node.id) !== node.id) {\n continue;\n }\n const run = runs.get(node.id);\n if (!run) {\n nodes.push(node);\n continue;\n }\n const members = run.map((id) => byId.get(id));\n const backbone = members.filter(isBackbone);\n const first = backbone.length ? backbone.reduce((a, b) => a.stable.start <= b.stable.start ? a : b) : members[0];\n nodes.push({\n id: node.id,\n name: node.name,\n length: members.reduce((sum, n) => sum + n.length, 0),\n depth: node.depth,\n stable: first.stable\n });\n }\n const seen = /* @__PURE__ */ new Set();\n const edges = [];\n graph.edges.forEach((edge, ei) => {\n const from = runOf.get(edge.from);\n const to = runOf.get(edge.to);\n const side = sides[ei];\n const key = `${from}|${side.from}>${to}|${side.to}`;\n if (joined.has(ei) || seen.has(key)) {\n return;\n }\n seen.add(key);\n edges.push({\n from,\n to,\n ...side.from === \"start\" ? { fromStrand: flip(ownStrand(from)) } : {},\n ...side.to === \"end\" ? { toStrand: flip(ownStrand(to)) } : {}\n });\n });\n return {\n graph: { ...graph, nodes, edges, paths: void 0, pathVisits: void 0 },\n runs\n };\n}\nfunction splitRuns(positions, runs, weightOf) {\n const out = { ...positions };\n for (const [id, members] of runs) {\n const line = positions[id];\n if (!line?.length) {\n continue;\n }\n delete out[id];\n const arc = arcPrefix(line);\n const total = arc.at(-1);\n const weights = members.map((m) => Math.max(weightOf(m), 0));\n const weightSum = weights.reduce((a, b) => a + b, 0);\n let from = 0;\n members.forEach((member, k) => {\n const share = weightSum ? weights[k] / weightSum * total : total / members.length;\n const to = k === members.length - 1 ? total : from + share;\n out[member] = slice(line, arc, from, to);\n from = to;\n });\n }\n return out;\n}\nfunction polylineSlice(line, from, to) {\n if (line.length === 0) {\n return [];\n }\n const arc = arcPrefix(line);\n const total = arc.at(-1);\n return slice(line, arc, from * total, to * total);\n}\nfunction polylineMidpoint(line) {\n const arc = arcPrefix(line);\n return pointAt(line, arc, arc.at(-1) / 2);\n}\nfunction arcPrefix(line) {\n const arc = [0];\n for (let i = 1; i < line.length; i++) {\n arc.push(\n arc[i - 1] + Math.hypot(line[i].x - line[i - 1].x, line[i].y - line[i - 1].y)\n );\n }\n return arc;\n}\nfunction firstReaching(arc, s) {\n let lo = 0;\n let hi = arc.length;\n while (lo < hi) {\n const mid = lo + hi >> 1;\n if (arc[mid] < s) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n return lo;\n}\nfunction pointAt(line, arc, s) {\n if (s <= 0) {\n return { ...line[0] };\n }\n const i = firstReaching(arc, s);\n if (i >= arc.length) {\n return { ...line.at(-1) };\n }\n const span = arc[i] - arc[i - 1];\n const t = span > 0 ? (s - arc[i - 1]) / span : 0;\n const a = line[i - 1];\n const b = line[i];\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n}\nfunction slice(line, arc, from, to) {\n const points = [pointAt(line, arc, from)];\n for (let i = firstReaching(arc, from); i < line.length && arc[i] < to; i++) {\n if (arc[i] > from) {\n points.push({ ...line[i] });\n }\n }\n points.push(pointAt(line, arc, to));\n return points;\n}\n\nexport {\n mergeRuns,\n splitRuns,\n polylineSlice,\n polylineMidpoint\n};\n", "import {\n pathOrigin,\n trimOrigins\n} from \"./chunk-BRH73RCH.js\";\nimport {\n PathVisitsBuilder\n} from \"./chunk-BEUTROKU.js\";\nimport {\n isBackbone,\n overlapsWindow\n} from \"./chunk-RJWPJCIB.js\";\n\n// src/layout/trimToWindow.ts\nfunction trimToWindow(graph, window) {\n const inWindow = new Set(\n graph.nodes.filter((n) => isBackbone(n) && overlapsWindow(n, window)).map((n) => n.id)\n );\n const paths = graph.paths ?? [];\n if (inWindow.size === 0 || paths.length === 0) {\n return graph;\n }\n const spans = paths.map((path) => {\n let first = -1;\n let last = -1;\n path.nodeIds.forEach((id, i) => {\n if (inWindow.has(id)) {\n if (first < 0) {\n first = i;\n }\n last = i;\n }\n });\n return first < 0 ? void 0 : { first, last };\n });\n if (spans.every(\n (span, i) => span?.first === 0 && span.last === paths[i].nodeIds.length - 1\n )) {\n return graph;\n }\n const kept = /* @__PURE__ */ new Set();\n const trimmed = [];\n const stretches = /* @__PURE__ */ new Map();\n paths.forEach((path, i) => {\n const span = spans[i];\n if (span) {\n const nodeIds = path.nodeIds.slice(span.first, span.last + 1);\n for (const id of nodeIds) {\n kept.add(id);\n }\n trimmed.push({ ...path, nodeIds });\n stretches.set(path.name, { first: span.first, nodeIds });\n }\n });\n return {\n ...graph,\n nodes: graph.nodes.filter((n) => kept.has(n.id)),\n edges: graph.edges.filter((e) => kept.has(e.from) && kept.has(e.to)),\n paths: trimmed,\n pathVisits: graph.pathVisits && trimVisits(\n graph.pathVisits,\n paths,\n spans,\n new Map(graph.nodes.map((n) => [n.id, n.name]))\n ),\n anchorPaths: trimOrigins(graph, stretches)\n };\n}\nfunction trimVisits(visits, paths, spans, nameOf) {\n const next = visits.replay();\n const out = new PathVisitsBuilder();\n paths.forEach((path, p) => {\n const origin = visits.pathIndex(pathOrigin(path.name).name);\n const span = spans[p];\n path.nodeIds.forEach((id, i) => {\n const segment = nameOf.get(id) ?? id;\n const at = next(visits.slot(segment), origin);\n if (at >= 0 && span && i >= span.first && i <= span.last) {\n out.add(\n segment,\n visits.paths[origin],\n visits.samples[origin],\n visits.start[at],\n visits.reversed[at] === 1\n );\n }\n });\n });\n return out.build();\n}\nfunction clipToWindow(graph, window, reachBp) {\n const nodes = graph.nodes.map((node) => {\n if (!isBackbone(node)) {\n return node;\n }\n const from = node.stable.start;\n const to = from + node.length;\n const [start, end] = overlapsWindow(node, window) ? [Math.max(from, window.start), Math.min(to, window.end)] : to <= window.start ? [Math.max(from, to - reachBp), to] : [from, Math.min(to, from + reachBp)];\n return start === from && end === to ? node : {\n ...node,\n length: end - start,\n stable: { ...node.stable, start },\n unclipped: { start: from, length: node.length }\n };\n });\n return nodes.some((node, i) => node !== graph.nodes[i]) ? { ...graph, nodes } : graph;\n}\nfunction unclipped(graph) {\n return graph.nodes.some((n) => n.unclipped) ? {\n ...graph,\n nodes: graph.nodes.map(\n ({ unclipped: full, ...node }) => full && node.stable ? {\n ...node,\n length: full.length,\n stable: { ...node.stable, start: full.start }\n } : node\n )\n } : graph;\n}\n\nexport {\n trimToWindow,\n clipToWindow,\n unclipped\n};\n", "import {\n unclipped\n} from \"./chunk-H4UHV22B.js\";\nimport {\n referenceVisitStarts\n} from \"./chunk-BRH73RCH.js\";\nimport {\n computeEdgeCurves,\n edgeJoinOf,\n routedEdgeCurves,\n strandSides\n} from \"./chunk-JJV2GT2Z.js\";\nimport {\n groupBy\n} from \"./chunk-BSOZW3FC.js\";\nimport {\n firstNodeAtOrAfter,\n isBackbone\n} from \"./chunk-RJWPJCIB.js\";\nimport {\n partitionPoint\n} from \"./chunk-HOAIOEI7.js\";\n\n// src/deletionEdges.ts\nvar MIN_DELETION_BP = 1;\nvar deletionKey = (reference) => `skips ${reference ?? \"the reference\"} sequence (a deletion)`;\nfunction bypassedPoints(nodePositions, bypassed) {\n return bypassed.flatMap((id) => nodePositions[id] ?? []);\n}\nfunction edgeCurvesOf(nodePositions, edge, axis, bypassed, route, stranded) {\n const from = nodePositions[edge.from];\n const to = nodePositions[edge.to];\n if (!from?.length || !to?.length) {\n return void 0;\n }\n return route ? routedEdgeCurves(\n from,\n to,\n route,\n stranded ? strandSides(edge) : void 0\n ) : computeEdgeCurves(\n from,\n to,\n edgeJoinOf(edge, stranded),\n axis,\n bypassed ? bypassedPoints(nodePositions, bypassed) : []\n );\n}\nfunction backboneBySequence(graph) {\n const bySequence = groupBy(\n graph.nodes.filter(isBackbone),\n (node) => node.stable.refName\n );\n for (const list of bySequence.values()) {\n list.sort((a, b) => a.stable.start - b.stable.start);\n }\n return bySequence;\n}\nfunction bypassedNodes(nodes, start, end) {\n const bypassed = [];\n if (nodes) {\n for (let i = firstNodeAtOrAfter(nodes, start); i < nodes.length; i++) {\n const node = nodes[i];\n if (node.stable.start >= end) {\n break;\n }\n if (node.stable.start + node.length <= end) {\n bypassed.push(node.id);\n }\n }\n }\n return bypassed;\n}\nfunction skipsBetween(edge, from, to, forwards) {\n const { fromStrand, toStrand } = edge;\n if (fromStrand === void 0 || toStrand === void 0) {\n return true;\n }\n const leavesRight = fromStrand === (from.stable.strand ?? \"+\");\n const arrivesLeft = toStrand === (to.stable.strand ?? \"+\");\n return forwards ? leavesRight && arrivesLeft : !leavesRight && !arrivesLeft;\n}\nfunction skippedSpan(edge, from, to, startsOf) {\n let best;\n for (const a of startsOf(from)) {\n for (const b of startsOf(to)) {\n const forwards = a <= b;\n const span = forwards ? { start: a + from.length, end: b } : { start: b + to.length, end: a };\n if (skipsBetween(edge, from, to, forwards) && (!best || Math.abs(span.end - span.start) < Math.abs(best.end - best.start))) {\n best = span;\n }\n }\n }\n return best;\n}\nvar COPY_SWITCH_SHARE = 0.01;\nfunction repeatCopies(backbone, startsOf) {\n const bySequence = /* @__PURE__ */ new Map();\n for (const [refName, nodes] of backbone) {\n const copies = nodes.flatMap((node) => {\n const starts = startsOf(node);\n return starts.slice(1).map((next, i) => ({\n at: starts[i],\n copy: next - starts[i]\n }));\n });\n if (copies.length) {\n bySequence.set(\n refName,\n copies.sort((a, b) => a.at - b.at)\n );\n }\n }\n return bySequence;\n}\nfunction switchesCopy(copies, start, bp) {\n if (!copies) {\n return false;\n }\n const i = partitionPoint(copies.length, (k) => copies[k].at < start);\n const near = [copies[i - 1], copies[i]].filter((c) => c !== void 0).sort((a, b) => Math.abs(a.at - start) - Math.abs(b.at - start))[0];\n return near !== void 0 && Math.abs(near.at - start) <= near.copy && Math.abs(bp - near.copy) <= near.copy * COPY_SWITCH_SHARE;\n}\nfunction deletionEdges(cut) {\n const graph = unclipped(cut);\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const backbone = backboneBySequence(graph);\n const startsOf = referenceVisitStarts(graph);\n const copies = repeatCopies(backbone, startsOf);\n const found = [];\n for (let edgeIndex = 0; edgeIndex < graph.edges.length; edgeIndex++) {\n const edge = graph.edges[edgeIndex];\n const from = byId.get(edge.from);\n const to = byId.get(edge.to);\n if (!edge.foldBridge && from !== void 0 && to !== void 0 && isBackbone(from) && isBackbone(to) && from.stable.refName === to.stable.refName) {\n const span = skippedSpan(edge, from, to, startsOf);\n const refName = from.stable.refName;\n const bp = span ? span.end - span.start : 0;\n if (span && bp >= MIN_DELETION_BP && !switchesCopy(copies.get(refName), span.start, bp)) {\n const { start, end } = span;\n found.push({\n edgeIndex,\n from: edge.from,\n to: edge.to,\n ...edge.fromStrand ? { fromStrand: edge.fromStrand } : {},\n ...edge.toStrand ? { toStrand: edge.toStrand } : {},\n refName,\n start,\n end,\n bp,\n bypassed: bypassedNodes(backbone.get(refName), start, end)\n });\n }\n }\n }\n return found;\n}\nfunction closableDeletions(graph, deletions) {\n const parent = /* @__PURE__ */ new Map();\n const root = (id) => {\n let r = id;\n while (parent.has(r)) {\n r = parent.get(r);\n }\n if (r !== id) {\n parent.set(id, r);\n }\n return r;\n };\n const join = (a, b) => {\n const [ra, rb] = [root(a), root(b)];\n if (ra !== rb) {\n parent.set(ra, rb);\n }\n return ra !== rb;\n };\n const candidates = new Set(deletions.map((d) => d.edgeIndex));\n graph.edges.forEach((e, ei) => {\n if (!candidates.has(ei)) {\n join(e.from, e.to);\n }\n });\n return new Set(\n deletions.filter((d) => !join(d.from, d.to)).map((d) => d.edgeIndex)\n );\n}\nfunction dashedDeletions(shown, lift) {\n return lift?.walks.length ? shown.filter((d) => !lift.edgeIndexes.has(d.edgeIndex)) : shown;\n}\nvar drawings = /* @__PURE__ */ new WeakMap();\nfunction deletionDrawing(graph, deletions, show = true) {\n let byShow = drawings.get(deletions);\n if (!byShow) {\n byShow = /* @__PURE__ */ new Map();\n drawings.set(deletions, byShow);\n }\n let drawing = byShow.get(show);\n if (!drawing) {\n const hidden = show ? /* @__PURE__ */ new Set() : closableDeletions(graph, deletions);\n drawing = {\n shown: deletions.filter((d) => !hidden.has(d.edgeIndex)),\n bypassed: new Map(deletions.map((d) => [d.edgeIndex, d.bypassed])),\n hidden\n };\n byShow.set(show, drawing);\n }\n return drawing;\n}\n\nexport {\n deletionKey,\n edgeCurvesOf,\n deletionEdges,\n closableDeletions,\n dashedDeletions,\n deletionDrawing\n};\n", "import {\n weakMemo\n} from \"./chunk-HMXCN6PG.js\";\nimport {\n labelWidth,\n occupancy\n} from \"./chunk-S43IBA5Y.js\";\nimport {\n polylineMidpoint\n} from \"./chunk-HNNP5QUN.js\";\nimport {\n edgeCurvesOf\n} from \"./chunk-ALGYCMMH.js\";\nimport {\n curveBounds,\n curveMidpoint,\n polylinePx\n} from \"./chunk-JJV2GT2Z.js\";\n\n// src/graphLabels.ts\nvar MIN_DELETION_LABEL_PX = 26;\nvar PX_PER_NODE_LABEL = 4e4;\nvar MIN_NODE_LABELS = 8;\nvar LEADER_GAP_PX = 8;\nvar LABEL_CHAR_PX = 5.7;\nvar LABEL_PAD_PX = 6;\nvar LABEL_HEIGHT_PX = 13;\nvar LABEL_GAP_PX = 3;\nvar MAX_LABEL_OVERHANG = 2;\nfunction labelHalfWidth(text) {\n return (text.length * LABEL_CHAR_PX + LABEL_PAD_PX + LABEL_GAP_PX) / 2;\n}\nvar LABEL_HALF_HEIGHT = (LABEL_HEIGHT_PX + LABEL_GAP_PX) / 2;\nvar MIN_LABEL_HALF_WIDTH = labelHalfWidth(\"1 bp\");\nfunction boxAt(halfW, x, y) {\n return {\n x0: x - halfW,\n x1: x + halfW,\n y0: y - LABEL_HALF_HEIGHT,\n y1: y + LABEL_HALF_HEIGHT\n };\n}\nfunction rowLabelBox(text, screenY) {\n return {\n x0: 6,\n x1: 6 + labelWidth(text) + LABEL_GAP_PX,\n y0: screenY - 8 - LABEL_GAP_PX / 2,\n y1: screenY + 8 + LABEL_GAP_PX / 2\n };\n}\nfunction clamp(v, lo, hi) {\n return hi < lo ? v : Math.min(Math.max(v, lo), hi);\n}\nfunction groupDigits(n) {\n return String(n).replace(/\\B(?=(\\d{3})+$)/g, \",\");\n}\nfunction formatBp(bp) {\n const [value, unit] = bp >= 999500 ? [bp / 1e6, \"Mb\"] : bp >= 1e3 ? [bp / 1e3, \"kb\"] : [];\n if (value === void 0) {\n return `${bp} bp`;\n }\n return `${+value.toFixed(value >= 100 ? 0 : 1)} ${unit}`;\n}\nfunction deletionText(bp) {\n return `${formatBp(bp)} del`;\n}\nfunction arcOutward(curves, apex, scaleX, scaleY) {\n const first = curves[0];\n const last = curves[curves.length - 1];\n const dx = (apex.x - (first.x0 + last.x1) / 2) * scaleX;\n const dy = (apex.y - (first.y0 + last.y1) / 2) * scaleY;\n const len = Math.hypot(dx, dy);\n return len === 0 ? { x: 0, y: -1 } : { x: dx / len, y: dy / len };\n}\nfunction boxSupport(box, dir) {\n return Math.abs(dir.x) * (box.x1 - box.x0) / 2 + Math.abs(dir.y) * (box.y1 - box.y0) / 2;\n}\nfunction boxRayCrossing(box, dir) {\n const halfW = (box.x1 - box.x0) / 2;\n const halfH = (box.y1 - box.y0) / 2;\n return Math.min(\n dir.x === 0 ? Infinity : halfW / Math.abs(dir.x),\n dir.y === 0 ? Infinity : halfH / Math.abs(dir.y)\n );\n}\nfunction runBounds(nodeIds, nodePositions) {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const id of nodeIds) {\n for (const p of nodePositions[id] ?? []) {\n minX = Math.min(minX, p.x);\n maxX = Math.max(maxX, p.x);\n minY = Math.min(minY, p.y);\n maxY = Math.max(maxY, p.y);\n }\n }\n return minX === Infinity ? void 0 : { minX, minY, maxX, maxY };\n}\nvar nodeOrderCache = weakMemo();\nfunction labelOrder(nodePositions, nodeLengths) {\n return nodeOrderCache(\n nodePositions,\n [nodeLengths],\n () => Object.entries(nodePositions).filter(([id, segments]) => segments.length > 0 && nodeLengths.has(id)).sort(([a], [b]) => nodeLengths.get(b) - nodeLengths.get(a))\n );\n}\nvar arcCache = weakMemo();\nfunction arcPlacements(nodePositions, deletions, axis, version, routes, stranded) {\n const { scaleX, scaleY } = axis;\n return arcCache(\n nodePositions,\n [deletions, routes, stranded, scaleX, scaleY, version],\n () => {\n const arcs = [];\n for (const deletion of [...deletions].sort((a, b) => b.bp - a.bp)) {\n const curves = edgeCurvesOf(\n nodePositions,\n deletion,\n axis,\n deletion.bypassed,\n routes?.[deletion.edgeIndex],\n stranded\n );\n const apex = curves ? curveMidpoint(curves) : void 0;\n if (curves && apex) {\n const { minX, minY, maxX, maxY } = curveBounds(curves);\n arcs.push({\n deletion,\n curves,\n apex,\n // in screen px, so the two axes' units cannot be added by accident\n extent: Math.max((maxX - minX) * scaleX, (maxY - minY) * scaleY)\n });\n }\n }\n return arcs;\n }\n );\n}\nfunction sizeLabelCandidates({\n nodePositions,\n nodeLengths,\n deletions,\n deletionRoutes,\n stranded = false,\n alleleDeletions,\n axis,\n translateX,\n translateY,\n width,\n height,\n version = 0\n}) {\n const { scaleX, scaleY } = axis;\n const deletionCandidates = [];\n const nodeCandidates = [];\n for (const { deletion, curves, apex, extent } of arcPlacements(\n nodePositions,\n deletions,\n axis,\n version,\n deletionRoutes,\n stranded\n )) {\n if (extent >= MIN_DELETION_LABEL_PX) {\n const text = deletionText(deletion.bp);\n const halfW = labelHalfWidth(text);\n const box = boxAt(halfW, 0, 0);\n const arcX = apex.x * scaleX + translateX;\n const arcY = apex.y * scaleY + translateY;\n if (arcX < 0 || arcX > width || arcY < 0 || arcY > height) {\n continue;\n }\n const fits = extent >= halfW * 2 / MAX_LABEL_OVERHANG;\n const bow = arcOutward(curves, apex, scaleX, scaleY);\n const offset = boxSupport(box, bow) + LEADER_GAP_PX;\n const x = fits ? arcX : clamp(arcX + bow.x * offset, halfW, width - halfW);\n const y = fits ? arcY : clamp(\n arcY + bow.y * offset,\n LABEL_HALF_HEIGHT,\n height - LABEL_HALF_HEIGHT\n );\n const away = Math.hypot(x - arcX, y - arcY);\n let leader;\n if (away > 0) {\n const dir = { x: (x - arcX) / away, y: (y - arcY) / away };\n const crossing = boxRayCrossing(box, dir);\n leader = {\n arcX,\n arcY,\n labelX: x - dir.x * crossing,\n labelY: y - dir.y * crossing\n };\n }\n deletionCandidates.push({\n label: {\n key: `del:${deletion.edgeIndex}`,\n text,\n x,\n y,\n kind: \"deletion\",\n leader\n },\n box: boxAt(halfW, x, y)\n });\n }\n }\n const labelledByDeletion = /* @__PURE__ */ new Set();\n const alleleRuns = [...alleleDeletions ?? []].sort((a, b) => b.bp - a.bp);\n for (const run of alleleRuns) {\n const drawn = runBounds(run.nodeIds, nodePositions);\n if (!drawn) {\n continue;\n }\n const shownLeft = Math.max(drawn.minX * scaleX + translateX, 0);\n const shownRight = Math.min(drawn.maxX * scaleX + translateX, width);\n const shownTop = Math.max(drawn.minY * scaleY + translateY, 0);\n const shownBottom = Math.min(drawn.maxY * scaleY + translateY, height);\n if (shownRight < shownLeft || shownBottom < shownTop) {\n continue;\n }\n const extent = Math.max(shownRight - shownLeft, shownBottom - shownTop);\n const text = deletionText(run.bp);\n const halfW = labelHalfWidth(text);\n if (extent >= halfW * 2 / MAX_LABEL_OVERHANG) {\n for (const id of run.nodeIds) {\n labelledByDeletion.add(id);\n }\n const x = clamp((shownLeft + shownRight) / 2, halfW, width - halfW);\n const y = clamp(\n (shownTop + shownBottom) / 2,\n LABEL_HALF_HEIGHT,\n height - LABEL_HALF_HEIGHT\n );\n deletionCandidates.push({\n label: {\n key: `alleledel:${run.nodeIds.join(\",\")}`,\n text,\n x,\n y,\n kind: \"deletion\"\n },\n box: boxAt(halfW, x, y)\n });\n }\n }\n for (const [id, segments] of labelOrder(nodePositions, nodeLengths)) {\n if (labelledByDeletion.has(id)) {\n continue;\n }\n const { x, y } = polylineMidpoint(segments);\n const screenY = y * scaleY + translateY;\n if (screenY + LABEL_HALF_HEIGHT <= 0 || screenY - LABEL_HALF_HEIGHT >= height) {\n continue;\n }\n const drawn = polylinePx(segments, scaleX, scaleY);\n if (drawn < MIN_LABEL_HALF_WIDTH * 2 / MAX_LABEL_OVERHANG) {\n continue;\n }\n const text = formatBp(nodeLengths.get(id));\n const halfW = labelHalfWidth(text);\n if (drawn >= halfW * 2 / MAX_LABEL_OVERHANG) {\n const screenX = x * scaleX + translateX;\n nodeCandidates.push({\n label: {\n key: `node:${id}`,\n text,\n x: screenX,\n y: screenY,\n kind: \"node\"\n },\n box: boxAt(halfW, screenX, screenY)\n });\n }\n }\n return { deletions: deletionCandidates, nodes: nodeCandidates };\n}\nfunction nodeLabelBudget(width, height) {\n return Math.max(\n MIN_NODE_LABELS,\n Math.floor(width * height / PX_PER_NODE_LABEL)\n );\n}\nfunction placeSizeLabels(candidates, take, budget = Infinity) {\n const labels = [];\n for (const { label, box } of candidates) {\n if (labels.length >= budget) {\n break;\n }\n if (take(box)) {\n labels.push(label);\n }\n }\n return labels;\n}\nfunction graphLabels({\n reserved,\n take,\n ...args\n}) {\n take ??= occupancy(args, reserved);\n const { deletions, nodes } = sizeLabelCandidates(args);\n return [\n ...placeSizeLabels(deletions, take),\n ...placeSizeLabels(nodes, take, nodeLabelBudget(args.width, args.height))\n ];\n}\n\nexport {\n rowLabelBox,\n groupDigits,\n formatBp,\n sizeLabelCandidates,\n nodeLabelBudget,\n placeSizeLabels,\n graphLabels\n};\n", "import {\n groupDigits\n} from \"./chunk-OPTHW6IZ.js\";\nimport {\n pathOrigin\n} from \"./chunk-BRH73RCH.js\";\nimport {\n isGenericSample\n} from \"./chunk-2JL2JVZ2.js\";\n\n// src/pathColors.ts\nfunction nameHue(name) {\n let hash = 0;\n for (let i = 0; i < name.length; i++) {\n hash = name.charCodeAt(i) + ((hash << 5) - hash);\n }\n return Math.abs(hash % 360);\n}\nfunction pathHueAt(index, count) {\n return index * 360 / count;\n}\nvar PATH_SATURATION = 0.7;\nvar PATH_LIGHTNESS = 0.5;\nvar MAX_PATH_COLORS = 16;\nfunction pathColorsLegible(pathCount) {\n return pathCount > 0 && pathCount <= MAX_PATH_COLORS;\n}\nfunction pathCssColor(index, count) {\n return `hsl(${pathHueAt(index, count)}, ${PATH_SATURATION * 100}%, ${PATH_LIGHTNESS * 100}%)`;\n}\nfunction pathGreyCssColor(index, count) {\n const lightness = count > 1 ? 25 + 45 * index / (count - 1) : 45;\n return `hsl(0, 0%, ${lightness}%)`;\n}\nfunction labelTiers(name) {\n const parts = pathOrigin(name).name.split(\"#\");\n const full = parts.join(\"#\");\n if (parts.length >= 3 && isGenericSample(parts[0])) {\n const contig = parts.slice(2).join(\"#\");\n return [contig, contig, full];\n }\n return [parts[0], parts.slice(0, 2).join(\"#\"), full];\n}\nfunction offsetTiers(name, tiers) {\n const { start } = pathOrigin(name);\n return tiers.map((t) => `${t} @${groupDigits(start)}`);\n}\nfunction pathLegend(paths, colors) {\n const firstOf = /* @__PURE__ */ new Map();\n paths.forEach((path, i) => {\n if (!firstOf.has(path.name)) {\n firstOf.set(path.name, i);\n }\n });\n const entries = [...firstOf].map(([name2, i]) => ({ name: name2, i }));\n const named = entries.map((e) => labelTiers(e.name));\n const name = (t) => entries.map((_, k) => named[k][t]);\n const offset = (t) => entries.map((e, k) => offsetTiers(e.name, named[k])[t]);\n const candidates = [\n name(0),\n name(1),\n offset(0),\n name(2),\n offset(1),\n offset(2)\n ];\n const distinct = candidates.find(\n (labels2) => new Set(labels2).size === entries.length\n );\n const labels = distinct ?? candidates.at(-1);\n return entries.map(({ name: name2, i }, k) => ({\n name: name2,\n label: labels[k],\n color: colors?.[i] ?? pathCssColor(i, paths.length)\n }));\n}\nfunction walkLabelsOf(entries) {\n const seen = /* @__PURE__ */ new Map();\n return new Map(\n [...entries].sort((a, b) => a.label.localeCompare(b.label)).map((e) => {\n const n = (seen.get(e.label) ?? 0) + 1;\n seen.set(e.label, n);\n return [e.name, n > 1 ? `${e.label} (${n})` : e.label];\n })\n );\n}\n\nexport {\n nameHue,\n pathHueAt,\n PATH_SATURATION,\n PATH_LIGHTNESS,\n MAX_PATH_COLORS,\n pathColorsLegible,\n pathCssColor,\n pathGreyCssColor,\n pathLegend,\n walkLabelsOf\n};\n", "import {\n panSNHaplotype\n} from \"./chunk-2JL2JVZ2.js\";\n\n// src/nodeWidths.ts\nvar NODE_WIDTHS = [\n {\n value: \"depth\",\n label: \"By depth\",\n description: \"Thicker the more paths carry a node, on the square root of its depth against the mean. A graph with one depth everywhere draws uniform.\"\n },\n {\n value: \"frequency\",\n label: \"By frequency\",\n description: \"As wide as the share of haplotypes that pass a node, or its AF tag: full width at 100%, half at 50%, and wider where a haplotype passes it more than once.\"\n },\n {\n value: \"uniform\",\n label: \"Uniform\",\n description: \"Every node the same thickness.\"\n }\n];\nvar MIN_FACTOR = 0.3;\nvar MAX_FACTOR = 3;\nvar MIN_FREQUENCY_FACTOR = 0.05;\nfunction meanDepth(graph) {\n let weighted = 0;\n let length = 0;\n for (const node of graph.nodes) {\n weighted += node.depth * node.length;\n length += node.length;\n }\n return length > 0 ? weighted / length : 0;\n}\nfunction haplotypeOf(path) {\n return path.sample === void 0 ? panSNHaplotype(path.name) ?? path.name : `${path.sample}#${path.haplotype ?? 0}`;\n}\nfunction haplotypeCount(graph) {\n return new Set((graph.paths ?? []).map(haplotypeOf)).size;\n}\nfunction nodeFrequency(node, haplotypes) {\n return node.frequency ?? (haplotypes > 0 ? node.depth / haplotypes : void 0);\n}\nfunction withFrequencies(graph, frequencies) {\n if (!frequencies) {\n return graph;\n }\n const nodes = graph.nodes.map((node) => {\n const frequency = frequencies[node.name];\n return frequency === void 0 ? node : { ...node, frequency };\n });\n return { ...graph, nodes };\n}\nfunction widthNorm(graph, nodeWidth) {\n return nodeWidth === \"depth\" ? meanDepth(graph) : nodeWidth === \"frequency\" ? haplotypeCount(graph) : 0;\n}\nfunction frequencyFactor(f) {\n return Math.min(MAX_FACTOR, Math.max(MIN_FREQUENCY_FACTOR, f));\n}\nfunction frequencyWidthFactor(node, haplotypes) {\n const f = nodeFrequency(node, haplotypes);\n return f === void 0 ? 1 : frequencyFactor(f);\n}\nfunction frequencyKey(contigThickness) {\n return [1, 0.5, 0.1].map((f) => ({\n label: `${f * 100}%`,\n widthPx: contigThickness * frequencyFactor(f)\n }));\n}\nfunction depthWidthFactor(node, mean) {\n if (!(mean > 0) || !(node.depth > 0)) {\n return 1;\n }\n return Math.min(\n MAX_FACTOR,\n Math.max(MIN_FACTOR, Math.sqrt(node.depth / mean))\n );\n}\nfunction nodeWidthPx(node, contigThickness, nodeWidth, norm) {\n return contigThickness * (nodeWidth === \"depth\" ? depthWidthFactor(node, norm) : nodeWidth === \"frequency\" ? frequencyWidthFactor(node, norm) : 1);\n}\nfunction maxNodeWidthPx(contigThickness, nodeWidth) {\n return contigThickness * (nodeWidth === \"uniform\" ? 1 : MAX_FACTOR);\n}\nvar MIN_WALK_LANE_PX = 4;\nfunction walkLaneWidthPx(width, lanes) {\n return Math.max(width / lanes, MIN_WALK_LANE_PX);\n}\nfunction nodeInk(graph, nodeById, contigThickness, nodeWidth, lanes = 0) {\n const norm = graph ? widthNorm(graph, nodeWidth) : 0;\n const reach = (width) => lanes > 0 ? walkLaneWidthPx(width, lanes) * lanes / 2 : width / 2;\n return {\n maxHalfWidthPx: reach(maxNodeWidthPx(contigThickness, nodeWidth)),\n halfWidthPx: (id) => {\n const node = nodeById?.get(id);\n return reach(\n node ? nodeWidthPx(node, contigThickness, nodeWidth, norm) : contigThickness\n );\n }\n };\n}\n\nexport {\n NODE_WIDTHS,\n meanDepth,\n haplotypeCount,\n nodeFrequency,\n withFrequencies,\n widthNorm,\n frequencyKey,\n nodeWidthPx,\n maxNodeWidthPx,\n walkLaneWidthPx,\n nodeInk\n};\n", "// src/edgeWidths.ts\nvar EDGE_WIDTHS = [\n {\n value: \"uniform\",\n label: \"Uniform\",\n description: \"Every link the same thickness.\"\n },\n {\n value: \"walks\",\n label: \"By walks\",\n description: \"Thicker the more walks take a link, on the square root of its count against the busiest link in the cut. A graph without walks draws uniform.\"\n }\n];\nvar MIN_FACTOR = 0.5;\nvar MAX_FACTOR = 4;\nfunction busiestEdge(graph) {\n let most = 0;\n for (const edge of graph.edges) {\n most = Math.max(most, edge.pathIds?.length ?? 0);\n }\n return most;\n}\nfunction edgeWidthFactor(walks, busiest, edgeWidth) {\n if (edgeWidth === \"uniform\" || busiest === 0) {\n return 1;\n }\n return MIN_FACTOR + (MAX_FACTOR - MIN_FACTOR) * Math.sqrt(walks / busiest);\n}\n\nexport {\n EDGE_WIDTHS,\n busiestEdge,\n edgeWidthFactor\n};\n"],
|
|
5
|
+
"mappings": "+JACA,IAAIA,GAAgB,GCIpB,SAASC,GAAQC,EAAQ,CACvB,IAAMC,EAASC,GAAM,KAAK,MAAMA,EAAI,GAAG,EAAI,IAC3C,OAAOF,EAAO,IAAI,CAACG,EAAGC,IAAM,GAAGA,EAAI,IAAM,GAAG,GAAGH,EAAME,EAAE,CAAC,CAAC,IAAIF,EAAME,EAAE,CAAC,CAA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AUC,EAAOC,CAAS,EAAI,EAC7CyB,EAASJ,GAAUC,EAAQ,EAAIF,GAAgBC,EAAOC,CAAK,EAAIA,EAAQ,EAAID,EAAQ,EACzF,MAAO,CACL,eAAgBI,EAAMP,GAAeN,EAAiBZ,CAAS,CAAC,EAChE,YAAc0B,GAAO,CACnB,IAAMlB,EAAOgB,GAAU,IAAIE,CAAE,EAC7B,OAAOD,EACLjB,EAAOQ,GAAYR,EAAMI,EAAiBZ,EAAWiB,CAAI,EAAIL,CAC/D,CACF,CACF,CACF,CCnGA,IAAIe,GAAc,CAChB,CACE,MAAO,UACP,MAAO,UACP,YAAa,gCACf,EACA,CACE,MAAO,QACP,MAAO,WACP,YAAa,+IACf,CACF,EACIC,GAAa,GACbC,GAAa,EACjB,SAASC,GAAYC,EAAO,CAC1B,IAAIC,EAAO,EACX,QAAWC,KAAQF,EAAM,MACvBC,EAAO,KAAK,IAAIA,EAAMC,EAAK,SAAS,QAAU,CAAC,EAEjD,OAAOD,CACT,CACA,SAASE,GAAgBC,EAAOC,EAASC,EAAW,CAClD,OAAIA,IAAc,WAAaD,IAAY,EAClC,EAEFR,IAAcC,GAAaD,IAAc,KAAK,KAAKO,EAAQC,CAAO,CAC3E",
|
|
6
|
+
"names": ["ROW_HEIGHT_PX", "svgPath", "points", "round", "v", "p", "i", "projectLine", "x1", "y1", "x2", "y2", "distance", "d", "vx", "vy", "curvePointAt", "c", "t", "u", "a", "b", "e", "curveMidpoint", "curves", "mid", "curveBounds", "minX", "minY", "maxX", "maxY", "subCurve", "t0", "t1", "p0", "p1", "dt", "d0", "curveTangentAt", "d1", "VISIBLE_SAMPLES", "visibleStretches", "lengths", "bounds", "yToX", "stretches", "start", "k", "length", "pad", "last", "next", "from", "to", "prev", "dashSpans", "curves", "dashWorld", "yToX", "bounds", "lengths", "c", "total", "a", "b", "periods", "spans", "stretches", "visibleStretches", "seen", "out", "i", "from", "to", "dash", "along", "start", "k", "length", "end", "t0", "t1", "subCurve", "slideCurves", "curves", "fromDx", "fromDy", "toDx", "toDy", "n", "out", "i", "c", "a", "b", "adx", "ady", "bdx", "bdy", "translateCurves", "dx", "dy", "attachment", "segments", "side", "last", "TANGENT_SPAN_FACTOR", "MAX_TANGENT", "ownStrand", "id", "strandSides", "edge", "own", "strand", "spanOf", "min", "max", "s", "distanceToSpan", "x", "span", "facingSide", "other", "tieBreak", "startGap", "endGap", "facingSides", "fromSegments", "toSegments", "laidSides", "heldFacingSides", "byTo", "sides", "APEX_FRACTION", "BOW_CLEARANCE", "ALONG_FRACTION", "MAX_ROW_BOW_PX", "ROW_HEIGHT_PX", "bowAround", "p1x", "p1y", "p2x", "p2y", "toward", "maxBow", "chord", "ux", "uy", "reach", "minAlong", "maxAlong", "p", "perp", "along", "uncapped", "size", "yToXOf", "scaleX", "scaleY", "PATH_RIBBON_SPACING_PX", "drawnDirection", "yToX", "len", "pathRibbonOffsets", "count", "axis", "spacing", "dir", "offsets", "distance", "scaleYOf", "points", "unscaleYOf", "polylinePx", "total", "SELF_LOOP_MIN_PX", "SELF_LOOP_MAX_PX", "selfLoopReach", "scale", "nodePx", "selfLinkOf", "edgeJoinOf", "stranded", "self", "hairpinCurves", "attach", "at", "inward", "px", "py", "nearX", "nearY", "apexX", "apexY", "sideX", "sideY", "computeEdgeCurves", "join", "bypassed", "maxBowIn", "loop", "fromAttach", "toAttach", "fromEnd", "toStart", "segDirX", "segDirY", "ext", "perpX", "perpY", "midX", "midY", "cp1x", "cp1y", "cp2x", "cp2y", "fromPrev", "toNext", "dist", "tangentProj", "prev", "towardX", "towardY", "towardToX", "towardToY", "cx1", "cy1", "projectLine", "cx2", "cy2", "bulge", "chordLen", "bulgeX", "bulgeY", "spreadX", "spreadY", "nearerEnd", "to", "start", "end", "routedEdgeCurves", "route", "tangent", "q", "next", "ta", "tb", "weakMemo", "cache", "key", "deps", "compute", "hit", "d", "i", "value", "LABEL_PX", "LABEL_CHAR_PX", "LABEL_PAD", "labelWidth", "text", "overlaps", "a", "b", "offFrame", "box", "frame", "insideFrame", "occupancy", "reserved", "placed", "p", "placeLabels", "candidates", "take", "out", "row", "stackFrom", "from", "direction", "w", "crowded", "tries", "y", "place", "first", "flip", "strand", "mergeRuns", "graph", "alone", "sides", "strandSides", "at", "attach", "id", "side", "ei", "pushTo", "edge", "joinAfter", "a", "out", "joined", "runOf", "runs", "node", "into", "pred", "run", "next", "byId", "n", "nodes", "members", "backbone", "isBackbone", "first", "b", "sum", "seen", "edges", "from", "to", "key", "ownStrand", "splitRuns", "positions", "weightOf", "line", "arc", "arcPrefix", "total", "weights", "m", "weightSum", "member", "k", "share", "slice", "polylineSlice", "polylineMidpoint", "pointAt", "i", "firstReaching", "s", "lo", "hi", "mid", "span", "t", "points", "trimToWindow", "graph", "window", "inWindow", "n", "isBackbone", "overlapsWindow", "paths", "spans", "path", "first", "last", "id", "i", "span", "kept", "trimmed", "stretches", "nodeIds", "e", "trimVisits", "trimOrigins", "visits", "nameOf", "next", "out", "PathVisitsBuilder", "p", "origin", "pathOrigin", "segment", "at", "clipToWindow", "reachBp", "nodes", "node", "from", "to", "start", "end", "unclipped", "full", "MIN_DELETION_BP", "deletionKey", "reference", "bypassedPoints", "nodePositions", "bypassed", "id", "edgeCurvesOf", "edge", "axis", "route", "stranded", "from", "to", "routedEdgeCurves", "strandSides", "computeEdgeCurves", "edgeJoinOf", "backboneBySequence", "graph", "bySequence", "groupBy", "isBackbone", "node", "list", "a", "b", "bypassedNodes", "nodes", "start", "end", "i", "firstNodeAtOrAfter", "skipsBetween", "forwards", "fromStrand", "toStrand", "leavesRight", "arrivesLeft", "skippedSpan", "startsOf", "best", "span", "COPY_SWITCH_SHARE", "repeatCopies", "backbone", "refName", "copies", "starts", "next", "switchesCopy", "bp", "partitionPoint", "k", "near", "c", "deletionEdges", "cut", "unclipped", "byId", "n", "referenceVisitStarts", "found", "edgeIndex", "closableDeletions", "deletions", "parent", "root", "r", "join", "ra", "rb", "candidates", "d", "e", "ei", "dashedDeletions", "shown", "lift", "drawings", "deletionDrawing", "show", "byShow", "drawing", "hidden", "MIN_DELETION_LABEL_PX", "PX_PER_NODE_LABEL", "MIN_NODE_LABELS", "LEADER_GAP_PX", "LABEL_CHAR_PX", "LABEL_PAD_PX", "LABEL_HEIGHT_PX", "LABEL_GAP_PX", "MAX_LABEL_OVERHANG", "labelHalfWidth", "text", "LABEL_HALF_HEIGHT", "MIN_LABEL_HALF_WIDTH", "boxAt", "halfW", "x", "y", "rowLabelBox", "screenY", "labelWidth", "clamp", "v", "lo", "hi", "groupDigits", "n", "formatBp", "bp", "value", "unit", "deletionText", "arcOutward", "curves", "apex", "scaleX", "scaleY", "first", "last", "dx", "dy", "len", "boxSupport", "box", "dir", "boxRayCrossing", "halfH", "runBounds", "nodeIds", "nodePositions", "minX", "minY", "maxX", "maxY", "id", "p", "nodeOrderCache", "weakMemo", "labelOrder", "nodeLengths", "segments", "a", "b", "arcCache", "arcPlacements", "deletions", "axis", "version", "routes", "stranded", "arcs", "deletion", "edgeCurvesOf", "curveMidpoint", "curveBounds", "sizeLabelCandidates", "deletionRoutes", "alleleDeletions", "translateX", "translateY", "width", "height", "deletionCandidates", "nodeCandidates", "extent", "arcX", "arcY", "fits", "bow", "offset", "away", "leader", "crossing", "labelledByDeletion", "alleleRuns", "run", "drawn", "shownLeft", "shownRight", "shownTop", "shownBottom", "polylineMidpoint", "polylinePx", "screenX", "nodeLabelBudget", "placeSizeLabels", "candidates", "take", "budget", "labels", "label", "graphLabels", "reserved", "args", "occupancy", "nodes", "nameHue", "name", "hash", "i", "pathHueAt", "index", "count", "PATH_SATURATION", "PATH_LIGHTNESS", "MAX_PATH_COLORS", "pathColorsLegible", "pathCount", "pathCssColor", "pathGreyCssColor", "labelTiers", "parts", "pathOrigin", "full", "isGenericSample", "contig", "offsetTiers", "tiers", "start", "t", "groupDigits", "pathLegend", "paths", "colors", "firstOf", "path", "entries", "name2", "named", "e", "_", "k", "offset", "candidates", "labels", "labels2", "walkLabelsOf", "seen", "a", "b", "n", "NODE_WIDTHS", "MIN_FACTOR", "MAX_FACTOR", "MIN_FREQUENCY_FACTOR", "meanDepth", "graph", "weighted", "length", "node", "haplotypeOf", "path", "panSNHaplotype", "haplotypeCount", "nodeFrequency", "haplotypes", "widthNorm", "graph", "nodeWidth", "meanDepth", "haplotypeCount", "frequencyFactor", "f", "MAX_FACTOR", "MIN_FREQUENCY_FACTOR", "frequencyWidthFactor", "node", "haplotypes", "nodeFrequency", "frequencyKey", "contigThickness", "depthWidthFactor", "mean", "MIN_FACTOR", "nodeWidthPx", "norm", "maxNodeWidthPx", "MIN_WALK_LANE_PX", "walkLaneWidthPx", "width", "lanes", "nodeInk", "nodeById", "reach", "id", "EDGE_WIDTHS", "MIN_FACTOR", "MAX_FACTOR", "busiestEdge", "graph", "most", "edge", "edgeWidthFactor", "walks", "busiest", "edgeWidth"]
|
|
7
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ce,b as N,c as Ee,d as Q,e as ee,f as Ft,g as Ue,h as We,i as qt,j as zt,k as He,l as Oe,m as Pe,n as Dt,o as jt,p as Ut,q as Wt,r as Vt}from"./chunk-M2D7NUOY.js";import{a as _t,g as Tt}from"./chunk-B6YUND32.js";import{c as Ot}from"./chunk-ELO4G2TG.js";import{a as Ct,g as Bt}from"./chunk-CCPRHM4X.js";var Ln=4096;function pt(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ln?n[1]=t:e.push([t,t])}return e}var Hn=32768,Gt={mostChosenPaths:32},lt=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},re=class extends Error{};function Ve(a,e,t,n){return a==="forward"?e+t:e-n}function Qt(a,e,t,n){return a==="forward"?e-n:e+t}function Kt(a){return Pe(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function Ce(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Zt(a){let{db:e,records:t,signal:n}=a,s=performance.now(),o=()=>{let w=performance.now(),S=w-s;return s=w,S},r={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(w,S)=>{let A=`${w}: ${S}`;r.walks[A]=(r.walks[A]??0)+1},h=await e.haplotypeSampleInterval()??4096,c=new Map,d=async w=>{let S=t.get(w)??c.get(w);if(S)return S;let A=await e.getRecord(w);if(r.graphFetches+=1,!A)throw new Error(`Node record ${w} is missing from the database`);return c.set(w,A),A},f=w=>t.get(w).sequenceLen,p=await e.pathsByHandle(),y=w=>{let S=p.get(w);return S!==void 0&&a.keep(S.name)},g=[],l=new lt,b=new Map,x=new Set,P=new Set,E=async w=>{let S=(await d(w.node)).gbwt().lf(w.offset);return S===void 0||S.node===0?void 0:S},R=async(w,S)=>{let A=(await d(ee(w.node))).gbwt().predecessorAt(w.offset);if(A===void 0||S!==void 0&&!S.has(A))return;let M=(await d(A)).gbwt().offsetTo(w);if(M===void 0)throw new Error(`No offset in ${A} leads to ${w.node}:${w.offset}`);return{node:A,offset:M}},m=(w,S,A,M)=>{let B=A.map(W=>W.pos.node),U=A.map(W=>W.pos.offset),J=0;for(let W of B)J+=f(W);let O=S==="forward"?A[0].left:A[A.length-1].left,L=g.length;g.push({pathHandle:w,orientation:S,handles:B,offsets:U,len:J,hapStart:O,hapEnd:O+J,canonical:Pe(B[0],B[B.length-1]),source:M});for(let W of A)l.set(W.pos,L);let G=b.get(w);return G?G.push(L):b.set(w,[L]),L},I=async(w,S,A,M)=>{let B=[],U=w;for(;;){n?.throwIfAborted();let O=await R(U.pos,t);if(!O)break;U={pos:O,left:Qt(A,U.left,f(U.pos.node),f(O.node))},B.push(U)}B.reverse();let J=[w];for(U=w;;){n?.throwIfAborted();let O=await E(U.pos);if(!O||!t.has(O.node))break;U={pos:O,left:Ve(A,U.left,f(U.pos.node),f(O.node))},J.push(U)}return m(S,A,[...B,...J],M)},$=async(w,S,A,M)=>g[l.get(w.pos)??await I(w,S,A,M)],F=w=>{let S=w.handles[w.handles.length-1];return{pos:{node:S,offset:w.offsets[w.offsets.length-1]},left:w.orientation==="forward"?w.hapEnd-f(S):w.hapStart}},_=w=>{let S=w.handles[0];return{pos:{node:S,offset:w.offsets[0]},left:w.orientation==="forward"?w.hapStart:w.hapEnd-f(S)}},D=await I({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),C=g[D],H=()=>{if(r.fallback!==void 0)return{reference:C,pieces:[],stats:r};let w=new Map;g.forEach((A,M)=>{M!==D&&w.set(Ce(A),[...w.get(Ce(A))??[],A])});let S=[];for(let A of w.values()){let M=new Set;for(let B of A)B.canonical&&!M.has(B.orientation)&&(M.add(B.orientation),S.push(B),r.sources[B.source]+=1)}return r.sources.reference=1,r.pieces=S.length+1,{reference:C,pieces:S,stats:r}},k=async(w,S)=>{let A=S?x:P,M=S?P:x,B=w;for(;;){if(A.has(B))return;A.add(B);let U=g[B],J=S?F(U):_(U),O=0,L;for(;L===void 0;){n?.throwIfAborted();let G=S?await E(J.pos):await R(J.pos);if(!G){L="endmarker";break}let W=(await d(J.pos.node)).sequenceLen,ue=(await d(G.node)).sequenceLen,se=S?Ve(U.orientation,J.left,W,ue):Qt(U.orientation,J.left,W,ue);if(t.has(G.node)){let Y=l.get(G);Y===void 0?(B=await I({pos:G,left:se},U.pathHandle,U.orientation,"chain"),M.add(B),L="landed"):(M.add(Y),L="merge")}else O>Hn?L="bound":(O+=ue,J={pos:G,left:se})}if(i("chain",L),L!=="landed")return}},j=async w=>{if(a.context>w.context)throw new re(`the context of ${a.context} bp exceeds the ${w.context} bp the haplotype index's stray rows cover`);let S=r.spacing;if(S===void 0)throw new re("the haplotype index has no anchors");let{bin:A,bound:M}=w,{fills:B,inserted:U}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new re("the haplotype index's stray rows cover contained snarls only");for(let u of B){if(u.inserted>0&&u.low===u.high)throw new re(`the haplotype index's stray rows leave out the snarl bounded by node ${u.low} at both ends`);if(u.inserted>0&&(w.snarlNodes===void 0||u.nodes>w.snarlNodes))throw new re(w.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${u.nodes} nodes exceeds the ${w.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(a.window.start/A),O=Math.floor((a.window.end-1)/A),L=J*A,G=(O+1)*A,W=new Map,ue=async(u,v)=>{let z=await e.haplotypeAnchorsBetween(a.referenceHandle,u*S,v*S);for(let T of z)W.set(T.anchorOffset/S,T)},se=Math.max(0,Math.floor((L-M)/S)-1),Y=Math.ceil((G+M)/S)+1,[{listed:De,strays:ae}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,J,O),ue(se,Y)]);for(let u of t.keys()){let v=N(u);if(!Q(u)&&!De(v)&&!U.has(v))throw new re(`the haplotype index lists node ${v} of the subgraph in no bin that the window touches`)}r.scans=pt([...t.keys()].sort((u,v)=>u-v));let ie=Promise.all(r.scans.map(([u,v])=>e.haplotypeSamplesInRange(u,v)));for(ie.catch(()=>{});se>0&&(W.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=L-M;)se-=1,await ue(se,se);for(;W.has(Y)&&W.get(Y).pathOffset<=G+M;)Y+=1,await ue(Y,Y);let pe=[...W.keys()].sort((u,v)=>u-v),ye=W.get(pe[0]??-1);if(!ye)throw new re("the haplotype index has no anchors on this path");let he=u=>W.get(u).pathOffset,Ne=new Map;for(let u of pe){let v=N(W.get(u).node);Ne.set(v,[...Ne.get(v)??[],u])}let ct=[...Ne.keys()],Et=ct.map(u=>W.get(Ne.get(u)[0]).visits);if(!Et[ct.indexOf(N(ye.node))].some(u=>u.pathHandle===a.referenceHandle&&u.orientation==="forward"&&u.pathOffset===ye.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${ye.pathOffset} (node ${N(ye.node)}); it does not match this graph`);let kt=pe.filter(u=>he(u)<=a.window.start),$n=pe.filter(u=>he(u)>=a.window.end);r.anchors=[he(kt[kt.length-1]??pe[0]),he($n[0]??pe[pe.length-1])],r.anchorsRead=pe.length;let dt=new Map,vt=new Set;if(ct.forEach((u,v)=>{let z=Ne.get(u),T=z.length===1?z[0]:void 0;for(let q of Et[v])vt.add(q.pathHandle),q.orientation==="forward"&&y(q.pathHandle)&&dt.set(q.pathHandle,[...dt.get(q.pathHandle)??[],{k:T,row:q}])}),r.chosenPaths=[...vt].filter(y).length,r.chosenPaths>Gt.mostChosenPaths)throw new re(`${r.chosenPaths} chosen paths pass the anchors, more than ${Gt.mostChosenPaths}`);let je=[],Ie=Number.POSITIVE_INFINITY,be=0;for(let[u,v]of dt){v.sort((z,T)=>z.row.pathOffset-T.row.pathOffset);for(let z=0;z+1<v.length;z++){let T=v[z],q=v[z+1];if(T.k===void 0||q.k===void 0||Math.abs(T.k-q.k)!==1)continue;let[Z,te]=he(T.k)<=he(q.k)?[T,q]:[q,T],ne=he(Z.k),oe=he(te.k);ne<G&&oe>=L?(je.push({pathHandle:u,from:T.row,to:q.row}),Ie=Math.min(Ie,ne-M),be=Math.max(be,oe+M)):ne>=G&&ne-G<=M?(je.push({pathHandle:u,from:Z.row,to:void 0}),Ie=Math.min(Ie,ne-M),be=Math.max(be,ne+M)):oe<L&&L-oe<=M&&(je.push({pathHandle:u,from:te.row,to:void 0}),Ie=Math.min(Ie,oe-M),be=Math.max(be,oe+M))}}let Rn=new Set(B.map(u=>`${u.low}:${u.high}`)),Nn=ae.filter(u=>y(u.pathHandle)&&(u.snarl===void 0||Rn.has(`${u.snarl[0]}:${u.snarl[1]}`))).sort((u,v)=>u.pathHandle-v.pathHandle||u.pathStart-v.pathStart);r.strays={bins:O-J+1,rows:ae.length,walked:0,outsideBp:0},be>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ie),be+1),r.ms.scan=o();let Pt=8*S+2*(a.window.end-a.window.start),At=r.strays,Me=0,$t=u=>{if(At.outsideBp+=u,Me+=u,Me>Pt)throw new re(`a walk of a chosen path near the window went past its cap of ${Pt} bp`)},ft=new Map,Rt=(u,v,z)=>(ft.get(u)??[]).some(([T,q])=>T<=v&&z<q),Nt=(u,v,z)=>{ft.set(u,[...ft.get(u)??[],[v,z]])},Mt=async(u,v,z,T,q)=>{let Z=v,te=z,ne=te;for(;Z&&te<=T;){n?.throwIfAborted();let oe;if(t.has(Z.node)){let Le=await $({pos:Z,left:te},u,"forward",q),Ht=F(Le);Z=Ht.pos,te=Ht.left,oe=f(Z.node),ne=Math.max(ne,Le.hapEnd)}else oe=(await d(Z.node)).sequenceLen,$t(oe),ne=Math.max(ne,te+oe);Z=await E(Z),te+=oe}return ne},Mn=async(u,v,z,T)=>{let q={pos:v,left:z},Z=z;for(;q.left>T;){n?.throwIfAborted();let te=await R(q.pos);if(!te)break;let ne=(await d(te.node)).sequenceLen,oe=q.left-ne;if(t.has(te.node)){let Le=await $({pos:te,left:oe},u,"forward","section");q=_(Le),Z=Math.min(Z,Le.hapStart)}else $t(ne),q={pos:te,left:oe},Z=Math.min(Z,oe)}return Z};for(let{pathHandle:u,from:v,to:z}of je){let T=v.pathOffset,q=(z??v).pathOffset+M;if(Rt(u,T-M,q))continue;let Z={node:v.node,offset:v.offset};Me=0;let te=await Mt(u,Z,T,q,"section");Me=0;let ne=await Mn(u,Z,T,T-M);Nt(u,Math.min(ne,T-M),Math.max(te,q+1)),i(z?"section":"visit",z?"past the far anchor":"bound")}for(let u of Nn){if(Rt(u.pathHandle,u.pathStart,u.pathEnd))continue;Me=0;let v=await Mt(u.pathHandle,{node:u.node,offset:u.offset},u.pathStart,u.pathEnd,"stray");Nt(u.pathHandle,u.pathStart,Math.max(v,u.pathEnd+1)),At.walked+=1}r.ms.walks=o();let Lt=[];for(let u of await ie)for(let v of u)if(r.scanRows+=1,t.has(v.node)&&y(v.pathHandle)){if(!(b.get(v.pathHandle)??[]).some(z=>{let T=g[z];return T.hapStart<=v.pathOffset&&v.pathOffset<T.hapEnd}))throw new re(`chosen path ${v.pathHandle} has a sample at ${v.pathOffset} on the window's nodes that no walk reached`);v.orientation==="reverse"&&Lt.push(v)}for(let u of Lt)await $({pos:{node:u.node,offset:u.offset},left:u.pathOffset},u.pathHandle,"reverse","twin");r.ms.check=o()},X=async()=>{let w=new Map,S=O=>{let L=Ce(O),G=w.get(L);G?G.add(O.orientation):w.set(L,new Set([O.orientation]))},A=0,M=()=>{for(;A<g.length;A++)S(g[A])};M();let B=O=>(w.get(Ce(O))?.size??0)>1,U=2*h,J=(O,L)=>L===D?y(a.referenceHandle)&&Kt(O):!O.canonical||Kt(O);for(let O=0;O<g.length;O++){let L=g[O];if(B(L)||!J(L,O))continue;r.twins.tried+=1;let G=L.orientation==="forward"?"reverse":"forward",W=F(L),ue=0,se;for(;!se&&ue<=U;){n?.throwIfAborted();let ae=await E(W.pos);if(!ae)break;let ie=(await d(ae.node)).sequenceLen,pe=Ve(L.orientation,W.left,(await d(W.pos.node)).sequenceLen,ie),ye=ee(ae.node);se=(await e.haplotypeSamplesInRange(ye,ye)).find(he=>he.pathHandle===L.pathHandle&&he.orientation===G&&he.pathOffset===pe),ue+=ie,W={pos:ae,left:pe}}let Y=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},De=0;for(;Y&&!B(L)&&De<=U+L.len;){if(n?.throwIfAborted(),t.has(Y.pos.node)){let ae=await $(Y,L.pathHandle,G,"twin"),ie=g.indexOf(ae);await k(ie,!0),await k(ie,!1),M(),Y=F(ae)}if(!B(L)){let ae=(await d(Y.pos.node)).sequenceLen;De+=ae;let ie=await E(Y.pos);Y=ie?{pos:ie,left:Ve(G,Y.left,ae,(await d(ie.node)).sequenceLen)}:void 0}}if(M(),!B(L))throw new re(`piece ${Ce(L)} was found in one orientation where extractPaths keeps the other`);r.twins.found+=1}r.ms.twins=o()};try{let w=await e.haplotypeStrayOptions();if(w===void 0)throw new re("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await j(w),await X()}catch(w){if(!(w instanceof re))throw w;r.fallback=w.message}return H()}function Xt(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var On=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Jt(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let o=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint32Array(64);for(let c=0;c<e;c++){for(let P=0;P<16;P++)r[P]=n.getUint32(c*64+P*4);for(let P=16;P<64;P++){let E=r[P-15],R=r[P-2],m=we(E,7)^we(E,18)^E>>>3,I=we(R,17)^we(R,19)^R>>>10;r[P]=r[P-16]+m+r[P-7]+I}let d=o[0],f=o[1],p=o[2],y=o[3],g=o[4],l=o[5],b=o[6],x=o[7];for(let P=0;P<64;P++){let E=we(g,6)^we(g,11)^we(g,25),R=g&l^~g&b,m=x+E+R+On[P]+r[P]|0,I=we(d,2)^we(d,13)^we(d,22),$=d&f^d&p^f&p;x=b,b=l,l=g,g=y+m|0,y=p,p=f,f=d,d=m+I+$|0}[d,f,p,y,g,l,b,x].forEach((P,E)=>{o[E]=o[E]+P})}let i=new Uint8Array(32),h=new DataView(i.buffer);for(let c=0;c<8;c++)h.setUint32(c*4,o[c]);return i}function Yt(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[o,r]=s;if(s.length!==2||!o||!r)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(o);i||(i=new Set,t.set(o,i)),i.add(r)}return t}function nn(a){return{name:a.get("pggname"),subgraph:Yt(a.get("subgraph"),"subgraph"),translation:Yt(a.get("translation"),"translation")}}function en(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let o of n)s.add(o)}}function sn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),en(t.subgraph,e.subgraph),en(t.translation,e.translation)),t}function tn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function on(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of tn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of tn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function rn(a){let e=a.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Jt(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}var Cn="_gbwt_ref";function fe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Bn=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,_n=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Tn(a){let e=Bn.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=_n.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Ae(a){return typeof a=="string"?Tn(a):a}function $e(a,e){return{sample:a.sample??Cn,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var le=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 ut(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var _e=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let o=s.length-1;for(;o>0;){let r=o-1>>1;if(ut(s[o],s[r]))[s[o],s[r]]=[s[r],s[o]],o=r;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let o=2*s+1,r=o+1,i=s;if(o<e.length&&ut(e[o],e[i])&&(i=o),r<e.length&&ut(e[r],e[i])&&(i=r),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function Fn(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],o)=>{e[o]=n,t[o]=s}),{pathAt:e,refAt:t,count:a.length}}function qn(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ke(a){return`${a.node}:${a.offset}`}function Be(a){return a.map(e=>ee(e)).reverse()}function zn(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Dn(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],o=n.edits.map(([c,d])=>[c,d]);hn(o,t.insertion,t.deletion);for(let[c,d]of s.edits)K(o,c,d);let r=a.identity.walkForward,[i,h]=r?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:o,weight:void 0,path:[...i.path,...h.path],start:i.start,pieces:[...i.pieces,...h.pieces],soloAligned:[...i.soloAligned,...h.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:r}}}function jn(a,e,t){if(a.some(r=>r.weight!==void 0))return a;let n=new Map;a.forEach((r,i)=>{if(r.identity){let h=n.get(r.identity.pathHandle);h?h.push(i):n.set(r.identity.pathHandle,[i])}});let s=new Map,o=new Set;for(let r of n.values()){r.sort((d,f)=>a[d].identity.hapStart-a[f].identity.hapStart);let i=r[0],h=a[i],c=[];for(let d of r.slice(1)){let f=a[d],p=c.length===0?zn(h,f):void 0;if(p){h=Dn(h,f,p),o.add(d);continue}if(!e(f)){c.push(d);continue}let y=e(h)?t([h,...c.map(g=>a[g]),f]):void 0;if(y){h=y;for(let g of[...c,d])o.add(g)}else s.set(i,h),i=d,h=f;c=[]}s.set(i,h)}return a.flatMap((r,i)=>o.has(i)?[]:[s.get(i)??r])}function Ge(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Un=32768;function Wn(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Un?s[1]=n:t.push([n,n])}return t}var Te=class a{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 a(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(ce(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 le(this.limit);let t=await this.db.getRecord(ce(e,"forward")),n=await this.db.getRecord(ce(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${fe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let o=n,r=s;for(;;){await this.ensureNode(N(r.node));let i=this.record(r.node);if(o+i.sequenceLen>t)return{position:{seqOffset:t,handle:r.node,nodeOffset:t-o,gbwtOffset:r.offset},name:e.name,handle:e.handle};o+=i.sequenceLen;let h=i.gbwt().lf(r.offset);if(!h)throw new Error(`The fragment of ${fe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);r=h}}async aroundPosition(e,t,n){let s=N(e);await this.ensureNode(s);let o=this.record(e),r=Ee(e),i=new _e;return i.push(t,s,Ue(r)),i.push(o.sequenceLen-t-1,s,We(r)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,o]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&o){let r=s.pos.node,i=o.pos.node;if(!await this.db.prefetchRecords([[Math.min(r,i),Math.max(r,i)+1]])){let c=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Wn(c.map(d=>d.pos.node)).map(([d,f])=>[d,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof le&&s.windowBp===void 0?new le(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},o=e.nodeOffset,r=t,i=new _e;for(;;){let h=N(s.node),c=Ee(s.node);this.walkedBp=t-r,await this.ensureNode(h);let d=this.record(s.node);if(o>=d.sequenceLen)throw new Error(`Offset ${o} in node ${h} of length ${d.sequenceLen}`);i.push(o,h,Ue(c));let f=d.sequenceLen-o;if(r<=f){i.push(r===f?0:f-r-1,h,We(c));break}i.push(0,h,We(c));let p=d.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,o=0,r-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new _e;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let r of this.records.keys())s.add(N(r));let o=0;for(;e.size>0;){let[r,i,h]=e.pop(),c=`${i}:${h}`;if(n.has(c))continue;n.add(c),s.delete(i),this.hasNode(i)||(await this.addNode(i),o+=1);let d=Ft(h);if(!n.has(`${i}:${d}`)){let y=this.record(ce(i,qt(h))),g=r+y.sequenceLen-1;g<=t&&e.push(g,i,d)}let f=this.record(ce(i,zt(h))),p=r+1;if(p<=t)for(let y of f.successors()){let g=N(y),l=Ue(Ee(y));n.has(`${g}:${l}`)||e.push(p,g,l)}}for(let r of s)this.records.delete(ce(r,"forward")),this.records.delete(ce(r,"reverse"));return{inserted:o,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([N(e),N(t)]),o=[];for(;n.length>0;){let r=n.pop(),i=N(r);this.hasNode(i)||(await this.addNode(i),o.push(i));for(let h of this.record(r).successors()){let c=N(h);s.has(c)||(n.push(h,ee(h)),s.add(c))}}return{inserted:o,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:o,nodes:r}=await this.fillBetween(n,s),i=N(n),h=N(s);this.snarlFills.push({low:Math.min(i,h),high:Math.max(i,h),nodes:r,inserted:o.length});for(let c of o)this.snarlNodes.add(c);t+=o.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let o=this.record(s),r=o.next;r!==void 0&&(n=!0,this.hasHandle(r)?He(s,r)&&t.push([s,r]):e==="overlapping"&&this.isSnarlEntryInSubgraph(o)&&t.push([s,r]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let o=t.get(n);if(!o){if(o=await this.db.getRecord(n),e?.(),!o)throw new Error(`Node record ${n} is missing from the database`);t.set(n,o)}return o}}async findCoveringSnarl(){let e=this.recordReader(),t=async h=>{let c=h.successors(),d=c[0];return d===void 0?!1:c.length>1||(await e(ee(d))).successors().length>1},n=async h=>{let c=await e(ee(h));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[ee(h),c.next]}:{kind:"chain"}:(await e(h)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,o=this.sortedHandles().flatMap(h=>this.record(h).successors()),r,i=!1;for(;!i&&o.length>0;){let h=o.shift(),c=N(h);if(!this.hasHandle(h)&&!s.has(c)){s.add(c);let d=await n(h);if(d.kind==="snarl-exit")r=d.snarl,i=!0;else if(d.kind==="chain")i=!0;else for(let f of["forward","reverse"])o.push(...(await e(ce(c,f))).successors())}}return r}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),o=s.length,r=new Map;s.forEach((m,I)=>r.set(m,I));let i=new Int32Array(o+1),h=new Int32Array(o),c=[];for(let m=0;m<o;m++){let I=this.record(s[m]),$=I.gbwt().decompressArrays();h[m]=I.sequenceLen,c.push($),i[m+1]=i[m]+$.nodes.length}let d=i[o],f=new Int32Array(d),p=new Int32Array(d),y=new Uint8Array(d);for(let m=0;m<o;m++){let I=c[m];f.set(I.nodes,i[m]),p.set(I.offsets,i[m])}c.length=0;for(let m=0;m<d;m++){let I=r.get(f[m]);I===void 0?f[m]=-1:(f[m]=I,y[i[I]+p[m]]=1)}let g=n===void 0?void 0:r.get(n.handle),l=n?.gbwtOffset,b,x=(m,I,$)=>{let F=[],_=0,D=0,C=-1,H=m,k=I;for(;;){H===g&&k===l&&(C=_),$&&($.push(s[H]),F.push(k)),_+=1,D+=h[H];let j=i[H]+k,X=f[j];if(X<0)break;k=p[j],H=X}return{offsets:F,len:D,refAt:C,last:H}},P=(m,I,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:m,offsets:I,len:$,weight:void 0,identity:void 0})},E=new Int32Array(o);for(let m=0;m<o;m++){let I=s[m];if(!Q(I)){let $=i[m],F=i[m+1]-$;for(let _=0;_<F;_++)if(y[$+_]===0){let D=[],{offsets:C,len:H,refAt:k,last:j}=x(m,_,D),X=s[j];if(k>=0||Pe(I,X)){if(P(D,C,H,k),!Q(X)){let w=r.get(ee(X));E[w]=E[w]+1}}else this.twinStarts.add(ke({node:I,offset:_}))}}}for(let m=0;m<o;m++){let I=s[m];if(Q(I)){let $=i[m],F=i[m+1]-$,_=0;for(let C=0;C<F;C++)y[$+C]===0&&(_+=1);let D=(g===void 0||b!==void 0)&&_===E[m];for(let C=0;C<F;C++)if(y[$+C]===0){let H=D?void 0:x(m,C,void 0);if(H&&(H.refAt>=0||Pe(I,s[H.last]))){let k=[],{offsets:j,len:X,refAt:w}=x(m,C,k);P(k,j,X,w)}else this.twinStarts.add(ke({node:I,offset:C}))}}}let R=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((m,I)=>m.path[0]-I.path[0]||m.offsets[0]-I.offsets[0]),R&&(this.refId=this.paths.indexOf(R)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let m=this.paths[this.refId],I=n.nodeOffset;for(let F of m.path.slice(0,b))I+=this.record(F).sequenceLen;let $=n.seqOffset-I;this.refInterval=[$,$+m.len],m.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+m.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Oe(n)?Be(n):void 0,o=c=>s!==void 0&&wt(c,s)===0||Oe(Be(c)),r=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,d)=>wt(c.path,d.path)||c.len-d.len||(c===t?-1:d===t?1:0));let i=[],h;for(let c of this.paths){let d=i[i.length-1],f=r&&c!==t&&o(c.path);this.twinDeferred||=f,d&&wt(d.path,c.path)===0&&!f?d.weight=(d.weight??1)+(c.weight??1):(c===t&&(h=i.length),i.push({...c,weight:c.weight??1}))}this.paths=i,this.refId=h}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=r=>`${r.pathHandle}:${r.hapStart}-${r.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let r of this.paths)r!==e&&r.identity?.orientation==="forward"&&s.add(n(r.identity));let o=this.paths.filter(r=>r===e||r.identity?.orientation!=="reverse"||!s.has(n(r.identity)));o.length<this.paths.length&&(this.paths=o,this.refId=e===void 0?void 0:o.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(r=>r.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((r,i)=>i!==this.refId&&r.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((r,i)=>i===this.refId||r.identity!==void 0&&e(r.identity.name)),o=new Set;for(let r of s)for(let i of r.path)o.add(N(i));for(let r of[...this.records.keys()])o.has(N(r))||this.records.delete(r);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let o=e.position.seqOffset,r=await Zt({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(d,f,p)=>this.prefetchReferenceRange(d,f,p)});if(this.stats.keep=r.stats,r.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),h=d=>({path:d.handles,offsets:d.offsets,len:d.len,weight:void 0,identity:{pathHandle:d.pathHandle,name:d===r.reference?e.name:i.get(d.pathHandle).name,orientation:d.orientation,hapStart:d.hapStart,hapEnd:d.hapEnd}}),c=[r.reference,...r.pieces].sort(Xt);return this.paths=c.map(h),this.refId=c.indexOf(r.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[r.reference.hapStart,r.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=pt(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ke(l),l);let o=l=>{let b=0,x=t.length-1;for(;b<x;){let E=b+x+1>>1;t[E][0]<=l?b=E:x=E-1}let P=t[b];return P[0]<=l&&l<=P[1]},r=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&r.set(ke(Ge(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let h=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=l=>(i.graphLookups+=1,h(l)),d=async(l,b)=>{if(o(l.node))return n.get(ke(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},y=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},g=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],P=new Set,E={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(E);let R,m=0,I=l,$;for(;R===void 0;){if(this.signal?.throwIfAborted(),I!==void 0){if(P.has(I)){E.end="cycle";break}P.add(I);let H=this.paths[I];x.push({index:I,startBp:m}),E.fragments+=1;let k=m;for(let X=0;X<H.path.length;X++){let w=Ge(H,X),S=n.get(ke(w)),A=this.record(w.node).sequenceLen;if(S){R=y(S,k,A);break}k+=A}if(m+=H.len,R){E.end="in-fragment sample";break}let j=Ge(H,H.path.length-1);$=this.record(j.node).gbwt().lf(j.offset),I=void 0}if($===void 0||$.node===0){E.end="endmarker";break}let F=ke($),_=r.get(F);if(_!==void 0){let H=this.paths[_].identity;if(H){R=g(H,m),E.end="identified sibling";break}I=_;continue}this.records.has($.node)&&(E.reentries+=1),this.twinStarts.has(F)&&(E.twinLandings+=1);let D=await d($,E),C=await c($.node);if(D){R=y(D,m,C.sequenceLen),E.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,E.steps+=1,m-x[x.length-1].startBp>4*e+4*C.sequenceLen){E.end="bound";break}m+=C.sequenceLen,$=C.gbwt().lf($.offset)}if(R){E.pathHandle=R.pathHandle;let F=await p(R.pathHandle);for(let{index:_,startBp:D}of x){let C=this.paths[_];C.identity=R.orientation==="forward"?{pathHandle:R.pathHandle,name:F,orientation:"forward",hapStart:R.base+D,hapEnd:R.base+D+C.len}:{pathHandle:R.pathHandle,name:F,orientation:"reverse",hapStart:R.base-D-C.len,hapEnd:R.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let o=t.get(n);o?o.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),o=new Int32Array(e.length),r=0,i=-1;for(let h=0;h<e.length;h++){let c=n.get(e[h]);if(c){let d=qn(c,i);if(d===void 0)return;s[r]=h,o[r]=d,r+=1,i=d}}return{pathAt:s,refAt:o,count:r}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[s]).sequence,c=this.record(t[o]).sequence;for(;r<h.length&&i<c.length;){if(h[r]!==c[i])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[e.length-s-1]).sequence,c=this.record(t[t.length-o-1]).sequence;for(;r<h.length&&i<c.length;){if(h[h.length-r-1]!==c[c.length-i-1])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),o=this.pathLen(t),r=this.prefixMatches(e,t),i=this.suffixMatches(e,t);r+i>s&&(i=s-r),r+i>o&&(i=o-r),K(n,"M",r),hn(n,s-r-i,o-r-i),K(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let o of e)n.has(o)&&(s+=this.record(o).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??Fn(Ut(e,t,f=>this.record(f).sequenceLen)[0]),o=[],r=this.refPrefix(t),i=(f,p,y,g)=>{f===p?K(o,"D",r[g]-r[y]):y===g?K(o,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(y,g),o)},h=0,c=0,d=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],y=s.refAt[f];(c!==p||d!==y)&&i(c,p,d,y);let g=this.record(e[p]).sequenceLen;K(o,"M",g),h+=g,c=p+1,d=y+1}return i(c,e.length,d,t.length),{edits:o,matched:h,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Oe(n)&&(t.identity===void 0||!Oe(Be(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let o=Be(t.path),r=this.sharedWeight(t.path,n);if(this.sharedWeight(o,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(r===0)s={...this.editsAgainst(o,n),flipped:!0};else{let h=this.editsAgainst(t.path,n),c=this.editsAgainst(o,n);s=c.matched>h.matched?{...c,flipped:!0}:{...h,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(d,f,p,y)=>{let g=Gn(d),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,P=x?.orientation==="forward",[E,R]=P?[l,b]:[b,l];return{strand:f,refStart:e.start+g.leading,refEnd:e.start+n-g.trailing,edits:g.edits,weight:l.weight,path:p.flatMap(m=>this.paths[m].path),start:Ge(l,0),pieces:p,soloAligned:y,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+E.identity.hapStart,hapEnd:x.name.fragment+R.identity.hapEnd,walkForward:P}}},o=d=>d.soloAligned.reduce((f,p)=>f+p,0),r=d=>d.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=d=>2*o(d)>=r(d),h=d=>{let f=d[0],p=d[d.length-1],y=f.identity.walkForward;if(d.some((k,j)=>k.strand!==f.strand||k.identity.walkForward!==y||j>0&&k.identity.hapStart<d[j-1].identity.hapEnd))return;let g=y?d:[...d].reverse(),l=g.flatMap(k=>k.pieces),b=g.flatMap(k=>k.soloAligned),x=f.strand==="+"!==y,P=l.map(k=>this.paths[k]),E=P.slice(1).map((k,j)=>{let X=P[j].identity;return y?k.identity.hapStart-X.hapEnd:X.hapStart-k.identity.hapEnd}),R=x?[...P].reverse():P,m=x?[...E].reverse():E,I=R.flatMap(k=>x?Be(k.path):k.path),{edits:$}=this.editsAgainst(I,t),F=an($,R.map(k=>k.len)),_=new Map((x?[...l].reverse():l).map((k,j)=>[k,F[j]])),D=k=>2*k.pieces.reduce((j,X)=>j+_.get(X),0)>=o(k);if(!D(f)||!D(p))return;let C=[],H=0;return R.slice(0,-1).forEach((k,j)=>{H+=k.len,C.push([H,m[j]])}),s(Qn($,C),f.strand,l,b)},c=[];return this.paths.forEach((d,f)=>{if(f===this.refId)return;let{edits:p,flipped:y}=this.alignment(f),g=d.identity,l=g?g.orientation==="forward"!==y:!y;c.push(s(p,l?"+":"-",[f],an(p,[d.len])))}),jn(c,i,h).map(d=>{let{edits:f,identity:p,pieces:y,soloAligned:g,...l}=d,b={...l,cigar:Kn(f)};return p?{...b,resolved:!0,name:p.name,label:fe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,o=this.paths.flatMap(d=>{let{identity:f}=d;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:Ke(d,f)}]:[]}),r=d=>f=>f.sample===d.sample&&f.haplotype===d.haplotype,i=r(t),h=n?r(n):d=>!i(d),c=d=>this.record(ce(d,"forward")).sequence;return o.filter(d=>i(d.name)).flatMap(d=>o.filter(f=>h(f.name)).flatMap(f=>Wt({...s,query:f.steps,target:d.steps,sequenceOf:c}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:d.name,targetStart:d.start+p.targetStart,targetEnd:d.start+p.targetEnd,cigar:Vt(p.edits),matches:p.edits.reduce((y,[g,l])=>y+(g==="="?l:0),0),columns:p.edits.reduce((y,[,g])=>y+g,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=ce(e,n);for(let o of this.record(s).successors())this.hasHandle(o)&&He(s,o)&&t.push([n==="reverse"?1:0,N(o),Q(o)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!Q(n)){let s=N(n),o=`S ${s} ${this.record(n).sequence}
|
|
1
|
+
import{a as ce,b as N,c as Ee,d as Q,e as ee,f as Ft,g as Ue,h as We,i as qt,j as zt,k as He,l as Oe,m as Pe,n as Dt,o as jt,p as Ut,q as Wt,r as Vt}from"./chunk-M2D7NUOY.js";import{a as _t,g as Tt}from"./chunk-HQ7FQACT.js";import{c as Ot}from"./chunk-HICKAMKK.js";import{a as Ct,g as Bt}from"./chunk-L372SDUG.js";var Ln=4096;function pt(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ln?n[1]=t:e.push([t,t])}return e}var Hn=32768,Gt={mostChosenPaths:32},lt=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},re=class extends Error{};function Ve(a,e,t,n){return a==="forward"?e+t:e-n}function Qt(a,e,t,n){return a==="forward"?e-n:e+t}function Kt(a){return Pe(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function Ce(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Zt(a){let{db:e,records:t,signal:n}=a,s=performance.now(),o=()=>{let w=performance.now(),S=w-s;return s=w,S},r={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(w,S)=>{let A=`${w}: ${S}`;r.walks[A]=(r.walks[A]??0)+1},h=await e.haplotypeSampleInterval()??4096,c=new Map,d=async w=>{let S=t.get(w)??c.get(w);if(S)return S;let A=await e.getRecord(w);if(r.graphFetches+=1,!A)throw new Error(`Node record ${w} is missing from the database`);return c.set(w,A),A},f=w=>t.get(w).sequenceLen,p=await e.pathsByHandle(),y=w=>{let S=p.get(w);return S!==void 0&&a.keep(S.name)},g=[],l=new lt,b=new Map,x=new Set,P=new Set,E=async w=>{let S=(await d(w.node)).gbwt().lf(w.offset);return S===void 0||S.node===0?void 0:S},R=async(w,S)=>{let A=(await d(ee(w.node))).gbwt().predecessorAt(w.offset);if(A===void 0||S!==void 0&&!S.has(A))return;let M=(await d(A)).gbwt().offsetTo(w);if(M===void 0)throw new Error(`No offset in ${A} leads to ${w.node}:${w.offset}`);return{node:A,offset:M}},m=(w,S,A,M)=>{let B=A.map(W=>W.pos.node),U=A.map(W=>W.pos.offset),J=0;for(let W of B)J+=f(W);let O=S==="forward"?A[0].left:A[A.length-1].left,L=g.length;g.push({pathHandle:w,orientation:S,handles:B,offsets:U,len:J,hapStart:O,hapEnd:O+J,canonical:Pe(B[0],B[B.length-1]),source:M});for(let W of A)l.set(W.pos,L);let G=b.get(w);return G?G.push(L):b.set(w,[L]),L},I=async(w,S,A,M)=>{let B=[],U=w;for(;;){n?.throwIfAborted();let O=await R(U.pos,t);if(!O)break;U={pos:O,left:Qt(A,U.left,f(U.pos.node),f(O.node))},B.push(U)}B.reverse();let J=[w];for(U=w;;){n?.throwIfAborted();let O=await E(U.pos);if(!O||!t.has(O.node))break;U={pos:O,left:Ve(A,U.left,f(U.pos.node),f(O.node))},J.push(U)}return m(S,A,[...B,...J],M)},$=async(w,S,A,M)=>g[l.get(w.pos)??await I(w,S,A,M)],F=w=>{let S=w.handles[w.handles.length-1];return{pos:{node:S,offset:w.offsets[w.offsets.length-1]},left:w.orientation==="forward"?w.hapEnd-f(S):w.hapStart}},_=w=>{let S=w.handles[0];return{pos:{node:S,offset:w.offsets[0]},left:w.orientation==="forward"?w.hapStart:w.hapEnd-f(S)}},D=await I({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),C=g[D],H=()=>{if(r.fallback!==void 0)return{reference:C,pieces:[],stats:r};let w=new Map;g.forEach((A,M)=>{M!==D&&w.set(Ce(A),[...w.get(Ce(A))??[],A])});let S=[];for(let A of w.values()){let M=new Set;for(let B of A)B.canonical&&!M.has(B.orientation)&&(M.add(B.orientation),S.push(B),r.sources[B.source]+=1)}return r.sources.reference=1,r.pieces=S.length+1,{reference:C,pieces:S,stats:r}},k=async(w,S)=>{let A=S?x:P,M=S?P:x,B=w;for(;;){if(A.has(B))return;A.add(B);let U=g[B],J=S?F(U):_(U),O=0,L;for(;L===void 0;){n?.throwIfAborted();let G=S?await E(J.pos):await R(J.pos);if(!G){L="endmarker";break}let W=(await d(J.pos.node)).sequenceLen,ue=(await d(G.node)).sequenceLen,se=S?Ve(U.orientation,J.left,W,ue):Qt(U.orientation,J.left,W,ue);if(t.has(G.node)){let Y=l.get(G);Y===void 0?(B=await I({pos:G,left:se},U.pathHandle,U.orientation,"chain"),M.add(B),L="landed"):(M.add(Y),L="merge")}else O>Hn?L="bound":(O+=ue,J={pos:G,left:se})}if(i("chain",L),L!=="landed")return}},j=async w=>{if(a.context>w.context)throw new re(`the context of ${a.context} bp exceeds the ${w.context} bp the haplotype index's stray rows cover`);let S=r.spacing;if(S===void 0)throw new re("the haplotype index has no anchors");let{bin:A,bound:M}=w,{fills:B,inserted:U}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new re("the haplotype index's stray rows cover contained snarls only");for(let u of B){if(u.inserted>0&&u.low===u.high)throw new re(`the haplotype index's stray rows leave out the snarl bounded by node ${u.low} at both ends`);if(u.inserted>0&&(w.snarlNodes===void 0||u.nodes>w.snarlNodes))throw new re(w.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${u.nodes} nodes exceeds the ${w.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(a.window.start/A),O=Math.floor((a.window.end-1)/A),L=J*A,G=(O+1)*A,W=new Map,ue=async(u,v)=>{let z=await e.haplotypeAnchorsBetween(a.referenceHandle,u*S,v*S);for(let T of z)W.set(T.anchorOffset/S,T)},se=Math.max(0,Math.floor((L-M)/S)-1),Y=Math.ceil((G+M)/S)+1,[{listed:De,strays:ae}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,J,O),ue(se,Y)]);for(let u of t.keys()){let v=N(u);if(!Q(u)&&!De(v)&&!U.has(v))throw new re(`the haplotype index lists node ${v} of the subgraph in no bin that the window touches`)}r.scans=pt([...t.keys()].sort((u,v)=>u-v));let ie=Promise.all(r.scans.map(([u,v])=>e.haplotypeSamplesInRange(u,v)));for(ie.catch(()=>{});se>0&&(W.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=L-M;)se-=1,await ue(se,se);for(;W.has(Y)&&W.get(Y).pathOffset<=G+M;)Y+=1,await ue(Y,Y);let pe=[...W.keys()].sort((u,v)=>u-v),ye=W.get(pe[0]??-1);if(!ye)throw new re("the haplotype index has no anchors on this path");let he=u=>W.get(u).pathOffset,Ne=new Map;for(let u of pe){let v=N(W.get(u).node);Ne.set(v,[...Ne.get(v)??[],u])}let ct=[...Ne.keys()],Et=ct.map(u=>W.get(Ne.get(u)[0]).visits);if(!Et[ct.indexOf(N(ye.node))].some(u=>u.pathHandle===a.referenceHandle&&u.orientation==="forward"&&u.pathOffset===ye.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${ye.pathOffset} (node ${N(ye.node)}); it does not match this graph`);let kt=pe.filter(u=>he(u)<=a.window.start),$n=pe.filter(u=>he(u)>=a.window.end);r.anchors=[he(kt[kt.length-1]??pe[0]),he($n[0]??pe[pe.length-1])],r.anchorsRead=pe.length;let dt=new Map,vt=new Set;if(ct.forEach((u,v)=>{let z=Ne.get(u),T=z.length===1?z[0]:void 0;for(let q of Et[v])vt.add(q.pathHandle),q.orientation==="forward"&&y(q.pathHandle)&&dt.set(q.pathHandle,[...dt.get(q.pathHandle)??[],{k:T,row:q}])}),r.chosenPaths=[...vt].filter(y).length,r.chosenPaths>Gt.mostChosenPaths)throw new re(`${r.chosenPaths} chosen paths pass the anchors, more than ${Gt.mostChosenPaths}`);let je=[],Ie=Number.POSITIVE_INFINITY,be=0;for(let[u,v]of dt){v.sort((z,T)=>z.row.pathOffset-T.row.pathOffset);for(let z=0;z+1<v.length;z++){let T=v[z],q=v[z+1];if(T.k===void 0||q.k===void 0||Math.abs(T.k-q.k)!==1)continue;let[Z,te]=he(T.k)<=he(q.k)?[T,q]:[q,T],ne=he(Z.k),oe=he(te.k);ne<G&&oe>=L?(je.push({pathHandle:u,from:T.row,to:q.row}),Ie=Math.min(Ie,ne-M),be=Math.max(be,oe+M)):ne>=G&&ne-G<=M?(je.push({pathHandle:u,from:Z.row,to:void 0}),Ie=Math.min(Ie,ne-M),be=Math.max(be,ne+M)):oe<L&&L-oe<=M&&(je.push({pathHandle:u,from:te.row,to:void 0}),Ie=Math.min(Ie,oe-M),be=Math.max(be,oe+M))}}let Rn=new Set(B.map(u=>`${u.low}:${u.high}`)),Nn=ae.filter(u=>y(u.pathHandle)&&(u.snarl===void 0||Rn.has(`${u.snarl[0]}:${u.snarl[1]}`))).sort((u,v)=>u.pathHandle-v.pathHandle||u.pathStart-v.pathStart);r.strays={bins:O-J+1,rows:ae.length,walked:0,outsideBp:0},be>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ie),be+1),r.ms.scan=o();let Pt=8*S+2*(a.window.end-a.window.start),At=r.strays,Me=0,$t=u=>{if(At.outsideBp+=u,Me+=u,Me>Pt)throw new re(`a walk of a chosen path near the window went past its cap of ${Pt} bp`)},ft=new Map,Rt=(u,v,z)=>(ft.get(u)??[]).some(([T,q])=>T<=v&&z<q),Nt=(u,v,z)=>{ft.set(u,[...ft.get(u)??[],[v,z]])},Mt=async(u,v,z,T,q)=>{let Z=v,te=z,ne=te;for(;Z&&te<=T;){n?.throwIfAborted();let oe;if(t.has(Z.node)){let Le=await $({pos:Z,left:te},u,"forward",q),Ht=F(Le);Z=Ht.pos,te=Ht.left,oe=f(Z.node),ne=Math.max(ne,Le.hapEnd)}else oe=(await d(Z.node)).sequenceLen,$t(oe),ne=Math.max(ne,te+oe);Z=await E(Z),te+=oe}return ne},Mn=async(u,v,z,T)=>{let q={pos:v,left:z},Z=z;for(;q.left>T;){n?.throwIfAborted();let te=await R(q.pos);if(!te)break;let ne=(await d(te.node)).sequenceLen,oe=q.left-ne;if(t.has(te.node)){let Le=await $({pos:te,left:oe},u,"forward","section");q=_(Le),Z=Math.min(Z,Le.hapStart)}else $t(ne),q={pos:te,left:oe},Z=Math.min(Z,oe)}return Z};for(let{pathHandle:u,from:v,to:z}of je){let T=v.pathOffset,q=(z??v).pathOffset+M;if(Rt(u,T-M,q))continue;let Z={node:v.node,offset:v.offset};Me=0;let te=await Mt(u,Z,T,q,"section");Me=0;let ne=await Mn(u,Z,T,T-M);Nt(u,Math.min(ne,T-M),Math.max(te,q+1)),i(z?"section":"visit",z?"past the far anchor":"bound")}for(let u of Nn){if(Rt(u.pathHandle,u.pathStart,u.pathEnd))continue;Me=0;let v=await Mt(u.pathHandle,{node:u.node,offset:u.offset},u.pathStart,u.pathEnd,"stray");Nt(u.pathHandle,u.pathStart,Math.max(v,u.pathEnd+1)),At.walked+=1}r.ms.walks=o();let Lt=[];for(let u of await ie)for(let v of u)if(r.scanRows+=1,t.has(v.node)&&y(v.pathHandle)){if(!(b.get(v.pathHandle)??[]).some(z=>{let T=g[z];return T.hapStart<=v.pathOffset&&v.pathOffset<T.hapEnd}))throw new re(`chosen path ${v.pathHandle} has a sample at ${v.pathOffset} on the window's nodes that no walk reached`);v.orientation==="reverse"&&Lt.push(v)}for(let u of Lt)await $({pos:{node:u.node,offset:u.offset},left:u.pathOffset},u.pathHandle,"reverse","twin");r.ms.check=o()},X=async()=>{let w=new Map,S=O=>{let L=Ce(O),G=w.get(L);G?G.add(O.orientation):w.set(L,new Set([O.orientation]))},A=0,M=()=>{for(;A<g.length;A++)S(g[A])};M();let B=O=>(w.get(Ce(O))?.size??0)>1,U=2*h,J=(O,L)=>L===D?y(a.referenceHandle)&&Kt(O):!O.canonical||Kt(O);for(let O=0;O<g.length;O++){let L=g[O];if(B(L)||!J(L,O))continue;r.twins.tried+=1;let G=L.orientation==="forward"?"reverse":"forward",W=F(L),ue=0,se;for(;!se&&ue<=U;){n?.throwIfAborted();let ae=await E(W.pos);if(!ae)break;let ie=(await d(ae.node)).sequenceLen,pe=Ve(L.orientation,W.left,(await d(W.pos.node)).sequenceLen,ie),ye=ee(ae.node);se=(await e.haplotypeSamplesInRange(ye,ye)).find(he=>he.pathHandle===L.pathHandle&&he.orientation===G&&he.pathOffset===pe),ue+=ie,W={pos:ae,left:pe}}let Y=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},De=0;for(;Y&&!B(L)&&De<=U+L.len;){if(n?.throwIfAborted(),t.has(Y.pos.node)){let ae=await $(Y,L.pathHandle,G,"twin"),ie=g.indexOf(ae);await k(ie,!0),await k(ie,!1),M(),Y=F(ae)}if(!B(L)){let ae=(await d(Y.pos.node)).sequenceLen;De+=ae;let ie=await E(Y.pos);Y=ie?{pos:ie,left:Ve(G,Y.left,ae,(await d(ie.node)).sequenceLen)}:void 0}}if(M(),!B(L))throw new re(`piece ${Ce(L)} was found in one orientation where extractPaths keeps the other`);r.twins.found+=1}r.ms.twins=o()};try{let w=await e.haplotypeStrayOptions();if(w===void 0)throw new re("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await j(w),await X()}catch(w){if(!(w instanceof re))throw w;r.fallback=w.message}return H()}function Xt(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var On=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Jt(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let o=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint32Array(64);for(let c=0;c<e;c++){for(let P=0;P<16;P++)r[P]=n.getUint32(c*64+P*4);for(let P=16;P<64;P++){let E=r[P-15],R=r[P-2],m=we(E,7)^we(E,18)^E>>>3,I=we(R,17)^we(R,19)^R>>>10;r[P]=r[P-16]+m+r[P-7]+I}let d=o[0],f=o[1],p=o[2],y=o[3],g=o[4],l=o[5],b=o[6],x=o[7];for(let P=0;P<64;P++){let E=we(g,6)^we(g,11)^we(g,25),R=g&l^~g&b,m=x+E+R+On[P]+r[P]|0,I=we(d,2)^we(d,13)^we(d,22),$=d&f^d&p^f&p;x=b,b=l,l=g,g=y+m|0,y=p,p=f,f=d,d=m+I+$|0}[d,f,p,y,g,l,b,x].forEach((P,E)=>{o[E]=o[E]+P})}let i=new Uint8Array(32),h=new DataView(i.buffer);for(let c=0;c<8;c++)h.setUint32(c*4,o[c]);return i}function Yt(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[o,r]=s;if(s.length!==2||!o||!r)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(o);i||(i=new Set,t.set(o,i)),i.add(r)}return t}function nn(a){return{name:a.get("pggname"),subgraph:Yt(a.get("subgraph"),"subgraph"),translation:Yt(a.get("translation"),"translation")}}function en(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let o of n)s.add(o)}}function sn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),en(t.subgraph,e.subgraph),en(t.translation,e.translation)),t}function tn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function on(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of tn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of tn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function rn(a){let e=a.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Jt(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}var Cn="_gbwt_ref";function fe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Bn=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,_n=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Tn(a){let e=Bn.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=_n.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Ae(a){return typeof a=="string"?Tn(a):a}function $e(a,e){return{sample:a.sample??Cn,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var le=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 ut(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var _e=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let o=s.length-1;for(;o>0;){let r=o-1>>1;if(ut(s[o],s[r]))[s[o],s[r]]=[s[r],s[o]],o=r;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let o=2*s+1,r=o+1,i=s;if(o<e.length&&ut(e[o],e[i])&&(i=o),r<e.length&&ut(e[r],e[i])&&(i=r),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function Fn(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],o)=>{e[o]=n,t[o]=s}),{pathAt:e,refAt:t,count:a.length}}function qn(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ke(a){return`${a.node}:${a.offset}`}function Be(a){return a.map(e=>ee(e)).reverse()}function zn(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Dn(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],o=n.edits.map(([c,d])=>[c,d]);hn(o,t.insertion,t.deletion);for(let[c,d]of s.edits)K(o,c,d);let r=a.identity.walkForward,[i,h]=r?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:o,weight:void 0,path:[...i.path,...h.path],start:i.start,pieces:[...i.pieces,...h.pieces],soloAligned:[...i.soloAligned,...h.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:r}}}function jn(a,e,t){if(a.some(r=>r.weight!==void 0))return a;let n=new Map;a.forEach((r,i)=>{if(r.identity){let h=n.get(r.identity.pathHandle);h?h.push(i):n.set(r.identity.pathHandle,[i])}});let s=new Map,o=new Set;for(let r of n.values()){r.sort((d,f)=>a[d].identity.hapStart-a[f].identity.hapStart);let i=r[0],h=a[i],c=[];for(let d of r.slice(1)){let f=a[d],p=c.length===0?zn(h,f):void 0;if(p){h=Dn(h,f,p),o.add(d);continue}if(!e(f)){c.push(d);continue}let y=e(h)?t([h,...c.map(g=>a[g]),f]):void 0;if(y){h=y;for(let g of[...c,d])o.add(g)}else s.set(i,h),i=d,h=f;c=[]}s.set(i,h)}return a.flatMap((r,i)=>o.has(i)?[]:[s.get(i)??r])}function Ge(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Un=32768;function Wn(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Un?s[1]=n:t.push([n,n])}return t}var Te=class a{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 a(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(ce(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 le(this.limit);let t=await this.db.getRecord(ce(e,"forward")),n=await this.db.getRecord(ce(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${fe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let o=n,r=s;for(;;){await this.ensureNode(N(r.node));let i=this.record(r.node);if(o+i.sequenceLen>t)return{position:{seqOffset:t,handle:r.node,nodeOffset:t-o,gbwtOffset:r.offset},name:e.name,handle:e.handle};o+=i.sequenceLen;let h=i.gbwt().lf(r.offset);if(!h)throw new Error(`The fragment of ${fe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);r=h}}async aroundPosition(e,t,n){let s=N(e);await this.ensureNode(s);let o=this.record(e),r=Ee(e),i=new _e;return i.push(t,s,Ue(r)),i.push(o.sequenceLen-t-1,s,We(r)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,o]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&o){let r=s.pos.node,i=o.pos.node;if(!await this.db.prefetchRecords([[Math.min(r,i),Math.max(r,i)+1]])){let c=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Wn(c.map(d=>d.pos.node)).map(([d,f])=>[d,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof le&&s.windowBp===void 0?new le(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},o=e.nodeOffset,r=t,i=new _e;for(;;){let h=N(s.node),c=Ee(s.node);this.walkedBp=t-r,await this.ensureNode(h);let d=this.record(s.node);if(o>=d.sequenceLen)throw new Error(`Offset ${o} in node ${h} of length ${d.sequenceLen}`);i.push(o,h,Ue(c));let f=d.sequenceLen-o;if(r<=f){i.push(r===f?0:f-r-1,h,We(c));break}i.push(0,h,We(c));let p=d.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,o=0,r-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new _e;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let r of this.records.keys())s.add(N(r));let o=0;for(;e.size>0;){let[r,i,h]=e.pop(),c=`${i}:${h}`;if(n.has(c))continue;n.add(c),s.delete(i),this.hasNode(i)||(await this.addNode(i),o+=1);let d=Ft(h);if(!n.has(`${i}:${d}`)){let y=this.record(ce(i,qt(h))),g=r+y.sequenceLen-1;g<=t&&e.push(g,i,d)}let f=this.record(ce(i,zt(h))),p=r+1;if(p<=t)for(let y of f.successors()){let g=N(y),l=Ue(Ee(y));n.has(`${g}:${l}`)||e.push(p,g,l)}}for(let r of s)this.records.delete(ce(r,"forward")),this.records.delete(ce(r,"reverse"));return{inserted:o,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([N(e),N(t)]),o=[];for(;n.length>0;){let r=n.pop(),i=N(r);this.hasNode(i)||(await this.addNode(i),o.push(i));for(let h of this.record(r).successors()){let c=N(h);s.has(c)||(n.push(h,ee(h)),s.add(c))}}return{inserted:o,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:o,nodes:r}=await this.fillBetween(n,s),i=N(n),h=N(s);this.snarlFills.push({low:Math.min(i,h),high:Math.max(i,h),nodes:r,inserted:o.length});for(let c of o)this.snarlNodes.add(c);t+=o.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let o=this.record(s),r=o.next;r!==void 0&&(n=!0,this.hasHandle(r)?He(s,r)&&t.push([s,r]):e==="overlapping"&&this.isSnarlEntryInSubgraph(o)&&t.push([s,r]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let o=t.get(n);if(!o){if(o=await this.db.getRecord(n),e?.(),!o)throw new Error(`Node record ${n} is missing from the database`);t.set(n,o)}return o}}async findCoveringSnarl(){let e=this.recordReader(),t=async h=>{let c=h.successors(),d=c[0];return d===void 0?!1:c.length>1||(await e(ee(d))).successors().length>1},n=async h=>{let c=await e(ee(h));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[ee(h),c.next]}:{kind:"chain"}:(await e(h)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,o=this.sortedHandles().flatMap(h=>this.record(h).successors()),r,i=!1;for(;!i&&o.length>0;){let h=o.shift(),c=N(h);if(!this.hasHandle(h)&&!s.has(c)){s.add(c);let d=await n(h);if(d.kind==="snarl-exit")r=d.snarl,i=!0;else if(d.kind==="chain")i=!0;else for(let f of["forward","reverse"])o.push(...(await e(ce(c,f))).successors())}}return r}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),o=s.length,r=new Map;s.forEach((m,I)=>r.set(m,I));let i=new Int32Array(o+1),h=new Int32Array(o),c=[];for(let m=0;m<o;m++){let I=this.record(s[m]),$=I.gbwt().decompressArrays();h[m]=I.sequenceLen,c.push($),i[m+1]=i[m]+$.nodes.length}let d=i[o],f=new Int32Array(d),p=new Int32Array(d),y=new Uint8Array(d);for(let m=0;m<o;m++){let I=c[m];f.set(I.nodes,i[m]),p.set(I.offsets,i[m])}c.length=0;for(let m=0;m<d;m++){let I=r.get(f[m]);I===void 0?f[m]=-1:(f[m]=I,y[i[I]+p[m]]=1)}let g=n===void 0?void 0:r.get(n.handle),l=n?.gbwtOffset,b,x=(m,I,$)=>{let F=[],_=0,D=0,C=-1,H=m,k=I;for(;;){H===g&&k===l&&(C=_),$&&($.push(s[H]),F.push(k)),_+=1,D+=h[H];let j=i[H]+k,X=f[j];if(X<0)break;k=p[j],H=X}return{offsets:F,len:D,refAt:C,last:H}},P=(m,I,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:m,offsets:I,len:$,weight:void 0,identity:void 0})},E=new Int32Array(o);for(let m=0;m<o;m++){let I=s[m];if(!Q(I)){let $=i[m],F=i[m+1]-$;for(let _=0;_<F;_++)if(y[$+_]===0){let D=[],{offsets:C,len:H,refAt:k,last:j}=x(m,_,D),X=s[j];if(k>=0||Pe(I,X)){if(P(D,C,H,k),!Q(X)){let w=r.get(ee(X));E[w]=E[w]+1}}else this.twinStarts.add(ke({node:I,offset:_}))}}}for(let m=0;m<o;m++){let I=s[m];if(Q(I)){let $=i[m],F=i[m+1]-$,_=0;for(let C=0;C<F;C++)y[$+C]===0&&(_+=1);let D=(g===void 0||b!==void 0)&&_===E[m];for(let C=0;C<F;C++)if(y[$+C]===0){let H=D?void 0:x(m,C,void 0);if(H&&(H.refAt>=0||Pe(I,s[H.last]))){let k=[],{offsets:j,len:X,refAt:w}=x(m,C,k);P(k,j,X,w)}else this.twinStarts.add(ke({node:I,offset:C}))}}}let R=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((m,I)=>m.path[0]-I.path[0]||m.offsets[0]-I.offsets[0]),R&&(this.refId=this.paths.indexOf(R)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let m=this.paths[this.refId],I=n.nodeOffset;for(let F of m.path.slice(0,b))I+=this.record(F).sequenceLen;let $=n.seqOffset-I;this.refInterval=[$,$+m.len],m.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+m.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Oe(n)?Be(n):void 0,o=c=>s!==void 0&&wt(c,s)===0||Oe(Be(c)),r=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,d)=>wt(c.path,d.path)||c.len-d.len||(c===t?-1:d===t?1:0));let i=[],h;for(let c of this.paths){let d=i[i.length-1],f=r&&c!==t&&o(c.path);this.twinDeferred||=f,d&&wt(d.path,c.path)===0&&!f?d.weight=(d.weight??1)+(c.weight??1):(c===t&&(h=i.length),i.push({...c,weight:c.weight??1}))}this.paths=i,this.refId=h}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=r=>`${r.pathHandle}:${r.hapStart}-${r.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let r of this.paths)r!==e&&r.identity?.orientation==="forward"&&s.add(n(r.identity));let o=this.paths.filter(r=>r===e||r.identity?.orientation!=="reverse"||!s.has(n(r.identity)));o.length<this.paths.length&&(this.paths=o,this.refId=e===void 0?void 0:o.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(r=>r.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((r,i)=>i!==this.refId&&r.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((r,i)=>i===this.refId||r.identity!==void 0&&e(r.identity.name)),o=new Set;for(let r of s)for(let i of r.path)o.add(N(i));for(let r of[...this.records.keys()])o.has(N(r))||this.records.delete(r);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let o=e.position.seqOffset,r=await Zt({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(d,f,p)=>this.prefetchReferenceRange(d,f,p)});if(this.stats.keep=r.stats,r.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),h=d=>({path:d.handles,offsets:d.offsets,len:d.len,weight:void 0,identity:{pathHandle:d.pathHandle,name:d===r.reference?e.name:i.get(d.pathHandle).name,orientation:d.orientation,hapStart:d.hapStart,hapEnd:d.hapEnd}}),c=[r.reference,...r.pieces].sort(Xt);return this.paths=c.map(h),this.refId=c.indexOf(r.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[r.reference.hapStart,r.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=pt(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ke(l),l);let o=l=>{let b=0,x=t.length-1;for(;b<x;){let E=b+x+1>>1;t[E][0]<=l?b=E:x=E-1}let P=t[b];return P[0]<=l&&l<=P[1]},r=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&r.set(ke(Ge(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let h=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=l=>(i.graphLookups+=1,h(l)),d=async(l,b)=>{if(o(l.node))return n.get(ke(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},y=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},g=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],P=new Set,E={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(E);let R,m=0,I=l,$;for(;R===void 0;){if(this.signal?.throwIfAborted(),I!==void 0){if(P.has(I)){E.end="cycle";break}P.add(I);let H=this.paths[I];x.push({index:I,startBp:m}),E.fragments+=1;let k=m;for(let X=0;X<H.path.length;X++){let w=Ge(H,X),S=n.get(ke(w)),A=this.record(w.node).sequenceLen;if(S){R=y(S,k,A);break}k+=A}if(m+=H.len,R){E.end="in-fragment sample";break}let j=Ge(H,H.path.length-1);$=this.record(j.node).gbwt().lf(j.offset),I=void 0}if($===void 0||$.node===0){E.end="endmarker";break}let F=ke($),_=r.get(F);if(_!==void 0){let H=this.paths[_].identity;if(H){R=g(H,m),E.end="identified sibling";break}I=_;continue}this.records.has($.node)&&(E.reentries+=1),this.twinStarts.has(F)&&(E.twinLandings+=1);let D=await d($,E),C=await c($.node);if(D){R=y(D,m,C.sequenceLen),E.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,E.steps+=1,m-x[x.length-1].startBp>4*e+4*C.sequenceLen){E.end="bound";break}m+=C.sequenceLen,$=C.gbwt().lf($.offset)}if(R){E.pathHandle=R.pathHandle;let F=await p(R.pathHandle);for(let{index:_,startBp:D}of x){let C=this.paths[_];C.identity=R.orientation==="forward"?{pathHandle:R.pathHandle,name:F,orientation:"forward",hapStart:R.base+D,hapEnd:R.base+D+C.len}:{pathHandle:R.pathHandle,name:F,orientation:"reverse",hapStart:R.base-D-C.len,hapEnd:R.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let o=t.get(n);o?o.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),o=new Int32Array(e.length),r=0,i=-1;for(let h=0;h<e.length;h++){let c=n.get(e[h]);if(c){let d=qn(c,i);if(d===void 0)return;s[r]=h,o[r]=d,r+=1,i=d}}return{pathAt:s,refAt:o,count:r}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[s]).sequence,c=this.record(t[o]).sequence;for(;r<h.length&&i<c.length;){if(h[r]!==c[i])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[e.length-s-1]).sequence,c=this.record(t[t.length-o-1]).sequence;for(;r<h.length&&i<c.length;){if(h[h.length-r-1]!==c[c.length-i-1])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),o=this.pathLen(t),r=this.prefixMatches(e,t),i=this.suffixMatches(e,t);r+i>s&&(i=s-r),r+i>o&&(i=o-r),K(n,"M",r),hn(n,s-r-i,o-r-i),K(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let o of e)n.has(o)&&(s+=this.record(o).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??Fn(Ut(e,t,f=>this.record(f).sequenceLen)[0]),o=[],r=this.refPrefix(t),i=(f,p,y,g)=>{f===p?K(o,"D",r[g]-r[y]):y===g?K(o,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(y,g),o)},h=0,c=0,d=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],y=s.refAt[f];(c!==p||d!==y)&&i(c,p,d,y);let g=this.record(e[p]).sequenceLen;K(o,"M",g),h+=g,c=p+1,d=y+1}return i(c,e.length,d,t.length),{edits:o,matched:h,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Oe(n)&&(t.identity===void 0||!Oe(Be(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let o=Be(t.path),r=this.sharedWeight(t.path,n);if(this.sharedWeight(o,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(r===0)s={...this.editsAgainst(o,n),flipped:!0};else{let h=this.editsAgainst(t.path,n),c=this.editsAgainst(o,n);s=c.matched>h.matched?{...c,flipped:!0}:{...h,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(d,f,p,y)=>{let g=Gn(d),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,P=x?.orientation==="forward",[E,R]=P?[l,b]:[b,l];return{strand:f,refStart:e.start+g.leading,refEnd:e.start+n-g.trailing,edits:g.edits,weight:l.weight,path:p.flatMap(m=>this.paths[m].path),start:Ge(l,0),pieces:p,soloAligned:y,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+E.identity.hapStart,hapEnd:x.name.fragment+R.identity.hapEnd,walkForward:P}}},o=d=>d.soloAligned.reduce((f,p)=>f+p,0),r=d=>d.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=d=>2*o(d)>=r(d),h=d=>{let f=d[0],p=d[d.length-1],y=f.identity.walkForward;if(d.some((k,j)=>k.strand!==f.strand||k.identity.walkForward!==y||j>0&&k.identity.hapStart<d[j-1].identity.hapEnd))return;let g=y?d:[...d].reverse(),l=g.flatMap(k=>k.pieces),b=g.flatMap(k=>k.soloAligned),x=f.strand==="+"!==y,P=l.map(k=>this.paths[k]),E=P.slice(1).map((k,j)=>{let X=P[j].identity;return y?k.identity.hapStart-X.hapEnd:X.hapStart-k.identity.hapEnd}),R=x?[...P].reverse():P,m=x?[...E].reverse():E,I=R.flatMap(k=>x?Be(k.path):k.path),{edits:$}=this.editsAgainst(I,t),F=an($,R.map(k=>k.len)),_=new Map((x?[...l].reverse():l).map((k,j)=>[k,F[j]])),D=k=>2*k.pieces.reduce((j,X)=>j+_.get(X),0)>=o(k);if(!D(f)||!D(p))return;let C=[],H=0;return R.slice(0,-1).forEach((k,j)=>{H+=k.len,C.push([H,m[j]])}),s(Qn($,C),f.strand,l,b)},c=[];return this.paths.forEach((d,f)=>{if(f===this.refId)return;let{edits:p,flipped:y}=this.alignment(f),g=d.identity,l=g?g.orientation==="forward"!==y:!y;c.push(s(p,l?"+":"-",[f],an(p,[d.len])))}),jn(c,i,h).map(d=>{let{edits:f,identity:p,pieces:y,soloAligned:g,...l}=d,b={...l,cigar:Kn(f)};return p?{...b,resolved:!0,name:p.name,label:fe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,o=this.paths.flatMap(d=>{let{identity:f}=d;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:Ke(d,f)}]:[]}),r=d=>f=>f.sample===d.sample&&f.haplotype===d.haplotype,i=r(t),h=n?r(n):d=>!i(d),c=d=>this.record(ce(d,"forward")).sequence;return o.filter(d=>i(d.name)).flatMap(d=>o.filter(f=>h(f.name)).flatMap(f=>Wt({...s,query:f.steps,target:d.steps,sequenceOf:c}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:d.name,targetStart:d.start+p.targetStart,targetEnd:d.start+p.targetEnd,cigar:Vt(p.edits),matches:p.edits.reduce((y,[g,l])=>y+(g==="="?l:0),0),columns:p.edits.reduce((y,[,g])=>y+g,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=ce(e,n);for(let o of this.record(s).successors())this.hasHandle(o)&&He(s,o)&&t.push([n==="reverse"?1:0,N(o),Q(o)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!Q(n)){let s=N(n),o=`S ${s} ${this.record(n).sequence}
|
|
2
2
|
`;for(let[r,i,h]of this.canonicalEdges(s))o+=`L ${s} ${r?"-":"+"} ${i} ${h?"-":"+"}
|
|
3
3
|
`;t.push(e.encode(o))}return rn(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",...on(sn(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let c of s)Q(c)||n.push(`S ${N(c)} ${this.record(c).sequence}`);let o=c=>Q(c)?"-":"+";for(let c of s)for(let d of this.record(c).successors())this.hasHandle(d)&&He(c,d)&&n.push(`L ${N(c)} ${o(c)} ${N(d)} ${o(d)} 0M`);let r=(c,d,f,p,y)=>{let g=Ke(c,d).map(x=>`${Q(x)?"<":">"}${N(x)}`).join(""),l=c.weight===void 0?"":` WT:i:${c.weight}`,b=y===void 0?"":` CG:Z:${y}`;return`W ${f.sample} ${f.haplotype} ${f.contig} ${f.fragment} ${p} ${g}${l}${b}`},i=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.push(r(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let h=1;return this.paths.forEach((c,d)=>{if(d!==this.refId){let f=e.names!=="anonymous"?c.identity:void 0,p=t?this.alignToRef(d):void 0;n.push(f?r(c,f,{...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd,p):r(c,void 0,{sample:"unknown",contig:i,haplotype:h,fragment:0},c.len,p)),h+=1}}),`${n.join(`
|
|
4
4
|
`)}
|
|
@@ -6,4 +6,4 @@ import{a as ce,b as N,c as Ee,d as Q,e as ee,f as Ft,g as Ue,h as We,i as qt,j a
|
|
|
6
6
|
`).filter(p=>p!=="")),n=(f,p)=>f.filter(y=>y.startsWith(`${p} `)),s=cs(t.flat()),o=0,r=t.map(f=>{let p=n(f,"W").map(hs),y=o;for(let g of p.filter(l=>l.fields[1]===is)){let l=+g.fields[2]+y;g.fields[2]=String(l),g.name=g.fields.slice(1,4).join(" "),o=Math.max(o,l)}return p}),h=[...Ot([...r.flatMap(f=>f.slice(0,1)),...r.flatMap(f=>f.slice(1))],f=>f.name).values()].flatMap(f=>fs(f,s,e)),c=new Set(t.flatMap(f=>n(f,"L")));for(let f of h)for(let p of ls(f))!c.has(p.forward)&&!c.has(p.reverse)&&c.add(p.forward);return`${[...new Set([...n(t[0],"H"),...t.flatMap(f=>n(f,"S")),...c,...h.map(f=>f.fields.join(" "))])].join(`
|
|
7
7
|
`)}
|
|
8
8
|
`}var In=class extends Error{constructor(a,e){super(e.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${a}" maps to none; set referenceSample`:`the anchor "${a}" is none of the graph's reference samples (${e.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`),this.name="NoReferenceSampleError"}},En=class extends Error{constructor(a,e,t){super(`this ${e.toLocaleString()} bp window reads more than nodeLimit (${a.toLocaleString()}) graph nodes; zoom in to about ${t.toLocaleString()} bp or raise nodeLimit`),this.fitsBp=t,this.name="NodeLimitError",this.regionTooLarge=!0}};function kn(a){return`${a.sample}#${a.haplotype}`}function ps(a,e){let t=kn(a);return e===void 0||e.some(n=>Bt(t,n))}async function us(a){return(await a.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function vn(a,e){let t=a.toLowerCase(),n=_t(a)?.toLowerCase();return e.find(s=>s===a)??e.find(s=>s.toLowerCase()===t)??e.find(s=>s.toLowerCase()===n)}function ws({configured:a,anchorPrefix:e,referenceSamples:t}){if(a!=="")return a;let n=vn(Ct(e),t)??(t.length===1?t[0]:void 0);if(n===void 0)throw new In(e,t);return n}async function gs(a,e,t){let n=(await a.paths()).find(s=>s.isIndexed&&s.name.sample===e&&s.name.contig===t);return n?{sample:n.name.sample,contig:t,haplotype:n.name.haplotype}:void 0}function Pn(a,e,t){if(a instanceof Error&&(a.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(a.message))){let s=a.walkedBp,o=typeof s=="number"&&s>0?Math.floor(s*.8):Math.floor(t/2);return new En(e,t,Math.max(o,1))}else return}var ms={context:1e3,snarls:"contained",limit:1e5};async function ys(a,e,t,n,s){return a.getSubgraphs({...s,path:e,start:t,end:n,haplotypes:"all"}).catch(o=>{throw Pn(o,s.limit,n-t)??o})}async function bs(a,e){let t=await a.paths();return Sn(await Promise.all(e.map(n=>n.toGFA())),(n,s,o,r)=>t.some(({name:i})=>i.sample===n&&i.haplotype===s&&i.contig===o&&i.fragment===r))}async function xs(a,e,t,n,s){if(!e)return"";let o=await ys(a,e,t,n,s);if(o.length===1)return An(o[0].toCompactSubgraph());let r=await bs(a,o);return r&&Tt(r)||r}function Ss(a,e){let t=1/0,n=-1/0;for(let i of a)t=Math.min(t,i),n=Math.max(n,i);let s=n-t+1,o=a.length>0&&s<=16*a.length?new Int32Array(s).fill(-1):void 0,r=new Map;return a.forEach((i,h)=>{o?o[i-t]=h:r.set(i,h)}),i=>{let h=N(i),c=o!==void 0&&h>=t&&h<=n,d=c?o[h-t]:r.get(h)??-1;return d>=0?d:(c?o[h-t]=e.length:r.set(h,e.length),e.push(String(h)),e.length-1)}}var Is=/^(.*)\[(\d+)-(\d+)\]$/;function An(a){let e=Array.from(a.nodeIds,String),t=Ss(a.nodeIds,e),n=a.nodeIds.length,s=a.edges.length/2,o=new Int32Array(s),r=new Int32Array(s),i=new Uint8Array(s);for(let l=0;l<s;l++){let b=a.edges[2*l],x=a.edges[2*l+1];o[l]=t(b),r[l]=t(x),i[l]=(Q(b)?1:0)|(Q(x)?2:0)}let h=a.paths.filter(l=>l.steps.length>0),c=new Int32Array(h.length+1);h.forEach((l,b)=>{c[b+1]=c[b]+l.steps.length});let d=new Int32Array(c[h.length]),f=new Uint8Array(d.length),p=new Float64Array(h.length),y=new Float64Array(h.length),g=h.map((l,b)=>{let x=Is.exec(l.name);p[b]=x?+x[2]:0,y[b]=x?+x[3]:-1;let P=c[b];for(let E of l.steps)d[P]=t(E),f[P++]=Q(E)?1:0;return x?x[1]:l.name});return{nodes:{names:e,lengths:Int32Array.from(a.nodeSequences,l=>l.length),refs:new Int32Array(n).fill(-1),starts:new Float64Array(n),ranks:new Int32Array(n),refNames:[]},links:{from:o,to:r,strands:i},walks:{names:g,starts:p,ends:y,offsets:c,steps:d,reversed:f}}}export{le as a,St as b,En as c,kn as d,ps as e,us as f,ws as g,gs as h,Pn as i,ms as j,xs as k};
|
|
9
|
-
//# sourceMappingURL=chunk-
|
|
9
|
+
//# sourceMappingURL=chunk-EVKN4Y3R.js.map
|