jbrowse-plugin-graphgenomeviewer 4.0.20 → 4.0.22
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 +5 -2
- package/dist/chunks/AddTrackWorkflow-NKKGI6SM.js +2 -0
- package/dist/chunks/{AddTrackWorkflow-WYRVQYH2.js.map → AddTrackWorkflow-NKKGI6SM.js.map} +1 -1
- package/dist/chunks/{GbzBaseSyntenyAdapter-KKSNCZXY.js → GbzBaseSyntenyAdapter-HNETLUW4.js} +3 -3
- package/dist/chunks/{GbzBaseSyntenyAdapter-KKSNCZXY.js.map → GbzBaseSyntenyAdapter-HNETLUW4.js.map} +2 -2
- package/dist/chunks/{GraphGenomeView-YKR42OER.js → GraphGenomeView-GMHRO7E4.js} +2 -2
- package/dist/chunks/{GraphGenomeView-YKR42OER.js.map → GraphGenomeView-GMHRO7E4.js.map} +1 -1
- package/dist/chunks/{GraphTrackSettingsDialog-2QV6TPX7.js → GraphTrackSettingsDialog-QF5OMTCH.js} +2 -2
- package/dist/chunks/LinearGraphDisplay-I2OOPQKB.js +2 -0
- package/dist/chunks/{LinearGraphDisplay-AFTQJKEI.js.map → LinearGraphDisplay-I2OOPQKB.js.map} +1 -1
- package/dist/chunks/{MinigraphBubbleAdapter-NRDD66AK.js → MinigraphBubbleAdapter-FIFZYJ27.js} +2 -2
- package/dist/chunks/chunk-2PYVZZ3R.js +3 -0
- package/dist/chunks/chunk-2PYVZZ3R.js.map +7 -0
- package/dist/chunks/{chunk-5E7TVPCI.js → chunk-CLRXQ6BM.js} +2 -2
- package/dist/chunks/chunk-D7XFR2IV.js +2 -0
- package/dist/chunks/chunk-D7XFR2IV.js.map +7 -0
- package/dist/chunks/chunk-DMYUVGGI.js +3 -0
- package/dist/chunks/{chunk-QSH263Y6.js.map → chunk-DMYUVGGI.js.map} +4 -4
- package/dist/chunks/chunk-JXSDDOKD.js +3 -0
- package/dist/chunks/chunk-JXSDDOKD.js.map +7 -0
- package/dist/chunks/chunk-OSTJHAAK.js +2 -0
- package/dist/chunks/chunk-OSTJHAAK.js.map +7 -0
- package/dist/chunks/chunk-VIFXYTIS.js +2 -0
- package/dist/chunks/chunk-VIFXYTIS.js.map +7 -0
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +1 -2
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +2 -2
- package/src/GbzBaseSyntenyAdapter/GbzBaseSyntenyAdapter.ts +1 -1
- package/src/GetSubgraph.ts +3 -0
- package/src/GraphGenomeView/components/FacetPanels.tsx +204 -0
- package/src/GraphGenomeView/components/GenePins.tsx +12 -5
- package/src/GraphGenomeView/components/GraphCanvas.tsx +86 -42
- package/src/GraphGenomeView/components/ReferenceStripOverlay.tsx +19 -7
- package/src/GraphGenomeView/model.test.ts +36 -10
- package/src/GraphGenomeView/model.ts +130 -9
- package/src/GraphGenomeView/viewModel.ts +15 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +23 -2
- package/src/LinearGraphDisplay/model.ts +7 -2
- package/src/version.ts +1 -1
- package/dist/chunks/AddTrackWorkflow-WYRVQYH2.js +0 -2
- package/dist/chunks/LinearGraphDisplay-AFTQJKEI.js +0 -2
- package/dist/chunks/chunk-47UXFQEI.js +0 -2
- package/dist/chunks/chunk-47UXFQEI.js.map +0 -7
- package/dist/chunks/chunk-ERKI3TAL.js +0 -3
- package/dist/chunks/chunk-ERKI3TAL.js.map +0 -7
- package/dist/chunks/chunk-IUIIYSGF.js +0 -2
- package/dist/chunks/chunk-IUIIYSGF.js.map +0 -7
- package/dist/chunks/chunk-QSH263Y6.js +0 -2
- package/dist/chunks/chunk-SCMIJAAX.js +0 -3
- package/dist/chunks/chunk-SCMIJAAX.js.map +0 -7
- package/dist/chunks/chunk-XK7OPCRQ.js +0 -2
- package/dist/chunks/chunk-XK7OPCRQ.js.map +0 -7
- /package/dist/chunks/{GraphTrackSettingsDialog-2QV6TPX7.js.map → GraphTrackSettingsDialog-QF5OMTCH.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-NRDD66AK.js.map → MinigraphBubbleAdapter-FIFZYJ27.js.map} +0 -0
- /package/dist/chunks/{chunk-5E7TVPCI.js.map → chunk-CLRXQ6BM.js.map} +0 -0
package/README.md
CHANGED
|
@@ -24,14 +24,17 @@ session spec does the same with `loadedTrackId` and `loadedRegion`.
|
|
|
24
24
|
|
|
25
25
|

|
|
26
26
|
|
|
27
|
+

|
|
28
|
+
|
|
27
29
|
## Features
|
|
28
30
|
|
|
29
31
|
- Seven layouts: force-directed (Bandage FMMM), ordered, anchored, sample rows,
|
|
30
32
|
walk rows, and sequenceTubeMap's tube map on its own axis or the reference's
|
|
31
33
|
- Genes from the session's annotation track, drawn on the graph
|
|
32
34
|
- Bubbles from `gfatools bubble` or the graph itself, opened level by level
|
|
33
|
-
- gbz-base haplotypes as walks: carriage as node thickness,
|
|
34
|
-
|
|
35
|
+
- gbz-base haplotypes as walks: carriage as node thickness, walks lifted out as
|
|
36
|
+
metro-map lanes or side by side, one panel per walk, each shading from its
|
|
37
|
+
start to its end
|
|
35
38
|
- GAF reads in the tube map, with their mismatches, from a gbz-base track
|
|
36
39
|
|
|
37
40
|
## Usage
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as F,b as T,h as y}from"./chunk-OSTJHAAK.js";import{a as W}from"./chunk-FCWXYIFC.js";import"./chunk-D7XFR2IV.js";import{a as N}from"./chunk-J4OLMLS5.js";import{a as C,b as B,c as H,d as _,e as O}from"./chunk-XEJ47DLD.js";import{a as w,b as t}from"./chunk-FY3BTKY4.js";var S=w((q,L)=>{L.exports=JBrowseExports["@jbrowse/core/util/tss-react"]});var s=t(O(),1),i=t(_(),1),l=t(N(),1),A=t(S(),1),R=t(W(),1),e=t(H(),1),x=t(B(),1);var o=t(C(),1),j=(0,A.makeStyles)()(n=>({paper:{margin:n.spacing(),padding:n.spacing()},field:{marginTop:n.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),D=["RgfaTabixAdapter","MinigraphBubbleAdapter"],J=(0,x.observer)(function({model:r}){let{classes:c}=j(),h=(0,l.getSession)(r),b=(0,R.getRoot)(r),[m,G]=(0,s.useState)("RgfaTabixAdapter"),[p,v]=(0,s.useState)(),[g,P]=(0,s.useState)(),[u,I]=(0,s.useState)(""),[d,M]=(0,s.useState)("Pangenome graph"),[f,k]=(0,s.useState)();function E(){if(!(!p||!r.assembly))try{k(void 0);let a=d.trim();(0,l.addTrackFromWidget)({model:r,session:h,conf:y({choice:m,loc:p,indexLoc:g,assembly:r.assembly,sample:u,trackId:(0,l.makeTrackId)({name:a}),name:a})})}catch(a){k(a)}}return(0,o.jsxs)(e.Paper,{className:c.paper,children:[f?(0,o.jsx)(i.ErrorMessage,{error:f}):null,(0,o.jsxs)(e.FormControl,{children:[(0,o.jsx)(e.FormLabel,{children:"File type"}),(0,o.jsx)(e.RadioGroup,{value:m,onChange:a=>{G(a.target.value)},children:D.map(a=>(0,o.jsx)(e.FormControlLabel,{value:a,control:(0,o.jsx)(e.Radio,{}),label:F[a]},a))})]}),(0,o.jsx)(i.FileSelector,{location:p,name:T[m],rootModel:b,setLocation:v}),(0,o.jsx)(i.FileSelector,{location:g,name:"Path to tabix index (optional; the sibling .tbi is assumed, a .csi is recognised by name)",rootModel:b,setLocation:P}),(0,o.jsx)(e.TextField,{className:c.field,value:u,onChange:a=>{I(a.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare",placeholder:"GRCh38",fullWidth:!0}),(0,o.jsx)(e.TextField,{className:c.field,value:d,helperText:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:a=>{M(a.target.value)}}),(0,o.jsx)(i.AssemblySelector,{session:h,helperText:"Select assembly to add track to",selected:r.assembly,onChange:a=>{r.setAssembly(a)},fullWidth:!0}),(0,o.jsx)(e.Button,{variant:"contained",className:c.submit,disabled:!p||!d.trim()||!r.assembly,onClick:E,children:"Submit"})]})}),K=J;export{K as default};
|
|
2
|
+
//# sourceMappingURL=AddTrackWorkflow-NKKGI6SM.js.map
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["global-externals:@jbrowse/core/util/tss-react", "../../src/GraphAddTrackWorkflow/AddTrackWorkflow.tsx"],
|
|
4
4
|
"sourcesContent": ["module.exports = JBrowseExports[\"@jbrowse/core/util/tss-react\"];", "import { useState } from 'react'\n\nimport { AssemblySelector, ErrorMessage, FileSelector } from '@jbrowse/core/ui'\nimport { addTrackFromWidget, getSession, makeTrackId } from '@jbrowse/core/util'\nimport { makeStyles } from '@jbrowse/core/util/tss-react'\nimport { getRoot } from '@jbrowse/mobx-state-tree'\nimport {\n Button,\n FormControl,\n FormControlLabel,\n FormLabel,\n Paper,\n Radio,\n RadioGroup,\n TextField,\n} from '@mui/material'\nimport { observer } from 'mobx-react'\n\nimport {\n GRAPH_FILE_FIELDS,\n GRAPH_FILE_LABELS,\n buildTrackConfig,\n} from './buildTrackConfig'\n\nimport type { GraphFileChoice } from './buildTrackConfig'\nimport type {\n AbstractRootModel,\n AddTrackWorkflowModel,\n FileLocation,\n} from '@jbrowse/core/util'\n\nconst useStyles = makeStyles()(theme => ({\n paper: {\n margin: theme.spacing(),\n padding: theme.spacing(),\n },\n field: {\n marginTop: theme.spacing(2),\n },\n submit: {\n marginTop: 25,\n marginBottom: 100,\n display: 'block',\n },\n}))\n\nconst CHOICES: GraphFileChoice[] = [\n 'RgfaTabixAdapter',\n 'MinigraphBubbleAdapter',\n]\n\nconst GraphAddTrackWidget = observer(function GraphAddTrackWidget({\n model,\n}: {\n model: AddTrackWorkflowModel\n}) {\n const { classes } = useStyles()\n const session = getSession(model)\n const rootModel = getRoot<AbstractRootModel>(model)\n const [choice, setChoice] = useState<GraphFileChoice>('RgfaTabixAdapter')\n const [loc, setLoc] = useState<FileLocation>()\n const [indexLoc, setIndexLoc] = useState<FileLocation>()\n const [sample, setSample] = useState('')\n const [trackName, setTrackName] = useState('Pangenome graph')\n const [error, setError] = useState<unknown>()\n\n function handleSubmit() {\n if (!loc || !model.assembly) {\n return\n }\n try {\n setError(undefined)\n const name = trackName.trim()\n addTrackFromWidget({\n model,\n session,\n conf: buildTrackConfig({\n choice,\n loc,\n indexLoc,\n assembly: model.assembly,\n sample,\n trackId: makeTrackId({ name }),\n name,\n }),\n })\n } catch (e) {\n setError(e)\n }\n }\n\n return (\n <Paper className={classes.paper}>\n {error ? <ErrorMessage error={error} /> : null}\n <FormControl>\n <FormLabel>File type</FormLabel>\n <RadioGroup\n value={choice}\n onChange={event => {\n setChoice(event.target.value as GraphFileChoice)\n }}\n >\n {CHOICES.map(option => (\n <FormControlLabel\n key={option}\n value={option}\n control={<Radio />}\n label={GRAPH_FILE_LABELS[option]}\n />\n ))}\n </RadioGroup>\n </FormControl>\n <FileSelector\n location={loc}\n name={GRAPH_FILE_FIELDS[choice]}\n rootModel={rootModel}\n setLocation={setLoc}\n />\n <FileSelector\n location={indexLoc}\n name=\"Path to tabix index (optional; the sibling .tbi is assumed, a .csi is recognised by name)\"\n rootModel={rootModel}\n setLocation={setIndexLoc}\n />\n <TextField\n className={classes.field}\n value={sample}\n onChange={event => {\n setSample(event.target.value)\n }}\n label=\"Sample name in the graph\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-sample-input' } }}\n helperText=\"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare\"\n placeholder=\"GRCh38\"\n fullWidth\n />\n <TextField\n className={classes.field}\n value={trackName}\n helperText=\"Track name\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-track-name-input' } }}\n onChange={event => {\n setTrackName(event.target.value)\n }}\n />\n <AssemblySelector\n session={session}\n helperText=\"Select assembly to add track to\"\n selected={model.assembly}\n onChange={arg => {\n model.setAssembly(arg)\n }}\n fullWidth\n />\n <Button\n variant=\"contained\"\n className={classes.submit}\n disabled={!loc || !trackName.trim() || !model.assembly}\n onClick={handleSubmit}\n >\n Submit\n </Button>\n </Paper>\n )\n})\n\nexport default GraphAddTrackWidget\n"],
|
|
5
|
-
"mappings": "
|
|
5
|
+
"mappings": "qRAAA,IAAAA,EAAAC,EAAA,CAAAC,EAAAC,IAAA,CAAAA,EAAO,QAAU,eAAe,8BAA8B,ICA9D,IAAAC,EAAyB,SAEzBC,EAA6D,SAC7DC,EAA4D,SAC5DC,EAA2B,SAC3BC,EAAwB,SACxBC,EASO,SACPC,EAAyB,SA6EV,IAAAC,EAAA,SA9DTC,KAAY,cAAW,EAAEC,IAAU,CACvC,MAAO,CACL,OAAQA,EAAM,QAAQ,EACtB,QAASA,EAAM,QAAQ,CACzB,EACA,MAAO,CACL,UAAWA,EAAM,QAAQ,CAAC,CAC5B,EACA,OAAQ,CACN,UAAW,GACX,aAAc,IACd,QAAS,OACX,CACF,EAAE,EAEIC,EAA6B,CACjC,mBACA,wBACF,EAEMC,KAAsB,YAAS,SAA6B,CAChE,MAAAC,CACF,EAEG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIL,EAAU,EACxBM,KAAU,cAAWF,CAAK,EAC1BG,KAAY,WAA2BH,CAAK,EAC5C,CAACI,EAAQC,CAAS,KAAI,YAA0B,kBAAkB,EAClE,CAACC,EAAKC,CAAM,KAAI,YAAuB,EACvC,CAACC,EAAUC,CAAW,KAAI,YAAuB,EACjD,CAACC,EAAQC,CAAS,KAAI,YAAS,EAAE,EACjC,CAACC,EAAWC,CAAY,KAAI,YAAS,iBAAiB,EACtD,CAACC,EAAOC,CAAQ,KAAI,YAAkB,EAE5C,SAASC,GAAe,CACtB,GAAI,GAACV,GAAO,CAACN,EAAM,UAGnB,GAAI,CACFe,EAAS,MAAS,EAClB,IAAME,EAAOL,EAAU,KAAK,KAC5B,sBAAmB,CACjB,MAAAZ,EACA,QAAAE,EACA,KAAMgB,EAAiB,CACrB,OAAAd,EACA,IAAAE,EACA,SAAAE,EACA,SAAUR,EAAM,SAChB,OAAAU,EACA,WAAS,eAAY,CAAE,KAAAO,CAAK,CAAC,EAC7B,KAAAA,CACF,CAAC,CACH,CAAC,CACH,OAASE,EAAG,CACVJ,EAASI,CAAC,CACZ,CACF,CAEA,SACE,QAAC,SAAM,UAAWlB,EAAQ,MACvB,UAAAa,KAAQ,OAAC,gBAAa,MAAOA,EAAO,EAAK,QAC1C,QAAC,eACC,oBAAC,aAAU,qBAAS,KACpB,OAAC,cACC,MAAOV,EACP,SAAUgB,GAAS,CACjBf,EAAUe,EAAM,OAAO,KAAwB,CACjD,EAEC,SAAAtB,EAAQ,IAAIuB,MACX,OAAC,oBAEC,MAAOA,EACP,WAAS,OAAC,UAAM,EAChB,MAAOC,EAAkBD,CAAM,GAH1BA,CAIP,CACD,EACH,GACF,KACA,OAAC,gBACC,SAAUf,EACV,KAAMiB,EAAkBnB,CAAM,EAC9B,UAAWD,EACX,YAAaI,EACf,KACA,OAAC,gBACC,SAAUC,EACV,KAAK,4FACL,UAAWL,EACX,YAAaM,EACf,KACA,OAAC,aACC,UAAWR,EAAQ,MACnB,MAAOS,EACP,SAAUU,GAAS,CACjBT,EAAUS,EAAM,OAAO,KAAK,CAC9B,EACA,MAAM,2BACN,UAAW,CAAE,UAAW,CAAE,cAAe,oBAAqB,CAAE,EAChE,WAAW,qJACX,YAAY,SACZ,UAAS,GACX,KACA,OAAC,aACC,UAAWnB,EAAQ,MACnB,MAAOW,EACP,WAAW,aACX,UAAW,CAAE,UAAW,CAAE,cAAe,wBAAyB,CAAE,EACpE,SAAUQ,GAAS,CACjBP,EAAaO,EAAM,OAAO,KAAK,CACjC,EACF,KACA,OAAC,oBACC,QAASlB,EACT,WAAW,kCACX,SAAUF,EAAM,SAChB,SAAUwB,GAAO,CACfxB,EAAM,YAAYwB,CAAG,CACvB,EACA,UAAS,GACX,KACA,OAAC,UACC,QAAQ,YACR,UAAWvB,EAAQ,OACnB,SAAU,CAACK,GAAO,CAACM,EAAU,KAAK,GAAK,CAACZ,EAAM,SAC9C,QAASgB,EACV,kBAED,GACF,CAEJ,CAAC,EAEMS,EAAQ1B",
|
|
6
6
|
"names": ["require_tss_react", "__commonJSMin", "exports", "module", "import_react", "import_ui", "import_util", "import_tss_react", "import_mobx_state_tree", "import_material", "import_mobx_react", "import_jsx_runtime", "useStyles", "theme", "CHOICES", "GraphAddTrackWidget", "model", "classes", "session", "rootModel", "choice", "setChoice", "loc", "setLoc", "indexLoc", "setIndexLoc", "sample", "setSample", "trackName", "setTrackName", "error", "setError", "handleSubmit", "name", "buildTrackConfig", "e", "event", "option", "GRAPH_FILE_LABELS", "GRAPH_FILE_FIELDS", "arg", "AddTrackWorkflow_default"]
|
|
7
7
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as Ir,b as Ar,c as Rr,d as Ts}from"./chunk-JAQ2RQAE.js";import{a as Cr}from"./chunk-QSH263Y6.js";import{a as Pr}from"./chunk-KWAXLUPQ.js";import"./chunk-LGKM2PZH.js";import{a as Ns,e as Mr,f as _r}from"./chunk-XK7OPCRQ.js";import{a as et}from"./chunk-J4OLMLS5.js";import{a as kr,b as Or}from"./chunk-SCMIJAAX.js";import"./chunk-EFVAQ2KM.js";import{a as Er,e as ze,f as je,g as Pn}from"./chunk-KULNKXPT.js";import{a as Ls,b as le}from"./chunk-FY3BTKY4.js";var ys=Ls((xp,ws)=>{ws.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function me(n,e){return 2*n+(e==="reverse"?1:0)}function _(n){return Math.floor(n/2)}function Ue(n){return n%2===0?"forward":"reverse"}function q(n){return n%2===1}function K(n){return n%2===0?n+1:n-1}function Lr(n){return n==="left"?"right":"left"}function bt(n){return n==="forward"?"left":"right"}function St(n){return n==="forward"?"right":"left"}function Tr(n){return n==="left"?"forward":"reverse"}function Nr(n){return n==="right"?"forward":"reverse"}function We(n,e){let t=_(n),r=_(e);return q(n)?r>t||r===t&&!q(e):r>=t}function Fr(n){return Ne(n[0],n[n.length-1])}function Ne(n,e){return n===void 0||e===void 0?!0:q(n)===q(e)?!q(n):We(n,e)}var tt=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},qr=255,qs=256,vt=class{source;sigma;threshold;constructor(e,t){this.source=new tt(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<qr?Math.floor(qs/this.sigma):0}next(){if(this.sigma>=qr){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let o=this.source.int();if(o===void 0)return;r+=o}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function $r(n){let e=new tt(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var It=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new vt(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:K(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];_(s.node)===_(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var $s=["","A","C","G","T","N"];function Hr(n){let e=n[n.length-1];if(e===void 0)return 0;let t=e,r=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),r+=1;return 3*(n.length-1)+r}function Gr(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=$s[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var Hs={A:"T",C:"G",G:"C",T:"A",N:"N"};function At(n){let e="";for(let t=n.length-1;t>=0;t--)e+=Hs[n[t]]??"N";return e}function Br(n,e){let t=new Map;if(n!==void 0)for(let r of n.split(";")){let o=r.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function jr(n){return{name:n.get("pggname"),subgraph:Br(n.get("subgraph"),"subgraph"),translation:Br(n.get("translation"),"translation")}}function Dr(n,e){for(let[t,r]of e){let o=n.get(t);o||(o=new Set,n.set(t,o));for(let s of r)o.add(s)}}function Ur(n,e){let t={name:n,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(n,new Set([e.name])),Dr(t.subgraph,e.subgraph),Dr(t.translation,e.translation)),t}function zr(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function Wr(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of zr(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of zr(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function Qr(n){let e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;let o=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(o)].map(s=>s.toString(16).padStart(2,"0")).join("")}var Gs="_gbwt_ref";function ge(n,e){return`${n.sample}#${n.haplotype}#${n.contig}[${n.fragment}-${e}]`}var Bs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Ds=/^([^#]+?)(?:\[\d+-\d+\])?$/;function zs(n){let e=Bs.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Ds.exec(n);if(t)return{contig:t[1]};throw new Error(`"${n}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Yr(n){return typeof n=="string"?zs(n):n}function Et(n,e){return{sample:n.sample??Gs,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var js=4096;function kn(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=js?r[1]=t:e.push([t,t])}return e}var Ee=32768,Vr={mostChosenPaths:32},_n=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let r=this.byNode.get(e.node);r||(r=new Map,this.byNode.set(e.node,r)),r.set(e.offset,t)}},ne=class extends Error{};function nt(n,e,t,r){return n==="forward"?e+t:e-r}function Mn(n,e,t,r){return n==="forward"?e-r:e+t}function Kr(n){return Ne(K(n.handles[n.handles.length-1]),K(n.handles[0]))}function Fe(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function Xr(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let v=performance.now(),C=v-o;return o=v,C},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,seeds:0,pieces:0,sources:{reference:0,sample:0,interval:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,intervals:0,seeds:0,chains:0,twins:0}},a=(v,C)=>{let P=`${v}: ${C}`;i.walks[P]=(i.walks[P]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async v=>{let C=t.get(v)??c.get(v);if(C)return C;let P=await e.getRecord(v);if(i.graphFetches+=1,!P)throw new Error(`Node record ${v} is missing from the database`);return c.set(v,P),P},p=v=>t.get(v).sequenceLen,u=await e.pathsByHandle(),d=v=>{let C=u.get(v);return C!==void 0&&n.keep(C.name)},h=[],m=new _n,y=new Map,S=new Set,I=new Set,g=async v=>{let C=(await l(v.node)).gbwt().lf(v.offset);return C===void 0||C.node===0?void 0:C},b=async(v,C)=>{let P=(await l(K(v.node))).gbwt().predecessorAt(v.offset);if(P===void 0||C!==void 0&&!C.has(P))return;let G=(await l(P)).gbwt().offsetTo(v);if(G===void 0)throw new Error(`No offset in ${P} leads to ${v.node}:${v.offset}`);return{node:P,offset:G}},x=(v,C,P,G)=>{let j=P.map(ae=>ae.pos.node),X=P.map(ae=>ae.pos.offset),ee=0;for(let ae of j)ee+=p(ae);let te=C==="forward"?P[0].left:P[P.length-1].left,ve=h.length;h.push({pathHandle:v,orientation:C,handles:j,offsets:X,len:ee,hapStart:te,hapEnd:te+ee,canonical:Ne(j[0],j[j.length-1]),source:G});for(let ae of P)m.set(ae.pos,ve);let Oe=y.get(v);return Oe?Oe.push(ve):y.set(v,[ve]),ve},A=async(v,C,P,G)=>{let j=[],X=v;for(;;){r?.throwIfAborted();let te=await b(X.pos,t);if(!te)break;X={pos:te,left:Mn(P,X.left,p(X.pos.node),p(te.node))},j.push(X)}j.reverse();let ee=[v];for(X=v;;){r?.throwIfAborted();let te=await g(X.pos);if(!te||!t.has(te.node))break;X={pos:te,left:nt(P,X.left,p(X.pos.node),p(te.node))},ee.push(X)}return x(C,P,[...j,...ee],G)},M=async(v,C,P,G)=>h[m.get(v.pos)??await A(v,C,P,G)],L=v=>{let C=v.handles[v.handles.length-1];return{pos:{node:C,offset:v.offsets[v.offsets.length-1]},left:v.orientation==="forward"?v.hapEnd-p(C):v.hapStart}},k=v=>{let C=v.handles[0];return{pos:{node:C,offset:v.offsets[0]},left:v.orientation==="forward"?v.hapStart:v.hapEnd-p(C)}},T=await A({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),R=h[T],B=()=>{if(i.fallback!==void 0)return{reference:R,pieces:[],stats:i};let v=new Map;h.forEach((P,G)=>{G!==T&&v.set(Fe(P),[...v.get(Fe(P))??[],P])});let C=[];for(let P of v.values()){let G=new Set;for(let j of P)j.canonical&&!G.has(j.orientation)&&(G.add(j.orientation),C.push(j),i.sources[j.source]+=1)}return i.sources.reference=1,i.pieces=C.length,{reference:R,pieces:C,stats:i}};try{let v=i.spacing;if(v===void 0)throw new ne("the haplotype index has no anchors");let C=Math.floor(n.window.start/v),P=Math.ceil(n.window.end/v),G=w=>w>=0?e.haplotypeAnchor(n.referenceHandle,w*v):Promise.resolve(void 0),[j,X]=await Promise.all([Promise.all([0,1,2].map(w=>G(C-w))),Promise.all([0,1,2,3].map(w=>G(P+w)))]),ee=j[0],te=X.slice(0,2).findIndex(w=>w!==void 0&&w.pathOffset>=n.window.end),ve=X[te];if(!ee)throw new ne("the haplotype index has no anchor before the window");if(!ve)throw new ne("the haplotype index has no anchor after the window");i.anchors=[ee.pathOffset,ve.pathOffset];let Oe=j.filter(w=>w!==void 0),ae=X.slice(te,te+3).filter(w=>w!==void 0),Es=w=>{let E=w-w%2;return e.haplotypeSamplesInRange(E,E+1)},ht=new Map,bn=[...Oe,...ae],Cs=await Promise.all(bn.map(w=>Es(w.node)));if(bn.forEach((w,E)=>ht.set(w,Cs[E])),i.anchorsRead=bn.length,!ht.get(ee).some(w=>w.pathHandle===n.referenceHandle&&w.orientation==="forward"&&w.pathOffset===ee.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${ee.pathOffset} (node ${_(ee.node)}); it does not match this graph`);let yr=(w,E)=>{for(let O of w){let Z=ht.get(O).filter(W=>W.pathHandle===E);if(Z.length>0)return{anchor:O,rows:Z}}},De=new Map,dt=(w,E)=>{let O=De.get(w);O[0]=Math.min(O[0],E),O[1]=Math.max(O[1],E)},ut=[],Sn=new Set,Rs=async w=>{let E=yr(Oe,w),O=yr(ae,w);if(!E&&!O)return;let Z=E?.rows??[],W=O?.rows??[],Y=[...Z,...W].map(z=>z.pathOffset);De.set(w,[Math.min(...Y),Math.max(...Y)]);let N=E?.anchor??ee,Q=O?.anchor??ve,$=Q.pathOffset-N.pathOffset,H=d(w),V=!1;for(let z of Z){let U=z.orientation==="forward"?1:-1,fe=W.filter(Ae=>Ae.orientation===z.orientation&&(Ae.pathOffset-z.pathOffset)*U>0).sort((Ae,xt)=>(Ae.pathOffset-xt.pathOffset)*U)[0];if(!fe)continue;let ye=z.node===N.node,Le=fe.node===Q.node,Ie=fe.pathOffset,Te=0;ye&&!Le?Ie+=U*((await l(fe.node)).sequenceLen+$):!ye&&Le&&(Te=$),dt(w,Ie),dt(w,z.pathOffset-U*Te),V=!0,H&&(ut.push({row:z,stopAt:Ie,back:Te,kind:ye===Le?"interval":"inversion"}),Sn.add(w))}if(!V){let z=De.get(w);dt(w,z[0]-$),dt(w,z[1]+$);for(let U of[...Z,...W])if(H&&(U.node===N.node||U.node===K(Q.node))){let fe=U.orientation==="forward"?1:-1;ut.push({row:U,stopAt:U.pathOffset+fe*$,back:0,kind:"one-sided"}),Sn.add(w)}}return V?"paired":"one-sided"},xr=new Set([...ht.values()].flat().map(w=>w.pathHandle)),mt=[...xr].filter(d);if(i.chosenPaths=mt.length,mt.length>Vr.mostChosenPaths)throw new ne(`${mt.length} chosen paths pass the anchors, more than ${Vr.mostChosenPaths}`);for(let w of xr)await Rs(w);let vn=[],In=[];i.scans=kn([...t.keys()].sort((w,E)=>w-E));for(let[w,E]of i.scans)for(let O of await e.haplotypeSamplesInRange(w,E))i.scanRows+=1,t.has(O.node)&&(In.push(O),d(O.pathHandle)&&vn.push(O));if(mt.length===0&&vn.length===0&&[...u.values()].some(w=>n.keep(w.name)))throw new ne("no chosen path passes the anchors or has a sample on the window's nodes");let Ps=new Set(In.map(w=>w.pathHandle).filter(w=>!De.has(w))),Ms=ae[ae.length-1].pathOffset-Oe[Oe.length-1].pathOffset;for(let w of Ps){let E=await e.haplotypeLength(w)??Number.POSITIVE_INFINITY;if(E>Ms+2*Ee)throw new ne(`path ${w} of ${E} bp has a sample on the window's nodes and no visit to the anchors`);if(d(w)){let O=(await e.getPath(w))?.fwStart;if(!O)throw new Error(`Path ${w} is missing from the database`);ut.push({row:{node:O.node,offset:O.offset,pathHandle:w,orientation:"forward",pathOffset:0},stopAt:E,back:0,kind:"whole"})}}for(let w of De.keys())if(d(w)&&!Sn.has(w))throw new ne(`chosen path ${w} has no walk from its visits to the anchors`);for(let w of In){let E=De.get(w.pathHandle);if(E&&(w.pathOffset<E[0]-Ee||w.pathOffset>E[1]+Ee))throw new ne(`path ${w.pathHandle} has a sample at ${w.pathOffset} on the window's nodes far from its anchor visits at ${E[0]}-${E[1]}`)}i.ms.scan=s();let An=new Map;await n.prefetchReferenceRange(n.referenceHandle,ee.pathOffset,ve.pathOffset+1);let br=8*v+2*(n.window.end-n.window.start);for(let{row:w,stopAt:E,back:O,kind:Z}of ut){let W=w.orientation,Y=(J,ue)=>W==="forward"?ue-J:J-ue,N=w.pathOffset,Q=w.pathOffset,$,H={node:w.node,offset:w.offset},V=w.pathOffset,z=!1,U=0,fe=0,ye="past the far anchor";for(;H&&(r?.throwIfAborted(),!z&&Y(V,E)<=0&&(z=!0),!(z&&U>Ee));){let J;if(t.has(H.node)){$??=V;let ce=await M({pos:H,left:V},w.pathHandle,W,"interval"),Rn=L(ce);H=Rn.pos,V=Rn.left,J=p(Rn.pos.node),N=Math.min(N,ce.hapStart),Q=Math.max(Q,ce.hapEnd),U=0}else{if(J=(await l(H.node)).sequenceLen,U+=J,fe+=J,fe>br){ye="cap";break}N=Math.min(N,V),Q=Math.max(Q,V+J)}let ue=await g(H);ue&&(V=nt(W,V,J,(await l(ue.node)).sequenceLen)),H=ue}if(!H&&ye!=="cap"&&(ye="endmarker"),a(Z,ye),ye==="cap")throw new ne(`the walk of path ${w.pathHandle} between the anchors reached its cap of ${br} bp`);if(Z==="one-sided"&&ye!=="endmarker")throw new ne(`chosen path ${w.pathHandle} runs on past the stretch from its visit to one anchor without a visit to the other`);let Le=$===void 0?0:Ee-Y(w.pathOffset,$),Ie={pos:{node:w.node,offset:w.offset},left:w.pathOffset},Te=0,Ae=O;for(;Le>0||Ae>0;){r?.throwIfAborted();let J=await b(Ie.pos);if(!J)break;let ue=Mn(W,Ie.left,(await l(Ie.pos.node)).sequenceLen,(await l(J.node)).sequenceLen);if(t.has(J.node)){let ce=await M({pos:J,left:ue},w.pathHandle,W,"interval");Ie=k(ce),N=Math.min(N,ce.hapStart),Q=Math.max(Q,ce.hapEnd),Le=Ee,Te=0,Ae-=ce.len}else{let ce=(await l(J.node)).sequenceLen;if(Te+=ce,Te>Le&&Ae<=0)break;Ae-=ce,Ie={pos:J,left:ue},N=Math.min(N,ue),Q=Math.max(Q,ue+ce)}}let xt=An.get(w.pathHandle);xt?xt.push([N,Q]):An.set(w.pathHandle,[[N,Q]])}let _s=w=>(An.get(w.pathHandle)??[]).some(([E,O])=>E<=w.hapStart&&w.hapEnd<=O);i.ms.intervals=s();for(let w of vn)m.get(w)===void 0&&!(y.get(w.pathHandle)??[]).some(E=>{let O=h[E];return O.canonical&&!Kr(O)&&O.hapStart<=w.pathOffset&&w.pathOffset<O.hapEnd})&&(i.seeds+=1,await A({pos:{node:w.node,offset:w.offset},left:w.pathOffset},w.pathHandle,w.orientation,"sample"));i.ms.seeds=s();let gt=async(w,E)=>{let O=E?S:I,Z=E?I:S,W=w;for(;;){if(O.has(W))return;O.add(W);let Y=h[W],N=E?L(Y):k(Y),Q=0,$;for(;$===void 0;){r?.throwIfAborted();let H=E?await g(N.pos):await b(N.pos);if(!H){$="endmarker";break}let V=(await l(N.pos.node)).sequenceLen,z=(await l(H.node)).sequenceLen,U=E?nt(Y.orientation,N.left,V,z):Mn(Y.orientation,N.left,V,z);if(t.has(H.node)){let fe=m.get(H);fe===void 0?(W=await A({pos:H,left:U},Y.pathHandle,Y.orientation,"chain"),Z.add(W),$="landed"):(Z.add(fe),$="merge")}else Q>Ee?$="bound":(Q+=z,N={pos:H,left:U})}if(a("chain",$),$!=="landed")return}};await Promise.all([n.prefetchReferenceRange(n.referenceHandle,Math.max(0,R.hapStart-Ee),R.hapStart),n.prefetchReferenceRange(n.referenceHandle,R.hapEnd,R.hapEnd+Ee)]);let Sr=new Set,ks=h.map((w,E)=>({piece:w,id:E})).filter(({piece:w,id:E})=>E!==T&&!_s(w)).sort((w,E)=>Number(E.piece.canonical)-Number(w.piece.canonical));for(let{piece:w,id:E}of ks)Sr.has(Fe(w))||(Sr.add(Fe(w)),await gt(E,!0),await gt(E,!1));i.ms.chains=s();let En=new Map,Os=w=>{let E=Fe(w),O=En.get(E);O?O.add(w.orientation):En.set(E,new Set([w.orientation]))},wt=0,Cn=()=>{for(;wt<h.length;wt++)wt!==T&&Os(h[wt])};Cn();let yt=w=>(En.get(Fe(w))?.size??0)>1,vr=2*f;for(let w=0;w<h.length;w++){let E=h[w];if(w===T||yt(E)||E.canonical&&!Kr(E))continue;i.twins.tried+=1;let O=E.orientation==="forward"?"reverse":"forward",Z=L(E),W=0,Y;for(;!Y&&W<=vr;){r?.throwIfAborted();let $=await g(Z.pos);if(!$)break;let H=(await l($.node)).sequenceLen,V=nt(E.orientation,Z.left,(await l(Z.pos.node)).sequenceLen,H),z=K($.node);Y=(await e.haplotypeSamplesInRange(z,z)).find(U=>U.pathHandle===E.pathHandle&&U.orientation===O&&U.pathOffset===V),W+=H,Z={pos:$,left:V}}let N=Y&&{pos:{node:Y.node,offset:Y.offset},left:Y.pathOffset},Q=0;for(;N&&!yt(E)&&Q<=vr+E.len;){if(r?.throwIfAborted(),t.has(N.pos.node)){let $=await M(N,E.pathHandle,O,"twin"),H=h.indexOf($);await gt(H,!0),await gt(H,!1),Cn(),N=L($)}if(!yt(E)){let $=(await l(N.pos.node)).sequenceLen;Q+=$;let H=await g(N.pos);N=H?{pos:H,left:nt(O,N.left,$,(await l(H.node)).sequenceLen)}:void 0}}if(Cn(),!yt(E))throw new ne(`piece ${Fe(E)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()}catch(v){if(!(v instanceof ne))throw v;i.fallback=v.message}return B()}function Zr(n,e){let t=n.handles[0],r=e.handles[0];return Number(q(t))-Number(q(r))||t-r||n.offsets[0]-e.offsets[0]}function Ct(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var Rt=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},On=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Ct(a,o)-Ct(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),p=Ct(c,o),u=Ct(c,s);for(let d=0;d<u-p;d++){let h=r===1?c[u-1-d]-o:s-1-c[p+d],m=i.bestBefore(h),y=(m===-1?0:i.ending[m])+l;if(y>i.ending[h]&&(i.raise(h,y),a)){let S=a.count++;a.row[S]=f,a.column[S]=h,a.previous[S]=m===-1?-1:a.endingMatch[m],a.endingMatch[h]=S}}}}chain(e,t,r,o,s){let i=new Rt(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let f=i.bestBefore(o-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,o,s){let i=new Rt(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let f=0;f<s-o;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(r-1,t-1,-1,o,s),c=0,l=-1;for(let p=0;p<=i;p++){let u=a[p]+f[i-p];u>l&&(l=u,c=p)}return o+c}};function Jr(n,e,t){let r=new On(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Us=100,Nn=4e6,Ws=5e3,oe=15,Qs=64,Ys=8,io=1,Fn=-4,re=-6,Ce=-1,Qe=-(2**30),Mt=0,Ln=1,ao=2;function qe(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function Pt(n,e,t){return n>=t&&n>=e?Mt:t>=e?ao:Ln}function fo(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Qe),f=new Int32Array(s).fill(Qe),c=new Int32Array(s).fill(Qe);a[0]=0;for(let h=1;h<=o;h++)c[h]=re+(h-1)*Ce,i[h]=(h===1?Mt:ao)<<4;for(let h=1;h<=r;h++){let m=new Int32Array(s).fill(Qe),y=new Int32Array(s).fill(Qe),S=new Int32Array(s).fill(Qe);y[0]=re+(h-1)*Ce,i[h*s]=(h===1?Mt:Ln)<<2;let I=n.charCodeAt(h-1);for(let g=1;g<=o;g++){let b=Pt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(I===e.charCodeAt(g-1)?io:Fn);let x=Pt(a[g]+re,f[g]+Ce,c[g]+re);y[g]=Math.max(a[g]+re,f[g]+Ce,c[g]+re);let A=Pt(m[g-1]+re,y[g-1]+re,S[g-1]+Ce);S[g]=Math.max(m[g-1]+re,y[g-1]+re,S[g-1]+Ce),i[h*s+g]=b|x<<2|A<<4}a=m,f=y,c=S}let l=[],p=r,u=o,d=Pt(a[o],f[o],c[o]);for(;p>0||u>0;){let h=i[p*s+u]>>2*d&3;d===Mt?(l.push(n[p-1]===e[u-1]?"=":"X"),p-=1,u-=1):d===Ln?(l.push("I"),p-=1):(l.push("D"),u-=1),d=h}for(let h of l.reverse())qe(t,h,1)}function Vs(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-re-(t-1)*Ce,-re+10*Math.log2(t)))+(Math.min(n,e)>0?-Fn:0)}function co(n,e){let t=Math.abs(n-e);return t===0?0:.01*oe*t+.5*Math.log2(t)}function eo(n,e,t){return{qs:n.qs+e,qe:n.qs+t,ts:n.flipped?n.te-t:n.ts+e,te:n.flipped?n.te-e:n.ts+t,flipped:n.flipped}}function Ks(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-n.qs),l=Math.min(r,f-n.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,n.flipped?n.te-f:a-n.ts),l=Math.min(r,n.flipped?n.te-a:f-n.ts);c<l&&o.push([c,l])}if(o.length===0)return[n];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=oe&&s.push(eo(n,i,a)),i=Math.max(i,f);return r-i>=oe&&s.push(eo(n,i,r)),s}function qn(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...n].sort((c,l)=>c.qs-l.qs||c.ts-l.ts);for(;f.length>0&&s.length<o;){let c=f.map(g=>g.qe-g.qs),l=new Int32Array(f.length).fill(-1),p=new Int32Array(f.length);for(let g=0;g<f.length;g++){let b=f[g],x=b.qe-b.qs;for(let A=g-1;A>=Math.max(0,g-Ws);A--){if(c[A]+x<=c[g])continue;let M=f[A];if(M.flipped===b.flipped&&M.qs<b.qs&&(b.flipped?b.te<M.te:M.ts<b.ts)){let k=Math.max(0,M.qe-b.qs,b.flipped?b.te-M.ts:M.te-b.ts),T=b.qs+k-M.qe,R=b.flipped?M.ts-(b.te-k):b.ts+k-M.te;if(k<x&&T<=e&&R<=e){let B=c[A]+x-k-r(T,R);B>c[g]&&(c[g]=B,l[g]=A,p[g]=k)}}}}let u=0;for(let g=1;g<f.length;g++)c[g]>c[u]&&(u=g);let d=[];for(let g=u;g>=0;g=l[g])d.push({run:f[g],trim:p[g]});if(d.reverse(),d.reduce((g,{run:b,trim:x})=>g+b.qe-b.qs-x,0)<t)break;s.push(d);let m=d[0],y=d.at(-1),{flipped:S}=m.run,I=S?a.flipped:a.forward;I.query.push([m.run.qs+m.trim,y.run.qe]),I.target.push(S?[y.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,y.run.te]);for(let{run:g,trim:b}of d)i.query.push([g.qs+b,g.qe]),i.target.push(g.flipped?[g.ts,g.te-b]:[g.ts+b,g.te]);f=f.flatMap(g=>{let b=g.flipped?a.flipped:a.forward;return Ks(g,[...i.query,...b.query],[...i.target,...b.target])}).sort((g,b)=>g.qs-b.qs||g.ts-b.ts)}return s}function Tn(n,e){let t=new Map;for(let s=0;s+oe<=e.length;s++){let i=e.slice(s,s+oe),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+oe<=n.length;s++){let i=t.get(n.slice(s,s+oe));if(i&&i.length<=Qs)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+oe,c.te=a+oe;else{let l={qs:s,qe:s+oe,ts:a,te:a+oe,flipped:!1};o.set(f,l),r.push(l)}}}return r}function Xs(n,e){return[...Tn(n,e),...Tn(n,At(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function _t(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,p=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?At(p):p,r,s.qe,c)}qe(r,"=",i.qe-f),s=i}}function $n(n,e,t){qe(t,"I",n.length),qe(t,"D",e.length)}function lo(n,e,t){n.length*e.length<=Nn?fo(n,e,t):$n(n,e,t)}function Hn(n,e,t,r=0){let[o]=n.length*e.length>Nn&&r<Ys?qn(Tn(n,e),1/0,oe,co,1):[];if(!o){lo(n,e,t);return}let s=(f,c,l)=>{Hn(f,c,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),_t(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function Zs(n,e,t){Hn(n,e,t)}function Js(n,e,t){let r=[];_t(n,e,t,r,Zs);let o=n[0],s=n.at(-1),{flipped:i}=o.run;return{queryStart:o.run.qs+o.trim,queryEnd:s.run.qe,targetStart:i?s.run.ts:o.run.ts+o.trim,targetEnd:i?o.run.te-o.trim:s.run.te,strand:i?"-":"+",edits:i?r.reverse():r,sharedBases:0}}function ei(n,e,t,r){let o=[];if(n.length*e.length<=Nn)fo(n,e,t);else{let s=qn(Xs(n,e),1/0,Math.max(r,oe),co),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>Js(a,n,e)),i){let a=(l,p,u,d,h)=>{o.some(y=>d<y.queryEnd&&y.queryStart<d+l.length||h<y.targetEnd&&y.targetStart<h+p.length)?lo(l,p,u):Hn(l,p,u)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),_t(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else $n(n,e,t)}return o}function Gn(n,e){let t=n.strand==="-",r=0,o=0;for(let[s,i]of n.edits)e(s,i,t?n.queryEnd-1-r:n.queryStart+r,n.targetStart+o),s!=="D"&&(r+=i),s!=="I"&&(o+=i)}function to(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return Gn(n,(i,a,f,c)=>{let l=e==="query"?f:c,p=u=>{let d=l+o*u;return d>=t&&d<r};if(i==="="||i==="X")for(let u=0;u<a;u++)p(u)&&(s+=i==="="?io:Fn);else if(i==="I"==(e==="query"))for(let u=0;u<a;u++)p(u)&&(s+=u===0?re:Ce);else p(0)&&(s+=re+(a-1)*Ce)}),s}function no(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function ti(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,f=new Uint8Array(n.queryEnd-n.queryStart);for(let[d,h]of n.shared)f.fill(1,d-n.queryStart,h-n.queryStart);let c=d=>f[d-n.queryStart]===1,l=()=>{qe(r,"I",o),qe(r,"D",s),o=0,s=0};Gn(n,(d,h,m)=>{if(d==="I")o+=h;else if(d==="D")s+=h;else{for(let y=0;y<h;y++)e[i+y]?(o+=1,s+=1,c(t?m-y:m+y)&&(a+=1)):((o>0||s>0)&&l(),qe(r,d,1));i+=h}}),l();let p={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[d,h]=r.shift();p[d]+=h}let u={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[d,h]=r.pop();u[d]+=h}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?u.I:p.I),queryEnd:n.queryEnd-(t?p.I:u.I),targetStart:n.targetStart+p.D,targetEnd:n.targetEnd-u.D,edits:r,sharedBases:n.sharedBases-a}}function ni(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];Gn(c,(p,u,d,h)=>{if(p==="="||p==="X")for(let m=0;m<u;m++)l.push([c.strand==="-"?d-m:d+m,h+m])});for(let[p,u]of l)o.query[p]=Math.min(255,o.query[p]+1),o.target[u]=Math.min(255,o.target[u]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[p,u]of c)for(let[d,h]of[["query",p],["target",u]])if(o[d][h]>1){let m=i[d].get(h);m?m.at(-1)!==l&&m.push(l):i[d].set(h,[l])}});let a=new Map,f=(c,l,p)=>{let u=`${p}:${c}:${l}`,d=a.get(u);if(d===void 0){let[h,m]=no(n[c],p),[y,S]=no(n[l],p),I=Math.max(h,y),g=Math.min(m,S),[b,x]=[n[c],n[l]];d=[to(x,p,I,g)-to(b,p,I,g),x.sharedBases-b.sharedBases,c-l].find(M=>M!==0)>0,a.set(u,d)}return d};return n.flatMap((c,l)=>{let p=s[l],u=new Uint8Array(p.length);if(p.forEach(([m,y],S)=>{for(let[I,g]of[["query",m],["target",y]])!u[S]&&i[I].get(g)?.some(b=>b!==l&&f(l,b,I))&&(u[S]=1)}),!u.includes(1))return[c];let d=ti(c,u),h=d?.edits.reduce((m,[y,S])=>m+(y==="="?S:0),0)??0;return d&&h>=r?[d]:[]})}function ro(n,e){return n.map(t=>{let r=e(_(t));return q(t)?At(r):r}).join("")}function oo(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(_(r)).length);return t}function so(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=_(i);e.has(f)?t.set(f,a):e.set(f,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function ri(n,e,t,r){let o=so(n),s=so(e),i=new Map;e.forEach((p,u)=>{s[u]||i.set(_(p),[u])});let a=2*e.length,f=(p,u,d)=>p*a+2*u+(d?1:0),c=new Set;n.forEach((p,u)=>{for(let d of o[u]?[]:i.get(_(p))??[])c.add(f(u,d,q(p)!==q(e[d])))});let l=[];return n.forEach((p,u)=>{for(let d of o[u]?[]:i.get(_(p))??[]){let h=q(p)!==q(e[d]),m=h?-1:1;if(!c.has(f(u-1,d-m,h))){let y=u,S=d;for(;y<n.length&&S>=0&&S<e.length&&c.has(f(y,S,h));)y+=1,S+=m;let I=S-m;l.push({qs:t[u],qe:t[y],ts:r[Math.min(d,I)],te:r[Math.max(d,I)+1],flipped:h})}}}),l}function po(n,e,t,r={}){let o=ro(n,t),s=ro(e,t),i=ri(n,e,oo(n,t),oo(e,t)),a=r.minMatch??Us,f=r.bases??!0,c=[];for(let l of qn(i,r.maxGap??1/0,a,Vs)){let p=[],u=l[0],d=l.at(-1),{flipped:h}=u.run;_t(l,o,s,p,f?(y,S,I,g,b)=>{for(let x of ei(y,S,I,a)){let A=b+S.length;c.push({...x,queryStart:g+x.queryStart,queryEnd:g+x.queryEnd,targetStart:h?A-x.targetEnd:b+x.targetStart,targetEnd:h?A-x.targetStart:b+x.targetEnd,strand:h?"+":"-",edits:h?x.edits.reverse():x.edits,shared:[]})}}:$n),c.push({queryStart:u.run.qs+u.trim,queryEnd:d.run.qe,targetStart:h?d.run.ts:u.run.ts+u.trim,targetEnd:h?u.run.te-u.trim:d.run.te,strand:h?"-":"+",edits:h?p.reverse():p,sharedBases:l.reduce((y,{run:S,trim:I})=>y+S.qe-S.qs-I,0),shared:l.map(({run:y,trim:S})=>[y.qs+S,y.qe])})}return ni(c,o.length,s.length,a).map(({shared:l,...p})=>p).sort((l,p)=>l.queryStart-p.queryStart)}function ho(n){return n.map(([e,t])=>`${t}${e}`).join("")}var Me=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 Bn(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var rt=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Bn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Bn(e[s],e[a])&&(a=s),i<e.length&&Bn(e[i],e[a])&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}}return t}get size(){return this.heap.length}};function oi(n){let e=new Int32Array(n.length),t=new Int32Array(n.length);return n.forEach(([r,o],s)=>{e[s]=r,t[s]=o}),{pathAt:e,refAt:t,count:n.length}}function si(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function $e(n){return`${n.node}:${n.offset}`}function ii(n,e){let t=e.identity.hapStart-n.identity.hapEnd,r=n.strand==="+"?e.refStart-n.refEnd:n.refStart-e.refEnd;return n.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function ai(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);uo(s,t.insertion,t.deletion);for(let[c,l]of o.edits)se(s,c,l);let i=n.identity.walkForward,[a,f]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function fi(n){if(n.some(o=>o.weight!==void 0))return n;let e=new Map;n.forEach((o,s)=>{if(o.identity){let i=e.get(o.identity.pathHandle);i?i.push(s):e.set(o.identity.pathHandle,[s])}});let t=new Map,r=new Set;for(let o of e.values()){o.sort((a,f)=>n[a].identity.hapStart-n[f].identity.hapStart);let s=o[0],i=n[s];for(let a of o.slice(1)){let f=n[a],c=ii(i,f);c?(i=ai(i,f,c),r.add(a)):(t.set(s,i),s=a,i=f)}t.set(s,i)}return n.flatMap((o,s)=>r.has(s)?[]:[t.get(s)??o])}function kt(n,e){return{node:n.path[e],offset:n.offsets[e]}}var ci=32768;function li(n){let e=[...n].sort((r,o)=>r-o),t=[];for(let r of e){let o=t[t.length-1];o&&r-o[1]<=ci?o[1]=r:t.push([r,r])}return t}var Tt=class{records=new Map;paths=[];twinStarts=new Set;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;stats={orderedAlignments:0,lcsAlignments:0,identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t={}){this.db=e,this.limit=t.limit,this.signal=t.signal}get nodeCount(){return this.records.size/2}get pathCount(){return this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(me(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 Me(this.limit);let t=await this.db.getRecord(me(e,"forward")),r=await this.db.getRecord(me(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering ${ge(e,e.fragment)}`);if(!t.isIndexed)throw new Error(`Path ${ge(t.name,t.name.fragment)} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`Path ${ge(t.name,t.name.fragment)} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(_(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`Path ${ge(e.name,e.name.fragment)} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=_(e);await this.ensureNode(o);let s=this.record(e),i=Ue(e),a=new rt;return a.push(t,o,bt(i)),a.push(s.sequenceLen-t-1,o,St(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords(Math.min(i,a),Math.max(i,a)+1)){let c=await this.db.indexedPositionsBetween(e,t,r),l=li(c.map(p=>p.pos.node));await Promise.all(l.map(([p,u])=>this.db.prefetchRecords(p,u+2)))}}return o}async aroundInterval(e,t,r){if(t===0)throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof Me&&o.windowBp===void 0?new Me(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new rt;for(;;){let f=_(o.node),c=Ue(o.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,bt(c));let p=l.sequenceLen-s;if(i<=p){a.push(i===p?0:p-i-1,f,St(c));break}a.push(0,f,St(c));let u=l.gbwt().lf(o.offset);if(!u)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=u,s=0,i-=p}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new rt;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths();let r=new Set,o=new Set;for(let i of this.records.keys())o.add(_(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=Lr(f);if(!r.has(`${a}:${l}`)){let d=this.record(me(a,Tr(f))),h=i+d.sequenceLen-1;h<=t&&e.push(h,a,l)}let p=this.record(me(a,Nr(f))),u=i+1;if(u<=t)for(let d of p.successors()){let h=_(d),m=bt(Ue(d));r.has(`${h}:${m}`)||e.push(u,h,m)}}for(let i of o)this.records.delete(me(i,"forward")),this.records.delete(me(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){this.clearPaths();let r=[e,K(t)],o=new Set([_(e),_(t)]),s=0;for(;r.length>0;){let i=r.pop(),a=_(i);this.hasNode(a)||(await this.addNode(a),s+=1);for(let f of this.record(i).successors()){let c=_(f);o.has(c)||(r.push(f,K(f)),o.add(c))}}return s}async extractSnarls(e){let t=0;for(let[r,o]of await this.overlappingSnarls(e))t+=await this.betweenNodes(r,o);return t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?We(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(o=>this.hasHandle(o));return r===void 0?!1:t.length>1||this.record(K(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(K(l))).successors().length>1},r=async f=>{let c=await e(K(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[K(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=_(f);if(!this.hasHandle(f)&&!o.has(c)){o.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let p of["forward","reverse"])s.push(...(await e(me(c,p))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((x,A)=>i.set(x,A));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let x=0;x<s;x++){let A=this.record(o[x]),M=A.gbwt().decompressArrays();f[x]=A.sequenceLen,c.push(M),a[x+1]=a[x]+M.nodes.length}let l=a[s],p=new Int32Array(l),u=new Int32Array(l),d=new Uint8Array(l);for(let x=0;x<s;x++){let A=c[x];p.set(A.nodes,a[x]),u.set(A.offsets,a[x])}c.length=0;for(let x=0;x<l;x++){let A=i.get(p[x]);A===void 0?p[x]=-1:(p[x]=A,d[a[A]+u[x]]=1)}let h=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,y,S=(x,A,M)=>{let L=[],k=0,T=0,R=-1,B=x,v=A;for(;;){B===h&&v===m&&(R=k),M&&(M.push(o[B]),L.push(v)),k+=1,T+=f[B];let C=a[B]+v,P=p[C];if(P<0)break;v=u[C],B=P}return{offsets:L,len:T,refAt:R,last:B}},I=(x,A,M,L)=>{L>=0&&(this.refId=this.paths.length,y=L),this.paths.push({path:x,offsets:A,len:M,weight:void 0,identity:void 0})},g=new Int32Array(s),b=h!==void 0&&q(o[h]);for(let x=0;x<s;x++){let A=o[x];if(!q(A)){let M=a[x],L=a[x+1]-M;for(let k=0;k<L;k++)if(d[M+k]===0){let T=[],{offsets:R,len:B,refAt:v,last:C}=S(x,k,T),P=o[C];if(v>=0||Ne(A,P)){if(I(T,R,B,v),!q(P)){let G=i.get(K(P));g[G]=g[G]+1}}else this.twinStarts.add($e({node:A,offset:k}))}}}for(let x=0;x<s;x++){let A=o[x];if(q(A)){let M=a[x],L=a[x+1]-M,k=0;for(let R=0;R<L;R++)d[M+R]===0&&(k+=1);let T=!b&&k===g[x];for(let R=0;R<L;R++)if(d[M+R]===0){let B=T?void 0:S(x,R,void 0);if(B&&(B.refAt>=0||Ne(A,o[B.last]))){let v=[],{offsets:C,len:P,refAt:G}=S(x,R,v);I(v,C,P,G)}else this.twinStarts.add($e({node:A,offset:R}))}}}if(r){if(y===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let x=this.paths[this.refId],A=r.nodeOffset;for(let L of x.path.slice(0,y))A+=this.record(L).sequenceLen;let M=r.seqOffset-A;this.refInterval=[M,M+x.len],x.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:M,hapEnd:M+x.len}}if(t==="distinct")this.distinctPaths();else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(){let e=this.refId===void 0?void 0:this.paths[this.refId].path;this.paths.sort((o,s)=>Dn(o.path,s.path)||o.len-s.len);let t=[],r;for(let o of this.paths){let s=t[t.length-1];s&&Dn(s.path,o.path)===0?s.weight=(s.weight??0)+1:(e&&Dn(o.path,e)===0&&(r=t.length),t.push({...o,weight:1}))}this.paths=t,this.refId=r}keepHaplotypes(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=this.paths.filter((s,i)=>i===this.refId||s.identity!==void 0&&e(s.identity.name)),o=new Set;for(let s of r)for(let i of s.path)o.add(_(i));for(let s of[...this.records.keys()])o.has(_(s))||this.records.delete(s);this.paths=r,this.refId=t===void 0?void 0:r.indexOf(t)}async extractChosenPaths(e,t,r){this.clearPaths();let o=e.position.seqOffset,s=await Xr({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},keep:r,signal:this.signal,prefetchReferenceRange:(c,l,p)=>this.prefetchReferenceRange(c,l,p)});if(this.stats.keep=s.stats,s.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),a=c=>({path:c.handles,offsets:c.offsets,len:c.len,weight:void 0,identity:{pathHandle:c.pathHandle,name:c===s.reference?e.name:i.get(c.pathHandle).name,orientation:c.orientation,hapStart:c.hapStart,hapEnd:c.hapEnd}}),f=[s.reference,...s.pieces].sort(Zr);return this.paths=f.map(a),this.refId=f.indexOf(s.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[s.reference.hapStart,s.reference.hapEnd],!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");let e=await this.db.haplotypeSampleInterval()??4096,t=kn(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[h,m]of t)for(let y of await this.db.haplotypeSamplesInRange(h,m))r.set($e(y),y);let o=h=>{let m=0,y=t.length-1;for(;m<y;){let I=m+y+1>>1;t[I][0]<=h?m=I:y=I-1}let S=t[m];return S[0]<=h&&h<=S[1]},s=new Map;this.paths.forEach((h,m)=>{h.path.length>0&&m!==this.refId&&s.set($e(kt(h,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((h,m)=>{m!==this.refId&&i.fragmentLengths.push(h.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),f=h=>(i.graphLookups+=1,a(h)),c=async(h,m)=>{if(o(h.node))return r.get($e(h));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let y=await this.db.haplotypeSampleAt(h.node,h.offset);return y||(i.companionMisses+=1),y},l=new Map,p=async h=>{let m=l.get(h);if(!m){let y=await this.db.getPath(h);if(!y)throw new Error(`Path ${h} is missing from the database`);m=y.name,l.set(h,m)}return m},u=(h,m,y)=>h.orientation==="forward"?{pathHandle:h.pathHandle,orientation:"forward",base:h.pathOffset-m}:{pathHandle:h.pathHandle,orientation:"reverse",base:h.pathOffset+m+y},d=(h,m)=>h.orientation==="forward"?{pathHandle:h.pathHandle,orientation:"forward",base:h.hapStart-m}:{pathHandle:h.pathHandle,orientation:"reverse",base:h.hapEnd+m};for(let h=0;h<this.paths.length;h++){let m=this.paths[h];if(h===this.refId||m.identity)continue;let y=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let g,b=0,x=h,A;for(;g===void 0;){if(this.signal?.throwIfAborted(),x!==void 0){if(S.has(x)){I.end="cycle";break}S.add(x);let R=this.paths[x];y.push({index:x,startBp:b}),I.fragments+=1;let B=b;for(let C=0;C<R.path.length;C++){let P=kt(R,C),G=r.get($e(P)),j=this.record(P.node).sequenceLen;if(G){g=u(G,B,j);break}B+=j}if(b+=R.len,g){I.end="in-fragment sample";break}let v=kt(R,R.path.length-1);A=this.record(v.node).gbwt().lf(v.offset),x=void 0}if(A===void 0||A.node===0){I.end="endmarker";break}let M=$e(A),L=s.get(M);if(L!==void 0){let R=this.paths[L].identity;if(R){g=d(R,b),I.end="identified sibling";break}x=L;continue}this.records.has(A.node)&&(I.reentries+=1),this.twinStarts.has(M)&&(I.twinLandings+=1);let k=await c(A,I),T=await f(A.node);if(k){g=u(k,b,T.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,b-y[y.length-1].startBp>4*e+4*T.sequenceLen){I.end="bound";break}b+=T.sequenceLen,A=T.gbwt().lf(A.offset)}if(g){I.pathHandle=g.pathHandle;let M=await p(g.pathHandle);for(let{index:L,startBp:k}of y){let T=this.paths[L];T.identity=g.orientation==="forward"?{pathHandle:g.pathHandle,name:M,orientation:"forward",hapStart:g.base+k,hapEnd:g.base+k+T.len}:{pathHandle:g.pathHandle,name:M,orientation:"reverse",hapStart:g.base-k-T.len,hapEnd:g.base-k}}}}}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=si(c,a);if(l===void 0)return;o[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[o]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[e.length-o-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),se(r,"M",i),uo(r,o-i-a,s-i-a),se(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??oi(Jr(e,t,p=>this.record(p).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(p,u,d,h)=>{p===u?se(s,"D",i[h]-i[d]):d===h?se(s,"I",this.pathLen(e.slice(p,u))):this.align(e.slice(p,u),t.slice(d,h),s)},f=0,c=0,l=0;for(let p=0;p<o.count;p++){let u=o.pathAt[p],d=o.refAt[p];(c!==u||l!==d)&&a(c,u,l,d);let h=this.record(e[u]).sequenceLen;se(s,"M",h),f+=h,c=u+1,l=d+1}return a(c,e.length,l,t.length),{edits:s,matched:f}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(Fr(r))o={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else{let s=t.path.map(f=>K(f)).reverse(),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else if(i===0)o={edits:this.editsAgainst(s,r).edits,flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);o=c.matched>f.matched?{edits:c.edits,flipped:!0}:{edits:f.edits,flipped:!1}}}return o}alignToRef(e){return this.alignment(e)?.edits.map(([t,r])=>`${r}${t}`).join("")}alignments(){let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,r=this.refPrefix(t)[t.length],o=[];return this.paths.forEach((s,i)=>{if(i===this.refId)return;let{edits:a,flipped:f}=this.alignment(i),c=0,l=0;for(;c<a.length&&a[c][0]==="D";)l+=a[c][1],c+=1;let p=a.length,u=0;for(;p>c&&a[p-1][0]==="D";)u+=a[p-1][1],p-=1;let d=s.identity,h=d?d.orientation==="forward"!==f:!f;o.push({strand:h?"+":"-",refStart:e.start+l,refEnd:e.start+r-u,edits:a.slice(c,p),weight:s.weight,path:s.path,start:kt(s,0),identity:d===void 0?void 0:{pathHandle:d.pathHandle,name:d.name,hapStart:d.name.fragment+d.hapStart,hapEnd:d.name.fragment+d.hapEnd,walkForward:d.orientation==="forward"}})}),fi(o).map(s=>{let{edits:i,identity:a,...f}=s,c={...f,cigar:hi(i)};return a?{...c,resolved:!0,name:a.name,label:ge({...a.name,fragment:a.hapStart},a.hapEnd),pathHandle:a.pathHandle,hapStart:a.hapStart,hapEnd:a.hapEnd}:{...c,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:p}=l;return p?[{name:p.name,start:p.name.fragment+p.hapStart,steps:Lt(l,p)}]:[]}),i=l=>p=>p.sample===l.sample&&p.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(me(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(p=>f(p.name)).flatMap(p=>po(p.steps,l.steps,c,o).map(u=>({query:p.name,queryStart:p.start+u.queryStart,queryEnd:p.start+u.queryEnd,strand:u.strand,target:l.name,targetStart:l.start+u.targetStart,targetEnd:l.start+u.targetEnd,cigar:ho(u.edits),matches:u.edits.reduce((d,[h,m])=>d+(h==="="?m:0),0),columns:u.edits.reduce((d,[,h])=>d+h,0),sharedBases:u.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=me(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&We(o,s)&&t.push([r==="reverse"?1:0,_(s),q(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!q(r)){let o=_(r),s=`S ${o} ${this.record(r).sequence}
|
|
1
|
+
import{a as Ir,b as Ar,c as Rr,d as Ts}from"./chunk-JAQ2RQAE.js";import"./chunk-LGKM2PZH.js";import{d as Mr,e as _r}from"./chunk-OSTJHAAK.js";import{a as Cr,f as kr,g as Or}from"./chunk-DMYUVGGI.js";import{a as Pr}from"./chunk-KWAXLUPQ.js";import{a as Ns}from"./chunk-D7XFR2IV.js";import{a as et}from"./chunk-J4OLMLS5.js";import"./chunk-EFVAQ2KM.js";import{a as Er,e as ze,f as je,g as Pn}from"./chunk-KULNKXPT.js";import{a as Ls,b as le}from"./chunk-FY3BTKY4.js";var ys=Ls((xp,ws)=>{ws.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function me(n,e){return 2*n+(e==="reverse"?1:0)}function _(n){return Math.floor(n/2)}function Ue(n){return n%2===0?"forward":"reverse"}function q(n){return n%2===1}function K(n){return n%2===0?n+1:n-1}function Lr(n){return n==="left"?"right":"left"}function bt(n){return n==="forward"?"left":"right"}function St(n){return n==="forward"?"right":"left"}function Tr(n){return n==="left"?"forward":"reverse"}function Nr(n){return n==="right"?"forward":"reverse"}function We(n,e){let t=_(n),r=_(e);return q(n)?r>t||r===t&&!q(e):r>=t}function Fr(n){return Ne(n[0],n[n.length-1])}function Ne(n,e){return n===void 0||e===void 0?!0:q(n)===q(e)?!q(n):We(n,e)}var tt=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},qr=255,qs=256,vt=class{source;sigma;threshold;constructor(e,t){this.source=new tt(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<qr?Math.floor(qs/this.sigma):0}next(){if(this.sigma>=qr){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let o=this.source.int();if(o===void 0)return;r+=o}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function $r(n){let e=new tt(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var It=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new vt(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:K(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];_(s.node)===_(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var $s=["","A","C","G","T","N"];function Hr(n){let e=n[n.length-1];if(e===void 0)return 0;let t=e,r=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),r+=1;return 3*(n.length-1)+r}function Gr(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=$s[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var Hs={A:"T",C:"G",G:"C",T:"A",N:"N"};function At(n){let e="";for(let t=n.length-1;t>=0;t--)e+=Hs[n[t]]??"N";return e}function Br(n,e){let t=new Map;if(n!==void 0)for(let r of n.split(";")){let o=r.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function jr(n){return{name:n.get("pggname"),subgraph:Br(n.get("subgraph"),"subgraph"),translation:Br(n.get("translation"),"translation")}}function Dr(n,e){for(let[t,r]of e){let o=n.get(t);o||(o=new Set,n.set(t,o));for(let s of r)o.add(s)}}function Ur(n,e){let t={name:n,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(n,new Set([e.name])),Dr(t.subgraph,e.subgraph),Dr(t.translation,e.translation)),t}function zr(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function Wr(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of zr(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of zr(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function Qr(n){let e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;let o=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(o)].map(s=>s.toString(16).padStart(2,"0")).join("")}var Gs="_gbwt_ref";function ge(n,e){return`${n.sample}#${n.haplotype}#${n.contig}[${n.fragment}-${e}]`}var Bs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Ds=/^([^#]+?)(?:\[\d+-\d+\])?$/;function zs(n){let e=Bs.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Ds.exec(n);if(t)return{contig:t[1]};throw new Error(`"${n}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Yr(n){return typeof n=="string"?zs(n):n}function Et(n,e){return{sample:n.sample??Gs,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var js=4096;function kn(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=js?r[1]=t:e.push([t,t])}return e}var Ee=32768,Vr={mostChosenPaths:32},_n=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let r=this.byNode.get(e.node);r||(r=new Map,this.byNode.set(e.node,r)),r.set(e.offset,t)}},ne=class extends Error{};function nt(n,e,t,r){return n==="forward"?e+t:e-r}function Mn(n,e,t,r){return n==="forward"?e-r:e+t}function Kr(n){return Ne(K(n.handles[n.handles.length-1]),K(n.handles[0]))}function Fe(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function Xr(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let v=performance.now(),C=v-o;return o=v,C},i={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,seeds:0,pieces:0,sources:{reference:0,sample:0,interval:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,intervals:0,seeds:0,chains:0,twins:0}},a=(v,C)=>{let P=`${v}: ${C}`;i.walks[P]=(i.walks[P]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async v=>{let C=t.get(v)??c.get(v);if(C)return C;let P=await e.getRecord(v);if(i.graphFetches+=1,!P)throw new Error(`Node record ${v} is missing from the database`);return c.set(v,P),P},p=v=>t.get(v).sequenceLen,u=await e.pathsByHandle(),d=v=>{let C=u.get(v);return C!==void 0&&n.keep(C.name)},h=[],m=new _n,y=new Map,S=new Set,I=new Set,g=async v=>{let C=(await l(v.node)).gbwt().lf(v.offset);return C===void 0||C.node===0?void 0:C},b=async(v,C)=>{let P=(await l(K(v.node))).gbwt().predecessorAt(v.offset);if(P===void 0||C!==void 0&&!C.has(P))return;let G=(await l(P)).gbwt().offsetTo(v);if(G===void 0)throw new Error(`No offset in ${P} leads to ${v.node}:${v.offset}`);return{node:P,offset:G}},x=(v,C,P,G)=>{let j=P.map(ae=>ae.pos.node),X=P.map(ae=>ae.pos.offset),ee=0;for(let ae of j)ee+=p(ae);let te=C==="forward"?P[0].left:P[P.length-1].left,ve=h.length;h.push({pathHandle:v,orientation:C,handles:j,offsets:X,len:ee,hapStart:te,hapEnd:te+ee,canonical:Ne(j[0],j[j.length-1]),source:G});for(let ae of P)m.set(ae.pos,ve);let Oe=y.get(v);return Oe?Oe.push(ve):y.set(v,[ve]),ve},A=async(v,C,P,G)=>{let j=[],X=v;for(;;){r?.throwIfAborted();let te=await b(X.pos,t);if(!te)break;X={pos:te,left:Mn(P,X.left,p(X.pos.node),p(te.node))},j.push(X)}j.reverse();let ee=[v];for(X=v;;){r?.throwIfAborted();let te=await g(X.pos);if(!te||!t.has(te.node))break;X={pos:te,left:nt(P,X.left,p(X.pos.node),p(te.node))},ee.push(X)}return x(C,P,[...j,...ee],G)},M=async(v,C,P,G)=>h[m.get(v.pos)??await A(v,C,P,G)],L=v=>{let C=v.handles[v.handles.length-1];return{pos:{node:C,offset:v.offsets[v.offsets.length-1]},left:v.orientation==="forward"?v.hapEnd-p(C):v.hapStart}},k=v=>{let C=v.handles[0];return{pos:{node:C,offset:v.offsets[0]},left:v.orientation==="forward"?v.hapStart:v.hapEnd-p(C)}},T=await A({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),R=h[T],B=()=>{if(i.fallback!==void 0)return{reference:R,pieces:[],stats:i};let v=new Map;h.forEach((P,G)=>{G!==T&&v.set(Fe(P),[...v.get(Fe(P))??[],P])});let C=[];for(let P of v.values()){let G=new Set;for(let j of P)j.canonical&&!G.has(j.orientation)&&(G.add(j.orientation),C.push(j),i.sources[j.source]+=1)}return i.sources.reference=1,i.pieces=C.length,{reference:R,pieces:C,stats:i}};try{let v=i.spacing;if(v===void 0)throw new ne("the haplotype index has no anchors");let C=Math.floor(n.window.start/v),P=Math.ceil(n.window.end/v),G=w=>w>=0?e.haplotypeAnchor(n.referenceHandle,w*v):Promise.resolve(void 0),[j,X]=await Promise.all([Promise.all([0,1,2].map(w=>G(C-w))),Promise.all([0,1,2,3].map(w=>G(P+w)))]),ee=j[0],te=X.slice(0,2).findIndex(w=>w!==void 0&&w.pathOffset>=n.window.end),ve=X[te];if(!ee)throw new ne("the haplotype index has no anchor before the window");if(!ve)throw new ne("the haplotype index has no anchor after the window");i.anchors=[ee.pathOffset,ve.pathOffset];let Oe=j.filter(w=>w!==void 0),ae=X.slice(te,te+3).filter(w=>w!==void 0),Es=w=>{let E=w-w%2;return e.haplotypeSamplesInRange(E,E+1)},ht=new Map,bn=[...Oe,...ae],Cs=await Promise.all(bn.map(w=>Es(w.node)));if(bn.forEach((w,E)=>ht.set(w,Cs[E])),i.anchorsRead=bn.length,!ht.get(ee).some(w=>w.pathHandle===n.referenceHandle&&w.orientation==="forward"&&w.pathOffset===ee.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${ee.pathOffset} (node ${_(ee.node)}); it does not match this graph`);let yr=(w,E)=>{for(let O of w){let Z=ht.get(O).filter(W=>W.pathHandle===E);if(Z.length>0)return{anchor:O,rows:Z}}},De=new Map,dt=(w,E)=>{let O=De.get(w);O[0]=Math.min(O[0],E),O[1]=Math.max(O[1],E)},ut=[],Sn=new Set,Rs=async w=>{let E=yr(Oe,w),O=yr(ae,w);if(!E&&!O)return;let Z=E?.rows??[],W=O?.rows??[],Y=[...Z,...W].map(z=>z.pathOffset);De.set(w,[Math.min(...Y),Math.max(...Y)]);let N=E?.anchor??ee,Q=O?.anchor??ve,$=Q.pathOffset-N.pathOffset,H=d(w),V=!1;for(let z of Z){let U=z.orientation==="forward"?1:-1,fe=W.filter(Ae=>Ae.orientation===z.orientation&&(Ae.pathOffset-z.pathOffset)*U>0).sort((Ae,xt)=>(Ae.pathOffset-xt.pathOffset)*U)[0];if(!fe)continue;let ye=z.node===N.node,Le=fe.node===Q.node,Ie=fe.pathOffset,Te=0;ye&&!Le?Ie+=U*((await l(fe.node)).sequenceLen+$):!ye&&Le&&(Te=$),dt(w,Ie),dt(w,z.pathOffset-U*Te),V=!0,H&&(ut.push({row:z,stopAt:Ie,back:Te,kind:ye===Le?"interval":"inversion"}),Sn.add(w))}if(!V){let z=De.get(w);dt(w,z[0]-$),dt(w,z[1]+$);for(let U of[...Z,...W])if(H&&(U.node===N.node||U.node===K(Q.node))){let fe=U.orientation==="forward"?1:-1;ut.push({row:U,stopAt:U.pathOffset+fe*$,back:0,kind:"one-sided"}),Sn.add(w)}}return V?"paired":"one-sided"},xr=new Set([...ht.values()].flat().map(w=>w.pathHandle)),mt=[...xr].filter(d);if(i.chosenPaths=mt.length,mt.length>Vr.mostChosenPaths)throw new ne(`${mt.length} chosen paths pass the anchors, more than ${Vr.mostChosenPaths}`);for(let w of xr)await Rs(w);let vn=[],In=[];i.scans=kn([...t.keys()].sort((w,E)=>w-E));for(let[w,E]of i.scans)for(let O of await e.haplotypeSamplesInRange(w,E))i.scanRows+=1,t.has(O.node)&&(In.push(O),d(O.pathHandle)&&vn.push(O));if(mt.length===0&&vn.length===0&&[...u.values()].some(w=>n.keep(w.name)))throw new ne("no chosen path passes the anchors or has a sample on the window's nodes");let Ps=new Set(In.map(w=>w.pathHandle).filter(w=>!De.has(w))),Ms=ae[ae.length-1].pathOffset-Oe[Oe.length-1].pathOffset;for(let w of Ps){let E=await e.haplotypeLength(w)??Number.POSITIVE_INFINITY;if(E>Ms+2*Ee)throw new ne(`path ${w} of ${E} bp has a sample on the window's nodes and no visit to the anchors`);if(d(w)){let O=(await e.getPath(w))?.fwStart;if(!O)throw new Error(`Path ${w} is missing from the database`);ut.push({row:{node:O.node,offset:O.offset,pathHandle:w,orientation:"forward",pathOffset:0},stopAt:E,back:0,kind:"whole"})}}for(let w of De.keys())if(d(w)&&!Sn.has(w))throw new ne(`chosen path ${w} has no walk from its visits to the anchors`);for(let w of In){let E=De.get(w.pathHandle);if(E&&(w.pathOffset<E[0]-Ee||w.pathOffset>E[1]+Ee))throw new ne(`path ${w.pathHandle} has a sample at ${w.pathOffset} on the window's nodes far from its anchor visits at ${E[0]}-${E[1]}`)}i.ms.scan=s();let An=new Map;await n.prefetchReferenceRange(n.referenceHandle,ee.pathOffset,ve.pathOffset+1);let br=8*v+2*(n.window.end-n.window.start);for(let{row:w,stopAt:E,back:O,kind:Z}of ut){let W=w.orientation,Y=(J,ue)=>W==="forward"?ue-J:J-ue,N=w.pathOffset,Q=w.pathOffset,$,H={node:w.node,offset:w.offset},V=w.pathOffset,z=!1,U=0,fe=0,ye="past the far anchor";for(;H&&(r?.throwIfAborted(),!z&&Y(V,E)<=0&&(z=!0),!(z&&U>Ee));){let J;if(t.has(H.node)){$??=V;let ce=await M({pos:H,left:V},w.pathHandle,W,"interval"),Rn=L(ce);H=Rn.pos,V=Rn.left,J=p(Rn.pos.node),N=Math.min(N,ce.hapStart),Q=Math.max(Q,ce.hapEnd),U=0}else{if(J=(await l(H.node)).sequenceLen,U+=J,fe+=J,fe>br){ye="cap";break}N=Math.min(N,V),Q=Math.max(Q,V+J)}let ue=await g(H);ue&&(V=nt(W,V,J,(await l(ue.node)).sequenceLen)),H=ue}if(!H&&ye!=="cap"&&(ye="endmarker"),a(Z,ye),ye==="cap")throw new ne(`the walk of path ${w.pathHandle} between the anchors reached its cap of ${br} bp`);if(Z==="one-sided"&&ye!=="endmarker")throw new ne(`chosen path ${w.pathHandle} runs on past the stretch from its visit to one anchor without a visit to the other`);let Le=$===void 0?0:Ee-Y(w.pathOffset,$),Ie={pos:{node:w.node,offset:w.offset},left:w.pathOffset},Te=0,Ae=O;for(;Le>0||Ae>0;){r?.throwIfAborted();let J=await b(Ie.pos);if(!J)break;let ue=Mn(W,Ie.left,(await l(Ie.pos.node)).sequenceLen,(await l(J.node)).sequenceLen);if(t.has(J.node)){let ce=await M({pos:J,left:ue},w.pathHandle,W,"interval");Ie=k(ce),N=Math.min(N,ce.hapStart),Q=Math.max(Q,ce.hapEnd),Le=Ee,Te=0,Ae-=ce.len}else{let ce=(await l(J.node)).sequenceLen;if(Te+=ce,Te>Le&&Ae<=0)break;Ae-=ce,Ie={pos:J,left:ue},N=Math.min(N,ue),Q=Math.max(Q,ue+ce)}}let xt=An.get(w.pathHandle);xt?xt.push([N,Q]):An.set(w.pathHandle,[[N,Q]])}let _s=w=>(An.get(w.pathHandle)??[]).some(([E,O])=>E<=w.hapStart&&w.hapEnd<=O);i.ms.intervals=s();for(let w of vn)m.get(w)===void 0&&!(y.get(w.pathHandle)??[]).some(E=>{let O=h[E];return O.canonical&&!Kr(O)&&O.hapStart<=w.pathOffset&&w.pathOffset<O.hapEnd})&&(i.seeds+=1,await A({pos:{node:w.node,offset:w.offset},left:w.pathOffset},w.pathHandle,w.orientation,"sample"));i.ms.seeds=s();let gt=async(w,E)=>{let O=E?S:I,Z=E?I:S,W=w;for(;;){if(O.has(W))return;O.add(W);let Y=h[W],N=E?L(Y):k(Y),Q=0,$;for(;$===void 0;){r?.throwIfAborted();let H=E?await g(N.pos):await b(N.pos);if(!H){$="endmarker";break}let V=(await l(N.pos.node)).sequenceLen,z=(await l(H.node)).sequenceLen,U=E?nt(Y.orientation,N.left,V,z):Mn(Y.orientation,N.left,V,z);if(t.has(H.node)){let fe=m.get(H);fe===void 0?(W=await A({pos:H,left:U},Y.pathHandle,Y.orientation,"chain"),Z.add(W),$="landed"):(Z.add(fe),$="merge")}else Q>Ee?$="bound":(Q+=z,N={pos:H,left:U})}if(a("chain",$),$!=="landed")return}};await Promise.all([n.prefetchReferenceRange(n.referenceHandle,Math.max(0,R.hapStart-Ee),R.hapStart),n.prefetchReferenceRange(n.referenceHandle,R.hapEnd,R.hapEnd+Ee)]);let Sr=new Set,ks=h.map((w,E)=>({piece:w,id:E})).filter(({piece:w,id:E})=>E!==T&&!_s(w)).sort((w,E)=>Number(E.piece.canonical)-Number(w.piece.canonical));for(let{piece:w,id:E}of ks)Sr.has(Fe(w))||(Sr.add(Fe(w)),await gt(E,!0),await gt(E,!1));i.ms.chains=s();let En=new Map,Os=w=>{let E=Fe(w),O=En.get(E);O?O.add(w.orientation):En.set(E,new Set([w.orientation]))},wt=0,Cn=()=>{for(;wt<h.length;wt++)wt!==T&&Os(h[wt])};Cn();let yt=w=>(En.get(Fe(w))?.size??0)>1,vr=2*f;for(let w=0;w<h.length;w++){let E=h[w];if(w===T||yt(E)||E.canonical&&!Kr(E))continue;i.twins.tried+=1;let O=E.orientation==="forward"?"reverse":"forward",Z=L(E),W=0,Y;for(;!Y&&W<=vr;){r?.throwIfAborted();let $=await g(Z.pos);if(!$)break;let H=(await l($.node)).sequenceLen,V=nt(E.orientation,Z.left,(await l(Z.pos.node)).sequenceLen,H),z=K($.node);Y=(await e.haplotypeSamplesInRange(z,z)).find(U=>U.pathHandle===E.pathHandle&&U.orientation===O&&U.pathOffset===V),W+=H,Z={pos:$,left:V}}let N=Y&&{pos:{node:Y.node,offset:Y.offset},left:Y.pathOffset},Q=0;for(;N&&!yt(E)&&Q<=vr+E.len;){if(r?.throwIfAborted(),t.has(N.pos.node)){let $=await M(N,E.pathHandle,O,"twin"),H=h.indexOf($);await gt(H,!0),await gt(H,!1),Cn(),N=L($)}if(!yt(E)){let $=(await l(N.pos.node)).sequenceLen;Q+=$;let H=await g(N.pos);N=H?{pos:H,left:nt(O,N.left,$,(await l(H.node)).sequenceLen)}:void 0}}if(Cn(),!yt(E))throw new ne(`piece ${Fe(E)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()}catch(v){if(!(v instanceof ne))throw v;i.fallback=v.message}return B()}function Zr(n,e){let t=n.handles[0],r=e.handles[0];return Number(q(t))-Number(q(r))||t-r||n.offsets[0]-e.offsets[0]}function Ct(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var Rt=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},On=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Ct(a,o)-Ct(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),p=Ct(c,o),u=Ct(c,s);for(let d=0;d<u-p;d++){let h=r===1?c[u-1-d]-o:s-1-c[p+d],m=i.bestBefore(h),y=(m===-1?0:i.ending[m])+l;if(y>i.ending[h]&&(i.raise(h,y),a)){let S=a.count++;a.row[S]=f,a.column[S]=h,a.previous[S]=m===-1?-1:a.endingMatch[m],a.endingMatch[h]=S}}}}chain(e,t,r,o,s){let i=new Rt(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let f=i.bestBefore(o-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,o,s){let i=new Rt(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let f=0;f<s-o;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(r-1,t-1,-1,o,s),c=0,l=-1;for(let p=0;p<=i;p++){let u=a[p]+f[i-p];u>l&&(l=u,c=p)}return o+c}};function Jr(n,e,t){let r=new On(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Us=100,Nn=4e6,Ws=5e3,oe=15,Qs=64,Ys=8,io=1,Fn=-4,re=-6,Ce=-1,Qe=-(2**30),Mt=0,Ln=1,ao=2;function qe(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function Pt(n,e,t){return n>=t&&n>=e?Mt:t>=e?ao:Ln}function fo(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Qe),f=new Int32Array(s).fill(Qe),c=new Int32Array(s).fill(Qe);a[0]=0;for(let h=1;h<=o;h++)c[h]=re+(h-1)*Ce,i[h]=(h===1?Mt:ao)<<4;for(let h=1;h<=r;h++){let m=new Int32Array(s).fill(Qe),y=new Int32Array(s).fill(Qe),S=new Int32Array(s).fill(Qe);y[0]=re+(h-1)*Ce,i[h*s]=(h===1?Mt:Ln)<<2;let I=n.charCodeAt(h-1);for(let g=1;g<=o;g++){let b=Pt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(I===e.charCodeAt(g-1)?io:Fn);let x=Pt(a[g]+re,f[g]+Ce,c[g]+re);y[g]=Math.max(a[g]+re,f[g]+Ce,c[g]+re);let A=Pt(m[g-1]+re,y[g-1]+re,S[g-1]+Ce);S[g]=Math.max(m[g-1]+re,y[g-1]+re,S[g-1]+Ce),i[h*s+g]=b|x<<2|A<<4}a=m,f=y,c=S}let l=[],p=r,u=o,d=Pt(a[o],f[o],c[o]);for(;p>0||u>0;){let h=i[p*s+u]>>2*d&3;d===Mt?(l.push(n[p-1]===e[u-1]?"=":"X"),p-=1,u-=1):d===Ln?(l.push("I"),p-=1):(l.push("D"),u-=1),d=h}for(let h of l.reverse())qe(t,h,1)}function Vs(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-re-(t-1)*Ce,-re+10*Math.log2(t)))+(Math.min(n,e)>0?-Fn:0)}function co(n,e){let t=Math.abs(n-e);return t===0?0:.01*oe*t+.5*Math.log2(t)}function eo(n,e,t){return{qs:n.qs+e,qe:n.qs+t,ts:n.flipped?n.te-t:n.ts+e,te:n.flipped?n.te-e:n.ts+t,flipped:n.flipped}}function Ks(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-n.qs),l=Math.min(r,f-n.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,n.flipped?n.te-f:a-n.ts),l=Math.min(r,n.flipped?n.te-a:f-n.ts);c<l&&o.push([c,l])}if(o.length===0)return[n];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=oe&&s.push(eo(n,i,a)),i=Math.max(i,f);return r-i>=oe&&s.push(eo(n,i,r)),s}function qn(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...n].sort((c,l)=>c.qs-l.qs||c.ts-l.ts);for(;f.length>0&&s.length<o;){let c=f.map(g=>g.qe-g.qs),l=new Int32Array(f.length).fill(-1),p=new Int32Array(f.length);for(let g=0;g<f.length;g++){let b=f[g],x=b.qe-b.qs;for(let A=g-1;A>=Math.max(0,g-Ws);A--){if(c[A]+x<=c[g])continue;let M=f[A];if(M.flipped===b.flipped&&M.qs<b.qs&&(b.flipped?b.te<M.te:M.ts<b.ts)){let k=Math.max(0,M.qe-b.qs,b.flipped?b.te-M.ts:M.te-b.ts),T=b.qs+k-M.qe,R=b.flipped?M.ts-(b.te-k):b.ts+k-M.te;if(k<x&&T<=e&&R<=e){let B=c[A]+x-k-r(T,R);B>c[g]&&(c[g]=B,l[g]=A,p[g]=k)}}}}let u=0;for(let g=1;g<f.length;g++)c[g]>c[u]&&(u=g);let d=[];for(let g=u;g>=0;g=l[g])d.push({run:f[g],trim:p[g]});if(d.reverse(),d.reduce((g,{run:b,trim:x})=>g+b.qe-b.qs-x,0)<t)break;s.push(d);let m=d[0],y=d.at(-1),{flipped:S}=m.run,I=S?a.flipped:a.forward;I.query.push([m.run.qs+m.trim,y.run.qe]),I.target.push(S?[y.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,y.run.te]);for(let{run:g,trim:b}of d)i.query.push([g.qs+b,g.qe]),i.target.push(g.flipped?[g.ts,g.te-b]:[g.ts+b,g.te]);f=f.flatMap(g=>{let b=g.flipped?a.flipped:a.forward;return Ks(g,[...i.query,...b.query],[...i.target,...b.target])}).sort((g,b)=>g.qs-b.qs||g.ts-b.ts)}return s}function Tn(n,e){let t=new Map;for(let s=0;s+oe<=e.length;s++){let i=e.slice(s,s+oe),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+oe<=n.length;s++){let i=t.get(n.slice(s,s+oe));if(i&&i.length<=Qs)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+oe,c.te=a+oe;else{let l={qs:s,qe:s+oe,ts:a,te:a+oe,flipped:!1};o.set(f,l),r.push(l)}}}return r}function Xs(n,e){return[...Tn(n,e),...Tn(n,At(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function _t(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,p=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?At(p):p,r,s.qe,c)}qe(r,"=",i.qe-f),s=i}}function $n(n,e,t){qe(t,"I",n.length),qe(t,"D",e.length)}function lo(n,e,t){n.length*e.length<=Nn?fo(n,e,t):$n(n,e,t)}function Hn(n,e,t,r=0){let[o]=n.length*e.length>Nn&&r<Ys?qn(Tn(n,e),1/0,oe,co,1):[];if(!o){lo(n,e,t);return}let s=(f,c,l)=>{Hn(f,c,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),_t(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function Zs(n,e,t){Hn(n,e,t)}function Js(n,e,t){let r=[];_t(n,e,t,r,Zs);let o=n[0],s=n.at(-1),{flipped:i}=o.run;return{queryStart:o.run.qs+o.trim,queryEnd:s.run.qe,targetStart:i?s.run.ts:o.run.ts+o.trim,targetEnd:i?o.run.te-o.trim:s.run.te,strand:i?"-":"+",edits:i?r.reverse():r,sharedBases:0}}function ei(n,e,t,r){let o=[];if(n.length*e.length<=Nn)fo(n,e,t);else{let s=qn(Xs(n,e),1/0,Math.max(r,oe),co),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>Js(a,n,e)),i){let a=(l,p,u,d,h)=>{o.some(y=>d<y.queryEnd&&y.queryStart<d+l.length||h<y.targetEnd&&y.targetStart<h+p.length)?lo(l,p,u):Hn(l,p,u)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),_t(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else $n(n,e,t)}return o}function Gn(n,e){let t=n.strand==="-",r=0,o=0;for(let[s,i]of n.edits)e(s,i,t?n.queryEnd-1-r:n.queryStart+r,n.targetStart+o),s!=="D"&&(r+=i),s!=="I"&&(o+=i)}function to(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return Gn(n,(i,a,f,c)=>{let l=e==="query"?f:c,p=u=>{let d=l+o*u;return d>=t&&d<r};if(i==="="||i==="X")for(let u=0;u<a;u++)p(u)&&(s+=i==="="?io:Fn);else if(i==="I"==(e==="query"))for(let u=0;u<a;u++)p(u)&&(s+=u===0?re:Ce);else p(0)&&(s+=re+(a-1)*Ce)}),s}function no(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function ti(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,f=new Uint8Array(n.queryEnd-n.queryStart);for(let[d,h]of n.shared)f.fill(1,d-n.queryStart,h-n.queryStart);let c=d=>f[d-n.queryStart]===1,l=()=>{qe(r,"I",o),qe(r,"D",s),o=0,s=0};Gn(n,(d,h,m)=>{if(d==="I")o+=h;else if(d==="D")s+=h;else{for(let y=0;y<h;y++)e[i+y]?(o+=1,s+=1,c(t?m-y:m+y)&&(a+=1)):((o>0||s>0)&&l(),qe(r,d,1));i+=h}}),l();let p={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[d,h]=r.shift();p[d]+=h}let u={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[d,h]=r.pop();u[d]+=h}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?u.I:p.I),queryEnd:n.queryEnd-(t?p.I:u.I),targetStart:n.targetStart+p.D,targetEnd:n.targetEnd-u.D,edits:r,sharedBases:n.sharedBases-a}}function ni(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];Gn(c,(p,u,d,h)=>{if(p==="="||p==="X")for(let m=0;m<u;m++)l.push([c.strand==="-"?d-m:d+m,h+m])});for(let[p,u]of l)o.query[p]=Math.min(255,o.query[p]+1),o.target[u]=Math.min(255,o.target[u]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[p,u]of c)for(let[d,h]of[["query",p],["target",u]])if(o[d][h]>1){let m=i[d].get(h);m?m.at(-1)!==l&&m.push(l):i[d].set(h,[l])}});let a=new Map,f=(c,l,p)=>{let u=`${p}:${c}:${l}`,d=a.get(u);if(d===void 0){let[h,m]=no(n[c],p),[y,S]=no(n[l],p),I=Math.max(h,y),g=Math.min(m,S),[b,x]=[n[c],n[l]];d=[to(x,p,I,g)-to(b,p,I,g),x.sharedBases-b.sharedBases,c-l].find(M=>M!==0)>0,a.set(u,d)}return d};return n.flatMap((c,l)=>{let p=s[l],u=new Uint8Array(p.length);if(p.forEach(([m,y],S)=>{for(let[I,g]of[["query",m],["target",y]])!u[S]&&i[I].get(g)?.some(b=>b!==l&&f(l,b,I))&&(u[S]=1)}),!u.includes(1))return[c];let d=ti(c,u),h=d?.edits.reduce((m,[y,S])=>m+(y==="="?S:0),0)??0;return d&&h>=r?[d]:[]})}function ro(n,e){return n.map(t=>{let r=e(_(t));return q(t)?At(r):r}).join("")}function oo(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(_(r)).length);return t}function so(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=_(i);e.has(f)?t.set(f,a):e.set(f,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function ri(n,e,t,r){let o=so(n),s=so(e),i=new Map;e.forEach((p,u)=>{s[u]||i.set(_(p),[u])});let a=2*e.length,f=(p,u,d)=>p*a+2*u+(d?1:0),c=new Set;n.forEach((p,u)=>{for(let d of o[u]?[]:i.get(_(p))??[])c.add(f(u,d,q(p)!==q(e[d])))});let l=[];return n.forEach((p,u)=>{for(let d of o[u]?[]:i.get(_(p))??[]){let h=q(p)!==q(e[d]),m=h?-1:1;if(!c.has(f(u-1,d-m,h))){let y=u,S=d;for(;y<n.length&&S>=0&&S<e.length&&c.has(f(y,S,h));)y+=1,S+=m;let I=S-m;l.push({qs:t[u],qe:t[y],ts:r[Math.min(d,I)],te:r[Math.max(d,I)+1],flipped:h})}}}),l}function po(n,e,t,r={}){let o=ro(n,t),s=ro(e,t),i=ri(n,e,oo(n,t),oo(e,t)),a=r.minMatch??Us,f=r.bases??!0,c=[];for(let l of qn(i,r.maxGap??1/0,a,Vs)){let p=[],u=l[0],d=l.at(-1),{flipped:h}=u.run;_t(l,o,s,p,f?(y,S,I,g,b)=>{for(let x of ei(y,S,I,a)){let A=b+S.length;c.push({...x,queryStart:g+x.queryStart,queryEnd:g+x.queryEnd,targetStart:h?A-x.targetEnd:b+x.targetStart,targetEnd:h?A-x.targetStart:b+x.targetEnd,strand:h?"+":"-",edits:h?x.edits.reverse():x.edits,shared:[]})}}:$n),c.push({queryStart:u.run.qs+u.trim,queryEnd:d.run.qe,targetStart:h?d.run.ts:u.run.ts+u.trim,targetEnd:h?u.run.te-u.trim:d.run.te,strand:h?"-":"+",edits:h?p.reverse():p,sharedBases:l.reduce((y,{run:S,trim:I})=>y+S.qe-S.qs-I,0),shared:l.map(({run:y,trim:S})=>[y.qs+S,y.qe])})}return ni(c,o.length,s.length,a).map(({shared:l,...p})=>p).sort((l,p)=>l.queryStart-p.queryStart)}function ho(n){return n.map(([e,t])=>`${t}${e}`).join("")}var Me=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 Bn(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var rt=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Bn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Bn(e[s],e[a])&&(a=s),i<e.length&&Bn(e[i],e[a])&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}}return t}get size(){return this.heap.length}};function oi(n){let e=new Int32Array(n.length),t=new Int32Array(n.length);return n.forEach(([r,o],s)=>{e[s]=r,t[s]=o}),{pathAt:e,refAt:t,count:n.length}}function si(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function $e(n){return`${n.node}:${n.offset}`}function ii(n,e){let t=e.identity.hapStart-n.identity.hapEnd,r=n.strand==="+"?e.refStart-n.refEnd:n.refStart-e.refEnd;return n.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function ai(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);uo(s,t.insertion,t.deletion);for(let[c,l]of o.edits)se(s,c,l);let i=n.identity.walkForward,[a,f]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function fi(n){if(n.some(o=>o.weight!==void 0))return n;let e=new Map;n.forEach((o,s)=>{if(o.identity){let i=e.get(o.identity.pathHandle);i?i.push(s):e.set(o.identity.pathHandle,[s])}});let t=new Map,r=new Set;for(let o of e.values()){o.sort((a,f)=>n[a].identity.hapStart-n[f].identity.hapStart);let s=o[0],i=n[s];for(let a of o.slice(1)){let f=n[a],c=ii(i,f);c?(i=ai(i,f,c),r.add(a)):(t.set(s,i),s=a,i=f)}t.set(s,i)}return n.flatMap((o,s)=>r.has(s)?[]:[t.get(s)??o])}function kt(n,e){return{node:n.path[e],offset:n.offsets[e]}}var ci=32768;function li(n){let e=[...n].sort((r,o)=>r-o),t=[];for(let r of e){let o=t[t.length-1];o&&r-o[1]<=ci?o[1]=r:t.push([r,r])}return t}var Tt=class{records=new Map;paths=[];twinStarts=new Set;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;stats={orderedAlignments:0,lcsAlignments:0,identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t={}){this.db=e,this.limit=t.limit,this.signal=t.signal}get nodeCount(){return this.records.size/2}get pathCount(){return this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(me(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 Me(this.limit);let t=await this.db.getRecord(me(e,"forward")),r=await this.db.getRecord(me(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering ${ge(e,e.fragment)}`);if(!t.isIndexed)throw new Error(`Path ${ge(t.name,t.name.fragment)} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`Path ${ge(t.name,t.name.fragment)} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(_(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`Path ${ge(e.name,e.name.fragment)} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=_(e);await this.ensureNode(o);let s=this.record(e),i=Ue(e),a=new rt;return a.push(t,o,bt(i)),a.push(s.sequenceLen-t-1,o,St(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords(Math.min(i,a),Math.max(i,a)+1)){let c=await this.db.indexedPositionsBetween(e,t,r),l=li(c.map(p=>p.pos.node));await Promise.all(l.map(([p,u])=>this.db.prefetchRecords(p,u+2)))}}return o}async aroundInterval(e,t,r){if(t===0)throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof Me&&o.windowBp===void 0?new Me(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new rt;for(;;){let f=_(o.node),c=Ue(o.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,bt(c));let p=l.sequenceLen-s;if(i<=p){a.push(i===p?0:p-i-1,f,St(c));break}a.push(0,f,St(c));let u=l.gbwt().lf(o.offset);if(!u)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=u,s=0,i-=p}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new rt;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths();let r=new Set,o=new Set;for(let i of this.records.keys())o.add(_(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=Lr(f);if(!r.has(`${a}:${l}`)){let d=this.record(me(a,Tr(f))),h=i+d.sequenceLen-1;h<=t&&e.push(h,a,l)}let p=this.record(me(a,Nr(f))),u=i+1;if(u<=t)for(let d of p.successors()){let h=_(d),m=bt(Ue(d));r.has(`${h}:${m}`)||e.push(u,h,m)}}for(let i of o)this.records.delete(me(i,"forward")),this.records.delete(me(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){this.clearPaths();let r=[e,K(t)],o=new Set([_(e),_(t)]),s=0;for(;r.length>0;){let i=r.pop(),a=_(i);this.hasNode(a)||(await this.addNode(a),s+=1);for(let f of this.record(i).successors()){let c=_(f);o.has(c)||(r.push(f,K(f)),o.add(c))}}return s}async extractSnarls(e){let t=0;for(let[r,o]of await this.overlappingSnarls(e))t+=await this.betweenNodes(r,o);return t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?We(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(o=>this.hasHandle(o));return r===void 0?!1:t.length>1||this.record(K(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(K(l))).successors().length>1},r=async f=>{let c=await e(K(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[K(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=_(f);if(!this.hasHandle(f)&&!o.has(c)){o.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let p of["forward","reverse"])s.push(...(await e(me(c,p))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((x,A)=>i.set(x,A));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let x=0;x<s;x++){let A=this.record(o[x]),M=A.gbwt().decompressArrays();f[x]=A.sequenceLen,c.push(M),a[x+1]=a[x]+M.nodes.length}let l=a[s],p=new Int32Array(l),u=new Int32Array(l),d=new Uint8Array(l);for(let x=0;x<s;x++){let A=c[x];p.set(A.nodes,a[x]),u.set(A.offsets,a[x])}c.length=0;for(let x=0;x<l;x++){let A=i.get(p[x]);A===void 0?p[x]=-1:(p[x]=A,d[a[A]+u[x]]=1)}let h=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,y,S=(x,A,M)=>{let L=[],k=0,T=0,R=-1,B=x,v=A;for(;;){B===h&&v===m&&(R=k),M&&(M.push(o[B]),L.push(v)),k+=1,T+=f[B];let C=a[B]+v,P=p[C];if(P<0)break;v=u[C],B=P}return{offsets:L,len:T,refAt:R,last:B}},I=(x,A,M,L)=>{L>=0&&(this.refId=this.paths.length,y=L),this.paths.push({path:x,offsets:A,len:M,weight:void 0,identity:void 0})},g=new Int32Array(s),b=h!==void 0&&q(o[h]);for(let x=0;x<s;x++){let A=o[x];if(!q(A)){let M=a[x],L=a[x+1]-M;for(let k=0;k<L;k++)if(d[M+k]===0){let T=[],{offsets:R,len:B,refAt:v,last:C}=S(x,k,T),P=o[C];if(v>=0||Ne(A,P)){if(I(T,R,B,v),!q(P)){let G=i.get(K(P));g[G]=g[G]+1}}else this.twinStarts.add($e({node:A,offset:k}))}}}for(let x=0;x<s;x++){let A=o[x];if(q(A)){let M=a[x],L=a[x+1]-M,k=0;for(let R=0;R<L;R++)d[M+R]===0&&(k+=1);let T=!b&&k===g[x];for(let R=0;R<L;R++)if(d[M+R]===0){let B=T?void 0:S(x,R,void 0);if(B&&(B.refAt>=0||Ne(A,o[B.last]))){let v=[],{offsets:C,len:P,refAt:G}=S(x,R,v);I(v,C,P,G)}else this.twinStarts.add($e({node:A,offset:R}))}}}if(r){if(y===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let x=this.paths[this.refId],A=r.nodeOffset;for(let L of x.path.slice(0,y))A+=this.record(L).sequenceLen;let M=r.seqOffset-A;this.refInterval=[M,M+x.len],x.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:M,hapEnd:M+x.len}}if(t==="distinct")this.distinctPaths();else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(){let e=this.refId===void 0?void 0:this.paths[this.refId].path;this.paths.sort((o,s)=>Dn(o.path,s.path)||o.len-s.len);let t=[],r;for(let o of this.paths){let s=t[t.length-1];s&&Dn(s.path,o.path)===0?s.weight=(s.weight??0)+1:(e&&Dn(o.path,e)===0&&(r=t.length),t.push({...o,weight:1}))}this.paths=t,this.refId=r}keepHaplotypes(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=this.paths.filter((s,i)=>i===this.refId||s.identity!==void 0&&e(s.identity.name)),o=new Set;for(let s of r)for(let i of s.path)o.add(_(i));for(let s of[...this.records.keys()])o.has(_(s))||this.records.delete(s);this.paths=r,this.refId=t===void 0?void 0:r.indexOf(t)}async extractChosenPaths(e,t,r){this.clearPaths();let o=e.position.seqOffset,s=await Xr({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},keep:r,signal:this.signal,prefetchReferenceRange:(c,l,p)=>this.prefetchReferenceRange(c,l,p)});if(this.stats.keep=s.stats,s.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),a=c=>({path:c.handles,offsets:c.offsets,len:c.len,weight:void 0,identity:{pathHandle:c.pathHandle,name:c===s.reference?e.name:i.get(c.pathHandle).name,orientation:c.orientation,hapStart:c.hapStart,hapEnd:c.hapEnd}}),f=[s.reference,...s.pieces].sort(Zr);return this.paths=f.map(a),this.refId=f.indexOf(s.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[s.reference.hapStart,s.reference.hapEnd],!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");let e=await this.db.haplotypeSampleInterval()??4096,t=kn(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[h,m]of t)for(let y of await this.db.haplotypeSamplesInRange(h,m))r.set($e(y),y);let o=h=>{let m=0,y=t.length-1;for(;m<y;){let I=m+y+1>>1;t[I][0]<=h?m=I:y=I-1}let S=t[m];return S[0]<=h&&h<=S[1]},s=new Map;this.paths.forEach((h,m)=>{h.path.length>0&&m!==this.refId&&s.set($e(kt(h,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((h,m)=>{m!==this.refId&&i.fragmentLengths.push(h.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),f=h=>(i.graphLookups+=1,a(h)),c=async(h,m)=>{if(o(h.node))return r.get($e(h));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let y=await this.db.haplotypeSampleAt(h.node,h.offset);return y||(i.companionMisses+=1),y},l=new Map,p=async h=>{let m=l.get(h);if(!m){let y=await this.db.getPath(h);if(!y)throw new Error(`Path ${h} is missing from the database`);m=y.name,l.set(h,m)}return m},u=(h,m,y)=>h.orientation==="forward"?{pathHandle:h.pathHandle,orientation:"forward",base:h.pathOffset-m}:{pathHandle:h.pathHandle,orientation:"reverse",base:h.pathOffset+m+y},d=(h,m)=>h.orientation==="forward"?{pathHandle:h.pathHandle,orientation:"forward",base:h.hapStart-m}:{pathHandle:h.pathHandle,orientation:"reverse",base:h.hapEnd+m};for(let h=0;h<this.paths.length;h++){let m=this.paths[h];if(h===this.refId||m.identity)continue;let y=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let g,b=0,x=h,A;for(;g===void 0;){if(this.signal?.throwIfAborted(),x!==void 0){if(S.has(x)){I.end="cycle";break}S.add(x);let R=this.paths[x];y.push({index:x,startBp:b}),I.fragments+=1;let B=b;for(let C=0;C<R.path.length;C++){let P=kt(R,C),G=r.get($e(P)),j=this.record(P.node).sequenceLen;if(G){g=u(G,B,j);break}B+=j}if(b+=R.len,g){I.end="in-fragment sample";break}let v=kt(R,R.path.length-1);A=this.record(v.node).gbwt().lf(v.offset),x=void 0}if(A===void 0||A.node===0){I.end="endmarker";break}let M=$e(A),L=s.get(M);if(L!==void 0){let R=this.paths[L].identity;if(R){g=d(R,b),I.end="identified sibling";break}x=L;continue}this.records.has(A.node)&&(I.reentries+=1),this.twinStarts.has(M)&&(I.twinLandings+=1);let k=await c(A,I),T=await f(A.node);if(k){g=u(k,b,T.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,b-y[y.length-1].startBp>4*e+4*T.sequenceLen){I.end="bound";break}b+=T.sequenceLen,A=T.gbwt().lf(A.offset)}if(g){I.pathHandle=g.pathHandle;let M=await p(g.pathHandle);for(let{index:L,startBp:k}of y){let T=this.paths[L];T.identity=g.orientation==="forward"?{pathHandle:g.pathHandle,name:M,orientation:"forward",hapStart:g.base+k,hapEnd:g.base+k+T.len}:{pathHandle:g.pathHandle,name:M,orientation:"reverse",hapStart:g.base-k-T.len,hapEnd:g.base-k}}}}}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=si(c,a);if(l===void 0)return;o[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[o]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[e.length-o-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),se(r,"M",i),uo(r,o-i-a,s-i-a),se(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??oi(Jr(e,t,p=>this.record(p).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(p,u,d,h)=>{p===u?se(s,"D",i[h]-i[d]):d===h?se(s,"I",this.pathLen(e.slice(p,u))):this.align(e.slice(p,u),t.slice(d,h),s)},f=0,c=0,l=0;for(let p=0;p<o.count;p++){let u=o.pathAt[p],d=o.refAt[p];(c!==u||l!==d)&&a(c,u,l,d);let h=this.record(e[u]).sequenceLen;se(s,"M",h),f+=h,c=u+1,l=d+1}return a(c,e.length,l,t.length),{edits:s,matched:f}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(Fr(r))o={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else{let s=t.path.map(f=>K(f)).reverse(),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else if(i===0)o={edits:this.editsAgainst(s,r).edits,flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);o=c.matched>f.matched?{edits:c.edits,flipped:!0}:{edits:f.edits,flipped:!1}}}return o}alignToRef(e){return this.alignment(e)?.edits.map(([t,r])=>`${r}${t}`).join("")}alignments(){let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,r=this.refPrefix(t)[t.length],o=[];return this.paths.forEach((s,i)=>{if(i===this.refId)return;let{edits:a,flipped:f}=this.alignment(i),c=0,l=0;for(;c<a.length&&a[c][0]==="D";)l+=a[c][1],c+=1;let p=a.length,u=0;for(;p>c&&a[p-1][0]==="D";)u+=a[p-1][1],p-=1;let d=s.identity,h=d?d.orientation==="forward"!==f:!f;o.push({strand:h?"+":"-",refStart:e.start+l,refEnd:e.start+r-u,edits:a.slice(c,p),weight:s.weight,path:s.path,start:kt(s,0),identity:d===void 0?void 0:{pathHandle:d.pathHandle,name:d.name,hapStart:d.name.fragment+d.hapStart,hapEnd:d.name.fragment+d.hapEnd,walkForward:d.orientation==="forward"}})}),fi(o).map(s=>{let{edits:i,identity:a,...f}=s,c={...f,cigar:hi(i)};return a?{...c,resolved:!0,name:a.name,label:ge({...a.name,fragment:a.hapStart},a.hapEnd),pathHandle:a.pathHandle,hapStart:a.hapStart,hapEnd:a.hapEnd}:{...c,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:p}=l;return p?[{name:p.name,start:p.name.fragment+p.hapStart,steps:Lt(l,p)}]:[]}),i=l=>p=>p.sample===l.sample&&p.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(me(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(p=>f(p.name)).flatMap(p=>po(p.steps,l.steps,c,o).map(u=>({query:p.name,queryStart:p.start+u.queryStart,queryEnd:p.start+u.queryEnd,strand:u.strand,target:l.name,targetStart:l.start+u.targetStart,targetEnd:l.start+u.targetEnd,cigar:ho(u.edits),matches:u.edits.reduce((d,[h,m])=>d+(h==="="?m:0),0),columns:u.edits.reduce((d,[,h])=>d+h,0),sharedBases:u.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=me(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&We(o,s)&&t.push([r==="reverse"?1:0,_(s),q(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!q(r)){let o=_(r),s=`S ${o} ${this.record(r).sequence}
|
|
2
2
|
`;for(let[i,a,f]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${f?"-":"+"}
|
|
3
3
|
`;t.push(e.encode(s))}return Qr(t)}async toGFA(e={}){let t=e.cigar??!1,r=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...Wr(Ur(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)q(c)||r.push(`S ${_(c)} ${this.record(c).sequence}`);let s=c=>q(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&We(c,l)&&r.push(`L ${_(c)} ${s(c)} ${_(l)} ${s(l)} 0M`);let i=(c,l,p,u,d)=>{let h=Lt(c,l).map(S=>`${q(S)?"<":">"}${_(S)}`).join(""),m=c.weight===void 0?"":` WT:i:${c.weight}`,y=d===void 0?"":` CG:Z:${d}`;return`W ${p.sample} ${p.haplotype} ${p.contig} ${p.fragment} ${u} ${h}${m}${y}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&r.push(i(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let f=1;return this.paths.forEach((c,l)=>{if(l!==this.refId){let p=e.names==="resolved"?c.identity:void 0,u=t?this.alignToRef(l):void 0;r.push(p?i(c,p,{...p.name,fragment:p.name.fragment+p.hapStart},p.name.fragment+p.hapEnd,u):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,u)),f+=1}}),`${r.join(`
|
|
4
4
|
`)}
|
|
5
5
|
`}outputPaths(e){let t=e.cigar??!1,r=[],o=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let i={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};r.push({info:this.paths[this.refId],identity:void 0,name:ge(i,this.refPath.fragment+this.refInterval[1]),cigar:void 0})}let s=1;return this.paths.forEach((i,a)=>{if(a===this.refId)return;let f=e.names==="resolved"?i.identity:void 0;r.push({info:i,identity:f,name:f?ge({...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd):ge({sample:"unknown",contig:o,haplotype:s,fragment:0},i.len),cigar:t?this.alignToRef(a):void 0}),s+=1}),r}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&We(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!q(s)).map(s=>({id:String(_(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(_(s)),from_is_reverse:q(s),to:String(_(i)),to_is_reverse:q(i)});let o=this.outputPaths(e).map(s=>pi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!q(i)),r=new Int32Array(t.length),o=[];t.forEach((i,a)=>{r[a]=_(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:r,nodeSequences:o,edges:Int32Array.from(s),paths:this.outputPaths(e).map(i=>({name:i.name,weight:i.info.weight,cigar:i.cigar,steps:Int32Array.from(Lt(i.info,i.identity))}))}}};function Lt(n,e){return e?.orientation==="reverse"?n.path.map(t=>K(t)).reverse():n.path}function pi(n,e,t,r){return{name:t,...n.weight===void 0?{}:{weight:n.weight},...r===void 0?{}:{cigar:r},path:Lt(n,e).map(o=>({id:String(_(o)),is_reverse:q(o)}))}}function Dn(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n[r],s=e[r];if(o!==s)return o<s?-1:1}return n.length-e.length}function se(n,e,t){if(t===0)return;let r=n[n.length-1];r?.[0]===e?r[1]+=t:n.push([e,t])}function Ot(n){return n===0?0:6+(n-1)}function uo(n,e,t){if(e===0)se(n,"D",t);else if(t===0)se(n,"I",e);else{let r=Math.min(e,t),o=4*r+Ot(e-r)+Ot(t-r),s=Ot(e)+Ot(t);o<=s?(se(n,"M",r),se(n,"I",e-r),se(n,"D",t-r)):(se(n,"I",e),se(n,"D",t))}}function hi(n){return n.map(([e,t])=>`${t}${e}`).join("")}async function mo(n,e,t,r,o){let s=new Tt(n,o);try{let i=await s.pathPosition(Et(e,t));return await s.prefetchReferenceWalk(i,r-t),await s.aroundInterval(i.position,r-t,o.context??100),await s.extractSnarls(o.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof Me&&i.windowBp===void 0?new Me(i.limit,{windowBp:r-t,walkedBp:s.referenceWalkedBp??0}):i}}async function go(n,e,t,r,o={}){let{subgraph:s,reference:i}=await mo(n,e,t,r,o);return s.extractPaths(i,o.haplotypes??"all"),s}async function wo(n,e,t,r,o){if(!n.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await mo(n,e,t,r,o),a=o.haplotypes??"all";return(a!=="all"||!await s.extractChosenPaths(i,r-t,o.keep))&&(s.extractPaths(i,a),await s.identifyPaths()),s.keepHaplotypes(o.keep),s}function xe(n,e){let t=0;for(let o=0;o<8;o++){let s=n[e+o];if(s===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(s&127),(s&128)===0)return[t,e+o+1]}let r=n[e+8];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+r,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function di(n,e,t){switch(t){case 1:return n.getInt8(e);case 2:return n.getInt16(e);case 3:return n.getInt8(e)<<16|n.getUint16(e+1);case 4:return n.getInt32(e);case 6:return n.getInt16(e)*4294967296+n.getUint32(e+2);default:{let r=n.getBigInt64(e);if(r>BigInt(Number.MAX_SAFE_INTEGER)||r<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${r} exceeds the safe integer range`);return Number(r)}}}var ui=new TextDecoder;function Nt(n){let[e,t]=xe(n,0),r=[],o=t;for(;o<e;){let[a,f]=xe(n,o);r.push(a),o=f}let s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=e;return r.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=di(s,i,f);return i+=f,c}if(a===7){let f=s.getFloat64(i);return i+=8,f}if(a===8)return 0;if(a===9)return 1;if(a>=12){let f=a-12>>1,c=n.subarray(i,i+f);return i+=f,a%2===0?c:ui.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var ot=2,qt=5,xo=10,Ft=13;function bo(n,e){return n[e]*256+n[e+1]}function _e(n,e){return n[e]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function mi(n,e){let t=n[e];if(t!==ot&&t!==qt&&t!==xo&&t!==Ft)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===ot||t===qt;return{type:t,cellCount:bo(n,e+3),rightChild:r?_e(n,e+8):0,cellPointers:e+(r?12:8)}}function Re(n,e,t){return bo(n,e.cellPointers+2*t)}var gi=4096,wi=4096,$t=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let r=this.usable,o=t?Math.floor((r-12)*64/255)-23:r-35;if(e<=o)return e;let s=Math.floor((r-12)*32/255)-23,i=s+(e-s)%(r-4);return i<=o?i:s}async payload(e,t,r,o){let s=this.localPayloadSize(r,o);if(s===r)return e.subarray(t,t+r);let i=new Uint8Array(r);i.set(e.subarray(t,t+s),0);let a=s,f=_e(e,t+s);for(;f!==0&&a<r;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,r-a));i.set(l,a),a+=l.length,f=_e(c,0)}if(a!==r)throw new Error("SQLite overflow chain ended before the payload was complete");return i}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:mi(t,e===1?100:0)}}tableDepth(e,t){let r=this.tableDepths.get(e);return r||(r=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Ft)return s;if(a.type!==qt)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:_e(i,Re(i,a,f))}})(),this.tableDepths.set(e,r),r.catch(()=>this.tableDepths.delete(e))),r}childIndexFor(e,t,r){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=xe(e,Re(e,t,i)+4);a<r?o=i+1:s=i}return o}async prefetchRowidRange(e,t,r){let o=await this.tableDepth(e,t),s=[e];for(let i=0;i<o;i++){let a=await Promise.all(s.map(c=>this.pageAt(c))),f=[];if(a.forEach(({page:c,header:l},p)=>{let u=p===0?this.childIndexFor(c,l,t):0,d=p===a.length-1?this.childIndexFor(c,l,r):l.cellCount;for(let h=u;h<=d;h++)f.push(h===l.cellCount?l.rightChild:_e(c,Re(c,l,h)))}),f.length>wi)return!1;this.pager.prefetch(f),s=f}return!0}async tableRowid(e,t){let r=e;for(;;){let{page:o,header:s}=await this.pageAt(r);if(s.type===Ft){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,p=Re(o,s,l),[u,d]=xe(o,p),[h,m]=xe(o,d);if(h===t)return Nt(await this.payload(o,m,u,!1));h<t?f=l+1:c=l}return}if(s.type!==qt)throw new Error("SQLite table b-tree contains an index page");let i=0,a=s.cellCount;for(;i<a;){let f=i+a>>1,c=Re(o,s,f),[l]=xe(o,c+4);l<t?i=f+1:a=f}r=i===s.cellCount?s.rightChild:_e(o,Re(o,s,i))}}async*tableScan(e){let{page:t,header:r}=await this.pageAt(e);if(r.type===Ft)for(let o=0;o<r.cellCount;o++){let s=Re(t,r,o),[i,a]=xe(t,s),[f,c]=xe(t,a);yield{rowid:f,values:Nt(await this.payload(t,c,i,!1))}}else{let o=[];for(let s=0;s<r.cellCount;s++)o.push(_e(t,Re(t,r,s)));o.push(r.rightChild),this.pager.prefetch(o);for(let s of o)yield*this.tableScan(s)}}decodedCells(e,t){let r=this.decodedIndexPages.get(e);if(r)this.decodedIndexPages.delete(e);else if(r=new Array(t.cellCount),this.decodedIndexPages.size>=gi){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,r),r}async indexCell(e,t,r,o){let s=this.decodedCells(e,r),i=s[o];if(!i){let a=Re(t,r,o),f=r.type===ot,[c,l]=xe(t,f?a+4:a);i={values:Nt(await this.payload(t,l,c,!0)),leftChild:f?_e(t,a):0},s[o]=i}return i}async*indexScanFrom(e,t){let{page:r,header:o}=await this.pageAt(e),s=0,i=o.cellCount;for(;s<i;){let a=s+i>>1,f=await this.indexCell(e,r,o,a);yo(f.values,t)<0?s=a+1:i=a}for(let a=s;a<o.cellCount;a++){let f=await this.indexCell(e,r,o,a);o.type===ot&&(yield*this.indexScanFrom(f.leftChild,t)),yield f.values}o.type===ot&&(yield*this.indexScanFrom(o.rightChild,t))}async indexSeekLE(e,t){let r,o=e;for(;;){let{page:s,header:i}=await this.pageAt(o),a=0,f=i.cellCount,c=0;for(;a<f;){let l=a+f>>1,p=await this.indexCell(o,s,i,l);yo(p.values,t)<=0?(r=p.values,a=l+1):(c=p.leftChild,f=l)}if(i.type===xo)return r;o=a===i.cellCount?i.rightChild:c}}};function yo(n,e){for(let t=0;t<e.length;t++){let r=n[t],o=e[t];if(typeof r!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(r!==o)return r<o?-1:1}return 0}var Ht=class{blocks=new Map;blockSize;maxBlocks;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,r,o={}){this.source=e,this.pageSize=t,this.fileSize=r;let s=o.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(s/t)*t),this.maxBlocks=o.maxBlocks??256}async read(e,t){let r=0;for(;;)try{let o=await this.source.read(e,t);return this.bytesFetched+=o.length,o}catch(o){if(r+=1,r>=3)throw o;await new Promise(s=>setTimeout(s,200*r))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){let t=this.blocks.get(e);if(t)return this.blocks.delete(e),this.blocks.set(e,t),t;let r=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-r),s=this.read(o,r);return this.fetches+=1,this.blocks.set(e,s),this.forgetOnFailure(s,[e]),this.evict(),s}prefetch(e){let t=[...new Set(e.map(o=>Math.floor((o-1)*this.pageSize/this.blockSize)))].filter(o=>!this.blocks.has(o)).sort((o,s)=>o-s),r=0;for(;r<t.length;){let o=r+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[r],o-r),r=o}}fetchRun(e,t){let r=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-r),s=this.read(o,r);this.fetches+=1;let i=[];for(let a=0;a<t;a++){let f=a*this.blockSize;i.push(e+a),this.blocks.set(e+a,s.then(c=>c.subarray(f,f+this.blockSize)))}this.forgetOnFailure(s,i),this.evict()}forgetOnFailure(e,t){e.catch(()=>{for(let r of t)this.blocks.delete(r)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let r=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return r.subarray(o,o+this.pageSize)}};var st=class n{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){let{size:r}=await e.stat(),o=await e.read(Math.min(t.blockSize??65536,r),0),s=o.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3")throw new Error("Not a SQLite database");let a=new DataView(s.buffer,s.byteOffset,s.byteLength),f=a.getUint16(16),c=f===1?65536:f,l=s[20]??0,p=a.getUint32(56);if(p!==1)throw new Error(`SQLite text encoding ${p} is not UTF-8`);let u=new Ht(e,c,r,t);u.seed(0,o),u.fetches+=1,u.bytesFetched+=o.length;let d=new $t(u,l),h=new Map;for await(let{values:m}of d.tableScan(1)){let[y,S,I,g,b]=m;typeof y=="string"&&typeof S=="string"&&typeof I=="string"&&typeof g=="number"&&h.set(S,{type:y,name:S,tableName:I,rootPage:g,sql:typeof b=="string"?b:""})}return new n(u,d,h)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}indexOn(e){let t=[...this.objects.values()].find(r=>r.type==="index"&&r.tableName===e);if(!t)throw new Error(`SQLite table ${e} has no index`);return t.rootPage}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,r){return this.btree.prefetchRowidRange(this.rootPage(e),t,r)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t){return this.btree.indexScanFrom(this.indexOn(e),t)}has(e){return this.objects.has(e)}};var jn="GBZ-base version 4",Gt=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},Bt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: its Tags table has no version":`unsupported database schema "${e}"; this reader understands "${jn}"`),this.found=e}},Dt=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,r,o,s){this.handle=e,this.edges=t,this.bwt=r,this.encodedSequence=o,this.next=s,this.sequenceLen=Hr(o)}get id(){return _(this.handle)}get orientation(){return Ue(this.handle)}get sequence(){return this.decoded??=Gr(this.encodedSequence),this.decoded}successors(){return this.edges.filter(e=>e.node!==0).map(e=>e.node)}gbwt(){if(this.edges.length===0)throw new Error(`GBWT record for handle ${this.handle} is empty`);return new It(this.edges,this.bwt)}};function D(n,e){if(typeof n!="number")throw new Error(`${e} is not a number in the database`);return n}function zt(n,e){if(typeof n!="string")throw new Error(`${e} is not text in the database`);return n}function zn(n,e){if(!(n instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return n}function So(n,e){return{handle:n,fwStart:{node:D(e[1],"Paths.fw_node"),offset:D(e[2],"Paths.fw_offset")},revStart:{node:D(e[3],"Paths.rev_node"),offset:D(e[4],"Paths.rev_offset")},name:{sample:zt(e[5],"Paths.sample"),contig:zt(e[6],"Paths.contig"),haplotype:D(e[7],"Paths.haplotype"),fragment:D(e[8],"Paths.fragment")},isIndexed:D(e[9],"Paths.is_indexed")!==0}}async function vo(n){let e=new Map;for await(let{values:t}of n.scan("Tags"))e.set(zt(t[0],"Tags.key"),zt(t[1],"Tags.value"));return e}var it=class n{tagCache;pathCache;pathMapCache;indexTags=new Map;sqlite;index;constructor(e,t){this.sqlite=e,this.index=t}static async open(e,t={}){let{haplotypeIndex:r,...o}=t,s=await st.open(e,o);for(let c of["Tags","Nodes","Paths","ReferenceIndex"])s.rootPage(c);let i=r?await st.open(r,o):void 0,a=new n(s,i),f=await a.tag("version");if(f!==jn)throw new Bt(f);if(i){for(let d of["Tags","HaplotypeSamples","HaplotypeLengths"])i.rootPage(d);a.indexTags=await vo(i);let c=a.indexTags.get("haplotype_index_paths"),l=await a.tag("paths");if(c!==l)throw new Error(`haplotype index was built for ${c??"an unknown number of"} paths but the graph has ${l}`);let p=a.indexTags.get("haplotype_index_nodes"),u=await a.tag("nodes");if(p!==void 0&&p!==u)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${u}`);if(a.indexTags.get("haplotype_index_orientations")==="forward")throw new Gt}return a}tags(){return this.tagCache??=vo(this.sqlite),this.tagCache}async tag(e){return(await this.tags()).get(e)}prefetchRecords(e,t){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let r=t[4];return new Dt(e,$r(zn(t[1],"Nodes.edges")),zn(t[2],"Nodes.bwt"),zn(t[3],"Nodes.sequence"),typeof r=="number"?r:void 0)}paths(){return this.pathCache??=(async()=>{let e=[];for await(let{rowid:t,values:r}of this.sqlite.scan("Paths"))e.push(So(t,r));return e})(),this.pathCache}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?So(e,t):void 0}pathsByHandle(){return this.pathMapCache??=this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),this.pathMapCache}async findPath(e){return(await this.paths()).filter(r=>r.name.sample===e.sample&&r.name.contig===e.contig&&r.name.haplotype===e.haplotype&&r.name.fragment<=e.fragment).sort((r,o)=>o.name.fragment-r.name.fragment)[0]}async pathsForSample(e){return(await this.paths()).filter(t=>t.name.sample===e)}async pathsNamed(e){let t=Et(Yr(e),0);return(await this.paths()).filter(r=>r.name.sample===t.sample&&r.name.contig===t.contig&&r.name.haplotype===t.haplotype).sort((r,o)=>r.name.fragment-o.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let r=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!r){let i=await this.getPath(e);throw new Error(`Path ${i?ge(i.name,i.name.fragment):e} has not been indexed for random access`)}let o=r.pathOffset,s=r.pos;for(;;){let i=await this.getRecord(s.node);if(!i)throw new Error(`Node ${s.node} does not exist in the graph`);o+=i.sequenceLen;let a=i.gbwt().lf(s.offset);if(!a||a.node===0)return o;s=a}}return t}async pathFragmentsForRange(e,t,r){if(r<=t)return[];let o=await this.pathsNamed(e),s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<r);return(await Promise.all([...s,...i].map(async f=>({path:f,start:f.name.fragment,end:f.name.fragment+await this.pathLength(f.handle)})))).filter(f=>t<f.end)}async subgraphForFragment(e,t,r,o){let{keep:s,...i}=o;if(s!==void 0&&!this.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{sample:a,contig:f,haplotype:c}=e.path.name,l={sample:a,contig:f,haplotype:c},p=Math.max(t,e.start),u=Math.min(r,e.end),d=o.haplotypes??"all",h=d==="all"||d==="distinct",m;return s!==void 0&&d==="all"?m=await wo(this,l,p,u,{...i,keep:s}):(m=await go(this,l,p,u,i),this.hasHaplotypeIndex&&h&&(await m.identifyPaths(),s!==void 0&&m.keepHaplotypes(s))),m}async getSubgraphForRange(e,t,r,o={}){let[s]=await this.pathFragmentsForRange(e,t,r);return s?this.subgraphForFragment(s,t,r,o):void 0}async getAlignmentsForRange(e,t,r,o={}){let s=[];for(let i of await this.pathFragmentsForRange(e,t,r)){let a=await this.subgraphForFragment(i,t,r,o);s.push(...a.alignments())}return s}async graphName(){let e=new Map;for(let[r,o]of await this.tags())r.startsWith("gbz_")&&e.set(r.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=jr(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeAnchor(e,t){let r=await this.companion.indexSeekLE("HaplotypeAnchors",[e,t]),o=r?.[0]===e&&r[1]===t?await this.companion.byRowid("HaplotypeAnchors",D(r[2],"HaplotypeAnchors rowid")):void 0;return o?{node:D(o[2],"HaplotypeAnchors.node_handle"),pathOffset:D(o[3],"HaplotypeAnchors.path_offset")}:void 0}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:D(e[0],"HaplotypeSamples.node_handle"),offset:D(e[1],"HaplotypeSamples.node_offset"),pathHandle:D(e[2],"HaplotypeSamples.path_handle"),orientation:D(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:D(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let r=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0])){if(D(o[0],"HaplotypeSamples.node_handle")>t)break;let i=await this.companion.byRowid("HaplotypeSamples",D(o[2],"HaplotypeSamples rowid"));i&&r.push(this.sampleFromRow(i))}return r}async haplotypeSampleAt(e,t){let r=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);if(r?.[0]!==e||r[1]!==t)return;let o=await this.companion.byRowid("HaplotypeSamples",D(r[2],"HaplotypeSamples rowid"));return o?this.sampleFromRow(o):void 0}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?D(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:D(t[1],"ReferenceIndex.path_offset"),pos:{node:D(t[2],"ReferenceIndex.node_handle"),offset:D(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let r=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return r?.[0]===e?D(r[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let r=await this.indexedRowid(e,t);return r===void 0?void 0:this.indexedRow(r)}async indexedPositionsBetween(e,t,r){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,r)]),i=[];if(o!==void 0&&s!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",o,s+1);for(let a=o;a<=s;a++)i.push(await this.indexedRow(a))}return i}};var jt=class extends Error{constructor(t,r){super(r.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${t}" maps to none; set referenceSample`:`the anchor "${t}" is none of the graph's reference samples (${r.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`);this.name="NoReferenceSampleError"}},Ut=class extends Error{constructor(t,r,o){super(`this ${r.toLocaleString()} bp window reads more than nodeLimit (${t.toLocaleString()}) graph nodes; zoom in to about ${o.toLocaleString()} bp or raise nodeLimit`);this.name="NodeLimitError"}};function be(n){return`${n.sample}#${n.haplotype}`}function Io(n,e){let t=be(n);return e===void 0||e.some(r=>ze(t,r))}async function Ao(n){return(await n.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function yi(n,e){let t=n.toLowerCase(),r=Cr(n)?.toLowerCase();return e.find(o=>o===n)??e.find(o=>o.toLowerCase()===t)??e.find(o=>o.toLowerCase()===r)}function Un({configured:n,anchorPrefix:e,referenceSamples:t}){if(n!=="")return n;let r=yi(Er(e),t)??(t.length===1?t[0]:void 0);if(r===void 0)throw new jt(e,t);return r}async function Eo(n,e,t){let r=(await n.paths()).find(o=>o.isIndexed&&o.name.sample===e&&o.name.contig===t);return r?{sample:r.name.sample,contig:t,haplotype:r.name.haplotype}:void 0}function at(n,e,t){if(n instanceof Error&&(n.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(n.message))){let o=n.walkedBp,s=typeof o=="number"&&o>0?Math.floor(o*.8):Math.floor(t/2);return new Ut(e,t,Math.max(s,1))}else return}async function Co(n,e,t,r,{keep:o,...s}){let i=e?await n.getSubgraphForRange(e,t,r,{...s,haplotypes:"all",...o===void 0?{}:{keep:o}}).catch(a=>{throw at(a,s.limit,r-t)??a}):void 0;return i?i.toGFA({names:"resolved"}):""}var hr=le(Rr(),1),dr=le(et(),1),Je=le(Pr(),1),As=le(Ts(),1);var Po=le(Pr(),1);var Ro=/\.gbz\.db$/i;function xi(n){return Ro.test(Mr(n))?_r(n,e=>e.replace(Ro,".haplotype-index.db")):void 0}async function Mo(n,e){let t=xi(n);if(t)try{return await(0,Po.openLocation)(t,e).stat(),t}catch{return}}var bi=5e3,Si=50*2**20,Wn=class extends Error{constructor(t){super(`this GAF is ${(t/2**20).toFixed(0)} MB without an index; bgzip it and index it with tabix -p gaf`);this.name="UnindexedGafTooLargeError"}};function vi(n,e){if(n.length<=e)return n;let t=n.length/e;return Array.from({length:e},(r,o)=>n[Math.floor(o*t)])}var _o=(n,e)=>n.path.some(t=>e.has(t.name)),Wt=class{constructor(e,t){this.file=e;this.tabix=t}readWhole(e){return this.whole??=(async()=>{let{size:t}=await this.file.stat();if(t>Si)throw new Wn(t);let r=await this.file.readFile({signal:e}),o=new TextDecoder().decode(r[0]===31&&r[1]===139?await Ir(r):r);return Or(o)})().catch(t=>{throw this.whole=void 0,t}),this.whole}async readIndexed(e,t,r){let o=1/0,s=-1/0;for(let a of t){let f=Number(a);Number.isInteger(f)&&(o=Math.min(o,f),s=Math.max(s,f))}let i=[];return o<=s&&await e.getLines("{node}",o,s+1,{signal:r,lineCallback:a=>{let f=kr(a);f&&_o(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let r=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.readWhole(t)).filter(o=>_o(o,e));return{records:vi(r,bi),total:r.length}}};var Ss=le(Rr(),1),vs=le(et(),1);var Qn=function(n,e){return Qn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},Qn(n,e)};function ft(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Qn(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ko(n,e,t,r){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function a(l){try{c(r.next(l))}catch(p){i(p)}}function f(l){try{c(r.throw(l))}catch(p){i(p)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((r=r.apply(n,e||[])).next())})}function Qt(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(l){return f([c,l])}}function f(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(r=1,o&&(s=c[0]&2?o.return:c[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,c[1])).done)return s;switch(o=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(l){c=[6,l],o=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function He(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ye(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return s}function Ve(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function Ge(n){return this instanceof Ge?(this.v=n,this):new Ge(n)}function Oo(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(d){return function(h){return Promise.resolve(h).then(d,p)}}function a(d,h){r[d]&&(o[d]=function(m){return new Promise(function(y,S){s.push([d,m,y,S])>1||f(d,m)})},h&&(o[d]=h(o[d])))}function f(d,h){try{c(r[d](h))}catch(m){u(s[0][3],m)}}function c(d){d.value instanceof Ge?Promise.resolve(d.value.v).then(l,p):u(s[0][2],d)}function l(d){f("next",d)}function p(d){f("throw",d)}function u(d,h){d(h),s.shift(),s.length&&f(s[0][0],s[0][1])}}function Lo(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof He=="function"?He(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(i){return new Promise(function(a,f){i=n[s](i),o(a,f,i.done,i.value)})}}function o(s,i,a,f){Promise.resolve(f).then(function(c){s({value:c,done:a})},i)}}function F(n){return typeof n=="function"}function To(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Yt=To(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
6
6
|
`+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
7
|
-
`):"",this.name="UnsubscriptionError",this.errors=t}});function Yn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Vt=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=He(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(m){e={error:m}}finally{try{f&&!f.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(F(l))try{l()}catch(m){s=m instanceof Yt?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var u=He(p),d=u.next();!d.done;d=u.next()){var h=d.value;try{No(h)}catch(m){s=s??[],m instanceof Yt?s=Ve(Ve([],Ye(s)),Ye(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{d&&!d.done&&(o=u.return)&&o.call(u)}finally{if(r)throw r.error}}}if(s)throw new Yt(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)No(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Yn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Yn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var hf=Vt.EMPTY;function Kt(n){return n instanceof Vt||n&&"closed"in n&&F(n.remove)&&F(n.add)&&F(n.unsubscribe)}function No(n){F(n)?n():n.unsubscribe()}var we={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ke={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=Ke.delegate;return o?.setTimeout?o.setTimeout.apply(o,Ve([n,e],Ye(t))):setTimeout.apply(void 0,Ve([n,e],Ye(t)))},clearTimeout:function(n){var e=Ke.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function Xt(n){Ke.setTimeout(function(){var e=we.onUnhandledError;if(e)e(n);else throw n})}function Vn(){}var Fo=(function(){return Kn("C",void 0,void 0)})();function qo(n){return Kn("E",void 0,n)}function $o(n){return Kn("N",n,void 0)}function Kn(n,e,t){return{kind:n,value:e,error:t}}var Be=null;function Ho(n){if(we.useDeprecatedSynchronousErrorHandling){var e=!Be;if(e&&(Be={errorThrown:!1,error:null}),n(),e){var t=Be,r=t.errorThrown,o=t.error;if(Be=null,r)throw o}}else n()}function Go(n){we.useDeprecatedSynchronousErrorHandling&&Be&&(Be.errorThrown=!0,Be.error=n)}var ct=(function(n){ft(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Kt(t)&&t.add(r)):r.destination=Ci,r}return e.create=function(t,r,o){return new Jt(t,r,o)},e.prototype.next=function(t){this.isStopped?Zn($o(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?Zn(qo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?Zn(Fo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Vt);var Ii=Function.prototype.bind;function Xn(n,e){return Ii.call(n,e)}var Ai=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Zt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Zt(r)}else Zt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Zt(t)}},n})(),Jt=(function(n){ft(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(F(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&we.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Xn(t.next,a),error:t.error&&Xn(t.error,a),complete:t.complete&&Xn(t.complete,a)}):i=t}return s.destination=new Ai(i),s}return e})(ct);function Zt(n){we.useDeprecatedSynchronousErrorHandling?Go(n):Xt(n)}function Ei(n){throw n}function Zn(n,e){var t=we.onStoppedNotification;t&&Ke.setTimeout(function(){return t(n,e)})}var Ci={closed:!0,next:Vn,error:Ei,complete:Vn};var Xe=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Bo(n){return n}function Do(n){return n.length===0?Bo:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var ie=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Pi(e)?e:new Jt(e,t,r);return Ho(function(){var i=o,a=i.operator,f=i.source;s.add(a?a.call(s,f):f?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=zo(t),new t(function(o,s){var i=new Jt({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Xe]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Do(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=zo(e),new e(function(r,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},n.create=function(e){return new n(e)},n})();function zo(n){var e;return(e=n??we.Promise)!==null&&e!==void 0?e:Promise}function Ri(n){return n&&F(n.next)&&F(n.error)&&F(n.complete)}function Pi(n){return n&&n instanceof ct||Ri(n)&&Kt(n)}function Mi(n){return F(n?.lift)}function he(n){return function(e){if(Mi(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Pe(n,e,t,r,o){return new _i(n,e,t,r,o)}var _i=(function(n){ft(e,n);function e(t,r,o,s,i,a){var f=n.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=r?function(c){try{r(c)}catch(l){t.error(l)}}:n.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(ct);var en=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function tn(n){return F(n?.then)}function nn(n){return F(n[Xe])}function rn(n){return Symbol.asyncIterator&&F(n?.[Symbol.asyncIterator])}function on(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ki(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var sn=ki();function an(n){return F(n?.[sn])}function fn(n){return Oo(this,arguments,function(){var t,r,o,s;return Qt(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Ge(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,Ge(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ge(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function cn(n){return F(n?.getReader)}function Se(n){if(n instanceof ie)return n;if(n!=null){if(nn(n))return Oi(n);if(en(n))return Li(n);if(tn(n))return Ti(n);if(rn(n))return jo(n);if(an(n))return Ni(n);if(cn(n))return Fi(n)}throw on(n)}function Oi(n){return new ie(function(e){var t=n[Xe]();if(F(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Li(n){return new ie(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Ti(n){return new ie(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Xt)})}function Ni(n){return new ie(function(e){var t,r;try{for(var o=He(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function jo(n){return new ie(function(e){qi(n,e).catch(function(t){return e.error(t)})})}function Fi(n){return jo(fn(n))}function qi(n,e){var t,r,o,s;return ko(this,void 0,void 0,function(){var i,a;return Qt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Lo(n),f.label=1;case 1:return[4,t.next()];case 2:if(r=f.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];f.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=f.sent(),o={error:a},[3,11];case 6:return f.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function de(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function ln(n,e){return e===void 0&&(e=0),he(function(t,r){t.subscribe(Pe(r,function(o){return de(r,n,function(){return r.next(o)},e)},function(){return de(r,n,function(){return r.complete()},e)},function(o){return de(r,n,function(){return r.error(o)},e)}))})}function pn(n,e){return e===void 0&&(e=0),he(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function Uo(n,e){return Se(n).pipe(pn(e),ln(e))}function Wo(n,e){return Se(n).pipe(pn(e),ln(e))}function Qo(n,e){return new ie(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function Yo(n,e){return new ie(function(t){var r;return de(t,e,function(){r=n[sn](),de(t,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return F(r?.return)&&r.return()}})}function hn(n,e){if(!n)throw new Error("Iterable cannot be null");return new ie(function(t){de(t,e,function(){var r=n[Symbol.asyncIterator]();de(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function Vo(n,e){return hn(fn(n),e)}function Ko(n,e){if(n!=null){if(nn(n))return Uo(n,e);if(en(n))return Qo(n,e);if(tn(n))return Wo(n,e);if(rn(n))return hn(n,e);if(an(n))return Yo(n,e);if(cn(n))return Vo(n,e)}throw on(n)}function Jn(n,e){return e?Ko(n,e):Se(n)}function lt(n,e){return he(function(t,r){var o=0;t.subscribe(Pe(r,function(s){r.next(n.call(e,s,o++))}))})}function Xo(n,e,t,r,o,s,i,a){var f=[],c=0,l=0,p=!1,u=function(){p&&!f.length&&!c&&e.complete()},d=function(m){return c<r?h(m):f.push(m)},h=function(m){s&&e.next(m),c++;var y=!1;Se(t(m,l++)).subscribe(Pe(e,function(S){o?.(S),s?d(S):e.next(S)},function(){y=!0},void 0,function(){if(y)try{c--;for(var S=function(){var I=f.shift();i?de(e,i,function(){return h(I)}):h(I)};f.length&&c<r;)S();u()}catch(I){e.error(I)}}))};return n.subscribe(Pe(e,d,function(){p=!0,u()})),function(){a?.()}}function Ze(n,e,t){return t===void 0&&(t=1/0),F(e)?Ze(function(r,o){return lt(function(s,i){return e(r,s,o,i)})(Se(n(r,o)))},t):(typeof e=="number"&&(t=e),he(function(r,o){return Xo(r,o,n,t)}))}function Zo(n,e,t,r,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var p=c++;f=a?n(f,l,p):(a=!0,l),r&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function Jo(n,e){return he(Zo(n,e,arguments.length>=2,!1,!0))}var $i=function(n,e){return n.push(e),n};function dn(){return he(function(n,e){Jo($i,[])(n).subscribe(e)})}function es(n){let e=[],t=0,r;for(let o=0,s=n.length;o<s;o++){let i=n.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)r=t,t=0;else{let a=n[o];a==="M"||a==="="||a==="X"?e.push({own:r===void 0?t:r,mate:t,op:"M"}):a==="I"?e.push({own:0,mate:t,op:a}):(a==="D"||a==="N")&&e.push({own:t,mate:0,op:a}),r=void 0,t=0}}return e}function nr(n){let e="";for(let{own:t,mate:r,op:o}of es(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var er=2**28-1;function tr(n,e,t){for(let r=e;r>0;r-=er)n.push((Math.min(r,er)<<4|t)>>>0)}function Hi(n,e,t){if(e===t)tr(n,e,0);else{let r=Math.ceil(Math.max(e,t)/er);for(let o=0;o<r;o++){let s=Math.floor(e*(o+1)/r)-Math.floor(e*o/r),i=Math.floor(t*(o+1)/r)-Math.floor(t*o/r);n.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function rr(n){let e=[];for(let{own:t,mate:r,op:o}of es(n))o==="M"?Hi(e,t,r):o==="I"?tr(e,r,1):tr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function Gi(n){return n>=48&&n<=57}function Bi(n){return n!==void 0&&/[A-Za-z]/.test(n)}function ts(n,e){let t=e;for(;t<n.length&&Bi(n[t]);)t++;return t}function ns(n,e){let t=e,r=0;for(;t<n.length&&Gi(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function as(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=ns(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=ts(n,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(r==="*")e("*",1,1,t+1,Math.min(t+3,n.length)),t+=3;else if(r==="+"||r==="-"){let o=ts(n,t+1),s=o-t-1;e(r,r==="-"?s:0,r==="+"?s:0,t+1,o),t=o}else if(r==="~"){let{value:o,next:s}=ns(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function or(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;as(n,(a,f,c,l,p)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,n[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let u=n.slice(l,p);e(73,i,c,u,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function fs(n,e,t,r){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=n.length;f<c;f++){let l=n[f],p=l>>>4,u=l&15;if(u===0||u===7){if(a)for(let d=0;d<p;d++)(e.charCodeAt(s+d)|32)!==(t.charCodeAt(o+d)|32)&&i.push({start:o+d,type:"mismatch",base:e[s+d],altbase:t[o+d],length:1});s+=p,o+=p}else if(u===1)i.push({start:o,type:"insertion",insertlen:p,insertedBases:e?.slice(s,s+p),length:0}),s+=p;else if(u===2)i.push({start:o,type:"deletion",length:p}),o+=p;else if(u===3)i.push({start:o,type:"skip",length:p}),o+=p;else if(u===8){for(let d=0;d<p;d++)i.push({start:o+d,type:"mismatch",base:e?.[s+d]||"X",qual:r?.[s+d],length:1});s+=p,o+=p}else u===5?i.push({start:o,type:"hardclip",cliplen:p,length:1}):u===4&&(i.push({start:o,type:"softclip",cliplen:p,length:1}),s+=p)}return i}function cs(n,e,t,r,o){if(!e)return[];let s=[],i=e.length,a=r.length,f=o!==void 0,c=t.length,l=!1;for(let I=0;I<c;I++)if(t[I].type==="skip"){l=!0;break}let p=0,u=0,d=0,h=0,m=0,y=0,S=n.length;for(;y<S;){let I=n.charCodeAt(y);if(I>=48&&I<=57){let g=0;for(;y<S;){let b=n.charCodeAt(y);if(b>=48&&b<=57)g=g*10+(b-48),y++;else break}p+=g}else if(I===94)for(y++;y<S&&n.charCodeAt(y)>=65;)y++,p++;else if(I>=65){let g=n[y];if(y++,l&&c>0)for(let L=m;L<c;L++){let k=t[L];k.type==="skip"&&p>=k.start&&(p+=k.length,m=L+1)}let b=d,x=h;for(let L=u;L<i&&x<=p;L++,u=L){let k=e[L],T=k>>>4,R=k&15;R===4||R===1?b+=T:R===2||R===6||R===3?x+=T:R!==5&&(b+=T,x+=T)}d=b,h=x;let A=b-(x-p),M=A<a?r[A]:"X";s.push({start:p,base:M,qual:f?o[A]:void 0,altbase:g,length:1,type:"mismatch"}),p++}else y++}return s}var ls={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function ps(n=""){let e=0,t=[];for(let r=0,o=n.length;r<o;r++){let s=n.charCodeAt(r);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=ls[s];t.push(e<<4|i),e=0}}return t}function ar(n=""){let e=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),r=0,o=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);a>=48&&a<=57?r=r*10+(a-48):(t[o++]=r<<4|ls[a],r=0)}return t}function yn(n,e,t,r,o){let s=ps(n),i=n?fs(s,t,r,o):[];return e&&t?i.concat(cs(e,s,i,t,o)):i}var ji=397,Ui=387,Wi=385;function hs(n){return(1<<n&ji)!==0}function ds(n){return(1<<n&Ui)!==0}function us(n){return(1<<n&Wi)!==0}function fr(n,e,t,r,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?r:t,l=[],p=1/0,u=-1/0,d=1/0,h=-1/0,m=(y,S)=>{d=Math.min(d,y,S),h=Math.max(h,y,S)};for(let y=0;y<n.length;y++){let S=n[y],I=S>>>4,g=S&15,b=g===9,x=b||hs(g)?I:0,A=b?n[++y]>>>4:ds(g)?I:0,M=f+x,L=c+A*a,k=f,T=M;if(T>=s&&k<=i)if(x>0){let R=Math.max(k,s),B=Math.min(T,i);if(B>R)if(p=Math.min(p,R),u=Math.max(u,B),b){let v=A/I,C=B-R,P=Math.round(C*v),G=Math.round(c+(R-f)*v*a);l.push(C<<4|9,P<<4|9),m(G,G+P*a)}else l.push(B-R<<4|g),us(g)?m(c+(R-f)*a,c+(B-f)*a):m(c,c)}else A>0&&(b?l.push(S,n[y]):l.push(S),p=Math.min(p,f),u=Math.max(u,f),m(c,L));if(f=M,c=L,f>i)break}if(l.length!==0)return{start:p,end:u,mateStart:d,mateEnd:h,cigar:Uint32Array.from(l)}}function Qi(n){return n===1||n===2||n===3}function cr(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?r:t,l,p=!1,u=()=>{l!==void 0&&p&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,p=!1};for(let d=0;d<n.length;d++){let h=n[d],m=h>>>4,y=h&15,S=y===9,I=S?n[++d]:void 0,g=S||hs(y)?m:0,b=I!==void 0?I>>>4:ds(y)?m:0,x=c+b*i;Qi(y)&&m>=s?u():(g>0||b>0)&&(l===void 0&&(l={qLo:f,qHi:f,tLo:c,tHi:c,ops:[]}),l.qHi=f+g,l.tLo=Math.min(l.tLo,c,x),l.tHi=Math.max(l.tHi,c,x),l.ops.push(h),I!==void 0&&l.ops.push(I),p=p||S||us(y)),f+=g,c=x}return u(),a}function ms(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function gs(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function lr(n){let e=ms(n),t=e===void 0?gs(n):void 0;return e!==void 0?ar(e):t!==void 0?rr(t):void 0}var Yi=le(et(),1),Vi=le(ys(),1);var Ki=le(et(),1);var Xi=le(Ns(),1);var xs=le(et(),1),ke=class extends xs.SimpleFeature{get(e){return e==="mismatches"?yn(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?nr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let r=this.get("start"),o=t?.start===void 0?void 0:t.start-r,s=t?.end===void 0?void 0:t.end-r,i=this.get("cs");if(i)or(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of yn(this.walkableCigar))(c.type==="deletion"||c.type==="skip"?c.start<f&&c.start+c.length>a:c.start>=a&&c.start<=f)&&(c.type==="mismatch"?e(88,c.start,c.length,c.base,c.qual??-1,0,0):c.type==="insertion"?e(73,c.start,c.length,c.insertedBases??"",-1,0,c.insertlen):c.type==="deletion"?e(68,c.start,c.length,"",-1,0,0):c.type==="skip"&&e(78,c.start,c.length,"",-1,0,0))}}};var Zi=["CIGAR","cs","coarseCigar","cg","cr"];function Ji(n){return typeof n=="object"&&n!==null&&"refName"in n&&"start"in n&&"end"in n&&typeof n.refName=="string"&&typeof n.start=="number"&&typeof n.end=="number"}function ea(n){let e=n.get("mate");return Ji(e)?e:void 0}function ta(n,e,t,r){let o=Math.max(n.start,r.start),s=Math.min(n.end,r.end),i=(e.end-e.start)/Math.max(n.end-n.start,1),a=l=>t===-1?e.end-(l-n.start)*i:e.start+(l-n.start)*i,f=Math.round(a(o)),c=Math.round(a(s));return s>o?{start:o,end:s,mateStart:Math.min(f,c),mateEnd:Math.max(f,c)}:void 0}function na(n,e,t,r,o){let s={start:n.get("start"),end:n.get("end")},i=n.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&r===void 0&&!o?void 0:lr(n);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ta(s,e,i,t);return c===void 0?[]:[c]}else return(r===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:cr(f,s.start,e.start,e.end,i,r)).flatMap(l=>{let p=fr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return p===void 0?[]:[p]})}function ra(n,e,t,r,o,s){let i=`:${r.start}-${r.end}${o}`,a=n.toJSON(),f={...a,uniqueId:`${n.id()}${i}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};a.syntenyId!==void 0&&(f.syntenyId=`${String(a.syntenyId)}${i}`);for(let c of Zi)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new ke(f)}function bs(n,e,t,r=!1){let o=ea(n);if(o===void 0)return[n];{let s=na(n,o,e,t,r);return s.map((i,a)=>ra(n,o,i,e,s.length>1?`/${a}`:"",r))}}var xn=class extends Ss.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=r,f=o&&this.recordsAreAlignments,c=(0,vs.createStatusFanOut)(a.statusCallback);return Jn(t).pipe(Ze((l,p)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(Ze(u=>f?bs(u,u.get("assemblyName")===l.assemblyName?l:{start:u.get("start"),end:u.get("end")},s,i):[u]),dn(),lt(u=>({index:p,features:u})))),dn(),Ze(l=>l.sort((p,u)=>p.index-u.index).flatMap(p=>p.features)))}};var ur=class extends Error{constructor(){super("no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation");this.name="NoHaplotypeIndexError"}},mr=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}},gr=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Is(n,e){let t=be(e);return n[t]??n[e.sample]??t}function oa(n,e){return`${be(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function sa({alignment:n,assemblyName:e,refName:t,lane:r}){let{refStart:o,refEnd:s,strand:i,cigar:a}=n;if(!(!n.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=n,p=oa(f,n),u={uniqueId:p,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:p,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new ke(u)}}function ia({pair:n,lane:e,mateLane:t}){let r=`${be(n.target)}#${n.target.contig}:${n.targetStart}-${n.targetEnd}|${be(n.query)}#${n.query.contig}:${n.queryStart}-${n.queryEnd}`;return new ke({uniqueId:r,assemblyName:e,refName:n.target.contig,start:n.targetStart,end:n.targetEnd,type:"match",strand:n.strand==="-"?-1:1,CIGAR:n.cigar,syntenyId:r,identity:n.matches/Math.max(n.columns,1),numMatches:n.matches,blockLen:n.columns,mate:{refName:n.query.contig,start:n.queryStart,end:n.queryEnd,assemblyName:t}})}var pr=n=>!("uri"in n)||n.uri!=="",wr=class extends xn{constructor(){super(...arguments);this.graph=(0,hr.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),r=this.getConf("haplotypeIndexLocation"),o=pr(r)?r:await Mo(t,this.pluginManager),s=await it.open((0,Je.openLocation)(t,this.pluginManager),o?{haplotypeIndex:(0,Je.openLocation)(o,this.pluginManager)}:{}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let a=await Ao(s),f=Un({configured:this.getConf("referenceSample"),anchorPrefix:je(this,i),referenceSamples:a});return{db:s,anchor:i,referenceSample:f,referenceSamples:a}}});this.gaf=(0,hr.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),r=this.getConf(["readsIndex","location"]),o=this.pluginManager;if(!pr(t))return;let s=(0,Je.openLocation)(t,o);return new Wt(s,pr(r)?new Ar({filehandle:s,...(0,Je.openTabixIndexFilehandle)(r,this.getConf(["readsIndex","indexType"]),o)}):void 0)}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r);return Eo(o,s,t)}async getHaplotypes(t={}){let{db:r,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=be(i.name),f=s.get(a);f?f.contigs.includes(i.name.contig)||f.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:o.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Pn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:Is(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:je(this,i),f=(await r.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:ze(be(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,r){let o=t===void 0||t.length===0?void 0:t.map(s=>je(this,s));return o===void 0&&r===void 0?void 0:s=>Io(s,o)&&(r===void 0||ze(be(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s}=await this.graph(),{assemblyName:i,refName:a,start:f,end:c}=t;if(i!==s)throw new gr(i,s);let l=await this.referenceQuery(a,{}),p=this.keepPredicate(r.haplotypes);return Co(o,l,f,c,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:r.signal,...p===void 0?{}:{keep:p}})}async getReads(t,r={}){let o=await this.gaf(r);return o?o.readsOver(new Set(t),r):{records:[],total:0}}async laneHaplotypes(t,r){let o=je(this,t);return(await this.getHaplotypes(r)).filter(s=>ze(s.prefix,o))}async referencePieces(t,r,o,s){let{db:i,referenceSample:a}=await this.graph(s),f=(await i.paths()).filter(l=>l.isIndexed&&l.name.sample===a&&l.name.contig===t&&l.name.fragment>r&&l.name.fragment<o).map(l=>l.name.fragment),c=[r,...[...new Set(f)].sort((l,p)=>l-p),o];return c.slice(1).map((l,p)=>({start:c[p],end:l}))}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:f}=t,c=je(this,r.targetAssemblyName),l=Pn(this),p=this.keepPredicate(r.haplotypes,c),u=await this.referenceQuery(i,r),d=this.getConf("nodeLimit");return(u?await(0,dr.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,r.statusCallback,()=>o.getAlignmentsForRange(u,a,f,{context:this.getConf("context"),haplotypes:"all",limit:d,signal:r.signal,...p===void 0?{}:{keep:p}}).catch(m=>{throw at(m,d,f-a)??m})):[]).flatMap(m=>{let y=m.resolved?sa({alignment:m,assemblyName:s,refName:i,lane:Is(l,m.name)}):void 0;return y===void 0?[]:[y]})}async pairFeatures(t,r,o){let{targetAssemblyName:s}=o;if(s===void 0)throw new mr(r);let{db:i}=await this.graph(o),{refName:a,start:f,end:c}=t,l=await this.laneHaplotypes(r,o),p=await this.laneHaplotypes(s,o),u=[...l,...p],d=await this.referenceQuery(a,o),h=this.getConf("nodeLimit"),m=await i.haplotypeAnchorSpacing()!==void 0,y=(g,b)=>i.getSubgraphForRange(g,b.start,b.end,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:h,signal:o.signal,keep:x=>u.some(A=>A.sample===x.sample&&A.haplotype===x.haplotype)}).catch(x=>{throw at(x,h,c-f)??x}),S=d&&m&&l.length>0&&p.length>0?(await(0,dr.updateStatus)(`Reading ${r} against ${s}`,o.statusCallback,async()=>Promise.all((await this.referencePieces(a,f,c,o)).map(g=>y(d,g))))).filter(g=>g!==void 0):[];return S.every(g=>{let b=g.stats.keep;return b!==void 0&&b.fallback===void 0})?S.flatMap(g=>l.flatMap(b=>p.flatMap(x=>g.pairAlignments({target:b,query:x,bases:!1}).map(A=>ia({pair:A,lane:r,mateLane:s}))))):[]}getFeatures(t,r={}){return(0,As.ObservableCreate)(async o=>{let{db:s,anchor:i}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new ur;if(t.assemblyName===i){let a=r.queryAssemblyName===void 0?await this.anchorFeatures(t,r):await this.pairFeatures(t,r.queryAssemblyName,r);for(let f of a)o.next(f)}o.complete()},r.signal)}};export{gr as HaplotypeWindowError,ur as NoHaplotypeIndexError,jt as NoReferenceSampleError,Ut as NodeLimitError,mr as PairTargetError,wr as default,sa as fragmentFeature,be as haplotypePrefix,Is as laneAssemblyName,at as nodeLimitError,ia as pairFeature,Un as resolveReferenceSample};
|
|
8
|
-
//# sourceMappingURL=GbzBaseSyntenyAdapter-
|
|
7
|
+
`):"",this.name="UnsubscriptionError",this.errors=t}});function Yn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Vt=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=He(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(m){e={error:m}}finally{try{f&&!f.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(F(l))try{l()}catch(m){s=m instanceof Yt?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var u=He(p),d=u.next();!d.done;d=u.next()){var h=d.value;try{No(h)}catch(m){s=s??[],m instanceof Yt?s=Ve(Ve([],Ye(s)),Ye(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{d&&!d.done&&(o=u.return)&&o.call(u)}finally{if(r)throw r.error}}}if(s)throw new Yt(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)No(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Yn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Yn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var hf=Vt.EMPTY;function Kt(n){return n instanceof Vt||n&&"closed"in n&&F(n.remove)&&F(n.add)&&F(n.unsubscribe)}function No(n){F(n)?n():n.unsubscribe()}var we={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ke={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=Ke.delegate;return o?.setTimeout?o.setTimeout.apply(o,Ve([n,e],Ye(t))):setTimeout.apply(void 0,Ve([n,e],Ye(t)))},clearTimeout:function(n){var e=Ke.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function Xt(n){Ke.setTimeout(function(){var e=we.onUnhandledError;if(e)e(n);else throw n})}function Vn(){}var Fo=(function(){return Kn("C",void 0,void 0)})();function qo(n){return Kn("E",void 0,n)}function $o(n){return Kn("N",n,void 0)}function Kn(n,e,t){return{kind:n,value:e,error:t}}var Be=null;function Ho(n){if(we.useDeprecatedSynchronousErrorHandling){var e=!Be;if(e&&(Be={errorThrown:!1,error:null}),n(),e){var t=Be,r=t.errorThrown,o=t.error;if(Be=null,r)throw o}}else n()}function Go(n){we.useDeprecatedSynchronousErrorHandling&&Be&&(Be.errorThrown=!0,Be.error=n)}var ct=(function(n){ft(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Kt(t)&&t.add(r)):r.destination=Ci,r}return e.create=function(t,r,o){return new Jt(t,r,o)},e.prototype.next=function(t){this.isStopped?Zn($o(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?Zn(qo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?Zn(Fo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Vt);var Ii=Function.prototype.bind;function Xn(n,e){return Ii.call(n,e)}var Ai=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Zt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Zt(r)}else Zt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Zt(t)}},n})(),Jt=(function(n){ft(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(F(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&we.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Xn(t.next,a),error:t.error&&Xn(t.error,a),complete:t.complete&&Xn(t.complete,a)}):i=t}return s.destination=new Ai(i),s}return e})(ct);function Zt(n){we.useDeprecatedSynchronousErrorHandling?Go(n):Xt(n)}function Ei(n){throw n}function Zn(n,e){var t=we.onStoppedNotification;t&&Ke.setTimeout(function(){return t(n,e)})}var Ci={closed:!0,next:Vn,error:Ei,complete:Vn};var Xe=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Bo(n){return n}function Do(n){return n.length===0?Bo:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var ie=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Pi(e)?e:new Jt(e,t,r);return Ho(function(){var i=o,a=i.operator,f=i.source;s.add(a?a.call(s,f):f?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=zo(t),new t(function(o,s){var i=new Jt({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Xe]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Do(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=zo(e),new e(function(r,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},n.create=function(e){return new n(e)},n})();function zo(n){var e;return(e=n??we.Promise)!==null&&e!==void 0?e:Promise}function Ri(n){return n&&F(n.next)&&F(n.error)&&F(n.complete)}function Pi(n){return n&&n instanceof ct||Ri(n)&&Kt(n)}function Mi(n){return F(n?.lift)}function he(n){return function(e){if(Mi(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Pe(n,e,t,r,o){return new _i(n,e,t,r,o)}var _i=(function(n){ft(e,n);function e(t,r,o,s,i,a){var f=n.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=r?function(c){try{r(c)}catch(l){t.error(l)}}:n.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(ct);var en=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function tn(n){return F(n?.then)}function nn(n){return F(n[Xe])}function rn(n){return Symbol.asyncIterator&&F(n?.[Symbol.asyncIterator])}function on(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ki(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var sn=ki();function an(n){return F(n?.[sn])}function fn(n){return Oo(this,arguments,function(){var t,r,o,s;return Qt(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Ge(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,Ge(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ge(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function cn(n){return F(n?.getReader)}function Se(n){if(n instanceof ie)return n;if(n!=null){if(nn(n))return Oi(n);if(en(n))return Li(n);if(tn(n))return Ti(n);if(rn(n))return jo(n);if(an(n))return Ni(n);if(cn(n))return Fi(n)}throw on(n)}function Oi(n){return new ie(function(e){var t=n[Xe]();if(F(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Li(n){return new ie(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Ti(n){return new ie(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Xt)})}function Ni(n){return new ie(function(e){var t,r;try{for(var o=He(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function jo(n){return new ie(function(e){qi(n,e).catch(function(t){return e.error(t)})})}function Fi(n){return jo(fn(n))}function qi(n,e){var t,r,o,s;return ko(this,void 0,void 0,function(){var i,a;return Qt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Lo(n),f.label=1;case 1:return[4,t.next()];case 2:if(r=f.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];f.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=f.sent(),o={error:a},[3,11];case 6:return f.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function de(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function ln(n,e){return e===void 0&&(e=0),he(function(t,r){t.subscribe(Pe(r,function(o){return de(r,n,function(){return r.next(o)},e)},function(){return de(r,n,function(){return r.complete()},e)},function(o){return de(r,n,function(){return r.error(o)},e)}))})}function pn(n,e){return e===void 0&&(e=0),he(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function Uo(n,e){return Se(n).pipe(pn(e),ln(e))}function Wo(n,e){return Se(n).pipe(pn(e),ln(e))}function Qo(n,e){return new ie(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function Yo(n,e){return new ie(function(t){var r;return de(t,e,function(){r=n[sn](),de(t,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return F(r?.return)&&r.return()}})}function hn(n,e){if(!n)throw new Error("Iterable cannot be null");return new ie(function(t){de(t,e,function(){var r=n[Symbol.asyncIterator]();de(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function Vo(n,e){return hn(fn(n),e)}function Ko(n,e){if(n!=null){if(nn(n))return Uo(n,e);if(en(n))return Qo(n,e);if(tn(n))return Wo(n,e);if(rn(n))return hn(n,e);if(an(n))return Yo(n,e);if(cn(n))return Vo(n,e)}throw on(n)}function Jn(n,e){return e?Ko(n,e):Se(n)}function lt(n,e){return he(function(t,r){var o=0;t.subscribe(Pe(r,function(s){r.next(n.call(e,s,o++))}))})}function Xo(n,e,t,r,o,s,i,a){var f=[],c=0,l=0,p=!1,u=function(){p&&!f.length&&!c&&e.complete()},d=function(m){return c<r?h(m):f.push(m)},h=function(m){s&&e.next(m),c++;var y=!1;Se(t(m,l++)).subscribe(Pe(e,function(S){o?.(S),s?d(S):e.next(S)},function(){y=!0},void 0,function(){if(y)try{c--;for(var S=function(){var I=f.shift();i?de(e,i,function(){return h(I)}):h(I)};f.length&&c<r;)S();u()}catch(I){e.error(I)}}))};return n.subscribe(Pe(e,d,function(){p=!0,u()})),function(){a?.()}}function Ze(n,e,t){return t===void 0&&(t=1/0),F(e)?Ze(function(r,o){return lt(function(s,i){return e(r,s,o,i)})(Se(n(r,o)))},t):(typeof e=="number"&&(t=e),he(function(r,o){return Xo(r,o,n,t)}))}function Zo(n,e,t,r,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var p=c++;f=a?n(f,l,p):(a=!0,l),r&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function Jo(n,e){return he(Zo(n,e,arguments.length>=2,!1,!0))}var $i=function(n,e){return n.push(e),n};function dn(){return he(function(n,e){Jo($i,[])(n).subscribe(e)})}function es(n){let e=[],t=0,r;for(let o=0,s=n.length;o<s;o++){let i=n.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)r=t,t=0;else{let a=n[o];a==="M"||a==="="||a==="X"?e.push({own:r===void 0?t:r,mate:t,op:"M"}):a==="I"?e.push({own:0,mate:t,op:a}):(a==="D"||a==="N")&&e.push({own:t,mate:0,op:a}),r=void 0,t=0}}return e}function nr(n){let e="";for(let{own:t,mate:r,op:o}of es(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var er=2**28-1;function tr(n,e,t){for(let r=e;r>0;r-=er)n.push((Math.min(r,er)<<4|t)>>>0)}function Hi(n,e,t){if(e===t)tr(n,e,0);else{let r=Math.ceil(Math.max(e,t)/er);for(let o=0;o<r;o++){let s=Math.floor(e*(o+1)/r)-Math.floor(e*o/r),i=Math.floor(t*(o+1)/r)-Math.floor(t*o/r);n.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function rr(n){let e=[];for(let{own:t,mate:r,op:o}of es(n))o==="M"?Hi(e,t,r):o==="I"?tr(e,r,1):tr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function Gi(n){return n>=48&&n<=57}function Bi(n){return n!==void 0&&/[A-Za-z]/.test(n)}function ts(n,e){let t=e;for(;t<n.length&&Bi(n[t]);)t++;return t}function ns(n,e){let t=e,r=0;for(;t<n.length&&Gi(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function as(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=ns(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=ts(n,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(r==="*")e("*",1,1,t+1,Math.min(t+3,n.length)),t+=3;else if(r==="+"||r==="-"){let o=ts(n,t+1),s=o-t-1;e(r,r==="-"?s:0,r==="+"?s:0,t+1,o),t=o}else if(r==="~"){let{value:o,next:s}=ns(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function or(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;as(n,(a,f,c,l,p)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,n[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let u=n.slice(l,p);e(73,i,c,u,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function fs(n,e,t,r){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=n.length;f<c;f++){let l=n[f],p=l>>>4,u=l&15;if(u===0||u===7){if(a)for(let d=0;d<p;d++)(e.charCodeAt(s+d)|32)!==(t.charCodeAt(o+d)|32)&&i.push({start:o+d,type:"mismatch",base:e[s+d],altbase:t[o+d],length:1});s+=p,o+=p}else if(u===1)i.push({start:o,type:"insertion",insertlen:p,insertedBases:e?.slice(s,s+p),length:0}),s+=p;else if(u===2)i.push({start:o,type:"deletion",length:p}),o+=p;else if(u===3)i.push({start:o,type:"skip",length:p}),o+=p;else if(u===8){for(let d=0;d<p;d++)i.push({start:o+d,type:"mismatch",base:e?.[s+d]||"X",qual:r?.[s+d],length:1});s+=p,o+=p}else u===5?i.push({start:o,type:"hardclip",cliplen:p,length:1}):u===4&&(i.push({start:o,type:"softclip",cliplen:p,length:1}),s+=p)}return i}function cs(n,e,t,r,o){if(!e)return[];let s=[],i=e.length,a=r.length,f=o!==void 0,c=t.length,l=!1;for(let I=0;I<c;I++)if(t[I].type==="skip"){l=!0;break}let p=0,u=0,d=0,h=0,m=0,y=0,S=n.length;for(;y<S;){let I=n.charCodeAt(y);if(I>=48&&I<=57){let g=0;for(;y<S;){let b=n.charCodeAt(y);if(b>=48&&b<=57)g=g*10+(b-48),y++;else break}p+=g}else if(I===94)for(y++;y<S&&n.charCodeAt(y)>=65;)y++,p++;else if(I>=65){let g=n[y];if(y++,l&&c>0)for(let L=m;L<c;L++){let k=t[L];k.type==="skip"&&p>=k.start&&(p+=k.length,m=L+1)}let b=d,x=h;for(let L=u;L<i&&x<=p;L++,u=L){let k=e[L],T=k>>>4,R=k&15;R===4||R===1?b+=T:R===2||R===6||R===3?x+=T:R!==5&&(b+=T,x+=T)}d=b,h=x;let A=b-(x-p),M=A<a?r[A]:"X";s.push({start:p,base:M,qual:f?o[A]:void 0,altbase:g,length:1,type:"mismatch"}),p++}else y++}return s}var ls={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function ps(n=""){let e=0,t=[];for(let r=0,o=n.length;r<o;r++){let s=n.charCodeAt(r);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=ls[s];t.push(e<<4|i),e=0}}return t}function ar(n=""){let e=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),r=0,o=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);a>=48&&a<=57?r=r*10+(a-48):(t[o++]=r<<4|ls[a],r=0)}return t}function yn(n,e,t,r,o){let s=ps(n),i=n?fs(s,t,r,o):[];return e&&t?i.concat(cs(e,s,i,t,o)):i}var ji=397,Ui=387,Wi=385;function hs(n){return(1<<n&ji)!==0}function ds(n){return(1<<n&Ui)!==0}function us(n){return(1<<n&Wi)!==0}function fr(n,e,t,r,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?r:t,l=[],p=1/0,u=-1/0,d=1/0,h=-1/0,m=(y,S)=>{d=Math.min(d,y,S),h=Math.max(h,y,S)};for(let y=0;y<n.length;y++){let S=n[y],I=S>>>4,g=S&15,b=g===9,x=b||hs(g)?I:0,A=b?n[++y]>>>4:ds(g)?I:0,M=f+x,L=c+A*a,k=f,T=M;if(T>=s&&k<=i)if(x>0){let R=Math.max(k,s),B=Math.min(T,i);if(B>R)if(p=Math.min(p,R),u=Math.max(u,B),b){let v=A/I,C=B-R,P=Math.round(C*v),G=Math.round(c+(R-f)*v*a);l.push(C<<4|9,P<<4|9),m(G,G+P*a)}else l.push(B-R<<4|g),us(g)?m(c+(R-f)*a,c+(B-f)*a):m(c,c)}else A>0&&(b?l.push(S,n[y]):l.push(S),p=Math.min(p,f),u=Math.max(u,f),m(c,L));if(f=M,c=L,f>i)break}if(l.length!==0)return{start:p,end:u,mateStart:d,mateEnd:h,cigar:Uint32Array.from(l)}}function Qi(n){return n===1||n===2||n===3}function cr(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?r:t,l,p=!1,u=()=>{l!==void 0&&p&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,p=!1};for(let d=0;d<n.length;d++){let h=n[d],m=h>>>4,y=h&15,S=y===9,I=S?n[++d]:void 0,g=S||hs(y)?m:0,b=I!==void 0?I>>>4:ds(y)?m:0,x=c+b*i;Qi(y)&&m>=s?u():(g>0||b>0)&&(l===void 0&&(l={qLo:f,qHi:f,tLo:c,tHi:c,ops:[]}),l.qHi=f+g,l.tLo=Math.min(l.tLo,c,x),l.tHi=Math.max(l.tHi,c,x),l.ops.push(h),I!==void 0&&l.ops.push(I),p=p||S||us(y)),f+=g,c=x}return u(),a}function ms(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function gs(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function lr(n){let e=ms(n),t=e===void 0?gs(n):void 0;return e!==void 0?ar(e):t!==void 0?rr(t):void 0}var Yi=le(et(),1),Vi=le(ys(),1);var Ki=le(et(),1);var Xi=le(Ns(),1);var xs=le(et(),1),ke=class extends xs.SimpleFeature{get(e){return e==="mismatches"?yn(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?nr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let r=this.get("start"),o=t?.start===void 0?void 0:t.start-r,s=t?.end===void 0?void 0:t.end-r,i=this.get("cs");if(i)or(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of yn(this.walkableCigar))(c.type==="deletion"||c.type==="skip"?c.start<f&&c.start+c.length>a:c.start>=a&&c.start<=f)&&(c.type==="mismatch"?e(88,c.start,c.length,c.base,c.qual??-1,0,0):c.type==="insertion"?e(73,c.start,c.length,c.insertedBases??"",-1,0,c.insertlen):c.type==="deletion"?e(68,c.start,c.length,"",-1,0,0):c.type==="skip"&&e(78,c.start,c.length,"",-1,0,0))}}};var Zi=["CIGAR","cs","coarseCigar","cg","cr"];function Ji(n){return typeof n=="object"&&n!==null&&"refName"in n&&"start"in n&&"end"in n&&typeof n.refName=="string"&&typeof n.start=="number"&&typeof n.end=="number"}function ea(n){let e=n.get("mate");return Ji(e)?e:void 0}function ta(n,e,t,r){let o=Math.max(n.start,r.start),s=Math.min(n.end,r.end),i=(e.end-e.start)/Math.max(n.end-n.start,1),a=l=>t===-1?e.end-(l-n.start)*i:e.start+(l-n.start)*i,f=Math.round(a(o)),c=Math.round(a(s));return s>o?{start:o,end:s,mateStart:Math.min(f,c),mateEnd:Math.max(f,c)}:void 0}function na(n,e,t,r,o){let s={start:n.get("start"),end:n.get("end")},i=n.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&r===void 0&&!o?void 0:lr(n);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ta(s,e,i,t);return c===void 0?[]:[c]}else return(r===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:cr(f,s.start,e.start,e.end,i,r)).flatMap(l=>{let p=fr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return p===void 0?[]:[p]})}function ra(n,e,t,r,o,s){let i=`:${r.start}-${r.end}${o}`,a=n.toJSON(),f={...a,uniqueId:`${n.id()}${i}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};a.syntenyId!==void 0&&(f.syntenyId=`${String(a.syntenyId)}${i}`);for(let c of Zi)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new ke(f)}function bs(n,e,t,r=!1){let o=ea(n);if(o===void 0)return[n];{let s=na(n,o,e,t,r);return s.map((i,a)=>ra(n,o,i,e,s.length>1?`/${a}`:"",r))}}var xn=class extends Ss.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=r,f=o&&this.recordsAreAlignments,c=(0,vs.createStatusFanOut)(a.statusCallback);return Jn(t).pipe(Ze((l,p)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(Ze(u=>f?bs(u,u.get("assemblyName")===l.assemblyName?l:{start:u.get("start"),end:u.get("end")},s,i):[u]),dn(),lt(u=>({index:p,features:u})))),dn(),Ze(l=>l.sort((p,u)=>p.index-u.index).flatMap(p=>p.features)))}};var ur=class extends Error{constructor(){super("no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation");this.name="NoHaplotypeIndexError"}},mr=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}},gr=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Is(n,e){let t=be(e);return n[t]??n[e.sample]??t}function oa(n,e){return`${be(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function sa({alignment:n,assemblyName:e,refName:t,lane:r}){let{refStart:o,refEnd:s,strand:i,cigar:a}=n;if(!(!n.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=n,p=oa(f,n),u={uniqueId:p,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:p,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new ke(u)}}function ia({pair:n,lane:e,mateLane:t}){let r=`${be(n.target)}#${n.target.contig}:${n.targetStart}-${n.targetEnd}|${be(n.query)}#${n.query.contig}:${n.queryStart}-${n.queryEnd}`;return new ke({uniqueId:r,assemblyName:e,refName:n.target.contig,start:n.targetStart,end:n.targetEnd,type:"match",strand:n.strand==="-"?-1:1,CIGAR:n.cigar,syntenyId:r,identity:n.matches/Math.max(n.columns,1),numMatches:n.matches,blockLen:n.columns,mate:{refName:n.query.contig,start:n.queryStart,end:n.queryEnd,assemblyName:t}})}var pr=n=>!("uri"in n)||n.uri!=="",wr=class extends xn{constructor(){super(...arguments);this.graph=(0,hr.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),r=this.getConf("haplotypeIndexLocation"),o=pr(r)?r:await Mo(t,this.pluginManager),s=await it.open((0,Je.openLocation)(t,this.pluginManager),o?{haplotypeIndex:(0,Je.openLocation)(o,this.pluginManager)}:{}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let a=await Ao(s),f=Un({configured:this.getConf("referenceSample"),anchorPrefix:je(this,i),referenceSamples:a});return{db:s,anchor:i,referenceSample:f,referenceSamples:a}}});this.gaf=(0,hr.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),r=this.getConf(["readsIndex","location"]),o=this.pluginManager;if(!pr(t))return;let s=(0,Je.openLocation)(t,o);return new Wt(s,pr(r)?new Ar({filehandle:s,...(0,Je.openTabixIndexFilehandle)(r,this.getConf(["readsIndex","indexType"]),o)}):void 0)}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r);return Eo(o,s,t)}async getHaplotypes(t={}){let{db:r,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=be(i.name),f=s.get(a);f?f.contigs.includes(i.name.contig)||f.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:o.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Pn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:Is(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:je(this,i),f=(await r.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:ze(be(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,r){let o=t===void 0||t.length===0?void 0:t.map(s=>je(this,s));return o===void 0&&r===void 0?void 0:s=>Io(s,o)&&(r===void 0||ze(be(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s}=await this.graph(),{assemblyName:i,refName:a,start:f,end:c}=t;if(i!==s)throw new gr(i,s);let l=await this.referenceQuery(a,{}),p=this.keepPredicate(r.haplotypes);return Co(o,l,f,c,{context:this.getConf("context"),snarls:r.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:r.signal,...p===void 0?{}:{keep:p}})}async getReads(t,r={}){let o=await this.gaf(r);return o?o.readsOver(new Set(t),r):{records:[],total:0}}async laneHaplotypes(t,r){let o=je(this,t);return(await this.getHaplotypes(r)).filter(s=>ze(s.prefix,o))}async referencePieces(t,r,o,s){let{db:i,referenceSample:a}=await this.graph(s),f=(await i.paths()).filter(l=>l.isIndexed&&l.name.sample===a&&l.name.contig===t&&l.name.fragment>r&&l.name.fragment<o).map(l=>l.name.fragment),c=[r,...[...new Set(f)].sort((l,p)=>l-p),o];return c.slice(1).map((l,p)=>({start:c[p],end:l}))}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:f}=t,c=je(this,r.targetAssemblyName),l=Pn(this),p=this.keepPredicate(r.haplotypes,c),u=await this.referenceQuery(i,r),d=this.getConf("nodeLimit");return(u?await(0,dr.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,r.statusCallback,()=>o.getAlignmentsForRange(u,a,f,{context:this.getConf("context"),haplotypes:"all",limit:d,signal:r.signal,...p===void 0?{}:{keep:p}}).catch(m=>{throw at(m,d,f-a)??m})):[]).flatMap(m=>{let y=m.resolved?sa({alignment:m,assemblyName:s,refName:i,lane:Is(l,m.name)}):void 0;return y===void 0?[]:[y]})}async pairFeatures(t,r,o){let{targetAssemblyName:s}=o;if(s===void 0)throw new mr(r);let{db:i}=await this.graph(o),{refName:a,start:f,end:c}=t,l=await this.laneHaplotypes(r,o),p=await this.laneHaplotypes(s,o),u=[...l,...p],d=await this.referenceQuery(a,o),h=this.getConf("nodeLimit"),m=await i.haplotypeAnchorSpacing()!==void 0,y=(g,b)=>i.getSubgraphForRange(g,b.start,b.end,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:h,signal:o.signal,keep:x=>u.some(A=>A.sample===x.sample&&A.haplotype===x.haplotype)}).catch(x=>{throw at(x,h,c-f)??x}),S=d&&m&&l.length>0&&p.length>0?(await(0,dr.updateStatus)(`Reading ${r} against ${s}`,o.statusCallback,async()=>Promise.all((await this.referencePieces(a,f,c,o)).map(g=>y(d,g))))).filter(g=>g!==void 0):[];return S.every(g=>{let b=g.stats.keep;return b!==void 0&&b.fallback===void 0})?S.flatMap(g=>l.flatMap(b=>p.flatMap(x=>g.pairAlignments({target:b,query:x,bases:!1}).map(A=>ia({pair:A,lane:r,mateLane:s}))))):[]}getFeatures(t,r={}){return(0,As.ObservableCreate)(async o=>{let{db:s,anchor:i}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new ur;if(t.assemblyName===i){let a=r.queryAssemblyName===void 0?await this.anchorFeatures(t,r):await this.pairFeatures(t,r.queryAssemblyName,r);for(let f of a)o.next(f)}o.complete()},r.signal)}};export{gr as HaplotypeWindowError,ur as NoHaplotypeIndexError,jt as NoReferenceSampleError,Ut as NodeLimitError,mr as PairTargetError,wr as default,sa as fragmentFeature,be as haplotypePrefix,Is as laneAssemblyName,at as nodeLimitError,ia as pairFeature,Un as resolveReferenceSample};
|
|
8
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-HNETLUW4.js.map
|