import{bU as O,a9 as U,u as w,H as B,v as p}from"./index-Bm2SqMk3.js";class k{constructor(e=[],a){this.data={};const{checkIndent:r=!0,skipValidation:i=!1}=a??{};let d;typeof e=="string"?d=e.trimEnd().split(/\r?\n/):e?d=e:d=[];let o,n;for(const c of d){if(c==="")throw new Error("Invalid stanza, contained blank lines");if(c.trim().startsWith("#"))continue;if(c.trimEnd().endsWith("\\")){const f=c.trimEnd().slice(0,-1);n?n+=f.trimStart():n=f;continue}let s=c;if(n&&(s=n+s.trimStart(),n=void 0),o??r){const f=s.match(/^([ \t]+)/);if(o===void 0)f?[,o]=f:o="";else if(o===""&&f!==null||o&&f&&o!==f[1])throw new Error("Inconsistent indentation of stanza")}else o="";const l=s.trim(),h=l.indexOf(" ");if(h===-1){if(!this.nameKey)throw new Error("First line in a stanza must have both a key and a value");if(this.data[l])continue;this.data[l]="";continue}const m=l.slice(0,h),u=l.slice(h+1);if(this.data[m]&&u!==this.data[m])throw new Error(`Got duplicate key with a different value in stanza: "${m}" key has both ${this.data[m]} and ${u}`);this.nameKey||(this.nameKey=m,this.name=l.slice(h+1)),this.data[m]=u}i||this.validate()}validate(){}}class z{constructor(e=[],a){this.data={};const{checkIndent:r=!0,skipValidation:i=!1}=a??{};let d;typeof e=="string"?d=e.trimEnd().split(/(?:[\t ]*\r?\n){2,}/):e?d=e:d=[];for(const o of d){if(o==="")throw new Error("Invalid stanza, was empty");if(o.trim().startsWith("#")&&o.trimEnd().split(/\r?\n/).map(s=>s.trim()).every(s=>s.startsWith("#")))continue;const n=new k(o,{checkIndent:r});if(!this.nameKey)this.nameKey=n.nameKey;else if(n.nameKey!==this.nameKey)throw new Error(`The first line in each stanza must have the same key. Saw both ${this.nameKey} and ${n.nameKey}`);if(!n.name)throw new Error(`No stanza name: ${n.name}`);if(this.data[n.name])throw new Error(`Got duplicate stanza name: ${n.name}`);this.data[n.name]=n}i||this.validate()}validate(){}}function L(t,e,a=""){const r=[];for(const i of e)t.data[i]||r.push(i);if(r.length>0)throw new Error(`${a} is missing required entr${r.length===1?"y":"ies"}: ${r.join(", ")}`)}class C extends z{constructor(e,a){super(e,{...a,checkIndent:!1})}validate(){var e;if(this.nameKey!=="track")throw new Error(`trackDb has "${this.nameKey}" instead of "track" as the first line in each track`);for(const[a,r]of Object.entries(this.data)){const i=Object.keys(r.data);L(r,["track","shortLabel"],`Track ${a}`);const d=new Set(["superTrack","compositeTrack","container","view"]);if(!i.some(c=>d.has(c))){if(!i.includes("bigDataUrl"))throw new Error(`Track ${a} is missing required key "bigDataUrl"`);if(!i.includes("type")&&!Object.keys(this.settings(a)).includes("type"))throw new Error(`Neither track ${a} nor any of its parent tracks have the required key "type"`)}let o=a;do o=(e=this.data[o])===null||e===void 0?void 0:e.parent,o&&([o]=o.split(" "));while(o);const n=this.data[a];n&&(this.data[a]=n)}}settings(e){var a;if(!this.data[e])throw new Error(`Track ${e} does not exist`);const r=[e];let i=e;do i=(a=this.data[i])===null||a===void 0?void 0:a.parent,i&&r.push(i);while(i);const d={};r.reverse();for(const o of r){const n=this.data[o];if(n)for(const[c,s]of Object.entries(n))d[c]=s}return d}}class G extends z{validate(e=["genome","trackDb"]){if(this.nameKey!=="genome")throw new Error('Genomes file must begin with a line like "genome <genome_name>"');for(const[a,r]of Object.entries(this.data))L(r,e,`genome ${a}`)}}class H extends k{validate(){L(this,["hub","shortLabel","longLabel","genomesFile","email"],"Hub file")}}class P{constructor(e){const[a,r,...i]=e.trimEnd().split(/(?:[\t ]*\r?\n){2,}/);this.hubData=new k(a),this.validateHub(),this.genome=new k(r),this.validateGenomeSection(),this.tracks=new C(i.join(`

`),{skipValidation:!1})}validateHub(){if(this.hubData.nameKey!=="hub")throw new Error('Hub file must begin with a line like "hub <hub_name>"');L(this.hubData,["hub","shortLabel","longLabel","email","descriptionUrl"])}validateGenomeSection(){if(this.genome.nameKey!=="genome")throw new Error('Genomes file must begin with a line like "genome <genome_name>"')}}var R=O();async function W(t){const e=await U.openLocation(t).readFile("utf8");return new G(e)}async function _(t){const e=await U.openLocation(t).readFile("utf8");return new C(e)}function F(t,e){return{uri:new URL(t,new URL(e.uri,e.baseUri)).href,locationType:"UriLocation"}}function $(t,e,a){return F(t||e,a)}function y(t,e){return t?{uri:t,locationType:"LocalPath"}:{uri:e,locationType:"UriLocation"}}function j({trackDb:t,trackDbLoc:e,assemblyName:a,sequenceAdapter:r}){return Object.entries(t.data).map(([i,d])=>{var o;const n=Object.keys(d),c=new Set(["superTrack","compositeTrack","container","view"]);if(n.some(u=>c.has(u)))return;const s=[];let l=i;do l=((o=t.data[l])===null||o===void 0?void 0:o.data.parent)||"",l&&(l=l.split(" ")[0],s.push(t.data[l]));while(l);s.reverse();const h=s.map(u=>u==null?void 0:u.data.shortLabel).filter(u=>!!u),m=V({track:d,categories:h,trackDbLoc:e,trackDb:t,sequenceAdapter:r});return{...m,trackId:`ucsc-trackhub-${w.objectHash(m)}`,assemblyNames:[a]}}).filter(w.notEmpty)}function V({track:t,categories:e,trackDbLoc:a,trackDb:r,sequenceAdapter:i}){var d;const o=t.data.type||((d=r.data[t.data.parent||""])===null||d===void 0?void 0:d.data.type)||"",n=t.data.shortLabel||"",c=t.data.bigDataUrl||"",s=t.data.bigDataIndex||"",l=w.isUriLocation(a);let h=o.split(" ")[0]||"";h==="bam"&&c.toLowerCase().endsWith("cram")&&(h="cram");const m=l?F(c,a):y(c);switch(h){case"bam":return{type:"AlignmentsTrack",name:t.data.longLabel,description:t.data.longLabel,category:e,adapter:{type:"BamAdapter",bamLocation:m,index:{location:l?$(s,`${c}.bai`,a):y(s,`${c}.bai`)}}};case"cram":return{type:"AlignmentsTrack",name:n,description:t.data.longLabel,category:e,adapter:{type:"CramAdapter",cramLocation:m,craiLocation:l?$(s,`${c}.crai`,a):y(s,`${c}.crai`),sequenceAdapter:i}};case"bigBarChart":case"bigBed":case"bigGenePred":case"bigChain":case"bigInteract":case"bigMaf":case"bigNarrowPeak":case"bigPsl":return{type:"FeatureTrack",name:n,description:t.data.longLabel,category:e,adapter:{type:"BigBedAdapter",bigBedLocation:m}};case"bigWig":return{type:"QuantitativeTrack",name:n,description:t.data.longLabel,category:e,adapter:{type:"BigWigAdapter",bigWigLocation:m}};case"vcfTabix":return{type:"VariantTrack",name:n,description:t.data.longLabel,category:e,adapter:{type:"VcfTabixAdapter",vcfGzLocation:m,index:{location:l?$(s,`${c}.tbi`,a):y(s,`${c}.tbi`)}}};case"hic":return{type:"HicTrack",name:n,description:t.data.longLabel,category:e,adapter:{type:"HicAdapter",hicLocation:m}};default:return B.generateUnknownTrackConf(n,h,e)}}function g(t,e){return new URL(t,e).href}async function Q(t){var e;const a=w.getSession(t),r=[];try{const i=p.getConf(t,"hubTxtLocation"),d=await U.openLocation(i).readFile("utf8"),o=g(i.uri,i.baseUri),{assemblyManager:n}=a;if(d.includes("useOneFile on")){const c=new P(d),{genome:s,tracks:l}=c,h=s.name;n.get(h)||a.addSessionAssembly({name:h,sequence:{type:"ReferenceSequenceTrack",trackId:`${h}-${R.nanoid()}`,adapter:{type:"TwoBitAdapter",twoBitLocation:{uri:g(s.data.twoBitPath,o)},chromSizesLocation:{uri:g(s.data.chromSizes,o)}}}});const u=n.get(h),f=p.getConf(u,["sequence","adapter"]),v=j({trackDb:l,trackDbLoc:i,assemblyName:h,sequenceAdapter:f});t.addTrackConfs(v)}else{const s=new H(d).data.genomesFile;if(!s)throw new Error("genomesFile not found on hub");const l=g(i.uri,i.baseUri),h=l?{uri:g(s,l),locationType:"UriLocation"}:{localPath:s,locationType:"LocalPathLocation"},m=await W(h),u={};for(const[b,T]of Object.entries(m.data)){const x=p.getConf(t,"assemblyNames");if(x.length>0&&!x.includes(b))continue;const K=n.get(b);if(!K){r.push(b);continue}const E=T.data.trackDb;if(!E)throw new Error("genomesFile not found on hub");const D=new URL(s,l),S=l?{uri:new URL(E,D).href,locationType:"UriLocation"}:{localPath:E,locationType:"LocalPathLocation"},I=await _(S),q=p.getConf(K,["sequence","adapter"]),A=j({trackDb:I,trackDbLoc:S,assemblyName:b,sequenceAdapter:q});t.addTrackConfs(A),u[b]=A.length}const f=Object.entries(u),v=f.length?`Loaded data from these assemblies: ${f.map(([b,T])=>`${b} (${T} tracks)`).join(", ")}`:"",N=r.length?`Skipped data from these assemblies: ${r.join(", ")}`:"";a.notify([v,N].filter(b=>!!b).join(". "),"success")}}catch(i){console.error(i),a.notifyError(`${p.getConf(t,"name")}: "${i}"`,i),(e=a.breakConnection)===null||e===void 0||e.call(a,t.configuration)}}export{Q as doConnect};
