jbrowse-plugin-graphgenomeviewer 10.20.0 → 10.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/AddTrackWorkflow-JIOQ5J2I.js +2 -0
- package/dist/chunks/{AddTrackWorkflow-YTYOE4OI.js.map → AddTrackWorkflow-JIOQ5J2I.js.map} +1 -1
- package/dist/chunks/GbzBaseSyntenyAdapter-H55DLBI3.js +11 -0
- package/dist/chunks/{GbzBaseSyntenyAdapter-OGG37QND.js.map → GbzBaseSyntenyAdapter-H55DLBI3.js.map} +4 -4
- package/dist/chunks/GfaTabixAdapter-VW2LDHVV.js +2 -0
- package/dist/chunks/GfaTabixAdapter-VW2LDHVV.js.map +7 -0
- package/dist/chunks/GfaWalksFormsAdapter-PPKEQWFW.js +2 -0
- package/dist/chunks/{GfaWalksFormsAdapter-OS2KRNR2.js.map → GfaWalksFormsAdapter-PPKEQWFW.js.map} +1 -1
- package/dist/chunks/GfaWalksSyntenyAdapter-SIF5NZ72.js +2 -0
- package/dist/chunks/{GfaWalksSyntenyAdapter-Z4XU5PWM.js.map → GfaWalksSyntenyAdapter-SIF5NZ72.js.map} +1 -1
- package/dist/chunks/{GraphGenomeView-XFQA47RY.js → GraphGenomeView-7OFAL5L2.js} +2 -2
- package/dist/chunks/GraphSettingsDialog-WSXM3BYP.js +2 -0
- package/dist/chunks/{HighlightColorDialog-LPEIFHCT.js → HighlightColorDialog-V6XJISCR.js} +2 -2
- package/dist/chunks/LinearGraphDisplay-4K6WGQEJ.js +2 -0
- package/dist/chunks/MinigraphBubbleAdapter-C4YZ72TM.js +2 -0
- package/dist/chunks/{MinigraphBubbleAdapter-HFBQTCCA.js.map → MinigraphBubbleAdapter-C4YZ72TM.js.map} +1 -1
- package/dist/chunks/{chunk-KSAKILCP.js → chunk-2MOWWQHO.js} +6 -6
- package/dist/chunks/chunk-2MOWWQHO.js.map +7 -0
- package/dist/chunks/chunk-6QVYCHYW.js +9 -0
- package/dist/chunks/chunk-6QVYCHYW.js.map +7 -0
- package/dist/chunks/chunk-6YCWMMQH.js +4 -0
- package/dist/chunks/chunk-6YCWMMQH.js.map +7 -0
- package/dist/chunks/{chunk-ZEHAQBOA.js → chunk-7INTU7WN.js} +1 -1
- package/dist/chunks/{chunk-ZEHAQBOA.js.map → chunk-7INTU7WN.js.map} +1 -1
- package/dist/chunks/{chunk-63K6DJ6R.js → chunk-A5LWOEK4.js} +2 -2
- package/dist/chunks/{chunk-63K6DJ6R.js.map → chunk-A5LWOEK4.js.map} +1 -1
- package/dist/chunks/{chunk-C242NSG7.js → chunk-BT4FAQDM.js} +1 -1
- package/dist/chunks/{chunk-C242NSG7.js.map → chunk-BT4FAQDM.js.map} +1 -1
- package/dist/chunks/{chunk-VNPIF6Z5.js → chunk-BVRZASLN.js} +2 -2
- package/dist/chunks/{chunk-S5LIOHKI.js → chunk-C6IYXPUI.js} +2 -2
- package/dist/chunks/chunk-CTDCNU5C.js +2 -0
- package/dist/chunks/chunk-CTDCNU5C.js.map +7 -0
- package/dist/chunks/chunk-DSNIXLI7.js +2 -0
- package/dist/chunks/chunk-DSNIXLI7.js.map +7 -0
- package/dist/chunks/chunk-ECNJGM74.js +2 -0
- package/dist/chunks/chunk-ECNJGM74.js.map +7 -0
- package/dist/chunks/chunk-GHZXTAN6.js +2 -0
- package/dist/chunks/{chunk-JDKYRDNW.js.map → chunk-GHZXTAN6.js.map} +2 -2
- package/dist/chunks/{chunk-WKD7ALOU.js → chunk-HNTK5LBJ.js} +2 -2
- package/dist/chunks/{chunk-WKD7ALOU.js.map → chunk-HNTK5LBJ.js.map} +2 -2
- package/dist/chunks/{chunk-JMJQK57L.js → chunk-IWZ4VAPS.js} +2 -2
- package/dist/chunks/chunk-JYKCHE2I.js +2 -0
- package/dist/chunks/chunk-JYKCHE2I.js.map +7 -0
- package/dist/chunks/chunk-KAXFQXNV.js +5 -0
- package/dist/chunks/chunk-KAXFQXNV.js.map +7 -0
- package/dist/chunks/chunk-N3QQ2EHI.js +2 -0
- package/dist/chunks/chunk-N3QQ2EHI.js.map +7 -0
- package/dist/chunks/{chunk-QJYN7JLE.js → chunk-NKB3H4CP.js} +2 -2
- package/dist/chunks/chunk-PFONXB5H.js +2 -0
- package/dist/chunks/{chunk-BLG5IZAA.js.map → chunk-PFONXB5H.js.map} +3 -3
- package/dist/chunks/chunk-Q7FDYU47.js +3 -0
- package/dist/chunks/chunk-Q7FDYU47.js.map +7 -0
- package/dist/chunks/chunk-WQZMHWAL.js +2 -0
- package/dist/chunks/chunk-WQZMHWAL.js.map +7 -0
- package/dist/chunks/chunk-XEMDXS4J.js +5 -0
- package/dist/chunks/chunk-XEMDXS4J.js.map +7 -0
- package/dist/chunks/{chunk-3VS3QSRQ.js → chunk-XV5KQ7D4.js} +2 -2
- package/dist/chunks/{chunk-3VS3QSRQ.js.map → chunk-XV5KQ7D4.js.map} +2 -2
- package/dist/chunks/chunk-YTH4CEBQ.js +2 -0
- package/dist/chunks/renderSvg-JVDFX72P.js +2 -0
- package/dist/chunks/{renderSvg-J2WUI63J.js.map → renderSvg-JVDFX72P.js.map} +1 -1
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +1 -1
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +3 -3
- package/src/GetRepeatNames.ts +59 -0
- package/src/GfaTabixAdapter/GfaTabixAdapter.ts +49 -1
- package/src/GfaTabixAdapter/configSchema.ts +13 -0
- package/src/GfaTabixAdapter/repeatNames.test.ts +133 -0
- package/src/GraphGenomeView/components/FacetPanels.test.tsx +9 -9
- package/src/GraphGenomeView/components/HoverTooltip.test.tsx +37 -0
- package/src/GraphGenomeView/components/HoverTooltip.tsx +5 -1
- package/src/GraphGenomeView/components/WalkStrip.test.tsx +17 -2
- package/src/GraphGenomeView/components/WalkStrip.tsx +1 -0
- package/src/GraphGenomeView/legendSections.test.ts +17 -26
- package/src/GraphGenomeView/legendSections.ts +17 -26
- package/src/GraphGenomeView/model.fold.test.ts +7 -8
- package/src/GraphGenomeView/model.labelRuns.test.ts +6 -6
- package/src/GraphGenomeView/model.ts +229 -9
- package/src/GraphGenomeView/model.walkRows.test.ts +1 -4
- package/src/GraphGenomeView/pane/graphViews.ts +4 -19
- package/src/GraphGenomeView/pane/launchActions.ts +14 -0
- package/src/GraphGenomeView/pane/paneBase.ts +18 -0
- package/src/GraphGenomeView/pane/settingActions.ts +3 -0
- package/src/GraphGenomeView/renderPipeline.test.ts +0 -55
- package/src/GraphGenomeView/repeatNames.display.test.ts +248 -0
- package/src/GraphGenomeView/threadFoldCut.ts +2 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +68 -43
- package/src/LinearGraphDisplay/model.ts +5 -1
- package/src/assemblyRepeats/assemblyRepeats.test.ts +174 -0
- package/src/assemblyRepeats/assemblyRepeats.ts +78 -0
- package/src/assemblyRepeats/repeatsFile.test.ts +137 -0
- package/src/assemblyRepeats/repeatsFile.ts +117 -0
- package/src/assemblyRepeats/test_data/HG00642-2.chr6.bases.json +7 -0
- package/src/assemblyRepeats/test_data/bed4-rows.json +141 -0
- package/src/index.ts +2 -0
- package/src/repeatNames/bedSource.ts +75 -0
- package/src/repeatNames/repeatNames.test.ts +146 -0
- package/src/repeatNames/repeatNames.ts +134 -0
- package/src/repeatNames/sourceNames.ts +95 -0
- package/src/version.ts +1 -1
- package/dist/chunks/AddTrackWorkflow-YTYOE4OI.js +0 -2
- package/dist/chunks/GbzBaseSyntenyAdapter-OGG37QND.js +0 -9
- package/dist/chunks/GfaTabixAdapter-ZNOBLXSB.js +0 -2
- package/dist/chunks/GfaTabixAdapter-ZNOBLXSB.js.map +0 -7
- package/dist/chunks/GfaWalksFormsAdapter-OS2KRNR2.js +0 -2
- package/dist/chunks/GfaWalksSyntenyAdapter-Z4XU5PWM.js +0 -2
- package/dist/chunks/GraphSettingsDialog-Y44LH6AY.js +0 -2
- package/dist/chunks/LinearGraphDisplay-NBIH3WZU.js +0 -2
- package/dist/chunks/MinigraphBubbleAdapter-HFBQTCCA.js +0 -2
- package/dist/chunks/chunk-22KNQ66U.js +0 -2
- package/dist/chunks/chunk-22KNQ66U.js.map +0 -7
- package/dist/chunks/chunk-24TKECTB.js +0 -2
- package/dist/chunks/chunk-24TKECTB.js.map +0 -7
- package/dist/chunks/chunk-52XA4HFU.js +0 -5
- package/dist/chunks/chunk-52XA4HFU.js.map +0 -7
- package/dist/chunks/chunk-BLG5IZAA.js +0 -2
- package/dist/chunks/chunk-BZKABZ5M.js +0 -2
- package/dist/chunks/chunk-BZKABZ5M.js.map +0 -7
- package/dist/chunks/chunk-CVKTD6XQ.js +0 -4
- package/dist/chunks/chunk-CVKTD6XQ.js.map +0 -7
- package/dist/chunks/chunk-DWFV26HC.js +0 -2
- package/dist/chunks/chunk-DWFV26HC.js.map +0 -7
- package/dist/chunks/chunk-G755GASC.js +0 -9
- package/dist/chunks/chunk-G755GASC.js.map +0 -7
- package/dist/chunks/chunk-JDKYRDNW.js +0 -2
- package/dist/chunks/chunk-K7MCIHO3.js +0 -3
- package/dist/chunks/chunk-K7MCIHO3.js.map +0 -7
- package/dist/chunks/chunk-KSAKILCP.js.map +0 -7
- package/dist/chunks/chunk-NFKN4P6Q.js +0 -5
- package/dist/chunks/chunk-NFKN4P6Q.js.map +0 -7
- package/dist/chunks/chunk-QBENI6U4.js +0 -2
- package/dist/chunks/chunk-QBENI6U4.js.map +0 -7
- package/dist/chunks/chunk-VGN36NAY.js +0 -2
- package/dist/chunks/chunk-WUIHYOTN.js +0 -2
- package/dist/chunks/chunk-WUIHYOTN.js.map +0 -7
- package/dist/chunks/renderSvg-J2WUI63J.js +0 -2
- /package/dist/chunks/{GraphGenomeView-XFQA47RY.js.map → GraphGenomeView-7OFAL5L2.js.map} +0 -0
- /package/dist/chunks/{GraphSettingsDialog-Y44LH6AY.js.map → GraphSettingsDialog-WSXM3BYP.js.map} +0 -0
- /package/dist/chunks/{HighlightColorDialog-LPEIFHCT.js.map → HighlightColorDialog-V6XJISCR.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-NBIH3WZU.js.map → LinearGraphDisplay-4K6WGQEJ.js.map} +0 -0
- /package/dist/chunks/{chunk-VNPIF6Z5.js.map → chunk-BVRZASLN.js.map} +0 -0
- /package/dist/chunks/{chunk-S5LIOHKI.js.map → chunk-C6IYXPUI.js.map} +0 -0
- /package/dist/chunks/{chunk-JMJQK57L.js.map → chunk-IWZ4VAPS.js.map} +0 -0
- /package/dist/chunks/{chunk-QJYN7JLE.js.map → chunk-NKB3H4CP.js.map} +0 -0
- /package/dist/chunks/{chunk-VGN36NAY.js.map → chunk-YTH4CEBQ.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as U,c as V,d as X,e as q,f as K,h as Q}from"./chunk-MQS4CLYS.js";import{e as D}from"./chunk-ZCNHZLT2.js";import{c as x,d as P}from"./chunk-HNTK5LBJ.js";import{j as r}from"./chunk-PCP5Y77D.js";import{B as j,C as z,D as J,G as h,a as E,f as I,g as d,o as B,t as N,u as _,v as O}from"./chunk-H42TSPVA.js";import{b as t,c as G,d as W}from"./chunk-DUU6T2I5.js";import"./chunk-TMM73K4C.js";import{g as H}from"./chunk-GHZXTAN6.js";import"./chunk-D6TY2QEG.js";import"./chunk-2MOWWQHO.js";import"./chunk-EGZZ3ADM.js";import"./chunk-7INTU7WN.js";import{b as A,h as R,j as v,n as M}from"./chunk-5L276I7O.js";var i=JBrowseExports["@jbrowse/core/util/tss-react"],le=o=>i!=null&&o in Object(i)?i[o]:Object.assign(function(){throw new Error("This JBrowse does not provide '"+o+"' from '@jbrowse/core/util/tss-react' to plugins: GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse")},{jbrowseHostMissing:o});var Y=le("makeStyles"),de=i&&i.__esModule?i.default:i;async function Z(o,a,s){try{let{references:p}=await H(o,a,s).getHeader({signal:AbortSignal.timeout(U)});return p[0]}catch{return}}var pe=Y()(o=>({paper:{margin:o.spacing(),padding:o.spacing()},field:{marginTop:o.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),ce=["GfaTabixAdapter","GfaWalksSyntenyAdapter","GbzBaseSyntenyAdapter","MinigraphBubbleAdapter"],me=W(function({model:a}){let{classes:s}=pe(),p=v(a),u=x(a),[n,$]=r("GfaTabixAdapter"),[l,ee]=r(),[f,F]=r(),[S,te]=r(),g=n==="GbzBaseSyntenyAdapter",c=n==="GfaWalksSyntenyAdapter",[b,ae]=r(""),[T,oe]=r(""),[y,re]=r("Pangenome graph"),[C,k]=r(),[w,L]=r(!1);async function se(){if(!l||!a.assembly)return;k(void 0),L(!0);let{pluginManager:e}=R(a),[ne,ie]=await Promise.all([n==="GfaTabixAdapter"?V(l,e):void 0,c&&!b.trim()?Z(l,f,e):void 0]);if(L(!1),!(!P(a)||!a.assembly))try{let m=y.trim();A({model:a,session:p,conf:Q({choice:n,loc:l,indexLoc:f,readsLoc:g?S:void 0,manifest:ne,assembly:a.assembly,sample:b,haplotypes:c?D(T):void 0,walkReference:ie,trackId:M({name:m}),name:m})})}catch(m){k(m)}}return G(j,{className:s.paper,children:[C?t(I,{error:C}):null,G(N,{children:[t(O,{children:"File type"}),t(J,{value:n,onChange:e=>{$(e.target.value),F(void 0),k(void 0)},children:ce.map(e=>t(_,{value:e,control:t(z,{}),label:X[e]},e))})]}),t(d,{location:l,name:q[n],rootModel:u,setLocation:ee}),t(d,{location:f,name:K[n],rootModel:u,setLocation:F}),g?t(d,{location:S,name:"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)",rootModel:u,setLocation:te}):null,t(h,{className:s.field,value:b,onChange:e=>{ae(e.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:g?"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample":c?"Optional. The PanSN sample this assembly is in the graph; blank takes it from the file name, GRCh38 in chr22.GRCh38.walks.gz":"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}),c?t(h,{className:s.field,value:T,onChange:e=>{oe(e.target.value)},label:"Haplotypes",slotProps:{htmlInput:{"data-testid":"graph-haplotypes-input"}},helperText:"Optional. The haplotypes the track cuts for until you pick others in its menu, as PanSN names separated by commas (HG002#1, or HG002 for both); blank is every haplotype in the file",placeholder:"HG002, HG00733",fullWidth:!0}):null,t(h,{className:s.field,value:y,label:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:e=>{re(e.target.value)}}),t(E,{session:p,helperText:"Select assembly to add track to",selected:a.assembly,onChange:e=>{a.setAssembly(e)},fullWidth:!0}),t(B,{variant:"contained",className:s.submit,disabled:!l||!y.trim()||!a.assembly||w,onClick:()=>{se()},children:w?"Reading\u2026":"Submit"})]})}),Re=me;export{Re as default};
|
|
2
|
+
//# sourceMappingURL=AddTrackWorkflow-JIOQ5J2I.js.map
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["jbrowse-host:@jbrowse/core/util/tss-react", "../../src/GraphAddTrackWorkflow/walkReference.ts", "../../src/GraphAddTrackWorkflow/AddTrackWorkflow.tsx"],
|
|
4
4
|
"sourcesContent": ["const host = JBrowseExports[\"@jbrowse/core/util/tss-react\"]\nconst read = name =>\n host != null && name in Object(host)\n ? host[name]\n : Object.assign(\n function () {\n throw new Error(\"This JBrowse does not provide '\" + name + \"' from '\" + \"@jbrowse/core/util/tss-react\" + \"' to plugins: \" + \"GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse\")\n },\n { jbrowseHostMissing: name },\n )\nexport const cx = /* @__PURE__ */ read(\"cx\")\nexport const keyframes = /* @__PURE__ */ read(\"keyframes\")\nexport const makeStyles = /* @__PURE__ */ read(\"makeStyles\")\nexport default host && host.__esModule ? host.default : host", "import { FETCH_TIMEOUT_MS } from './graphManifest'\nimport { openWalkFile } from '../panSNTabix'\n\nimport type PluginManager from '@jbrowse/core/PluginManager'\nimport type { FileLocation } from '@jbrowse/core/util'\n\n// The reference sample a walk file's header names, which its file name only\n// suggests. Undefined for a header that is missing or unreadable, so the form\n// falls back to the file name.\nexport async function readWalkReference(\n loc: FileLocation,\n indexLoc: FileLocation | undefined,\n pluginManager?: PluginManager,\n) {\n try {\n const { references } = await openWalkFile(\n loc,\n indexLoc,\n pluginManager,\n ).getHeader({ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })\n return references[0]\n } catch {\n return undefined\n }\n}\n", "import { useState } from 'react'\n\nimport { AssemblySelector, ErrorMessage, FileSelector } from '@jbrowse/core/ui'\nimport {\n addTrackFromWidget,\n getEnv,\n getSession,\n makeTrackId,\n} from '@jbrowse/core/util'\nimport { makeStyles } from '@jbrowse/core/util/tss-react'\nimport { getRoot, isAlive } 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 GRAPH_INDEX_FIELDS,\n buildTrackConfig,\n} from './buildTrackConfig'\nimport { readGraphManifest } from './graphManifest'\nimport { readWalkReference } from './walkReference'\nimport { parseHaplotypes } from '../graphTrackConfig'\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 'GfaTabixAdapter',\n 'GfaWalksSyntenyAdapter',\n 'GbzBaseSyntenyAdapter',\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>('GfaTabixAdapter')\n const [loc, setLoc] = useState<FileLocation>()\n const [indexLoc, setIndexLoc] = useState<FileLocation>()\n const [readsLoc, setReadsLoc] = useState<FileLocation>()\n const gbz = choice === 'GbzBaseSyntenyAdapter'\n const walks = choice === 'GfaWalksSyntenyAdapter'\n const [sample, setSample] = useState('')\n const [haplotypes, setHaplotypes] = useState('')\n const [trackName, setTrackName] = useState('Pangenome graph')\n const [error, setError] = useState<unknown>()\n const [submitting, setSubmitting] = useState(false)\n\n async function handleSubmit() {\n if (!loc || !model.assembly) {\n return\n }\n setError(undefined)\n setSubmitting(true)\n const { pluginManager } = getEnv(model)\n const [manifest, walkReference] = await Promise.all([\n choice === 'GfaTabixAdapter'\n ? readGraphManifest(loc, pluginManager)\n : undefined,\n walks && !sample.trim()\n ? readWalkReference(loc, indexLoc, pluginManager)\n : undefined,\n ])\n setSubmitting(false)\n if (!isAlive(model) || !model.assembly) {\n return\n }\n try {\n const name = trackName.trim()\n addTrackFromWidget({\n model,\n session,\n conf: buildTrackConfig({\n choice,\n loc,\n indexLoc,\n readsLoc: gbz ? readsLoc : undefined,\n manifest,\n assembly: model.assembly,\n sample,\n haplotypes: walks ? parseHaplotypes(haplotypes) : undefined,\n walkReference,\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 setIndexLoc(undefined)\n setError(undefined)\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={GRAPH_INDEX_FIELDS[choice]}\n rootModel={rootModel}\n setLocation={setIndexLoc}\n />\n {gbz ? (\n <FileSelector\n location={readsLoc}\n name=\"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)\"\n rootModel={rootModel}\n setLocation={setReadsLoc}\n />\n ) : null}\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={\n gbz\n ? \"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample\"\n : walks\n ? 'Optional. The PanSN sample this assembly is in the graph; blank takes it from the file name, GRCh38 in chr22.GRCh38.walks.gz'\n : \"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 }\n placeholder=\"GRCh38\"\n fullWidth\n />\n {walks ? (\n <TextField\n className={classes.field}\n value={haplotypes}\n onChange={event => {\n setHaplotypes(event.target.value)\n }}\n label=\"Haplotypes\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-haplotypes-input' } }}\n helperText=\"Optional. The haplotypes the track cuts for until you pick others in its menu, as PanSN names separated by commas (HG002#1, or HG002 for both); blank is every haplotype in the file\"\n placeholder=\"HG002, HG00733\"\n fullWidth\n />\n ) : null}\n <TextField\n className={classes.field}\n value={trackName}\n label=\"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 || submitting}\n onClick={() => {\n void handleSubmit()\n }}\n >\n {submitting ? 'Reading\u2026' : 'Submit'}\n </Button>\n </Paper>\n )\n})\n\nexport default GraphAddTrackWidget\n"],
|
|
5
|
-
"mappings": "
|
|
5
|
+
"mappings": "+lBAAA,IAAMA,EAAO,eAAe,8BAA8B,EACpDC,GAAOC,GACXF,GAAQ,MAAQE,KAAQ,OAAOF,CAAI,EAC/BA,EAAKE,CAAI,EACT,OAAO,OACL,UAAY,CACV,MAAM,IAAI,MAAM,kCAAoCA,EAAO,8IAA6J,CAC1N,EACA,CAAE,mBAAoBA,CAAK,CAC7B,EAGC,IAAMC,EAA6BC,GAAK,YAAY,EACpDC,GAAQC,GAAQA,EAAK,WAAaA,EAAK,QAAUA,ECJxD,eAAsBC,EACpBC,EACAC,EACAC,EACA,CACA,GAAI,CACF,GAAM,CAAE,WAAAC,CAAW,EAAI,MAAMC,EAC3BJ,EACAC,EACAC,CACF,EAAE,UAAU,CAAE,OAAQ,YAAY,QAAQG,CAAgB,CAAE,CAAC,EAC7D,OAAOF,EAAW,CAAC,CACrB,MAAQ,CACN,MACF,CACF,CCgBA,IAAMG,GAAYC,EAAW,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,GAA6B,CACjC,kBACA,yBACA,wBACA,wBACF,EAEMC,GAAsBC,EAAS,SAA6B,CAChE,MAAAC,CACF,EAEG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIP,GAAU,EACxBQ,EAAUC,EAAWH,CAAK,EAC1BI,EAAYC,EAA2BL,CAAK,EAC5C,CAACM,EAAQC,CAAS,EAAIC,EAA0B,iBAAiB,EACjE,CAACC,EAAKC,EAAM,EAAIF,EAAuB,EACvC,CAACG,EAAUC,CAAW,EAAIJ,EAAuB,EACjD,CAACK,EAAUC,EAAW,EAAIN,EAAuB,EACjDO,EAAMT,IAAW,wBACjBU,EAAQV,IAAW,yBACnB,CAACW,EAAQC,EAAS,EAAIV,EAAS,EAAE,EACjC,CAACW,EAAYC,EAAa,EAAIZ,EAAS,EAAE,EACzC,CAACa,EAAWC,EAAY,EAAId,EAAS,iBAAiB,EACtD,CAACe,EAAOC,CAAQ,EAAIhB,EAAkB,EACtC,CAACiB,EAAYC,CAAa,EAAIlB,EAAS,EAAK,EAElD,eAAemB,IAAe,CAC5B,GAAI,CAAClB,GAAO,CAACT,EAAM,SACjB,OAEFwB,EAAS,MAAS,EAClBE,EAAc,EAAI,EAClB,GAAM,CAAE,cAAAE,CAAc,EAAIC,EAAO7B,CAAK,EAChC,CAAC8B,GAAUC,EAAa,EAAI,MAAM,QAAQ,IAAI,CAClDzB,IAAW,kBACP0B,EAAkBvB,EAAKmB,CAAa,EACpC,OACJZ,GAAS,CAACC,EAAO,KAAK,EAClBgB,EAAkBxB,EAAKE,EAAUiB,CAAa,EAC9C,MACN,CAAC,EAED,GADAF,EAAc,EAAK,EACf,GAACQ,EAAQlC,CAAK,GAAK,CAACA,EAAM,UAG9B,GAAI,CACF,IAAMmC,EAAOd,EAAU,KAAK,EAC5Be,EAAmB,CACjB,MAAApC,EACA,QAAAE,EACA,KAAMmC,EAAiB,CACrB,OAAA/B,EACA,IAAAG,EACA,SAAAE,EACA,SAAUI,EAAMF,EAAW,OAC3B,SAAAiB,GACA,SAAU9B,EAAM,SAChB,OAAAiB,EACA,WAAYD,EAAQsB,EAAgBnB,CAAU,EAAI,OAClD,cAAAY,GACA,QAASQ,EAAY,CAAE,KAAAJ,CAAK,CAAC,EAC7B,KAAAA,CACF,CAAC,CACH,CAAC,CACH,OAASK,EAAG,CACVhB,EAASgB,CAAC,CACZ,CACF,CAEA,OACEC,EAACC,EAAA,CAAM,UAAWzC,EAAQ,MACvB,UAAAsB,EAAQoB,EAACC,EAAA,CAAa,MAAOrB,EAAO,EAAK,KAC1CkB,EAACI,EAAA,CACC,UAAAF,EAACG,EAAA,CAAU,qBAAS,EACpBH,EAACI,EAAA,CACC,MAAOzC,EACP,SAAU0C,GAAS,CACjBzC,EAAUyC,EAAM,OAAO,KAAwB,EAC/CpC,EAAY,MAAS,EACrBY,EAAS,MAAS,CACpB,EAEC,SAAA3B,GAAQ,IAAIoD,GACXN,EAACO,EAAA,CAEC,MAAOD,EACP,QAASN,EAACQ,EAAA,EAAM,EAChB,MAAOC,EAAkBH,CAAM,GAH1BA,CAIP,CACD,EACH,GACF,EACAN,EAACU,EAAA,CACC,SAAU5C,EACV,KAAM6C,EAAkBhD,CAAM,EAC9B,UAAWF,EACX,YAAaM,GACf,EACAiC,EAACU,EAAA,CACC,SAAU1C,EACV,KAAM4C,EAAmBjD,CAAM,EAC/B,UAAWF,EACX,YAAaQ,EACf,EACCG,EACC4B,EAACU,EAAA,CACC,SAAUxC,EACV,KAAK,4FACL,UAAWT,EACX,YAAaU,GACf,EACE,KACJ6B,EAACa,EAAA,CACC,UAAWvD,EAAQ,MACnB,MAAOgB,EACP,SAAU+B,GAAS,CACjB9B,GAAU8B,EAAM,OAAO,KAAK,CAC9B,EACA,MAAM,2BACN,UAAW,CAAE,UAAW,CAAE,cAAe,oBAAqB,CAAE,EAChE,WACEjC,EACI,mKACAC,EACE,+HACA,qJAER,YAAY,SACZ,UAAS,GACX,EACCA,EACC2B,EAACa,EAAA,CACC,UAAWvD,EAAQ,MACnB,MAAOkB,EACP,SAAU6B,GAAS,CACjB5B,GAAc4B,EAAM,OAAO,KAAK,CAClC,EACA,MAAM,aACN,UAAW,CAAE,UAAW,CAAE,cAAe,wBAAyB,CAAE,EACpE,WAAW,uLACX,YAAY,iBACZ,UAAS,GACX,EACE,KACJL,EAACa,EAAA,CACC,UAAWvD,EAAQ,MACnB,MAAOoB,EACP,MAAM,aACN,UAAW,CAAE,UAAW,CAAE,cAAe,wBAAyB,CAAE,EACpE,SAAU2B,GAAS,CACjB1B,GAAa0B,EAAM,OAAO,KAAK,CACjC,EACF,EACAL,EAACc,EAAA,CACC,QAASvD,EACT,WAAW,kCACX,SAAUF,EAAM,SAChB,SAAU0D,GAAO,CACf1D,EAAM,YAAY0D,CAAG,CACvB,EACA,UAAS,GACX,EACAf,EAACgB,EAAA,CACC,QAAQ,YACR,UAAW1D,EAAQ,OACnB,SAAU,CAACQ,GAAO,CAACY,EAAU,KAAK,GAAK,CAACrB,EAAM,UAAYyB,EAC1D,QAAS,IAAM,CACRE,GAAa,CACpB,EAEC,SAAAF,EAAa,gBAAa,SAC7B,GACF,CAEJ,CAAC,EAEMmC,GAAQ9D",
|
|
6
6
|
"names": ["host", "read", "name", "makeStyles", "read", "tss_react_default", "host", "readWalkReference", "loc", "indexLoc", "pluginManager", "references", "openWalkFile", "FETCH_TIMEOUT_MS", "useStyles", "makeStyles", "theme", "CHOICES", "GraphAddTrackWidget", "observer", "model", "classes", "session", "getSession", "rootModel", "getRoot", "choice", "setChoice", "useState", "loc", "setLoc", "indexLoc", "setIndexLoc", "readsLoc", "setReadsLoc", "gbz", "walks", "sample", "setSample", "haplotypes", "setHaplotypes", "trackName", "setTrackName", "error", "setError", "submitting", "setSubmitting", "handleSubmit", "pluginManager", "getEnv", "manifest", "walkReference", "readGraphManifest", "readWalkReference", "isAlive", "name", "addTrackFromWidget", "buildTrackConfig", "parseHaplotypes", "makeTrackId", "e", "jsxs", "Paper", "jsx", "ErrorMessage", "FormControl", "FormLabel", "RadioGroup", "event", "option", "FormControlLabel", "Radio", "GRAPH_FILE_LABELS", "FileSelector", "GRAPH_FILE_FIELDS", "GRAPH_INDEX_FIELDS", "TextField", "AssemblySelector", "arg", "Button", "AddTrackWorkflow_default"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{a as In,j as vn,k as Lt,l as Mt}from"./chunk-XEMDXS4J.js";import{a as fe,b as R,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j as gn,k as Fe,l as Te,m as Ne,n as wn,o as mn,p as yn,q as bn,r as xn,s as Rn,t as Ln,u as Cn,v as On}from"./chunk-BVRZASLN.js";import"./chunk-JM4W4PKP.js";import{a as xs,b as Mn,c as Hn,d as Ht}from"./chunk-IWZ4VAPS.js";import"./chunk-IASBT3FL.js";import{a as An}from"./chunk-YTH4CEBQ.js";import"./chunk-YBLNN5FU.js";import{j as kn}from"./chunk-DSNIXLI7.js";import{_ as En,c as Sn}from"./chunk-JYKCHE2I.js";import{a as Pn}from"./chunk-V55TK2NP.js";import"./chunk-TMM73K4C.js";import{b as _e,e as $n}from"./chunk-GHZXTAN6.js";import{a as Re}from"./chunk-D6TY2QEG.js";import{j as Nn}from"./chunk-2MOWWQHO.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as $t,g as Ae,h as $e,i as Rt}from"./chunk-7INTU7WN.js";import{e as hn,q as At}from"./chunk-5L276I7O.js";var ze=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},Bn=255,Ss=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new ze(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<Bn?Math.floor(Ss/this.sigma):0}next(){if(this.sigma>=Bn){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Fn(a){let e=new ze(a),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let o=e.int(),i=e.int();if(o===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=o,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(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(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),o=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:o+(e-n)};t[s.value]=o+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:ee(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],o=t[s];R(r.node)===R(o.node)&&(t[s-1]=o,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(o=>o.offset),t=0;for(let o of this.runs())t+=o.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let o of this.runs()){let i=this.edge(o.value),c=e[o.value];for(let d=0;d<o.len;d++)n[r]=i.node,s[r]=c,c+=1,r+=1;e[o.value]=c}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var Is=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Tn(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let d=0;d<e;d++){for(let S=0;S<16;S++)o[S]=n.getUint32(d*64+S*4);for(let S=16;S<64;S++){let I=o[S-15],N=o[S-2],y=we(I,7)^we(I,18)^I>>>3,E=we(N,17)^we(N,19)^N>>>10;o[S]=o[S-16]+y+o[S-7]+E}let h=r[0],f=r[1],p=r[2],w=r[3],u=r[4],l=r[5],b=r[6],x=r[7];for(let S=0;S<64;S++){let I=we(u,6)^we(u,11)^we(u,25),N=u&l^~u&b,y=x+I+N+Is[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),$=h&f^h&p^f&p;x=b,b=l,l=u,u=w+y|0,w=p,p=f,f=h,h=y+E+$|0}[h,f,p,w,u,l,b,x].forEach((S,I)=>{r[I]=r[I]+S})}let i=new Uint8Array(32),c=new DataView(i.buffer);for(let d=0;d<8;d++)c.setUint32(d*4,r[d]);return i}function _n(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[r,o]=s;if(s.length!==2||!r||!o)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(o)}return t}function Dn(a){return{name:a.get("pggname"),subgraph:_n(a.get("subgraph"),"subgraph"),translation:_n(a.get("translation"),"translation")}}function zn(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let r of n)s.add(r)}}function Gn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),zn(t.subgraph,e.subgraph),zn(t.translation,e.translation)),t}function qn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function jn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of qn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of qn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function Un(a){let e=a.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of a)t.set(o,n),n+=o.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Tn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Es="_gbwt_ref";function pe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var ks=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,vs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ps(a){let e=ks.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=vs.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Le(a){return typeof a=="string"?Ps(a):a}function Me(a,e){return{sample:a.sample??Es,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ns=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ns?n[1]=t:e.push([t,t])}return e}var As=32768,Wn={mostChosenPaths:32},Ct=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},oe=class extends Error{};function tt(a,e,t,n){return a==="forward"?e+t:e-n}function Qn(a,e,t,n){return a==="forward"?e-n:e+t}function Vn(a){return Ne(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function qe(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Zn(a){let{db:e,records:t,signal:n}=a,s=performance.now(),r=()=>{let m=performance.now(),k=m-s;return s=m,k},o={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(m,k)=>{let A=`${m}: ${k}`;o.walks[A]=(o.walks[A]??0)+1},c=await e.haplotypeSampleInterval()??4096,d=new Map,h=async m=>{let k=t.get(m)??d.get(m);if(k)return k;let A=await e.getRecord(m);if(o.graphFetches+=1,!A)throw new Error(`Node record ${m} is missing from the database`);return d.set(m,A),A},f=m=>t.get(m).sequenceLen,p=await e.pathsByHandle(),w=m=>{let k=p.get(m);return k!==void 0&&a.keep(k.name)},u=[],l=new Ct,b=new Map,x=new Set,S=new Set,I=async m=>{let k=(await h(m.node)).gbwt().lf(m.offset);return k===void 0||k.node===0?void 0:k},N=async(m,k)=>{let A=(await h(ee(m.node))).gbwt().predecessorAt(m.offset);if(A===void 0||k!==void 0&&!k.has(A))return;let L=(await h(A)).gbwt().offsetTo(m);if(L===void 0)throw new Error(`No offset in ${A} leads to ${m.node}:${m.offset}`);return{node:A,offset:L}},y=(m,k,A,L)=>{let B=A.map(U=>U.pos.node),j=A.map(U=>U.pos.offset),Y=0;for(let U of B)Y+=f(U);let C=k==="forward"?A[0].left:A[A.length-1].left,M=u.length;u.push({pathHandle:m,orientation:k,handles:B,offsets:j,len:Y,hapStart:C,hapEnd:C+Y,canonical:Ne(B[0],B[B.length-1]),source:L});for(let U of A)l.set(U.pos,M);let Q=b.get(m);return Q?Q.push(M):b.set(m,[M]),M},E=async(m,k,A,L)=>{let B=[],j=m;for(;;){n?.throwIfAborted();let C=await N(j.pos,t);if(!C)break;j={pos:C,left:Qn(A,j.left,f(j.pos.node),f(C.node))},B.push(j)}B.reverse();let Y=[m];for(j=m;;){n?.throwIfAborted();let C=await I(j.pos);if(!C||!t.has(C.node))break;j={pos:C,left:tt(A,j.left,f(j.pos.node),f(C.node))},Y.push(j)}return y(k,A,[...B,...Y],L)},$=async(m,k,A,L)=>u[l.get(m.pos)??await E(m,k,A,L)],F=m=>{let k=m.handles[m.handles.length-1];return{pos:{node:k,offset:m.offsets[m.offsets.length-1]},left:m.orientation==="forward"?m.hapEnd-f(k):m.hapStart}},T=m=>{let k=m.handles[0];return{pos:{node:k,offset:m.offsets[0]},left:m.orientation==="forward"?m.hapStart:m.hapEnd-f(k)}},D=await E({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),O=u[D],H=()=>{if(o.fallback!==void 0)return{reference:O,pieces:[],stats:o};let m=new Map;u.forEach((A,L)=>{L!==D&&m.set(qe(A),[...m.get(qe(A))??[],A])});let k=[];for(let A of m.values()){let L=new Set;for(let B of A)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),k.push(B),o.sources[B.source]+=1)}return o.sources.reference=1,o.pieces=k.length+1,{reference:O,pieces:k,stats:o}},v=async(m,k)=>{let A=k?x:S,L=k?S:x,B=m;for(;;){if(A.has(B))return;A.add(B);let j=u[B],Y=k?F(j):T(j),C=0,M;for(;M===void 0;){n?.throwIfAborted();let Q=k?await I(Y.pos):await N(Y.pos);if(!Q){M="endmarker";break}let U=(await h(Y.pos.node)).sequenceLen,ge=(await h(Q.node)).sequenceLen,se=k?tt(j.orientation,Y.left,U,ge):Qn(j.orientation,Y.left,U,ge);if(t.has(Q.node)){let J=l.get(Q);J===void 0?(B=await E({pos:Q,left:se},j.pathHandle,j.orientation,"chain"),L.add(B),M="landed"):(L.add(J),M="merge")}else C>As?M="bound":(C+=ge,Y={pos:Q,left:se})}if(i("chain",M),M!=="landed")return}},G=async m=>{if(a.context>m.context)throw new oe(`the context of ${a.context} bp exceeds the ${m.context} bp the haplotype index's stray rows cover`);let k=o.spacing;if(k===void 0)throw new oe("the haplotype index has no anchors");let{bin:A,bound:L}=m,{fills:B,inserted:j}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new oe("the haplotype index's stray rows cover contained snarls only");for(let g of B){if(g.inserted>0&&g.low===g.high)throw new oe(`the haplotype index's stray rows leave out the snarl bounded by node ${g.low} at both ends`);if(g.inserted>0&&(m.snarlNodes===void 0||g.nodes>m.snarlNodes))throw new oe(m.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${g.nodes} nodes exceeds the ${m.snarlNodes} the haplotype index's stray rows cover`)}let Y=Math.floor(a.window.start/A),C=Math.floor((a.window.end-1)/A),M=Y*A,Q=(C+1)*A,U=new Map,ge=async(g,P)=>{let q=await e.haplotypeAnchorsBetween(a.referenceHandle,g*k,P*k);for(let _ of q)U.set(_.anchorOffset/k,_)},se=Math.max(0,Math.floor((M-L)/k)-1),J=Math.ceil((Q+L)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,Y,C),ge(se,J)]);for(let g of t.keys()){let P=R(g);if(!V(g)&&!Ve(P)&&!j.has(P))throw new oe(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}o.scans=Ot([...t.keys()].sort((g,P)=>g-P));let he=Promise.all(o.scans.map(([g,P])=>e.haplotypeSamplesInRange(g,P)));for(he.catch(()=>{});se>0&&(U.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=M-L;)se-=1,await ge(se,se);for(;U.has(J)&&U.get(J).pathOffset<=Q+L;)J+=1,await ge(J,J);let ue=[...U.keys()].sort((g,P)=>g-P),be=U.get(ue[0]??-1);if(!be)throw new oe("the haplotype index has no anchors on this path");let de=g=>U.get(g).pathOffset,Ce=new Map;for(let g of ue){let P=R(U.get(g).node);Ce.set(P,[...Ce.get(P)??[],g])}let vt=[...Ce.keys()],Xt=vt.map(g=>U.get(Ce.get(g)[0]).visits);if(!Xt[vt.indexOf(R(be.node))].some(g=>g.pathHandle===a.referenceHandle&&g.orientation==="forward"&&g.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${be.pathOffset} (node ${R(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),ws=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(ws[0]??ue[ue.length-1])],o.anchorsRead=ue.length;let Pt=new Map,Jt=new Set;if(vt.forEach((g,P)=>{let q=Ce.get(g),_=q.length===1?q[0]:void 0;for(let z of Xt[P])Jt.add(z.pathHandle),z.orientation==="forward"&&w(z.pathHandle)&&Pt.set(z.pathHandle,[...Pt.get(z.pathHandle)??[],{k:_,row:z}])}),o.chosenPaths=[...Jt].filter(w).length,o.chosenPaths>Wn.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Wn.mostChosenPaths}`);let Ze=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[g,P]of Pt){P.sort((q,_)=>q.row.pathOffset-_.row.pathOffset);for(let q=0;q+1<P.length;q++){let _=P[q],z=P[q+1];if(_.k===void 0||z.k===void 0||Math.abs(_.k-z.k)!==1)continue;let[K,te]=de(_.k)<=de(z.k)?[_,z]:[z,_],ne=de(K.k),re=de(te.k);ne<Q&&re>=M?(Ze.push({pathHandle:g,from:_.row,to:z.row}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,re+L)):ne>=Q&&ne-Q<=L?(Ze.push({pathHandle:g,from:K.row,to:void 0}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,ne+L)):re<M&&M-re<=L&&(Ze.push({pathHandle:g,from:te.row,to:void 0}),Ee=Math.min(Ee,re-L),xe=Math.max(xe,re+L))}}let ms=new Set(B.map(g=>`${g.low}:${g.high}`)),ys=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ms.has(`${g.snarl[0]}:${g.snarl[1]}`))).sort((g,P)=>g.pathHandle-P.pathHandle||g.pathStart-P.pathStart);o.strays={bins:C-Y+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ee),xe+1),o.ms.scan=r();let en=8*k+2*(a.window.end-a.window.start),tn=o.strays,Oe=0,nn=g=>{if(tn.outsideBp+=g,Oe+=g,Oe>en)throw new oe(`a walk of a chosen path near the window went past its cap of ${en} bp`)},Nt=new Map,sn=(g,P,q)=>(Nt.get(g)??[]).some(([_,z])=>_<=P&&q<z),rn=(g,P,q)=>{Nt.set(g,[...Nt.get(g)??[],[P,q]])},on=async(g,P,q,_,z)=>{let K=P,te=q,ne=te;for(;K&&te<=_;){n?.throwIfAborted();let re;if(t.has(K.node)){let Be=await $({pos:K,left:te},g,"forward",z),cn=F(Be);K=cn.pos,te=cn.left,re=f(K.node),ne=Math.max(ne,Be.hapEnd)}else re=(await h(K.node)).sequenceLen,nn(re),ne=Math.max(ne,te+re);K=await I(K),te+=re}return ne},bs=async(g,P,q,_)=>{let z={pos:P,left:q},K=q;for(;z.left>_;){n?.throwIfAborted();let te=await N(z.pos);if(!te)break;let ne=(await h(te.node)).sequenceLen,re=z.left-ne;if(t.has(te.node)){let Be=await $({pos:te,left:re},g,"forward","section");z=T(Be),K=Math.min(K,Be.hapStart)}else nn(ne),z={pos:te,left:re},K=Math.min(K,re)}return K};for(let{pathHandle:g,from:P,to:q}of Ze){let _=P.pathOffset,z=(q??P).pathOffset+L;if(sn(g,_-L,z))continue;let K={node:P.node,offset:P.offset};Oe=0;let te=await on(g,K,_,z,"section");Oe=0;let ne=await bs(g,K,_,_-L);rn(g,Math.min(ne,_-L),Math.max(te,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let g of ys){if(sn(g.pathHandle,g.pathStart,g.pathEnd))continue;Oe=0;let P=await on(g.pathHandle,{node:g.node,offset:g.offset},g.pathStart,g.pathEnd,"stray");rn(g.pathHandle,g.pathStart,Math.max(P,g.pathEnd+1)),tn.walked+=1}o.ms.walks=r();let an=[];for(let g of await he)for(let P of g)if(o.scanRows+=1,t.has(P.node)&&w(P.pathHandle)){if(!(b.get(P.pathHandle)??[]).some(q=>{let _=u[q];return _.hapStart<=P.pathOffset&&P.pathOffset<_.hapEnd}))throw new oe(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&an.push(P)}for(let g of an)await $({pos:{node:g.node,offset:g.offset},left:g.pathOffset},g.pathHandle,"reverse","twin");o.ms.check=r()},X=async()=>{let m=new Map,k=C=>{let M=qe(C),Q=m.get(M);Q?Q.add(C.orientation):m.set(M,new Set([C.orientation]))},A=0,L=()=>{for(;A<u.length;A++)k(u[A])};L();let B=C=>(m.get(qe(C))?.size??0)>1,j=2*c,Y=(C,M)=>M===D?w(a.referenceHandle)&&Vn(C):!C.canonical||Vn(C);for(let C=0;C<u.length;C++){let M=u[C];if(B(M)||!Y(M,C))continue;o.twins.tried+=1;let Q=M.orientation==="forward"?"reverse":"forward",U=F(M),ge=0,se;for(;!se&&ge<=j;){n?.throwIfAborted();let ie=await I(U.pos);if(!ie)break;let he=(await h(ie.node)).sequenceLen,ue=tt(M.orientation,U.left,(await h(U.pos.node)).sequenceLen,he),be=ee(ie.node);se=(await e.haplotypeSamplesInRange(be,be)).find(de=>de.pathHandle===M.pathHandle&&de.orientation===Q&&de.pathOffset===ue),ge+=he,U={pos:ie,left:ue}}let J=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},Ve=0;for(;J&&!B(M)&&Ve<=j+M.len;){if(n?.throwIfAborted(),t.has(J.pos.node)){let ie=await $(J,M.pathHandle,Q,"twin"),he=u.indexOf(ie);await v(he,!0),await v(he,!1),L(),J=F(ie)}if(!B(M)){let ie=(await h(J.pos.node)).sequenceLen;Ve+=ie;let he=await I(J.pos);J=he?{pos:he,left:tt(Q,J.left,ie,(await h(he.node)).sequenceLen)}:void 0}}if(L(),!B(M))throw new oe(`piece ${qe(M)} was found in one orientation where extractPaths keeps the other`);o.twins.found+=1}o.ms.twins=r()};try{let m=await e.haplotypeStrayOptions();if(m===void 0)throw new oe("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(m),await X()}catch(m){if(!(m instanceof oe))throw m;o.fallback=m.message}return H()}function Kn(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var ae=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 Bt(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var Ge=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let o=r-1>>1;if(Bt(s[r],s[o]))[s[r],s[o]]=[s[o],s[r]],r=o;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,o=r+1,i=s;if(r<e.length&&Bt(e[r],e[i])&&(i=r),o<e.length&&Bt(e[o],e[i])&&(i=o),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function $s(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:a.length}}function Rs(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ve(a){return`${a.node}:${a.offset}`}function De(a){return a.map(e=>ee(e)).reverse()}function Ls(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Ms(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Yn(r,t.insertion,t.deletion);for(let[d,h]of s.edits)Z(r,d,h);let o=a.identity.walkForward,[i,c]=o?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...c.path],start:i.start,pieces:[...i.pieces,...c.pieces],soloAligned:[...i.soloAligned,...c.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:o}}}function Hs(a,e,t){if(a.some(o=>o.weight!==void 0))return a;let n=new Map;a.forEach((o,i)=>{if(o.identity){let c=n.get(o.identity.pathHandle);c?c.push(i):n.set(o.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let o of n.values()){o.sort((h,f)=>a[h].identity.hapStart-a[f].identity.hapStart);let i=o[0],c=a[i],d=[];for(let h of o.slice(1)){let f=a[h],p=d.length===0?Ls(c,f):void 0;if(p){c=Ms(c,f,p),r.add(h);continue}if(!e(f)){d.push(h);continue}let w=e(c)?t([c,...d.map(u=>a[u]),f]):void 0;if(w){c=w;for(let u of[...d,h])r.add(u)}else s.set(i,c),i=h,c=f;d=[]}s.set(i,c)}return a.flatMap((o,i)=>r.has(i)?[]:[s.get(i)??o])}function nt(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Cs=32768;function Os(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Cs?s[1]=n:t.push([n,n])}return t}var je=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(fe(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 ae(this.limit);let t=await this.db.getRecord(fe(e,"forward")),n=await this.db.getRecord(fe(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${pe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,o=s;for(;;){await this.ensureNode(R(o.node));let i=this.record(o.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:o.node,nodeOffset:t-r,gbwtOffset:o.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let c=i.gbwt().lf(o.offset);if(!c)throw new Error(`The fragment of ${pe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);o=c}}async aroundPosition(e,t,n){let s=R(e);await this.ensureNode(s);let r=this.record(e),o=ke(e),i=new Ge;return i.push(t,s,Xe(o)),i.push(r.sequenceLen-t-1,s,Ye(o)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let o=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(o,i),Math.max(o,i)+1]])){let d=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Os(d.map(h=>h.pos.node)).map(([h,f])=>[h,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof ae&&s.windowBp===void 0?new ae(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,o=t,i=new Ge;for(;;){let c=R(s.node),d=ke(s.node);this.walkedBp=t-o,await this.ensureNode(c);let h=this.record(s.node);if(r>=h.sequenceLen)throw new Error(`Offset ${r} in node ${c} of length ${h.sequenceLen}`);i.push(r,c,Xe(d));let f=h.sequenceLen-r;if(o<=f){i.push(o===f?0:f-o-1,c,Ye(d));break}i.push(0,c,Ye(d));let p=h.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,o-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new Ge;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let o of this.records.keys())s.add(R(o));let r=0;for(;e.size>0;){let[o,i,c]=e.pop(),d=`${i}:${c}`;if(n.has(d))continue;n.add(d),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let h=pn(c);if(!n.has(`${i}:${h}`)){let w=this.record(fe(i,un(c))),u=o+w.sequenceLen-1;u<=t&&e.push(u,i,h)}let f=this.record(fe(i,gn(c))),p=o+1;if(p<=t)for(let w of f.successors()){let u=R(w),l=Xe(ke(w));n.has(`${u}:${l}`)||e.push(p,u,l)}}for(let o of s)this.records.delete(fe(o,"forward")),this.records.delete(fe(o,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([R(e),R(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=R(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=R(c);s.has(d)||(n.push(c,ee(c)),s.add(d))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:o}=await this.fillBetween(n,s),i=R(n),c=R(s);this.snarlFills.push({low:Math.min(i,c),high:Math.max(i,c),nodes:o,inserted:r.length});for(let d of r)this.snarlNodes.add(d);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),o=r.next;o!==void 0&&(n=!0,this.hasHandle(o)?Fe(s,o)&&t.push([s,o]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,o]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async c=>{let d=c.successors(),h=d[0];return h===void 0?!1:d.length>1||(await e(ee(h))).successors().length>1},n=async c=>{let d=await e(ee(c));return d.next!==void 0?await t(d)?{kind:"snarl-exit",snarl:[ee(c),d.next]}:{kind:"chain"}:(await e(c)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(c=>this.record(c).successors()),o,i=!1;for(;!i&&r.length>0;){let c=r.shift(),d=R(c);if(!this.hasHandle(c)&&!s.has(d)){s.add(d);let h=await n(c);if(h.kind==="snarl-exit")o=h.snarl,i=!0;else if(h.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(fe(d,f))).successors())}}return o}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,o=new Map;s.forEach((y,E)=>o.set(y,E));let i=new Int32Array(r+1),c=new Int32Array(r),d=[];for(let y=0;y<r;y++){let E=this.record(s[y]),$=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push($),i[y+1]=i[y]+$.nodes.length}let h=i[r],f=new Int32Array(h),p=new Int32Array(h),w=new Uint8Array(h);for(let y=0;y<r;y++){let E=d[y];f.set(E.nodes,i[y]),p.set(E.offsets,i[y])}d.length=0;for(let y=0;y<h;y++){let E=o.get(f[y]);E===void 0?f[y]=-1:(f[y]=E,w[i[E]+p[y]]=1)}let u=n===void 0?void 0:o.get(n.handle),l=n?.gbwtOffset,b,x=(y,E,$)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),$&&($.push(s[H]),F.push(v)),T+=1,D+=c[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:F,len:D,refAt:O,last:H}},S=(y,E,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:$,weight:void 0,identity:void 0})},I=new Int32Array(r);for(let y=0;y<r;y++){let E=s[y];if(!V(E)){let $=i[y],F=i[y+1]-$;for(let T=0;T<F;T++)if(w[$+T]===0){let D=[],{offsets:O,len:H,refAt:v,last:G}=x(y,T,D),X=s[G];if(v>=0||Ne(E,X)){if(S(D,O,H,v),!V(X)){let m=o.get(ee(X));I[m]=I[m]+1}}else this.twinStarts.add(ve({node:E,offset:T}))}}}for(let y=0;y<r;y++){let E=s[y];if(V(E)){let $=i[y],F=i[y+1]-$,T=0;for(let O=0;O<F;O++)w[$+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[$+O]===0){let H=D?void 0:x(y,O,void 0);if(H&&(H.refAt>=0||Ne(E,s[H.last]))){let v=[],{offsets:G,len:X,refAt:m}=x(y,O,v);S(v,G,X,m)}else this.twinStarts.add(ve({node:E,offset:O}))}}}let N=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),N&&(this.refId=this.paths.indexOf(N)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let F of y.path.slice(0,b))E+=this.record(F).sequenceLen;let $=n.seqOffset-E;this.refInterval=[$,$+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Te(n)?De(n):void 0,r=d=>s!==void 0&&Ft(d,s)===0||Te(De(d)),o=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((d,h)=>Ft(d.path,h.path)||d.len-h.len||(d===t?-1:h===t?1:0));let i=[],c;for(let d of this.paths){let h=i[i.length-1],f=o&&d!==t&&r(d.path);this.twinDeferred||=f,h&&Ft(h.path,d.path)===0&&!f?h.weight=(h.weight??1)+(d.weight??1):(d===t&&(c=i.length),i.push({...d,weight:d.weight??1}))}this.paths=i,this.refId=c}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=o=>`${o.pathHandle}:${o.hapStart}-${o.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let o of this.paths)o!==e&&o.identity?.orientation==="forward"&&s.add(n(o.identity));let r=this.paths.filter(o=>o===e||o.identity?.orientation!=="reverse"||!s.has(n(o.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(o=>o.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((o,i)=>i!==this.refId&&o.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((o,i)=>i===this.refId||o.identity!==void 0&&e(o.identity.name)),r=new Set;for(let o of s)for(let i of o.path)r.add(R(i));for(let o of[...this.records.keys()])r.has(R(o))||this.records.delete(o);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,o=await Zn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(h,f,p)=>this.prefetchReferenceRange(h,f,p)});if(this.stats.keep=o.stats,o.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),c=h=>({path:h.handles,offsets:h.offsets,len:h.len,weight:void 0,identity:{pathHandle:h.pathHandle,name:h===o.reference?e.name:i.get(h.pathHandle).name,orientation:h.orientation,hapStart:h.hapStart,hapEnd:h.hapEnd}}),d=[o.reference,...o.pieces].sort(Kn);return this.paths=d.map(c),this.refId=d.indexOf(o.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[o.reference.hapStart,o.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ot(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ve(l),l);let r=l=>{let b=0,x=t.length-1;for(;b<x;){let I=b+x+1>>1;t[I][0]<=l?b=I:x=I-1}let S=t[b];return S[0]<=l&&l<=S[1]},o=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&o.set(ve(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let c=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),d=l=>(i.graphLookups+=1,c(l)),h=async(l,b)=>{if(r(l.node))return n.get(ve(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},w=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},u=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let N,y=0,E=l,$;for(;N===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){I.end="cycle";break}S.add(E);let H=this.paths[E];x.push({index:E,startBp:y}),I.fragments+=1;let v=y;for(let X=0;X<H.path.length;X++){let m=nt(H,X),k=n.get(ve(m)),A=this.record(m.node).sequenceLen;if(k){N=w(k,v,A);break}v+=A}if(y+=H.len,N){I.end="in-fragment sample";break}let G=nt(H,H.path.length-1);$=this.record(G.node).gbwt().lf(G.offset),E=void 0}if($===void 0||$.node===0){I.end="endmarker";break}let F=ve($),T=o.get(F);if(T!==void 0){let H=this.paths[T].identity;if(H){N=u(H,y),I.end="identified sibling";break}E=T;continue}this.records.has($.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h($,I),O=await d($.node);if(D){N=w(D,y,O.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,y-x[x.length-1].startBp>4*e+4*O.sequenceLen){I.end="bound";break}y+=O.sequenceLen,$=O.gbwt().lf($.offset)}if(N){I.pathHandle=N.pathHandle;let F=await p(N.pathHandle);for(let{index:T,startBp:D}of x){let O=this.paths[T];O.identity=N.orientation==="forward"?{pathHandle:N.pathHandle,name:F,orientation:"forward",hapStart:N.base+D,hapEnd:N.base+D+O.len}:{pathHandle:N.pathHandle,name:F,orientation:"reverse",hapStart:N.base-D-O.len,hapEnd:N.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),o=0,i=-1;for(let c=0;c<e.length;c++){let d=n.get(e[c]);if(d){let h=Rs(d,i);if(h===void 0)return;s[o]=c,r[o]=h,o+=1,i=h}}return{pathAt:s,refAt:r,count:o}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[s]).sequence,d=this.record(t[r]).sequence;for(;o<c.length&&i<d.length;){if(c[o]!==d[i])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[e.length-s-1]).sequence,d=this.record(t[t.length-r-1]).sequence;for(;o<c.length&&i<d.length;){if(c[c.length-o-1]!==d[d.length-i-1])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),o=this.prefixMatches(e,t),i=this.suffixMatches(e,t);o+i>s&&(i=s-o),o+i>r&&(i=r-o),Z(n,"M",o),Yn(n,s-o-i,r-o-i),Z(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??$s(yn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],o=this.refPrefix(t),i=(f,p,w,u)=>{f===p?Z(r,"D",o[u]-o[w]):w===u?Z(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(w,u),r)},c=0,d=0,h=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],w=s.refAt[f];(d!==p||h!==w)&&i(d,p,h,w);let u=this.record(e[p]).sequenceLen;Z(r,"M",u),c+=u,d=p+1,h=w+1}return i(d,e.length,h,t.length),{edits:r,matched:c,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Te(n)&&(t.identity===void 0||!Te(De(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=De(t.path),o=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(o===0)s={...this.editsAgainst(r,n),flipped:!0};else{let c=this.editsAgainst(t.path,n),d=this.editsAgainst(r,n);s=d.matched>c.matched?{...d,flipped:!0}:{...c,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(h,f,p,w)=>{let u=Fs(h),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,S=x?.orientation==="forward",[I,N]=S?[l,b]:[b,l];return{strand:f,refStart:e.start+u.leading,refEnd:e.start+n-u.trailing,edits:u.edits,weight:l.weight,path:p.flatMap(y=>this.paths[y].path),start:nt(l,0),pieces:p,soloAligned:w,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+I.identity.hapStart,hapEnd:x.name.fragment+N.identity.hapEnd,walkForward:S}}},r=h=>h.soloAligned.reduce((f,p)=>f+p,0),o=h=>h.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=h=>2*r(h)>=o(h),c=h=>{let f=h[0],p=h[h.length-1],w=f.identity.walkForward;if(h.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==w||G>0&&v.identity.hapStart<h[G-1].identity.hapEnd))return;let u=w?h:[...h].reverse(),l=u.flatMap(v=>v.pieces),b=u.flatMap(v=>v.soloAligned),x=f.strand==="+"!==w,S=l.map(v=>this.paths[v]),I=S.slice(1).map((v,G)=>{let X=S[G].identity;return w?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),N=x?[...S].reverse():S,y=x?[...I].reverse():I,E=N.flatMap(v=>x?De(v.path):v.path),{edits:$}=this.editsAgainst(E,t),F=Xn($,N.map(v=>v.len)),T=new Map((x?[...l].reverse():l).map((v,G)=>[v,F[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+T.get(X),0)>=r(v);if(!D(f)||!D(p))return;let O=[],H=0;return N.slice(0,-1).forEach((v,G)=>{H+=v.len,O.push([H,y[G]])}),s(Ts($,O),f.strand,l,b)},d=[];return this.paths.forEach((h,f)=>{if(f===this.refId)return;let{edits:p,flipped:w}=this.alignment(f),u=h.identity,l=u?u.orientation==="forward"!==w:!w;d.push(s(p,l?"+":"-",[f],Xn(p,[h.len])))}),Hs(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:_s(f)};return p?{...b,resolved:!0,name:p.name,label:pe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(h=>{let{identity:f}=h;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(h,f)}]:[]}),o=h=>f=>f.sample===h.sample&&f.haplotype===h.haplotype,i=o(t),c=n?o(n):h=>!i(h),d=h=>this.record(fe(h,"forward")).sequence;return r.filter(h=>i(h.name)).flatMap(h=>r.filter(f=>c(f.name)).flatMap(f=>bn({...s,query:f.steps,target:h.steps,sequenceOf:d}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:h.name,targetStart:h.start+p.targetStart,targetEnd:h.start+p.targetEnd,cigar:xn(p.edits),matches:p.edits.reduce((w,[u,l])=>w+(u==="="?l:0),0),columns:p.edits.reduce((w,[,u])=>w+u,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=fe(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Fe(s,r)&&t.push([n==="reverse"?1:0,R(r),V(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!V(n)){let s=R(n),r=`S ${s} ${this.record(n).sequence}
|
|
2
|
+
`;for(let[o,i,c]of this.canonicalEdges(s))r+=`L ${s} ${o?"-":"+"} ${i} ${c?"-":"+"}
|
|
3
|
+
`;t.push(e.encode(r))}return Un(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...jn(Gn(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let d of s)V(d)||n.push(`S ${R(d)} ${this.record(d).sequence}`);let r=d=>V(d)?"-":"+";for(let d of s)for(let h of this.record(d).successors())this.hasHandle(h)&&Fe(d,h)&&n.push(`L ${R(d)} ${r(d)} ${R(h)} ${r(h)} 0M`);let o=(d,h,f,p,w)=>{let u=rt(d,h).map(x=>`${V(x)?"<":">"}${R(x)}`).join(""),l=d.weight===void 0?"":` WT:i:${d.weight}`,b=w===void 0?"":` CG:Z:${w}`;return`W ${f.sample} ${f.haplotype} ${f.contig} ${f.fragment} ${p} ${u}${l}${b}`},i=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.push(o(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let c=1;return this.paths.forEach((d,h)=>{if(h!==this.refId){let f=e.names!=="anonymous"?d.identity:void 0,p=t?this.alignToRef(h):void 0;n.push(f?o(d,f,{...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd,p):o(d,void 0,{sample:"unknown",contig:i,haplotype:c,fragment:0},d.len,p)),c+=1}}),`${n.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`}outputPaths(e){this.settleDeferred();let t=e.cigar??!1,n=[],s=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let o={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};n.push({info:this.paths[this.refId],identity:void 0,name:pe({...o,end:this.refPath.fragment+this.refInterval[1]}),cigar:void 0})}let r=1;return this.paths.forEach((o,i)=>{if(i===this.refId)return;let c=e.names!=="anonymous"?o.identity:void 0;n.push({info:o,identity:c,name:c?pe({...c.name,fragment:c.name.fragment+c.hapStart,end:c.name.fragment+c.hapEnd}):pe({sample:"unknown",contig:s,haplotype:r,fragment:0,end:o.len}),cigar:t?this.alignToRef(i):void 0}),r+=1}),n}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Fe(e,t)&&(yield[e,t])}walkSpans(){return this.settleDeferred(),this.paths.flatMap((e,t)=>{let n=t===this.refId?void 0:e.identity;return n?[{name:n.name,start:n.name.fragment+n.hapStart,end:n.name.fragment+n.hapEnd}]:[]})}toSubgraphJson(e={}){let t=this.sortedHandles().filter(r=>!V(r)).map(r=>({id:String(R(r)),sequence:this.record(r).sequence})),n=[];for(let[r,o]of this.outputEdges())n.push({from:String(R(r)),from_is_reverse:V(r),to:String(R(o)),to_is_reverse:V(o)});let s=this.outputPaths(e).map(r=>Bs(r.info,r.identity,r.name,r.cigar));return{nodes:t,edges:n,paths:s}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(o=>!V(o)),n=new Int32Array(t.length),s=[];t.forEach((o,i)=>{n[i]=R(o),s.push(this.record(o).sequence)});let r=[];for(let[o,i]of this.outputEdges())r.push(o,i);return{nodeIds:n,nodeSequences:s,edges:Int32Array.from(r),paths:this.outputPaths(e).map(o=>({name:o.name,weight:o.info.weight,cigar:o.cigar,steps:Int32Array.from(rt(o.info,o.identity))}))}}};function rt(a,e){return e?.orientation==="reverse"?a.path.map(t=>ee(t)).reverse():a.path}function Bs(a,e,t,n){return{name:t,...a.weight===void 0?{}:{weight:a.weight},...n===void 0?{}:{cigar:n},path:rt(a,e).map(s=>({id:String(R(s)),is_reverse:V(s)}))}}function Ft(a,e){let t=Math.min(a.length,e.length);for(let n=0;n<t;n++){let s=a[n],r=e[n];if(s!==r)return s<r?-1:1}return a.length-e.length}function Z(a,e,t){if(t===0)return;let n=a[a.length-1];n?.[0]===e?n[1]+=t:a.push([e,t])}function st(a){return a===0?0:6+(a-1)}function Yn(a,e,t){if(e===0)Z(a,"D",t);else if(t===0)Z(a,"I",e);else{let n=Math.min(e,t),s=4*n+st(e-n)+st(t-n),r=st(e)+st(t);s<=r?(Z(a,"M",n),Z(a,"I",e-n),Z(a,"D",t-n)):(Z(a,"I",e),Z(a,"D",t))}}function Fs(a){let e=0;for(;e<a.length&&a[e][0]!=="M";)e+=1;if(e===a.length){let i=a.filter(([d])=>d==="I"),c=a.filter(([d])=>d==="D").reduce((d,[,h])=>d+h,0);return{edits:i.map(([d,h])=>[d,h]),leading:0,trailing:c}}let t=a.length;for(;a[t-1][0]!=="M";)t-=1;let n=i=>({inserted:i.reduce((c,[d,h])=>c+(d==="I"?h:0),0),deleted:i.reduce((c,[d,h])=>c+(d==="D"?h:0),0)}),s=n(a.slice(0,e)),r=n(a.slice(t)),o=[];Z(o,"I",s.inserted);for(let[i,c]of a.slice(e,t))Z(o,i,c);return Z(o,"I",r.inserted),{edits:o,leading:s.deleted,trailing:r.deleted}}function Xn(a,e){let t=e.map(()=>0),n=e.length-1,s=0,r=e[0],o=0;for(let[i,c]of a){if(i==="D")continue;let d=c;for(;d>0;){for(;s<n&&o>=r;)s+=1,r+=e[s];let h=s<n?Math.min(d,r-o):d;i==="M"&&(t[s]+=h),o+=h,d-=h}}return t}function Ts(a,e){let t=[],n=0,s=0;for(let[r,o]of a){if(r==="D"){Z(t,r,o);continue}let i=n;for(;s<e.length&&e[s][0]<n+o;){let[c,d]=e[s];Z(t,r,c-i),Z(t,"I",d),i=c,s+=1}Z(t,r,n+o-i),n+=o}for(;s<e.length;s++)Z(t,"I",e[s][1]);return t}function _s(a){return a.map(([e,t])=>`${t}${e}`).join("")}function Se(a,e,t=0){if(!Number.isSafeInteger(e)||e<t)throw new Error(`${a} must be a whole number${t>0?` of at least ${t}`:""}, not ${e}`);return e}function ot(a){return Se("context",a.context??100)}function at(a,e){return e.limit!==void 0&&Se("limit",e.limit),je.create(a,e)}async function Jn(a,e){let t=ot(e),n=at(a,e),s=await n.pathPosition(Me(Le(e.path),Se("offset",e.offset)));return await n.aroundPosition(s.position.handle,s.position.nodeOffset,t),await n.extractSnarls(e.snarls??"none"),n.extractPaths(s,e.haplotypes??"all"),n}async function zs(a,e){let t=Se("start",e.start),n=Se("end",e.end),s=ot(e),r=at(a,e);try{let o=await r.pathPosition(Me(Le(e.path),t));return await r.prefetchReferenceWalk(o,n-t),await r.aroundInterval(o.position,n-t,s),await r.extractSnarls(e.snarls??"none"),{subgraph:r,reference:o}}catch(o){throw o instanceof ae&&o.windowBp===void 0?new ae(o.limit,{windowBp:n-t,walkedBp:r.referenceWalkedBp??0}):o}}async function Tt(a,e){let{keep:t}=e,n=e.haplotypes??"all",s=n==="all"||n==="distinct";if(t!==void 0&&s&&!a.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:r,reference:o}=await zs(a,e);return t===void 0||!s?(r.extractPaths(o,n),r):(await r.extractChosenPaths(o,e.end-e.start,t,ot(e))||(r.extractPaths(o,"all"),await r.identifyPaths()),r.keepHaplotypes(t),n==="distinct"&&r.mergeDistinct(),r)}async function es(a,e){let t=e.haplotypes??"all",n=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(n==="overlapping"&&new Set(e.nodeIds).size>1)throw new Error("Overlapping snarls cannot be extracted for a node-based query with multiple nodes");let s=ot(e);for(let o of e.nodeIds)Se("node id",o,1);let r=at(a,e);return await r.aroundNodes(e.nodeIds,s),await r.extractSnarls(n),r.extractPaths(void 0,t),r}async function ts(a,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let n=at(a,e);return await n.betweenNodes(Se("startHandle",e.startHandle,2),Se("endHandle",e.endHandle,2)),n.extractPaths(void 0,t),n}function me(a,e){let t=0;for(let s=0;s<8;s++){let r=a[e+s];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(r&127),(r&128)===0){if(s===7&&!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+s+1]}}let n=a[e+8];if(n===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+n,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function qs(a,e,t){switch(t){case 1:return a.getInt8(e);case 2:return a.getInt16(e);case 3:return a.getInt8(e)<<16|a.getUint16(e+1);case 4:return a.getInt32(e);case 6:return a.getInt16(e)*4294967296+a.getUint32(e+2);default:{let n=a.getBigInt64(e);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${n} exceeds the safe integer range`);return Number(n)}}}var Ds=new TextDecoder;function it(a){let[e,t]=me(a,0),n=[],s=t;for(;s<e;){let[i,c]=me(a,s);n.push(i),s=c}let r=new DataView(a.buffer,a.byteOffset,a.byteLength),o=e;return n.map(i=>{if(i===0)return null;if(i>=1&&i<=6){let c=i<=4?i:i===5?6:8,d=qs(r,o,c);return o+=c,d}if(i===7){let c=r.getFloat64(o);return o+=8,c}if(i===8)return 0;if(i===9)return 1;if(i>=12){let c=i-12>>1,d=a.subarray(o,o+c);return o+=c,i%2===0?d:Ds.decode(d)}throw new Error(`SQLite serial type ${i} is reserved`)})}var ht=2,dt=5,ns=10,ct=13;function ss(a,e){return a[e]*256+a[e+1]}function Ie(a,e){return a[e]*16777216+a[e+1]*65536+a[e+2]*256+a[e+3]}function Gs(a,e){let t=a[e];if(t!==ht&&t!==dt&&t!==ns&&t!==ct)throw new Error(`SQLite page has unknown b-tree type ${t}`);let n=t===ht||t===dt;return{type:t,cellCount:ss(a,e+3),rightChild:n?Ie(a,e+8):0,cellPointers:e+(n?12:8)}}function ye(a,e,t){return ss(a,e.cellPointers+2*t)}var js=4096,ft=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let n=this.usable,s=t?Math.floor((n-12)*64/255)-23:n-35;if(e<=s)return e;let r=Math.floor((n-12)*32/255)-23,o=r+(e-r)%(n-4);return o<=s?o:r}async payload(e,t,n,s){let r=this.localPayloadSize(n,s);if(r===n)return e.subarray(t,t+n);let o=new Uint8Array(n);o.set(e.subarray(t,t+r),0);let i=r,c=Ie(e,t+r);for(;c!==0&&i<n;){let d=await this.pager.page(c),h=d.subarray(4,4+Math.min(this.usable-4,n-i));o.set(h,i),i+=h.length,c=Ie(d,0)}if(i!==n)throw new Error("SQLite overflow chain ended before the payload was complete");return o}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:Gs(t,e===1?100:0)}}tableDepth(e,t){let n=this.tableDepths.get(e);return n||(n=(async()=>{let s=e;for(let r=0;;r++){let{page:o,header:i}=await this.pageAt(s);if(i.type===ct)return r;if(i.type!==dt)throw new Error("SQLite table b-tree contains an index page");let c=this.childIndexFor(o,i,t);s=c===i.cellCount?i.rightChild:Ie(o,ye(o,i,c))}})(),this.tableDepths.set(e,n),n.catch(()=>this.tableDepths.delete(e))),n}childIndexFor(e,t,n){let s=0,r=t.cellCount;for(;s<r;){let o=s+r>>1,[i]=me(e,ye(e,t,o)+4);i<n?s=o+1:r=o}return s}async prefetchRowidRanges(e,t,n=!1){if(t.length===0)return!0;let s=await this.tableDepth(e,t[0][0]),r=t.map(()=>[e]);for(let o=0;o<s;o++){r=await Promise.all(r.map((c,d)=>this.childrenInRange(c,...t[d])));let i=r.flat();if(n)this.pager.prefetchLeading(i);else if(!this.pager.prefetch(i))return!1}return!0}async childrenInRange(e,t,n){let s=await Promise.all(e.map(o=>this.pageAt(o))),r=[];return s.forEach(({page:o,header:i},c)=>{let d=c===0?this.childIndexFor(o,i,t):0,h=c===s.length-1?this.childIndexFor(o,i,n):i.cellCount;for(let f=d;f<=h;f++)r.push(f===i.cellCount?i.rightChild:Ie(o,ye(o,i,f)))}),r}async tableRowid(e,t){let n=e;for(;;){let{page:s,header:r}=await this.pageAt(n);if(r.type===ct){let c=0,d=r.cellCount;for(;c<d;){let h=c+d>>1,f=ye(s,r,h),[p,w]=me(s,f),[u,l]=me(s,w);if(u===t)return it(await this.payload(s,l,p,!1));u<t?c=h+1:d=h}return}if(r.type!==dt)throw new Error("SQLite table b-tree contains an index page");let o=0,i=r.cellCount;for(;o<i;){let c=o+i>>1,d=ye(s,r,c),[h]=me(s,d+4);h<t?o=c+1:i=c}n=o===r.cellCount?r.rightChild:Ie(s,ye(s,r,o))}}async*tableScan(e){yield*this.scanPage(e,await this.tableDepth(e,0))}async*scanPage(e,t){let{page:n,header:s}=await this.pageAt(e);if(s.type===ct)for(let r=0;r<s.cellCount;r++){let o=ye(n,s,r),[i,c]=me(n,o),[d,h]=me(n,c);yield{rowid:d,values:it(await this.payload(n,h,i,!1))}}else{let r=[];for(let o=0;o<s.cellCount;o++)r.push(Ie(n,ye(n,s,o)));r.push(s.rightChild),t===1&&this.pager.prefetchLeading(r);for(let o of r)yield*this.scanPage(o,t-1)}}decodedCells(e,t){let n=this.decodedIndexPages.get(e);if(n)this.decodedIndexPages.delete(e);else if(n=new Array(t.cellCount),this.decodedIndexPages.size>=js){let s=this.decodedIndexPages.keys().next().value;s!==void 0&&this.decodedIndexPages.delete(s)}return this.decodedIndexPages.set(e,n),n}async indexCell(e,t,n,s){let r=this.decodedCells(e,n),o=r[s];if(!o){let i=ye(t,n,s),c=n.type===ht,[d,h]=me(t,c?i+4:i);o={values:it(await this.payload(t,h,d,!0)),leftChild:c?Ie(t,i):0},r[s]=o}return o}async lowerBound(e,t,n,s,r,o){let i=r,c=n.cellCount;for(;i<c;){let d=i+c>>1,h=await this.indexCell(e,t,n,d),f=_t(h.values,s);f<0||o&&f===0?i=d+1:c=d}return i}async*indexScanFrom(e,t,n){let{page:s,header:r}=await this.pageAt(e),o=await this.lowerBound(e,s,r,t,0,!1),i=r.type===ht;if(i&&n){let c=await this.lowerBound(e,s,r,n,o,!0),d=[];for(let h=o;h<=c;h++)d.push(h===r.cellCount?r.rightChild:(await this.indexCell(e,s,r,h)).leftChild);this.pager.prefetchLeading(d)}for(let c=o;c<r.cellCount;c++){let d=await this.indexCell(e,s,r,c);if(i&&(yield*this.indexScanFrom(d.leftChild,t,n)),n&&_t(d.values,n)>0)return;yield d.values}i&&(yield*this.indexScanFrom(r.rightChild,t,n))}async indexSeekLE(e,t){let n,s=e;for(;;){let{page:r,header:o}=await this.pageAt(s),i=0,c=o.cellCount,d=0;for(;i<c;){let h=i+c>>1,f=await this.indexCell(s,r,o,h);_t(f.values,t)<=0?(n=f.values,i=h+1):(d=f.leftChild,c=h)}if(o.type===ns)return n;s=i===o.cellCount?o.rightChild:d}}};function _t(a,e){for(let t=0;t<e.length;t++){let n=a[t],s=e[t];if(typeof n!="number"||s===void 0)throw new Error("SQLite index key is not numeric");if(n!==s)return n<s?-1:1}return 0}function rs({blockSize:a,maxBlocks:e}){if(a!==void 0&&!(Number.isSafeInteger(a)&&a>0))throw new Error(`blockSize must be a positive integer, not ${a}`);if(e!==void 0&&!(Number.isSafeInteger(e)&&e>0))throw new Error(`maxBlocks must be a positive integer, not ${e}`)}var lt=class{blocks=new Map;blockSize;maxBlocks;plan;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,n,s={}){this.source=e,this.pageSize=t,this.fileSize=n;let r=s.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(r/t)*t),this.maxBlocks=s.maxBlocks??256}async read(e,t){let n=await this.readRetrying(e,t);if(this.bytesFetched+=n.length,n.length<e)throw new Error(`the file ends at byte ${t+n.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return n}async readRetrying(e,t){let n=0;for(;;)try{return await this.source.read(e,t)}catch(s){if(n+=1,n>=3)throw s;await new Promise(r=>setTimeout(r,200*n))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){this.follow(e);let t=this.touch(e);if(t)return t;let n=e*this.blockSize,s=Math.min(this.blockSize,this.fileSize-n),r=this.read(s,n);return this.fetches+=1,this.store(e,r),this.evict(),r}touch(e){let t=this.blocks.get(e);return t&&(this.blocks.delete(e),this.blocks.set(e,t)),t}blockOf(e){return Math.floor((e-1)*this.pageSize/this.blockSize)}get prefetchBudget(){return Math.max(1,Math.floor(this.maxBlocks/2))}get chunk(){return Math.max(1,Math.floor(this.prefetchBudget/2))}prefetch(e){let t=new Set(e.map(n=>this.blockOf(n)));return t.size>this.prefetchBudget?!1:(this.fetchBlocks(t),!0)}prefetchLeading(e){let t=[],n=new Map;for(let s of e){let r=this.blockOf(s);n.has(r)||(n.set(r,t.length),t.push(r))}this.plan={blocks:t,position:n,next:0},this.advance(this.prefetchBudget)}advance(e){let t=this.plan;if(!t)return;let n=t.blocks.slice(t.next,t.next+e);t.next+=n.length,t.next>=t.blocks.length&&(this.plan=void 0),this.fetchBlocks(new Set(n))}follow(e){let t=this.plan,n=t?.position.get(e);t&&n!==void 0&&n>=t.next-Math.ceil(this.chunk/2)&&this.advance(this.chunk)}fetchBlocks(e){let t=[...e].filter(s=>!this.touch(s)).sort((s,r)=>s-r),n=0;for(;n<t.length;){let s=n+1;for(;s<t.length&&t[s]===t[s-1]+1;)s+=1;this.fetchRun(t[n],s-n),n=s}}fetchRun(e,t){let n=e*this.blockSize,s=Math.min(t*this.blockSize,this.fileSize-n),r=this.read(s,n);this.fetches+=1;for(let o=0;o<t;o++){let i=o*this.blockSize;this.store(e+o,r.then(c=>c.subarray(i,i+this.blockSize)))}this.evict()}store(e,t){this.blocks.set(e,t),t.catch(()=>{this.blocks.get(e)===t&&this.blocks.delete(e)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let n=await this.block(Math.floor(t/this.blockSize)),s=t%this.blockSize;return n.subarray(s,s+this.pageSize)}};var Ue=class a{pager;btree;objects;constructor(e,t,n){this.pager=e,this.btree=t,this.objects=n}static async open(e,t={}){rs(t);let n=await e.read(Math.max(512,t.blockSize??65536),0),s=n.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3"||s.length<100)throw new Error("Not a SQLite database");let o=new DataView(s.buffer,s.byteOffset,s.byteLength),i=o.getUint16(16),c=i===1?65536:i,d=s[20]??0,h=o.getUint32(56);if(h!==1)throw new Error(`SQLite text encoding ${h} is not UTF-8`);let f=o.getUint32(28);if(f===0||o.getUint32(24)!==o.getUint32(92))throw new Error("SQLite header has no valid database size; the file was written by SQLite older than 3.7.0");let p=f*c,w=new lt(e,c,p,t);w.seed(0,n),w.fetches+=1,w.bytesFetched+=n.length;let u=new ft(w,d),l=new Map;for await(let{values:b}of u.tableScan(1)){let[x,S,I,N,y]=b;typeof x=="string"&&typeof S=="string"&&typeof I=="string"&&typeof N=="number"&&l.set(S,{type:x,name:S,tableName:I,rootPage:N,sql:typeof y=="string"?y:""})}return new a(w,u,l)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}withoutRowid(e){let t=this.objects.get(e);return t?.type==="table"&&/without\s+rowid/i.test(t.sql)}indexOn(e){let t=[...this.objects.values()].find(n=>n.type==="index"&&n.tableName===e);if(t)return t.rootPage;if(this.withoutRowid(e))return this.rootPage(e);throw new Error(`SQLite table ${e} has no index`)}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,n=!1){return this.btree.prefetchRowidRanges(this.rootPage(e),t,n)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t,n){return this.btree.indexScanFrom(this.indexOn(e),t,n)}has(e){return this.objects.has(e)}};var Gt="GBZ-base version 4",pt=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${pe(e)}`),this.path=e}},ut=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},gt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: it has no version tag":`unsupported database schema "${e}"; this reader understands "${Gt}"`),this.found=e}};function Us(a){if(a.length===1)return a[0];let e=new Uint8Array(a.reduce((n,s)=>n+s.length,0)),t=0;for(let n of a)e.set(n,t),t+=n.length;return e}var zt=3,He=class{at=0;bytes;constructor(e){this.bytes=e}get done(){return this.at>=this.bytes.length}next(){let e=0,t=1;for(;;){let n=this.bytes[this.at++];if(n===void 0)throw new Error("a haplotype index blob ends inside a number");if(e+=(n&127)*t,t*=128,(n&128)===0)return e}}};function Ws(a,e){let t=new He(a),n=0;for(;!t.done;){let s=n+t.next();n=s+t.next(),e.push([s,n])}}function Qs(a){a.sort((n,s)=>n[0]-s[0]);let e=[],t=[];for(let[n,s]of a){let r=t.length-1;r>=0&&n<=t[r]+1?t[r]=Math.max(t[r],s):(e.push(n),t.push(s))}return n=>{let s=0,r=e.length;for(;s<r;){let o=s+r>>1;e[o]<=n?s=o+1:r=o}return s>0&&n<=t[s-1]}}function Vs(a,e,t){let n=new He(e);for(;!n.done;){let s=n.next(),r=n.next(),o=n.next(),i=n.next(),c=n.next();t.push({bin:a,pathHandle:s,pathStart:r,pathEnd:o,snarl:c>0?[i,c]:void 0,node:n.next(),offset:n.next()})}}function Zs(a,e,t){let n=R(a);for(let s of e){let r=new He(s);for(;!r.done;){let o=r.next(),i=o%2;t.push({node:2*n+i,offset:r.next(),pathHandle:(o-i)/2,orientation:"forward",pathOffset:r.next()})}}}var Dt=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,n,s,r){this.handle=e,this.edges=t,this.bwt=n,this.encodedSequence=s,this.next=r,this.sequenceLen=wn(s)}get id(){return R(this.handle)}get orientation(){return ke(this.handle)}get sequence(){return this.decoded??=mn(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 et(this.edges,this.bwt)}};function W(a,e){if(typeof a!="number")throw new Error(`${e} is not a number in the database`);return a}function We(a,e){if(typeof a!="string")throw new Error(`${e} is not text in the database`);return a}function Pe(a,e){if(!(a instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return a}function os(a,e){return{handle:a,fwStart:{node:W(e[1],"Paths.fw_node"),offset:W(e[2],"Paths.fw_offset")},revStart:{node:W(e[3],"Paths.rev_node"),offset:W(e[4],"Paths.rev_offset")},name:{sample:We(e[5],"Paths.sample"),contig:We(e[6],"Paths.contig"),haplotype:W(e[7],"Paths.haplotype"),fragment:W(e[8],"Paths.fragment")},isIndexed:W(e[9],"Paths.is_indexed")!==0}}function qt(a,e){return a.catch(e),a}async function as(a){let e=new Map;for await(let{values:t}of a.scan("Tags"))e.set(We(t[0],"Tags.key"),We(t[1],"Tags.value"));return e}var Qe=class a{pathCache;pathMapCache;indexTags=new Map;overviewRowsCache;sqlite;index;tagMap;constructor(e,t,n){this.sqlite=e,this.index=t,this.tagMap=n}static async open(e){let{source:t,haplotypeIndex:n}=e,s={blockSize:e.blockSize,maxBlocks:e.maxBlocks},r=await Ue.open(t,s),o=r.objects.has("Tags")?await as(r):new Map,i=o.get("version");if(i!==Gt)throw new gt(i);for(let h of["Nodes","Paths","ReferenceIndex"])r.rootPage(h);let c=n?await Ue.open(n,s):void 0,d=new a(r,c,o);if(c){for(let l of["Tags","HaplotypeSamples","HaplotypeLengths"])if(!c.objects.has(l))throw new Error(`haplotypeIndex is not a gbz-base haplotype index: it has no ${l} table`);d.indexTags=await as(c);let h=d.indexTags.get("haplotype_index_paths"),f=await d.tag("paths");if(h!==f)throw new Error(`haplotype index was built for ${h??"an unknown number of"} paths but the graph has ${f}`);let p=d.indexTags.get("haplotype_index_nodes"),w=await d.tag("nodes");if(p!==void 0&&p!==w)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${w}`);if(d.indexTags.get("haplotype_index_orientations")==="forward")throw new ut;let u=d.indexTags.get("haplotype_index_format");if(Number(u)!==zt)throw new Error(u===void 0?`the haplotype index predates format ${zt}; rebuild it with gbz-haplotype-index 0.3`:`the haplotype index has format ${u}; this version of @gmod/gbz-base reads format ${zt}`)}return d}async tags(){return this.tagMap}async tag(e){return this.tagMap.get(e)}prefetchRecords(e,t=!1){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let n=t[4];return new Dt(e,Fn(Pe(t[1],"Nodes.edges")),Pe(t[2],"Nodes.bwt"),Pe(t[3],"Nodes.sequence"),typeof n=="number"?n:void 0)}paths(){return this.pathCache??=qt(this.scanPaths(),()=>{this.pathCache=void 0}),this.pathCache}async scanPaths(){let e=[];for await(let{rowid:t,values:n}of this.sqlite.scan("Paths"))e.push(os(t,n));return e}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?os(e,t):void 0}pathsByHandle(){return this.pathMapCache??=qt(this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),()=>{this.pathMapCache=void 0}),this.pathMapCache}async findPath(e){return(await this.paths()).filter(n=>n.name.sample===e.sample&&n.name.contig===e.contig&&n.name.haplotype===e.haplotype&&n.name.fragment<=e.fragment).sort((n,s)=>s.name.fragment-n.name.fragment)[0]}async pathsNamed(e){let t=Me(Le(e),0);return(await this.paths()).filter(n=>n.name.sample===t.sample&&n.name.contig===t.contig&&n.name.haplotype===t.haplotype).sort((n,s)=>n.name.fragment-s.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let n=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!n){let o=await this.getPath(e);throw new Error(`${o?`The fragment of ${pe(o.name)} at ${o.name.fragment}`:`Path ${e}`} has not been indexed for random access`)}let s=n.pathOffset,r=n.pos;for(;;){let o=await this.getRecord(r.node);if(!o)throw new Error(`Node ${r.node} does not exist in the graph`);s+=o.sequenceLen;let i=o.gbwt().lf(r.offset);if(!i||i.node===0)return s;r=i}}return t}async getPathFragments(e){let{start:t,end:n}=e;if(Number.isNaN(t)||Number.isNaN(n))throw new Error(`The window ${t}..${n} is not a number range`);let s=await this.pathsNamed(e.path);if(s.length===0)throw new pt(Me(Le(e.path),0));if(n<=t)return[];let r=s.filter(c=>c.name.fragment<=t).slice(-1),o=s.filter(c=>c.name.fragment>t&&c.name.fragment<n);return(await Promise.all([...r,...o].map(async c=>({path:c,start:c.name.fragment,end:c.name.fragment+await this.pathLength(c.handle)})))).filter(c=>t<c.end)}async subgraphForFragment(e,t){let{sample:n,contig:s,haplotype:r}=e.path.name,o=Math.max(t.start,e.start),i=t.haplotypes??"all";try{let c=await Tt(this,{...t,path:{sample:n,contig:s,haplotype:r},start:o,end:Math.min(t.end,e.end)});return t.keep===void 0&&this.hasHaplotypeIndex&&(i==="all"||i==="distinct")&&await c.identifyPaths(),c}catch(c){throw c instanceof ae&&c.walkedBp!==void 0?new ae(c.limit,{windowBp:t.end-t.start,walkedBp:o-t.start+c.walkedBp}):c}}async getSubgraphs(e){let t=await this.getPathFragments(e);return(await Promise.allSettled(t.map(s=>this.subgraphForFragment(s,e)))).map(s=>{if(s.status==="rejected")throw s.reason;return s.value})}async getAlignments(e){return(await this.getSubgraphs(e)).flatMap(t=>t.alignments())}subgraphInInterval(e){return Tt(this,e)}subgraphAtOffset(e){return Jn(this,e)}subgraphAroundNodes(e){return es(this,e)}subgraphBetween(e){return ts(this,e)}fetchStats(){let e=({pager:t})=>({fetches:t.fetches,bytesFetched:t.bytesFetched});return{graph:e(this.sqlite),haplotypeIndex:this.index?e(this.index):void 0}}async graphName(){let e=new Map;for(let[n,s]of await this.tags())n.startsWith("gbz_")&&e.set(n.slice(4),s);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=Dn(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeSampleGap(){let e=await this.haplotypeSampleInterval(),t=this.indexTags.get("haplotype_index_reference_interval");return e===void 0?void 0:Math.max(e,t===void 0?0:Number(t))}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeStrayOptions(){let e=n=>this.indexTags.get(`haplotype_index_stray_${n}`);if(!this.index?.has("HaplotypeBins")||e("format")!=="2")return;let t=e("snarls")==="modeled"&&e("chain_links")===(await this.tag("chain_links")??"0");return{context:Number(e("context")),bin:Number(e("bin")),bound:Number(e("bound")),snarlNodes:t?Number(e("snarl_nodes")):void 0}}async blobRows(e,t,n){let s=[],r=[];for await(let o of this.companion.indexScanFrom(e,t,n))r.push(W(o[o.length-1],`${e} rowid`));r.length>1&&await this.companion.prefetchRows(e,[[Math.min(...r),Math.max(...r)+1]],!0);for(let o of r){let i=await this.companion.byRowid(e,o);i&&s.push(i)}return s}async haplotypeBinData(e,t,n){let s=[],r=[];for(let o of await this.blobRows("HaplotypeBins",[e,t],[e,n])){let i=W(o[1],"HaplotypeBins.bin");Ws(Pe(o[3],"HaplotypeBins.nodes"),s),Vs(i,Pe(o[4],"HaplotypeBins.strays"),r)}return{listed:Qs(s),strays:r}}async haplotypeAnchorsBetween(e,t,n){let s=[],r=[],o=()=>{let i=s[s.length-1];i&&Zs(i.node,r,i.visits),r=[]};for(let i of await this.blobRows("HaplotypeAnchors",[e,t],[e,n])){let c=W(i[1],"HaplotypeAnchors.anchor_offset");s[s.length-1]?.anchorOffset!==c&&(o(),s.push({anchorOffset:c,node:W(i[3],"HaplotypeAnchors.node_handle"),pathOffset:W(i[4],"HaplotypeAnchors.path_offset"),visits:[]})),r.push(Pe(i[5],"HaplotypeAnchors.visits"))}return o(),s}async haplotypeAnchor(e,t){let[n]=await this.haplotypeAnchorsBetween(e,t,t);return n&&{node:n.node,pathOffset:n.pathOffset}}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:W(e[0],"HaplotypeSamples.node_handle"),offset:W(e[1],"HaplotypeSamples.node_offset"),pathHandle:W(e[2],"HaplotypeSamples.path_handle"),orientation:W(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:W(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let n=[];for await(let s of this.companion.indexScanFrom("HaplotypeSamples",[e,0],[t,Number.MAX_SAFE_INTEGER]))n.push(this.sampleFromRow(s));return n}async haplotypeSampleAt(e,t){let n=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);return n?.[0]===e&&n[1]===t?this.sampleFromRow(n):void 0}overviewRows(){return this.overviewRowsCache??=qt((async()=>{let e=[];for await(let{rowid:t,values:n}of this.companion.scan("HaplotypeOverviewRows"))e[t]={sample:We(n[1],"HaplotypeOverviewRows.sample"),haplotype:W(n[2],"HaplotypeOverviewRows.haplotype")};return e})(),()=>{this.overviewRowsCache=void 0}),this.overviewRowsCache}async overviewChunks(e,t,n,s,r){let o=new Map;for(let i of await this.blobRows(e,[t,n,s],[t,n,r])){let c=W(i[2],`${e}.chunk`),d=o.get(c)??[];d.push(Pe(i[4],`${e} blob`)),o.set(c,d)}return new Map([...o].map(([i,c])=>[i,Us(c)]))}async haplotypeOverview(e){let{signal:t}=e;t?.throwIfAborted();let n=l=>this.indexTags.get(`haplotype_index_overview_${l}`);if(!this.index?.has("HaplotypeOverviewClasses")||n("format")!=="1")return;let s=Number(n("bin")),r=Number(n("chunk")),o=Number(n("levels")),i=Math.max(0,Math.min(Math.floor(e.level??0)||0,o-1));if(e.level===void 0&&e.bpPerPixel!==void 0)for(;i+1<o&&s*4**(i+1)<=e.bpPerPixel;)i+=1;let c=s*4**i,[d,h]=await Promise.all([this.getPathFragments(e),this.overviewRows()]);t?.throwIfAborted();let f=Math.ceil(h.length/2),p=[],w=[];for(let l of d){let b=l.end-l.start,x=Math.max(e.start,l.start)-l.start,S=Math.min(e.end,l.end)-l.start,I=Math.floor(x/c),N=Math.floor((S-1)/c),y=Math.floor(I/r),E=Math.floor(N/r),[$,F]=await Promise.all([this.overviewChunks("HaplotypeOverviewBins",l.path.handle,i,y,E),this.overviewChunks("HaplotypeOverviewClasses",l.path.handle,i,y,E)]);t?.throwIfAborted();for(let T=y;T<=E;T++){let D=new He($.get(T)??new Uint8Array),O=F.get(T)??new Uint8Array;for(let H=T*r;!D.done;H++){let v=Array.from({length:7},()=>D.next());if(H<I||H>N)continue;p.push({start:l.start+H*c,end:l.start+Math.min((H+1)*c,b),classes:[v[0],v[1],v[2],v[3]],excursions:v[4],variants:v[5],longestExcursion:v[6]});let G=(H-T*r)*f;w.push(O.subarray(G,G+f))}}}if(p.length===0)return;let u=new Uint8Array(p.length*h.length);return w.forEach((l,b)=>{for(let x=0;x<h.length;x++)u[b*h.length+x]=(l[x>>1]??0)>>4*(x%2)&15}),{level:i,bin:c,haplotypes:h,bins:p,cells:u}}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?W(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:W(t[1],"ReferenceIndex.path_offset"),pos:{node:W(t[2],"ReferenceIndex.node_handle"),offset:W(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let n=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return n?.[0]===e?W(n[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let n=await this.indexedRowid(e,t);return n===void 0?void 0:this.indexedRow(n)}async indexedPositionsBetween(e,t,n){let[s,r]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,n)]),o=[];if(s!==void 0&&r!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",[[s,r+1]]);for(let i=s;i<=r;i++)o.push(await this.indexedRow(i))}return o}};var Ks="unknown";function Xs(a){let e=a.split(" ");return{fields:e,name:e.slice(1,4).join(" "),start:+e[4],end:+e[5],seams:[]}}var Ys=a=>a.fields[6].match(/[<>][^<>]+/g)??[];function Js(a){let e=new Map;for(let t of a)if(t.startsWith("S ")){let[,n,s,...r]=t.split(" "),o=r.find(i=>i.startsWith("LN:i:"));e.set(n,s!=="*"?s.length:o?+o.slice(5):0)}return e}function er(a,e,t){if(e.end<=a.end)return a;let n=Ys(e),s=e.start;for(let[r,o]of n.entries()){if(s===a.end){let c=a.fields[6],d=Math.max(c.lastIndexOf(">"),c.lastIndexOf("<")),h=[...a.fields];h[5]=String(e.end),h[6]=c+n.slice(r).join("");let f=d<0?a.seams:[...a.seams,[c.slice(d),o]];return{...a,fields:h,end:e.end,seams:f}}let i=t.get(o.slice(1));if(s>a.end||i===void 0)return;s+=i}}function tr(a,e,t){let n=[];for(let s of a.sort((r,o)=>r.start-o.start)){let r=n.at(-1),[,o,i,c]=s.fields,h=r!==void 0&&(s.start<r.end||s.start===r.end&&!t(o,+i,c,s.start))?er(r,s,e):void 0;h?n[n.length-1]=h:n.push(s)}return n}var is=a=>a==="+"?"-":"+",cs=a=>a.startsWith(">")?"+":"-";function nr([a,e]){let t={id:a.slice(1),sign:cs(a)},n={id:e.slice(1),sign:cs(e)};return{forward:`L ${t.id} ${t.sign} ${n.id} ${n.sign} 0M`,reverse:`L ${n.id} ${is(n.sign)} ${t.id} ${is(t.sign)} 0M`}}var wt=(a,e)=>a.filter(t=>t.startsWith(`${e} `));function hs(a,e){if(a.length<=1)return a[0]??"";let t=a.map(h=>h.split(`
|
|
6
|
+
`).filter(f=>f!=="")),n=Js(t.flat()),s=0,r=t.map(h=>{let f=wt(h,"W").map(Xs),p=s;for(let w of f.filter(u=>u.fields[1]===Ks)){let u=+w.fields[2]+p;w.fields[2]=String(u),w.name=w.fields.slice(1,4).join(" "),s=Math.max(s,u)}return f}),i=[...Sn([...r.flatMap(h=>h.slice(0,1)),...r.flatMap(h=>h.slice(1))],h=>h.name).values()].flatMap(h=>tr(h,n,e)),c=new Set(t.flatMap(h=>wt(h,"L")));for(let h of i)for(let f of h.seams.map(nr))!c.has(f.forward)&&!c.has(f.reverse)&&c.add(f.forward);return`${[...new Set([...wt(t[0],"H"),...t.flatMap(h=>wt(h,"S")),...c,...i.map(h=>h.fields.join(" "))])].join(`
|
|
7
|
+
`)}
|
|
8
|
+
`}var jt=class extends Error{constructor(a,e){super(e.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${a}" maps to none; set referenceSample`:`the anchor "${a}" is none of the graph's reference samples (${e.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`),this.name="NoReferenceSampleError"}},mt=class extends Error{constructor(a,e,t){super(`this ${e.toLocaleString()} bp window reads more than nodeLimit (${a.toLocaleString()}) graph nodes; zoom in to about ${t.toLocaleString()} bp or raise nodeLimit`),this.fitsBp=t,this.name="NodeLimitError",this.regionTooLarge=!0}};function ce(a){return`${a.sample}#${a.haplotype}`}function yt(a,e){let t=ce(a);return e===void 0||e.some(n=>Ae(t,n))}async function bt(a){return(await a.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function Ut(a,e){let t=a.toLowerCase(),n=In(a)?.toLowerCase();return e.find(s=>s===a)??e.find(s=>s.toLowerCase()===t)??e.find(s=>s.toLowerCase()===n)}function Wt({configured:a,anchorPrefix:e,referenceSamples:t}){if(a!=="")return a;let n=Ut($t(e),t)??(t.length===1?t[0]:void 0);if(n===void 0)throw new jt(e,t);return n}async function xt(a,e,t){let n=(await a.paths()).find(s=>s.isIndexed&&s.name.sample===e&&s.name.contig===t);return n?{sample:n.name.sample,contig:t,haplotype:n.name.haplotype}:void 0}function St(a,e,t){if(a instanceof Error&&(a.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(a.message))){let s="walkedBp"in a?a.walkedBp:void 0,r=typeof s=="number"&&s>0?Math.floor(s*.8):Math.floor(t/2);return new mt(e,t,Math.max(r,1))}else return}async function sr(a,e,t,n,s){return a.getSubgraphs({...s,path:e,start:t,end:n,haplotypes:"all"}).catch(r=>{throw St(r,s.limit,n-t)??r})}function rr(a){let e=kn(Number.NaN),t=a.indexOf(`
|
|
9
|
+
`),n=t===-1?a.length:t;return a===""?a:a.startsWith("H ")?`${a.slice(0,n)} ${e}${a.slice(n)}`:`H VN:Z:1.1 ${e}
|
|
10
|
+
${a}`}async function or(a,e){let t=await a.paths();return rr(hs(await Promise.all(e.map(n=>n.toGFA())),(n,s,r,o)=>t.some(({name:i})=>i.sample===n&&i.haplotype===s&&i.contig===r&&i.fragment===o)))}async function Qt(a,e,t,n,s){if(!e)return"";let r=await sr(a,e,t,n,s);if(r.length===1)return ds(r[0].toCompactSubgraph());let o=await or(a,r);return(o===""?void 0:vn(o))??o}function ar(a,e){let t=1/0,n=-1/0;for(let i of a)t=Math.min(t,i),n=Math.max(n,i);let s=n-t+1,r=a.length>0&&s<=16*a.length?new Int32Array(s).fill(-1):void 0,o=new Map;return a.forEach((i,c)=>{r?r[i-t]=c:o.set(i,c)}),i=>{let c=R(i),d=r!==void 0&&c>=t&&c<=n,h=d?r[c-t]:o.get(c)??-1;return h>=0?h:(d?r[c-t]=e.length:o.set(c,e.length),e.push(String(c)),e.length-1)}}var ir=/^(.*)\[(\d+)-(\d+)\]$/;function ds(a){let e=Array.from(a.nodeIds,String),t=ar(a.nodeIds,e),n=a.nodeIds.length,s=a.edges.length/2,r=new Int32Array(s),o=new Int32Array(s),i=new Uint8Array(s);for(let l=0;l<s;l++){let b=a.edges[2*l],x=a.edges[2*l+1];r[l]=t(b),o[l]=t(x),i[l]=(V(b)?1:0)|(V(x)?2:0)}let c=a.paths.filter(l=>l.steps.length>0),d=new Int32Array(c.length+1);c.forEach((l,b)=>{d[b+1]=d[b]+l.steps.length});let h=new Int32Array(d[c.length]),f=new Uint8Array(h.length),p=new Float64Array(c.length),w=new Float64Array(c.length),u=c.map((l,b)=>{let x=ir.exec(l.name);p[b]=x?+x[2]:0,w[b]=x?+x[3]:-1;let S=d[b];for(let I of l.steps)h[S]=t(I),f[S++]=V(I)?1:0;return x?x[1]:l.name});return{nodes:{names:e,lengths:Int32Array.from(a.nodeSequences,l=>l.length),refs:new Int32Array(n).fill(-1),starts:new Float64Array(n),ranks:new Int32Array(n),refNames:[]},links:{from:r,to:o,strands:i},walks:{names:u,starts:p,ends:w,offsets:d,steps:h,reversed:f},departures:En(),revisited:Number.NaN}}function It(a){let e=/\.gbz\.db$/i;return e.test(a)?a.replace(e,".haplotype-index.db"):void 0}function dr(a){return fn(a)&&It(dn(a))?ln(a,e=>It(e)):void 0}function fr(a){return a instanceof Error&&(/\bHTTP 40[34]\b/.test(a.message)||a.code==="ENOENT")}async function fs(a,e){let t=dr(a);if(!t)return{};try{return await Re(t,e).stat(),{location:t}}catch(n){return fr(n)?{}:{unreadable:String(n)}}}var lr=5e3,pr=50*2**20,Vt=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 ur(a,e){if(a.length<=e)return a;let t=a.length/e;return Array.from({length:e},(n,s)=>a[Math.floor(s*t)])}var ls=(a,e)=>a.path.some(t=>e.has(t.name)),Et=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=_e({setup:async({signal:e})=>{let{size:t}=await this.file.stat();if(t>pr)throw new Vt(t);let n=await this.file.readFile({signal:e}),s=new TextDecoder().decode(n[0]===31&&n[1]===139?await Nn(n):n);return Mt(s)}})}async readIndexed(e,t,n){let s=1/0,r=-1/0;for(let i of t){let c=Number(i);Number.isInteger(c)&&(s=Math.min(s,c),r=Math.max(r,c))}let o=[];return s<=r&&await e.getLines("{node}",s,r+1,{signal:n,lineCallback:i=>{let c=Lt(i);c&&ls(c,t)&&o.push(c)}}),o}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(s=>ls(s,e));return{records:ur(n,lr),total:n.length}}};var kt=class extends Error{constructor(t){super(t===void 0?"no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation":`the haplotype index beside the graph database could not be checked (${t}), so the walks cannot be named; if it is there, reload to try again, or set haplotypeIndexLocation`);this.name="NoHaplotypeIndexError"}},Zt=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function gr(a,e){return`${ce(a)}#${a.contig}@${e.start.node}.${e.start.offset}`}function wr({alignment:a,assemblyName:e,refName:t,lane:n}){let{refStart:s,refEnd:r,strand:o,cigar:i}=a;if(!(r<=s)){let{name:c,hapStart:d,hapEnd:h}=a,f=gr(c,a),p={uniqueId:f,assemblyName:e,refName:t,start:s,end:r,type:"match",strand:o==="-"?-1:1,CIGAR:i,syntenyId:f,mate:{refName:c.contig,start:d,end:h,assemblyName:n}};return new Rn(p)}}function mr({pair:a,lane:e,mateLane:t}){return On({target:{name:`${ce(a.target)}#${a.target.contig}`,assemblyName:e,refName:a.target.contig,start:a.targetStart,end:a.targetEnd},query:{name:`${ce(a.query)}#${a.query.contig}`,assemblyName:t,refName:a.query.contig,start:a.queryStart,end:a.queryEnd},strand:a.strand,cigar:a.cigar,matches:a.matches,columns:a.columns})}var yr=12e4;function br(a,e){let t=new Map;for(let s of a)for(let{name:r,start:o,end:i}of s.walkSpans()){let c=ce(r);if(e.has(c)){let d=`${c}#${r.contig}`,h=t.get(d);h?h.push([o,i]):t.set(d,[[o,i]])}}let n=0;for(let s of t.values()){s.sort((r,o)=>r[0]-o[0]);for(let r=1;r<s.length;r++){let o=s[r][0]-s[r-1][1];o>0&&o<=yr&&(n=Math.max(n,o))}}return n}function gs(a,e){return a instanceof mt&&(a.message=`Zoom in to about ${hn(a.fitsBp)} to see ${e}`),a}var ps=(a,e,t)=>Cn(gs(St(a,e,t)??a,"lanes"),t),us=a=>({...a,start:Math.floor(a.start),end:Math.ceil(a.end)}),Kt=class extends Ln{constructor(){super(...arguments);this.graph=_e({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),s=Ke(n)?{location:n}:await fs(t,this.pluginManager),r=s.location,o=await Qe.open({source:Re(t,this.pluginManager),haplotypeIndex:r?Re(r,this.pluginManager):void 0}),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 c=await bt(o),d=Wt({configured:this.getConf("referenceSample"),anchorPrefix:$e(this,i),referenceSamples:c});return{db:o,anchor:i,referenceSample:d,referenceSamples:c,unreadableIndex:s.unreadable}}});this.gaf=_e({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return Ke(t)?new Et(Re(t,this.pluginManager),Ke(n)?$n(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:s,referenceSample:r}=await this.graph(n);return xt(s,r,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:s}=await this.graph(t),r=new Map;for(let o of await n.paths()){let i=ce(o.name),c=r.get(i);c?c.contigs.includes(o.name.contig)||c.contigs.push(o.name.contig):r.set(i,{prefix:i,sample:o.name.sample,haplotype:o.name.haplotype,contigs:[o.name.contig],isReference:s.includes(o.name.sample)})}return[...r.values()]}async getHeader(t={}){let{anchor:n,referenceSample:s}=await this.graph(t),r=Rt(this),o=[];for(let i of await this.getHaplotypes(t))i.sample!==s&&o.push({name:Ht(r,i.prefix),label:i.prefix,group:i.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,lanes:o}}async getRefNames(t={}){let{db:n,anchor:s,referenceSample:r}=await this.graph(t),{assemblyName:o}=t,i=o===s?void 0:$e(this,o),c=(await n.paths()).filter(d=>o===s?d.isIndexed&&d.name.sample===r:Ae(ce(d.name),i)).map(d=>d.name.contig);return[...new Set(c)]}keepPredicate(t,n){let s=t===void 0||t.length===0?void 0:t.map(r=>$e(this,r));return s===void 0&&n===void 0?void 0:r=>yt(r,s)&&(n===void 0||Ae(ce(r),n))}async getSubgraph(t,n={}){let{signal:s}=n,{db:r,anchor:o,referenceSample:i,unreadableIndex:c}=await this.graph({signal:s}),{assemblyName:d,refName:h,start:f,end:p}=us(t);if(d!==o)throw new Zt(d,o);let w=await this.referenceQuery(h,{signal:s});if(!w)throw new Error(`${i} has no indexed path ${h} in this graph`);let u=this.keepPredicate(n.haplotypes);if(u!==void 0&&!r.hasHaplotypeIndex)throw new kt(c);let l=await Qt(r,w,f,p,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:u}).catch(b=>{throw gs(b,"the graph")});return typeof l=="string"?l:An(l,{start:f,end:p},n.walkRows)}async getReads(t,n={}){let s=await this.gaf(n);return s?s.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let s=$e(this,t);return(await this.getHaplotypes(n)).filter(r=>Ae(r.prefix,s))}async anchorFeatures(t,n){let{db:s}=await this.graph(n),{assemblyName:r,refName:o,start:i,end:c}=t,d=$e(this,n.targetAssemblyName),h=Rt(this),f=this.keepPredicate(n.haplotypes,d),p=await this.referenceQuery(o,n),w=this.getConf("nodeLimit");return(p?await At(`Reading graph ${o}:${i.toLocaleString()}-${c.toLocaleString()}`,n.statusCallback,()=>s.getAlignments({path:p,start:i,end:c,context:this.getConf("context"),haplotypes:"all",limit:w,signal:n.signal,keep:f}).catch(l=>{throw ps(l,w,c-i)})):[]).flatMap(l=>{let b=l.resolved?wr({alignment:l,assemblyName:r,refName:o,lane:Ht(h,ce(l.name))}):void 0;return b===void 0?[]:[b]})}async pairFeatures(t,n,s){let{db:r}=await this.graph(s),{refName:o,start:i,end:c}=t,h=(await Promise.all(n.map(async S=>({pair:S,featureSide:await this.laneHaplotypes(S.queryAssemblyName,s),mateSide:await this.laneHaplotypes(S.targetAssemblyName,s)})))).filter(({featureSide:S,mateSide:I})=>S.length>0&&I.length>0),f=new Set(h.flatMap(({featureSide:S,mateSide:I})=>[...S,...I].map(ce))),p=await this.referenceQuery(o,s),w=this.getConf("nodeLimit"),u=this.getConf("context"),l=(S,I)=>r.getSubgraphs({path:S,start:i,end:c,context:I,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:w,signal:s.signal,keep:N=>f.has(ce(N))}),b=async S=>{let I=await l(S,u).catch(E=>{throw ps(E,w,c-i)}),N=br(I,f),y=Math.ceil(N/2)+2e3;return N>0&&y>u?l(S,y).catch(E=>{if(E instanceof ae)return I;throw E}):I};return(p&&h.length>0?await At(Hn(n),s.statusCallback,()=>b(p)):[]).flatMap(S=>h.flatMap(({pair:I,featureSide:N,mateSide:y})=>N.flatMap(E=>y.flatMap($=>S.pairAlignments({target:E,query:$,bases:!1}).map(F=>mr({pair:F,lane:I.queryAssemblyName,mateLane:I.targetAssemblyName}))))))}getFeatures(t,n={}){let s=us(t);return Pn(async r=>{let{db:o,anchor:i,unreadableIndex:c}=await this.graph(n);if(!o.hasHaplotypeIndex)throw new kt(c);if(s.assemblyName===i){let d=Mn(n),h=d.length>0?await this.pairFeatures(s,d,n):await this.anchorFeatures(s,n);for(let f of h)r.next(f)}r.complete()},n.signal)}};export{kt as NoHaplotypeIndexError,xs as PairTargetError,Kt as default,br as widestWalkGap};
|
|
11
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-H55DLBI3.js.map
|