@sjcrh/proteinpaint-server 2.43.1 → 2.43.2
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/package.json +1 -1
- package/routes/termdb.singlecellSamples.ts +10 -9
- package/server.js +1 -1
- package/server.js.map +1 -1
- package/src/serverconfig.js +9 -4
package/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(()=>{var e={5037:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>c});var s=n(9157),r=n(1017),o=n.n(r),i=n(334),a=n.n(i),l=n(3345);const c={endpoint:"burden",methods:{get:{init:({genomes:e})=>async(t,n)=>{try{const r=e[t.query.genome];if(!r)throw`invalid q.genome=${t.query.genome}`;const i=t.query,c=r.datasets[i.dslabel];if(!c)throw`invalid q.genome=${t.query.dslabel}`;if(!c.cohort.cumburden?.files)throw"missing ds.cohort.cumburden.files";const f=await async function(e,t){const n=o().join(a().cachedir,Math.random().toString()+".json");for(const t in e.query)e.query[t]=Number(e.query[t]);const r=Object.assign({},u,e.query);await(0,l.Sf)(n,JSON.stringify(r));const{fit:i,surv:c,sample:f}=t.cohort.cumburden.files;if(!i||!c||!f)throw"missing one or more of ds.cohort.burden.files.{fit, surv, sample}";const d=[n,`${a().tpmasterdir}/${i}`,`${a().tpmasterdir}/${c}`,`${a().tpmasterdir}/${f}`],p=await(0,s.default)(o().join(a().binpath,"utils/burden.R"),[],d),m=JSON.parse(p[0]);return m}(t,c),{keys:d,rows:p}=function(e){const t=Object.keys(e[0]),n=[],s=[];for(const e of t)if("chc"==e)s.push(e),n.push(e);else{const t=Number(e.slice(1).split(",")[0]);t<=60&&t%2==0&&(s.push(e),n.push(`burden${t}`))}const r=[];for(const t of e)r.push(s.map((e=>t[e])));return{keys:n,rows:r}}(f);n.send({status:"ok",keys:d,rows:p})}catch(e){n.send({status:"error",error:e.message||e})}},request:{typeId:"BurdenRequest"},response:{typeId:"BurdenResponse"},examples:[{request:{body:{genome:"hg38",dslabel:"SJLife",diaggrp:5,sex:1,white:1,agedx:1,bleo:0,etop:0,cisp:0,carbo:0,steriod:0,vcr:0,hdmtx:0,itmt:0,ced:0,dox:0,heart:0,brain:0,abd:0,pelvis:0,chest:0}},response:{header:{status:200}}}]}}};const u=Object.freeze({diaggrp:5,sex:0,white:1,agedx:1,steriod:0,bleo:0,vcr:0,etop:0,itmt:0,ced:0,cisp:0,dox:0,carbo:0,hdmtx:0,brain:0,chest:0,heart:0,pelvis:0,abd:0})},2538:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f,maxTotalSizeCompressed:()=>u});var s=n(1017),r=n.n(s),o=n(6452),i=n.n(o),a=n(334);const l=1e3,c="Aliquot Ensemble Somatic Variant Merging and Masking",u=n.n(a)().features.gdcMafMaxFileSize||4e8,f={endpoint:"gdc/maf",methods:{all:{init:function({genomes:e}){return async(t,n)=>{try{const s=e.hg38;if(!s)throw"hg38 missing";const o=s.datasets.GDC;if(!o)throw"hg38 GDC missing";const a=await async function(e,t){const n={op:"and",content:[{op:"=",content:{field:"data_format",value:"MAF"}},{op:"=",content:{field:"experimental_strategy",value:e.experimentalStrategy}},{op:"=",content:{field:"analysis.workflow_type",value:c}},{op:"=",content:{field:"access",value:"open"}}]},s={op:"and",content:[]};e.filter0&&s.content.push(e.filter0);const{host:o,headers:a}=t.getHostHeaders(e),d={filters:n,case_filters:s,size:l,fields:["id","file_size","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},p=await i().post(r().join(o.rest,"files"),{headers:a,body:JSON.stringify(d)});let m;try{m=JSON.parse(p.body)}catch(e){throw"invalid JSON from "+f.endpoint}if(!Number.isInteger(m.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(m.data?.hits))throw"re.data.hits[] not array";const h=[];for(const e of m.data.hits){const t=e.cases?.[0];if(!t)throw"h.cases[0] missing";const n={id:e.id,project_id:t.project.project_id,file_size:e.file_size};n.case_submitter_id=t.submitter_id,t.samples&&(n.sample_types=t.samples.map((e=>e.sample_type)).sort()),h.push(n)}return{files:h,filesTotal:m.data.pagination.total,maxTotalSizeCompressed:u}}(t.query,o);n.send(a)}catch(e){n.send({status:"error",error:e.message||e})}}},request:{typeId:"GdcMafRequest"},response:{typeId:"GdcMafResponse"},examples:[{request:{body:{experimentalStrategy:"WXS",embedder:"localhost"}},response:{header:{status:200}}}]}}}},86:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f});var s=n(6452),r=n.n(s),o=n(1017),i=n.n(o),a=n(1271),l=n(334),c=n.n(l),u=n(2538);const f={endpoint:"gdc/mafBuild",methods:{all:{init:function({genomes:e}){return async(t,n)=>{try{const s=e.hg38;if(!s)throw"hg38 missing";const o=s.datasets.GDC;if(!o)throw"hg38 GDC missing";await async function(e,t,n){const s=Date.now(),{host:o,headers:l}=n.getHostHeaders(e),f=await async function(e,t,n){if(0==e.length)throw"fileIdLst[] not array or blank";const s={filters:{op:"in",content:{field:"file_id",value:e}},size:1e4,fields:"file_size"},o=await r().post(i().join(t.rest,"files"),{headers:n,body:JSON.stringify(s)});let a;try{a=JSON.parse(o.body)}catch(e){throw"invalid json from getFileLstUnderSizeLimit"}if(!Array.isArray(a.data?.hits))throw"re.data.hits[] not array";const l=[];let c=0;for(const e of a.data.hits){if(c>=u.maxTotalSizeCompressed)break;if(!e.id)throw".id missing";if(!Number.isInteger(e.file_size))throw".file_size not integer";c+=e.file_size,l.push(e.id)}if(0==l.length)throw"no file available";return l}(e.fileIdLst,o,l);c().debugmode&&console.log(`${f.length} out of ${e.fileIdLst.length} input MAF files accepted by size limit`,Date.now()-s);const d={fileIdLst:f,columns:e.columns,host:i().join(o.rest,"data")},p=(0,a.run_rust_stream)("gdcmaf",JSON.stringify(d));t.setHeader("Content-Type","application/octet-stream"),t.setHeader("Content-Disposition","attachment; filename=cohort.maf.gz"),p.pipe(t),p.on("end",(()=>{c().debugmode&&console.log("rust gdcmaf",Date.now()-s),t.end()})),p.on("error",(e=>{console.error(e),t.statusCode=500,t.end("Internal Server Error")}))}(t.query,n,o)}catch(e){e.stack&&console.log(e.stack),n.send({status:"error",error:e.message||e})}}},request:{typeId:"GdcMafBuildRequest"},response:{typeId:null}}}}},889:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>l});var s=n(2273),r=n(6452),o=n.n(r),i=n(334),a=n.n(i);const l={endpoint:"gdc/topMutatedGenes",methods:{all:{init:function({genomes:e}){return async(t,n)=>{const r=t.query,i=e.hg38;if(!i)throw"hg38 missing";const l=i.datasets.GDC;if(!l)throw"hg38 GDC missing";try{const e=await async function(e,t){let n,r;const{host:i,headers:l}=t.getHostHeaders(e);a().features?.geneExpHost?(n=c.query,r=c.getVariables(e)):(n=u.query,r=u.getVariables(e));const f=await o().post(i.graphql,{headers:l,body:JSON.stringify({query:n,variables:r})}),d=JSON.parse(f.body),p=[];for(const e of d.data.genesTableViewer.explore.genes.hits.edges){if("object"!=typeof e.node)throw"node missing from re.data.genesTableViewer.explore.genes.hits.edges[]";const t=[];Number.isInteger(e.node.case_cnv_gain?.hits?.total)&&e.node.case_cnv_gain.hits.total>0&&t.push({class:s.mclasscnvgain,count:e.node.case_cnv_gain.hits.total}),Number.isInteger(e.node.case_cnv_loss?.hits?.total)&&e.node.case_cnv_loss.hits.total>0&&t.push({class:s.mclasscnvloss,count:e.node.case_cnv_loss.hits.total}),Number.isInteger(e.node.ssm_case?.hits?.total)&&e.node.ssm_case.hits.total>0&&t.push({dt:s.dtsnvindel,count:e.node.ssm_case.hits.total}),p.push({gene:e.node.symbol,mutationStat:t})}return p}(r,l),t={genes:e};n.send(t)}catch(e){n.send({status:"error",error:e.message||e})}}},request:{typeId:"GdcTopMutatedGeneRequest"},response:{typeId:"GdcTopMutatedGeneResponse"}}}};const c={query:"\nquery GenesTable_relayQuery(\n $genesTable_filters: FiltersArgument\n $genesTable_size: Int\n $genesTable_offset: Int\n $score: String\n $ssmCase: FiltersArgument\n $geneCaseFilter: FiltersArgument\n $ssmTested: FiltersArgument\n $cnvTested: FiltersArgument\n $cnvGainFilters: FiltersArgument\n $cnvLossFilters: FiltersArgument\n) {\n genesTableViewer: viewer {\n explore {\n cases {\n hits(first: 0, filters: $ssmTested) {\n total\n }\n }\n filteredCases: cases {\n hits(first: 0, filters: $geneCaseFilter) {\n total\n }\n }\n cnvCases: cases {\n hits(first: 0, filters: $cnvTested) {\n total\n }\n }\n genes {\n hits(first: $genesTable_size, offset: $genesTable_offset, filters: $genesTable_filters, score: $score) {\n total\n edges {\n node {\n id\n numCases: score\n symbol\n name\n cytoband\n biotype\n gene_id\n is_cancer_gene_census\n ssm_case: case {\n hits(first: 0, filters: $ssmCase) {\n total\n }\n }\n cnv_case: case {\n hits(first: 0, filters: $cnvTested) {\n total\n }\n }\n case_cnv_gain: case {\n hits(first: 0, filters: $cnvGainFilters) {\n total\n }\n }\n case_cnv_loss: case {\n hits(first: 0, filters: $cnvLossFilters) {\n total\n }\n }\n }\n }\n }\n }\n }\n }\n}\n",getVariables:e=>{const t={genesTable_filters:{op:"and",content:[]},genesTable_size:e.maxGenes||50,genesTable_offset:0,score:"case.project.project_id",ssmCase:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}},{op:"NOT",content:{field:"genes.case.ssm.observation.observation_id",value:"MISSING"}}]},geneCaseFilter:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},ssmTested:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},cnvTested:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"}]},cnvGainFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Gain"]},op:"in"}]},cnvLossFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Loss"]},op:"in"}]}};return e.filter0&&(t.genesTable_filters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.geneCaseFilter.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvTested.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvGainFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvLossFilters.content.push(JSON.parse(JSON.stringify(e.filter0)))),"CGC"==e.geneFilter&&(t.genesTable_filters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.geneCaseFilter.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvTested.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvGainFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvLossFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"})),t}},u={query:"\n query GenesTable(\n $caseFilters: FiltersArgument\n $genesTable_filters: FiltersArgument\n $genesTable_size: Int\n $genesTable_offset: Int\n $score: String\n $ssmCase: FiltersArgument\n $geneCaseFilter: FiltersArgument\n $ssmTested: FiltersArgument\n $cnvTested: FiltersArgument\n $cnvGainFilters: FiltersArgument\n $cnvLossFilters: FiltersArgument\n $sort: [Sort]\n ) {\n genesTableViewer: viewer {\n explore {\n cases {\n hits(first: 0, case_filters: $ssmTested) {\n total\n }\n }\n filteredCases: cases {\n hits(first: 0, case_filters: $geneCaseFilter) {\n total\n }\n }\n cnvCases: cases {\n hits(first: 0, case_filters: $cnvTested) {\n total\n }\n }\n genes {\n hits(\n first: $genesTable_size\n offset: $genesTable_offset\n filters: $genesTable_filters\n case_filters: $caseFilters\n score: $score\n sort: $sort\n ) {\n total\n edges {\n node {\n id\n numCases: score\n symbol\n name\n cytoband\n biotype\n gene_id\n is_cancer_gene_census\n ssm_case: case {\n hits(first: 0, filters: $ssmCase) {\n total\n }\n }\n cnv_case: case {\n hits(first: 0, filters: $cnvTested) {\n total\n }\n }\n case_cnv_gain: case {\n hits(first: 0, filters: $cnvGainFilters) {\n total\n }\n }\n case_cnv_loss: case {\n hits(first: 0, filters: $cnvLossFilters) {\n total\n }\n }\n }\n }\n }\n }\n }\n }\n }",getVariables:e=>{const t={caseFilters:{op:"and",content:[]},genesTable_filters:{op:"and",content:[]},genesTable_size:e.maxGenes||50,genesTable_offset:0,score:"case.project.project_id",ssmCase:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}},{op:"NOT",content:{field:"genes.case.ssm.observation.observation_id",value:"MISSING"}}]},geneCaseFilter:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},ssmTested:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},cnvTested:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"}]},cnvGainFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Gain"]},op:"in"}]},cnvLossFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Loss"]},op:"in"}]}};return e.filter0&&(t.caseFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.geneCaseFilter.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvLossFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvGainFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvTested.content.push(JSON.parse(JSON.stringify(e.filter0)))),"CGC"==e.geneFilter&&(t.genesTable_filters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvLossFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvGainFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"})),t}}},3202:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(4065);function r({genomes:e}){return(t,n)=>{try{t.query;const r=e[t.query.genome];if(!r)throw"invalid genome name";const o=(0,s.S)(r,t.query);n.send(o)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}const o={endpoint:"genelookup",methods:{get:{init:r,request:{typeId:"GeneLookupRequest"},response:{typeId:"GeneLookupResponse"},examples:[{request:{body:{input:"kr",genome:"hg38-test"}},response:{header:{status:200},body:{hits:["KRAS"]}}}]},post:{alternativeFor:"get",init:r}}}},1746:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2062);const r={endpoint:"healthcheck",methods:{get:{init:({genomes:e})=>async(t,n)=>{try{const t=await(0,s.W)(e);n.send(t)}catch(e){n.send({status:"error",error:e.message||e})}},request:{typeId:null},response:{typeId:"HealthCheckResponse"}}}}},3932:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>c});var s=n(3345),r=n(2081),o=n(4521),i=n.n(o),a=n(334),l=n.n(a);const c={endpoint:"hicdata",methods:{get:{init:u,request:{typeId:"HicdataRequest"},response:{typeId:"HicdataResponse"}},post:{alternativeFor:"get",init:u}}};function u(){return async(e,t)=>{try{const n=await function(e){return new Promise(((t,n)=>{const[o,a,c]=(0,s.ZX)({query:e});o&&n({error:"illegal file name"});const u=["log(oe)"==e.matrixType?"oe":e.matrixType?e.matrixType:"observed",e.nmeth||"NONE",a,e.pos1,e.pos2,e.isfrag?"FRAG":"BP",e.resolution],f=(0,r.spawn)(l().hicstraw,u),d=i().createInterface({input:f.stdout}),p=[],m=[];let h=0,g=0;d.on("line",(t=>{const n=t.split("\t");if(3!=n.length)return void h++;const s=Number.parseInt(n[0]),r=Number.parseInt(n[1]),o="log(oe)"==e.matrixType?Math.log(Number.parseFloat(n[2])):Number.parseFloat(n[2]);Number.isNaN(s)||Number.isNaN(r)||Number.isNaN(o)?g++:null!=e.mincutoff&&o<=e.mincutoff||p.push([s,r,o])})),f.stderr.on("data",(e=>m.push(e))),f.on("close",(()=>{const e=m.join("");e&&n({error:e}),h&&n({error:h+" lines have other than 3 fields"}),g&&n({error:g+" lines have non-numerical values in any of the 3 fields"}),t({items:p})}))}))}(e.query);t.send(n)}catch(e){t.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},6310:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>u});var s=n(3345),r=n(7147),o=n.n(r),i=n(6464),a=n.n(i),l=n(6452),c=n.n(l);const u={endpoint:"hicstat",methods:{get:{init:f,request:{typeId:"HicstatRequest"},response:{typeId:"HicstatResponse"},examples:[{request:{body:{genome:"hg19",file:"proteinpaint_demo/hg19/hic/hic_demo.hic",embedder:"localhost"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:f}}};function f(){return async(e,t)=>{try{const[n,r,i]=(0,s.ZX)(e);if(n)throw"illegal file name";i||await(0,s.Ic)(r);const l=await async function(e,t){const n={},s=t?await S(e,0,32e3):await N(e,0,32e3),r=new DataView(s);let i=0;if("HIC"!==A())throw Error("Unsupported hic file");const l=C();if(7!==l&&8!==l&&9!=l)throw Error("Unsupported hic version: "+l);n.version=l;const u=Number(j());let f=[];const d=1e5;if(8==l||7==l){let t=await q(e,u,d);const n=t.getInt32(0,!0);n>0&&(t=await q(e,u+n+4,d),f=await x(t,u+n+4))}const p=A();if(n["Genome ID"]=p,9==l){const t=Number(j()),n=Number(j());if(t>0&&n>0){const s=await q(e,t,n);f=await x(s,0)}}const m={},h=C();let g=0;for(;g!==h;)m[A()]=A(),g++;n.Chromosomes={},n.chrorder=[];const y=C();let b=0;for(;b!==y;){const e=A();n.chrorder.push(e),n.Chromosomes[e]=7==l||8==l?C():j(),b++}n["Base pair-delimited resolutions"]=[];const v=C();let w=0;for(;w!==v;){const e=C();n["Base pair-delimited resolutions"].push(e),w++}n["Fragment-delimited resolutions"]=[];const _=C();let k=0;for(;k!==_;){const e=C();n["Fragment-delimited resolutions"].push(e),k++}return BigInt.prototype.toJSON||Object.defineProperty(BigInt.prototype,"toJSON",{get(){return()=>String(this)}}),n.normalization=f,n;async function q(e,n,s){const r=t?await S(e,n,s):await N(e,n,s);return new DataView(r)}async function x(t,n){const s=Date.now();let r=[];const o=t.getInt32(0,!0);let i=4;for(let e=1;e<=o;e++){let e=await f("string");r.push(e),8==l||7==l?(e=await f("string"),c(4),c(8*await f("int32")),c(12*await f("int32"))):9==l&&(i+=4,e=await f("string"),i+=20)}r=[...new Set(r)];const a=Date.now()-s;return console.log(`Read normalization on ${e} on ${a/1e3} seconds`),r;async function c(e){i+e>d&&u(),i+=e}async function u(){t=await q(e,n+i,d),n+=i,i=0}async function f(e){let n;if("string"==e){let e,s="";for(;i<t.byteLength&&0!=(e=t.getUint8(i++));)i>d&&await u(),s+=String.fromCharCode(e);n=s}else{if("int32"!=e)throw"No value assigned [server/src/hicstat.ts getViewValue()]";if(i<0)return;i+4>t.byteLength&&await u(),n=t.getInt32(i,!0),i+=4}return n}}async function N(e,t,n){const s=a().promisify(o().open),r=a().promisify(o().read),i=Buffer.alloc(n),l=await s(e,"r"),c=await r(l,i,0,n,t);o().close(l,(function(e){return e}));const u=c.buffer;return u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength)}async function S(e,t,n){try{const s=t+"-"+(t+n-1);return(await c()(e,{headers:{Range:"bytes="+s}}).buffer()).buffer}catch(e){throw console.log(e.response),"error reading file, check file details"}}function A(){let e,t="";for(;0!=(e=r.getUint8(i++));)t+=String.fromCharCode(e);return t}function C(){const e=r.getInt32(i,!0);return i+=4,e}function j(){const e=r.getBigInt64(i,!0);return i+=8,e}}(r,i);t.send({out:l})}catch(e){t.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},5852:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(938),r=n(2974);const o={endpoint:"termdb/categories",methods:{get:{init:i,request:{typeId:"getcategoriesRequest"},response:{typeId:"getcategoriesResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getcategories:1,tid:"diaggrp",term1_q:{isAtomic:!0,hiddenValues:{},type:"values",groupsetting:{disabled:!0},mode:"discrete"},filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:i}}};function i({genomes:e}){return async(t,n)=>{const o=t.query;try{const i=e[t.query.genome];if(!i)throw"invalid genome name";const l=i.datasets[t.query.dslabel];if(!l)throw"invalid dataset name";const c=l.cohort.termdb;if(!c)throw"invalid termdb object";await async function(e,t,n,o,i){if(!e.tid)throw".tid missing";const l="geneVariant"==e.type?{name:e.tid,type:"geneVariant",isleaf:!0}:n.q.termjsonByOneid(e.tid),c={filter:e.filter,terms:"geneVariant"==e.type?[{term:l,q:{isAtomic:!0}}]:[{id:e.tid,term:l,q:e.term1_q||a(l,e)}],currentGeneNames:e.currentGeneNames,rglst:e.rglst},u=await(0,r.Yu)(c,o,i);if(u.error)throw u.error;const f=[];if("geneVariant"==e.type){const t=u.samples,n=new Map;if(o.assayAvailability?.byDt)for(const[e,t]of Object.entries(o.assayAvailability.byDt))t.byOrigin&&n.set(parseInt(e),{byOrigin:{germline:{},somatic:{}}});const s=new Set;for(const[r,o]of Object.entries(t)){const t=o[e.tid].values;s.clear();for(const e of t){n.has(e.dt)||n.set(e.dt,{});const t=n.get(e.dt);t.byOrigin?(t.byOrigin[e.origin][e.class]||(t.byOrigin[e.origin][e.class]=1,s.add(`${e.dt} ${e.origin} ${e.class}`)),s.has(`${e.dt} ${e.origin} ${e.class}`)||(s.add(`${e.dt} ${e.origin} ${e.class}`),t.byOrigin[e.origin][e.class]+=1)):(t[e.class]||(s.add(`${e.dt} ${e.class}`),t[e.class]=1),s.has(`${e.dt} ${e.class}`)||(s.add(`${e.dt} ${e.class}`),t[e.class]+=1))}}for(const[e,t]of n)f.push({dt:e,classes:t})}else{const t=new Map;for(const n in u.samples){const s=u.samples[n][e.tid];s&&("key"in s&&t.set(s.key,1+(t.get(s.key)||0)))}for(const[n,s]of t)f.push({samplecount:s,key:n,label:u.refs?.byTermId?.[e.tid]?.events?.find((e=>e.event===n)).label||l?.values?.[n]?.label||n})}const d=(0,s.Tt)(l,u.refs?.byTermId?.[e.tid]?.bins||[],u.refs?.byTermId?.[e.tid]?.events,e.term1_q);d.length&&f.sort(((e,t)=>d.indexOf(e.label)-d.indexOf(t.label)));t.send({lst:f,orderedLabels:d})}(o,n,c,l,i)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}function a(e,t){if("categorical"==e.type)return{};if("survival"==e.type)return{};if("integer"==e.type||"float"==e.type)return e.bins.default;if("condition"==e.type)return{mode:t.mode,breaks:t.breaks,bar_by_grade:t.bar_by_grade,bar_by_children:t.bar_by_children,value_by_max_grade:t.value_by_max_grade,value_by_most_recent:t.value_by_most_recent,value_by_computable_grade:t.value_by_computable_grade};if("geneVariant"==e.type)return{};throw"unknown term type"}},4924:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>m,validate_query_geneExpression:()=>g});var s=n(1017),r=n.n(s),o=n(7147),i=n.n(o),a=n(9157),l=n(3345),c=n(334),u=n.n(c),f=n(4555),d=n(901),p=n(2273);const m={endpoint:"termdb/cluster",methods:{all:{init:function({genomes:e}){return async(t,n)=>{const s=t.query;let o;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(n.__gdc&&!n.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";if(s.dataType!=p.dtgeneexpression)throw"unknown q.dataType "+s.dataType;if(!n.queries?.geneExpression)throw"no geneExpression data on this dataset";o=await async function(e,t){const{gene2sample2value:n,byTermId:s,bySampleId:o}=await t.queries.geneExpression.get(e);if(0==n.size)throw"no data";if(1==n.size){const e=Array.from(n.keys())[0];return{gene:e,data:n.get(e)}}const c=Date.now(),f=await async function(e,t){const n=new Set;for(const t of e.values()){for(const e in t)n.add(e);break}const s={matrix:[],row_names:[],col_names:[...n],cluster_method:t.clusterMethod,plot_image:!1};for(const[t,n]of e){s.row_names.push(t);const e=[];for(const t of s.col_names)e.push(n[t]||0);s.matrix.push(h(e))}const o=r().join(u().cachedir,Math.random().toString()+".json");await l.Sf(o,JSON.stringify(s));const c=JSON.parse(await(0,a.default)(r().join(u().binpath,"utils/hclust.R"),[],[o]));await i().promises.unlink(o);const f=c.RowOrder.map((e=>s.row_names.indexOf(e.name))),d=c.ColOrder.map((e=>s.col_names.indexOf(e.name))),p=[];for(const e of f){const t=[];for(const n of d)t.push(s.matrix[e][n]);p.push(t)}return{row:{merge:c.RowMerge,height:c.RowHeight,order:c.RowOrder,inputOrder:s.row_names},col:{merge:c.ColumnMerge,height:c.ColumnHeight,order:c.ColOrder,inputOrder:s.col_names},matrix:p}}(n,e);u().debugmode&&console.log("clustering done:",Date.now()-c,"ms");return{clustering:f,byTermId:s,bySampleId:o}}(s,n)}catch(e){e.stack&&console.log(e.stack),o={status:e.status||400,error:e.message||e}}n.send(o)}},request:{typeId:"TermdbClusterRequest"},response:{typeId:"TermdbClusterResponse"}}}};function h(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,n=Math.sqrt(e.reduce(((e,n)=>e+Math.pow(n-t,2)),0)/e.length);return 0==n?e:e.map((e=>(e-t)/n))}async function g(e,t){const n=e.queries.geneExpression;if(n)if("gdcapi"!=n.src){if("native"!=n.src)throw"unknown queries.geneExpression.src";await async function(e,t,n){e.file.startsWith(u().tpmasterdir)||(e.file=r().join(u().tpmasterdir,e.file));e.samples||(e.samples=[]);await l.LC(e.file),e.nochr=await l.Jy(e.file,null,n),e.samples=[];{const n=await l.ZD(e.file);if(!n[0])throw"header line missing from "+e.file;const s=n[0].split("\t");if("#chr\tstart\tstop\tgene"!=s.slice(0,4).join("\t"))throw"header line has wrong content for columns 1-4";for(let n=4;n<s.length;n++){const r=t.cohort.termdb.q.sampleName2id(s[n]);if(null==r)throw"queries.geneExpression: unknown sample from header: "+s[n];e.samples.push(r)}console.log(e.samples.length,"samples from geneExpression of",t.label)}e.get=async s=>{const r=await(0,d.T)(s,e.samples,t);if(0==r?.size)return{gene2sample2value:new Set,byTermId:{},bySampleId:{}};const o={},i=e.samples||[];if(r)for(const e of r)o[e]={label:t.cohort.termdb.q.id2sampleName(e)};else for(const e of i)o[e]={label:t.cohort.termdb.q.id2sampleName(e)};const a=new Map;for(const t of s.genes){if(!t.gene)continue;if(!t.chr){const e=n.genedb.getjsonbyname.all(t.gene);if(0==e.length)continue;const s=JSON.parse(e.find((e=>e.isdefault)).genemodel||e[0].genemodel);t.start=s.start,t.stop=s.stop,t.chr=s.chr}const s={};await l.UE({args:[e.file,(e.nochr?t.chr?.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],callback:e=>{const n=e.split("\t");if(n[3].toLowerCase()==t.gene.toLowerCase())for(let e=4;e<n.length;e++){const t=i[e-4];if(r&&!r.has(t))continue;if(!n[e])continue;const o=Number(n[e]);if(Number.isNaN(o))throw"exp value not number";s[t]=o}}}),Object.keys(s).length&&a.set(t.gene,s)}return{gene2sample2value:a,byTermId:{},bySampleId:o}}}(n,e,t)}else(0,f.eG)(e,t)}},2262:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(8907),r=n(8615);const o={endpoint:"termdb/descrstats",methods:{all:{init:function({genomes:e}){return async(t,n)=>{const o=t.query;try{const i=e[t.query.genome];if(!i)throw"invalid genome name";const a=i.datasets[t.query.dslabel];if(!a)throw"invalid dataset name";if(!a.cohort.termdb)throw"invalid termdb object";await async function(e,t,n){const o=n.cohort.termdb.q.termjsonByOneid(e.tid);if(!o)throw"invalid termid";if("float"!=o.type&&"integer"!=o.type)throw"not numerical term";const i=await(0,s.J4)({ds:n,key:e.tid,filter:e.filter}),a=[];for(const{value:t}of i)o.values?.[t]?.uncomputable||"log"===e.settings?.violin?.unit&&0===t||a.push(t);t.send((0,r.Z)(a))}(o,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}},request:{typeId:"getdescrstatsRequest"},response:{typeId:"getdescrstatsResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",tid:"hrtavg",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]}}}},5961:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(8907);const r={endpoint:"termdb/numericcategories",methods:{get:{init:o,request:{typeId:"getnumericcategoriesRequest"},response:{typeId:"getnumericcategoriesResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",tid:"aaclassic_5",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const i=o.datasets[t.query.dslabel];if(!i)throw"invalid dataset name";const a=i.cohort.termdb;if(!a)throw"invalid termdb object";await async function(e,t,n,r){if(!e.tid)throw".tid missing";n.q.termjsonByOneid(e.tid);const o={ds:r,term_id:e.tid,filter:e.filter},i=await s.tt(o);t.send({lst:i})}(r,n,a,i)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},2630:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(8907),r=n(7027);const o={endpoint:"termdb/getpercentile",methods:{get:{init:i,request:{typeId:"getpercentileRequest"},response:{typeId:"getpercentileResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getpercentile:[50],tid:"agedx",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:i}}};function i({genomes:e}){return async(t,n)=>{const o=t.query;try{const i=e[t.query.genome];if(!i)throw"invalid genome name";const a=i.datasets[t.query.dslabel];if(!a)throw"invalid dataset name";await async function(e,t,n){const o=n.cohort.termdb.q.termjsonByOneid(e.tid);if(!o)throw"invalid termid";if("float"!=o.type&&"integer"!=o.type)throw"not numerical term";const i=e.getpercentile,a=[],l=[],c=await s.J4({ds:n,key:e.tid,filter:e.filter?"string"==typeof e.filter?JSON.parse(e.filter):e.filter:null});for(const{value:e}of c)o.values&&o.values[e]&&o.values[e].uncomputable||o.skip0forPercentile&&0==e||l.push(Number(e));for(const e of i){const t=(0,r.Z)(l,e);a.push(t)}t.send({values:a})}(o,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},7095:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2826);const r={endpoint:"termdb/rootterm",methods:{get:{init:o,request:{typeId:"getroottermRequest"},response:{typeId:"getroottermResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",default_rootterm:1,cohortValues:"ABC"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;r.cohortValues&&r.cohortValues,r.treeFilter&&r.treeFilter;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const[i,a]=(0,s.pq)(o,r);if(!i)throw"invalid dataset name";if(!a)throw"invalid termdb object";await async function(e,t,n){const s=e.cohortValues?e.cohortValues:"",r=e.treeFilter?e.treeFilter:"";t.send({lst:await n.q.getRootTerms(s,r)})}(r,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},3967:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2826);const r={endpoint:"termdb/termchildren",methods:{get:{init:o,request:{typeId:"gettermchildrenRequest"},response:{typeId:"gettermchildrenResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",get_children:1,cohortValues:"ABC",tid:"GO:0000001"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const[i,a]=await(0,s.pq)(o,r);if(!i)throw"invalid dataset name";if(!a)throw"invalid termdb object";await async function(e,t,n){if(!e.tid)throw"no parent term id";const r=e.cohortValues?e.cohortValues:"",o=e.treeFilter?e.treeFilter:"",i=await n.q.getTermChildren(e.tid,r,o);t.send({lst:i.map(s.iK)})}(r,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},3677:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f,validate_query_singleSampleMutation:()=>d});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(334),c=n.n(l),u=n(4555);const f={endpoint:"termdb/singleSampleMutation",methods:{get:{init:function({genomes:e}){return async(t,n)=>{const s=t.query;let r;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleSampleMutation)throw"not supported on this dataset";r=await n.queries.singleSampleMutation.get(s)}catch(e){e.stack&&console.log(e.stack),r={status:e.status||400,error:e.message||e}}n.send(r)}},request:{typeId:"TermdbSingleSampleMutationRequest"},response:{typeId:"TermdbSingleSampleMutationResponse"}}}};async function d(e,t){const n=e.queries.singleSampleMutation;if(n)if("gdcapi"==n.src)(0,u.sV)(e,t);else{if("native"!=n.src)throw"unknown singleSampleMutation.src";n.get=async t=>{let s=t.sample;if(e.cohort?.termdb?.q?.sampleName2id&&(s=e.cohort.termdb.q.sampleName2id(t.sample),null==s))return[];const o=i().join(c().tpmasterdir,n.folder,s.toString());try{await r().promises.stat(o)}catch(e){if("EACCES"==e.code)throw"cannot read file, permission denied";if("ENOENT"==e.code)throw"no data for this sample";throw"failed to load data"}const l=await(0,a.b5)(o);return{mlst:JSON.parse(l)}}}}},5707:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>s});const s={endpoint:"termdb/singlecellData",methods:{get:{init:r,request:{typeId:"TermdbSinglecellDataRequest"},response:{typeId:"TermdbSinglecellDataResponse"}},post:{alternativeFor:"get",init:r}}};function r({genomes:e}){return async(t,n)=>{const s=t.query;let r;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleCell)throw"no singlecell data on this dataset";r=await n.queries.singleCell.data.get(s)}catch(e){e.stack&&console.log(e),r={status:e.status||400,error:e.message||e}}n.send(r)}}},7934:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f,validate_query_singleCell:()=>p});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(334),c=n.n(l),u=n(4555);const f={endpoint:"termdb/singlecellSamples",methods:{get:{init:d,request:{typeId:"TermdbSinglecellsamplesRequest"},response:{typeId:"TermdbSinglecellsamplesResponse"}},post:{alternativeFor:"get",init:d}}};function d({genomes:e}){return async(t,n)=>{const s=t.query;let r;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleCell)throw"no singlecell data on this dataset";r=await n.queries.singleCell.samples.get(s)}catch(e){e.stack&&console.log(e.stack),r={status:e.status||400,error:e.message||e}}n.send(r)}}async function p(e,t){const n=e.queries.singleCell;if(n){if("gdcapi"==n.samples.src)(0,u.z7)(e,t);else{if("native"!=n.samples.src)throw"unknown singleCell.samples.src";!async function(e,t){const n=t.cohort.termdb.q.getAllValues4term(e.isSampleTerm);if(0==n.size)throw"no samples found that are identified by isSampleTerm";const s=[];for(const e of n.keys())s.push({sample:t.cohort.termdb.q.id2sampleName(e),sampleid:e});if(e.sampleColumns)for(const n of e.sampleColumns){const e=t.cohort.termdb.q.getAllValues4term(n.termid);for(const t of s)e.has(t.sampleid)&&(t[n.termid]=e.get(t.sampleid))}for(const e of s)delete e.sampleid;e.get=()=>({samples:s})}(n.samples,e)}if("gdcapi"==n.data.src)(0,u.r8)(e,t);else{if("native"!=n.data.src)throw"unknown singleCell.data.src";!function(e,t){const n=new Set;for(const t of e.plots){if(n.has(t.name))throw"duplicate plot.name";n.add(t.name)}const s=[];for(const n of e.termIds){const e=t.cohort.termdb.q.termjsonByOneid(n);if(!e)throw"invalid term id from queries.singleCell.data.termIds[]";s.push(e)}e.get=async t=>{try{const n={};for(const t of e.termIds)n[t]={};const o=[];for(const s of e.plots){const l=i().join(c().tpmasterdir,s.folder,t.sample+s.fileSuffix);try{await r().promises.stat(l)}catch(e){if("ENOENT"==e.code)continue;if("EACCES"==e.code)throw"cannot read file, permission denied";throw"failed to load sc data file"}const u=(await(0,a.b5)(l)).trim().split("\n"),f=[];for(let t=1;t<u.length;t++){const r=u[t].split("\t"),o=r[0],i=Number(r[s.coordsColumns.x]),a=Number(r[s.coordsColumns.y]),l=r[s.colorColumn?.index]||"";if(!o)throw"cell id missing";if(!Number.isFinite(i)||!Number.isFinite(a))throw"x/y not number";f.push({cellId:o,x:i,y:a,category:l});for(const t of e.termIds)n[t][o]=r[1]}o.push({name:s.name,cells:f,colorBy:s.colorColumn?.name,colorMap:s.colorMap})}return 0==o.length?{nodata:!0}:{plots:o,terms:s,tid2cellvalue:n}}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}}(n.data,e)}}}},605:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2826);const r={endpoint:"termdb/termsbyids",methods:{get:{init:o,request:{typeId:"gettermsbyidsRequest"},response:{typeId:"gettermsbyidsResponse"}},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const i=o.datasets[t.query.dslabel];if(!i)throw"invalid dataset name";const a=i.cohort.termdb;if(!a)throw"invalid termdb object";await async function(e,t,n){const r={};for(const t of e.ids){const e=n.q.termjsonByOneid(t);e&&("categorical"!=e.type||e.values||e.groupsetting?.inuse||(e.values={},e.samplecount={})),r[t]=e?(0,s.iK)(e):void 0}t.send({terms:r})}(r,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},5057:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>d,validate_query_TopVariablyExpressedGenes:()=>p});var s=n(4555),r=n(1017),o=n.n(r),i=n(1271),a=n(6452),l=n.n(a),c=n(334),u=n.n(c),f=n(8907);const d={endpoint:"termdb/topVariablyExpressedGenes",methods:{all:{init:function({genomes:e}){return async(t,n)=>{try{const s=t.query,r=e[s.genome];if(!r)throw"invalid genome";const o=r.datasets?.[s.dslabel];if(!o)throw"invalid dslabel";if(!o.queries?.topVariablyExpressedGenes)throw"not supported on dataset";const i=Date.now(),a=await o.queries.topVariablyExpressedGenes.getGenes(s);u().debugmode&&console.log("topVariablyExpressedGenes",Date.now()-i,"ms"),n.send({genes:a})}catch(e){n.send({status:"error",error:e.message||e})}}},request:{typeId:"TermdbTopVariablyExpressedGenesRequest"},response:{typeId:"TermdbTopVariablyExpressedGenesResponse"}}}};function p(e,t){const n=e.queries.topVariablyExpressedGenes;if(n)if("gdcapi"==n.src)!function(e,t){function n(e,n){return{case_ids:n,gene_ids:m(t),selection_size:Number(e.maxGenes)}}e.queries.topVariablyExpressedGenes.getGenes=async r=>{if(u().features.gdcGenes)return console.log("!!GDC!! using serverconfig.features.gdcGenes[]"),u().features.gdcGenes;if(!e.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";const i=await(0,s.Z5)(r,e);if(0==i.length)return[];const{host:a,headers:c}=e.getHostHeaders(r),f=o().join(a.geneExp,"/gene_expression/gene_selection");try{const e=await l().post(f,{headers:c,body:JSON.stringify(n(r,i))}),s=JSON.parse(e.body),o=[];if(!Array.isArray(s.gene_selection))throw"re.gene_selection[] is not array";for(const e of s.gene_selection)if(e.gene_id&&"string"==typeof e.gene_id){const n=t.genedb.getNameByAlias.get(e.gene_id);n&&o.push(n.name)}else{if(!e.symbol||"string"!=typeof e.symbol)throw"one of re.gene_selection[] is missing both gene_id and symbol";o.push(e.symbol)}return o}catch(e){throw console.log(e.stack||e),e}}}(e,t);else{if("native"!=n.src)throw"unknown topVariablyExpressedGenes.src";!function(e,t){const n=e.queries.geneExpression;if(!n)throw"topVariablyExpressedGenes query given but geneExpression missing";if("native"!=n.src)throw"topVariablyExpressedGenes is native but geneExpression.src is not native";e.queries.topVariablyExpressedGenes.getGenes=async t=>{const s=[];if(t.filter){const r=await(0,f.cf)(t.filter,e);for(const t of r)if(n.samples.includes(t.id)){const n=e.cohort.termdb.q.id2sampleName(t.id);if(!n)throw"sample id cannot convert to string name";s.push(n)}}else for(const t of n.samples){const n=e.cohort.termdb.q.id2sampleName(t.id);if(!n)throw"sample id cannot convert to string name";s.push(n)}const r=await async function(e,t,n,s){const r={input_file:n,samples:s.join(","),filter_extreme_values:!0,num_genes:Number(e.maxGenes),param:"var"},o=(await(0,i.run_rust)("topGeneByExpressionVariance",JSON.stringify(r))).split("\n");let a;for(const e of o)e.includes("output_json:")?a=JSON.parse(e.replace("output_json:","")):console.log(e);return a.map((e=>e.gene_symbol))}(t,0,n.file,s);return r}}(e)}}function m(e){const t=[];for(const n of e.geneset[0].lst){const s=e.genedb.getAliasByName.all(n);if(s)for(const e of s)e.alias.startsWith("ENSG")&&t.push(e.alias)}return t}},2386:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>v});var s=n(7147),r=n(1868),o=n(334),i=n.n(o),a=n(9157),l=n(1017),c=n.n(l),u=n(3345),f=n(2974),d=n(6718),p=n(7011),m=n(8615),h=n(938);async function g(e,t,n,o){const l=n.cohort.termdb.q.termjsonByOneid(e.termid);if(!l)throw".termid invalid";if("integer"!=l.type&&"float"!=l.type)throw"term type is not integer/float.";const g=[{id:e.termid,term:l,q:{mode:"continuous"}}];e.divideTw&&(null===e.divideTw||void 0===e.divideTw||"object"!=typeof e.divideTw||"id"in e.divideTw||(e.divideTw.id=e.divideTw.term.name,e.divideTw.term.id=e.divideTw.term.name),g.push(e.divideTw),e.term2_q=e.divideTw.q);const v=await(0,f.Yu)({terms:g,filter:e.filter,currentGeneNames:e.currentGeneNames},n,o);if(v.error)throw v.error;e.divideTw&&v.refs.byTermId[e.divideTw?.id]&&(v.refs.byTermId[e.divideTw?.id].orderedLabels=(0,h.Tt)(e.divideTw,v.refs.byTermId[e.divideTw?.id]?.bins,void 0,e.divideTw.q)),e.scale&&function(e,t,n){if(!e.scale)return;const s=Number(e.scale);for(const[e,r]of Object.entries(t.samples))r[n.id]&&(n.values?.[r[n.id]?.value]?.uncomputable||(r[n.id].key=r[n.id].key/s,r[n.id].value=r[n.id].value/s))}(e,v,l);const w=function(e,t,n,s){const r="log"==e.unit,o=new Map;let i=1/0,a=-1/0;const l={};let c=0;for(const[e,u]of Object.entries(t.samples)){const e=u[n.id]?.value;if(Number.isFinite(e))if(n.values?.[e]?.uncomputable){const t=n.values[e].label;l[t]=(l[t]||0)+1}else if(r&&e<=0)c++;else if(i>e&&(i=e),a<e&&(a=e),"log"===r&&0===i&&(i=Math.max(i,e)),s){if(!u[s?.id])continue;if(s.term?.values?.[u[s.id]?.key]?.uncomputable){const e=s.term.values[u[s.id]?.value]?.label;l[e]=(l[e]||0)+1}o.has(u[s.id]?.key)||o.set(u[s.id]?.key,[]),o.get(u[s.id]?.key).push(e)}else o.has("All samples")||o.set("All samples",[]),o.get("All samples").push(e)}return{key2values:o,minMaxValues:{min:i,max:a},uncomputableValueObj:b(l),skipNonPositiveCount:c}}(e,v,l,e.divideTw),_=function(e,t,n){const s=n.divideTw,r={min:e.minMaxValues.min,max:e.minMaxValues.max,plots:[],pvalues:[],uncomputableValueObj:Object.keys(e.uncomputableValueObj).length>0?e.uncomputableValueObj:null};for(const[n,o]of function(e,t,n){const s=e.refs.byTermId[n?.term?.id]?.orderedLabels;return t=new Map([...t].sort(s?(e,t)=>s.indexOf(e[0])-s.indexOf(t[0]):"categorical"===n?.term?.type?(e,t)=>t[1].length-e[1].length:"condition"===n?.term?.type?(e,t)=>e[0]-t[0]:(e,t)=>e.toString().replace(/[^a-zA-Z0-9<]/g,"").localeCompare(t.toString().replace(/[^a-zA-Z0-9<]/g,""),void 0,{numeric:!0}))),t}(t,e.key2values,s))s?r.plots.push({label:s?.term?.values?.[n]?.label||n,values:o,seriesId:n,plotValueCount:o?.length,color:s?.term?.values?.[n]?.color||null,divideTwBins:y(s,t).has(n)?y(s,t).get(n):null,uncomputableValueObj:Object.keys(e.uncomputableValueObj).length>0?e.uncomputableValueObj:null}):r.plots.push({label:"All samples",values:o,plotValueCount:o.length});return r}(w,v,e);if(await async function(e,t){if(!e)return;const n=t.plots.length;if(n<2)return;const r=[];for(let e=0;e<n;e++){const s=t.plots[e].label,o=t.plots[e].values;for(let i=e+1;i<n;i++){const e=t.plots[i].label,n=t.plots[i].values;r.push({group1_id:s,group1_values:o,group2_id:e,group2_values:n})}}const o=c().join(i().cachedir,Math.random().toString()+".json");await(0,u.Sf)(o,JSON.stringify(r));const l=await(0,a.default)(c().join(i().binpath,"utils/wilcoxon.R"),[],[o]);(0,s.unlink)(o,(()=>{}));const f=JSON.parse(l);for(const e of f)null==e.pvalue||"null"==e.pvalue?t.pvalues.push([{value:e.group1_id},{value:e.group2_id},{html:"NA"}]):t.pvalues.push([{value:e.group1_id},{value:e.group2_id},{html:e.pvalue.toPrecision(4)}])}(e.divideTw,_),function(e,t,n){e.radius||(e.radius=5);if(e.radius<=0)throw"q.radius is not a number";e.radius=+e.radius;e.strokeWidth||(e.strokeWidth=.2);const s=4*e.radius;let o;const i="log"==e.unit;o=i?(0,r.p2C)().base(n.cohort.termdb.logscaleBase2?2:10).domain([t.min,t.max]).range("horizontal"===e.orientation?[0,e.svgw]:[e.svgw,0]):(0,r.BYU)().domain([t.min,t.max]).range("horizontal"===e.orientation?[0,e.svgw]:[e.svgw,0]);const[a,l]="horizontal"==e.orientation?[e.svgw*e.devicePixelRatio,s*e.devicePixelRatio]:[s*e.devicePixelRatio,e.svgw*e.devicePixelRatio],c=e.radius/e.devicePixelRatio,u=c*Math.PI;let f=0;for(const n of t.plots){const t=(0,d.createCanvas)(a,l),s=t.getContext("2d");s.strokeStyle="rgba(0,0,0,0.8)",s.lineWidth=e.strokeWidth/e.devicePixelRatio,s.globalAlpha=.5,s.fillStyle="#ffe6e6",1!=e.devicePixelRatio&&s.scale(e.devicePixelRatio,e.devicePixelRatio),"rug"===e.datasymbol?n.values.forEach((t=>{s.beginPath(),"horizontal"==e.orientation?(s.moveTo(+o(t),0),s.lineTo(+o(t),2*c)):(s.moveTo(0,+o(t)),s.lineTo(2*c,+o(t))),s.stroke()})):"bean"===e.datasymbol&&n.values.forEach((t=>{s.beginPath(),"horizontal"===e.orientation?s.arc(+o(t),e.radius,c,0,u):s.arc(e.radius,+o(t),c,0,u),s.fill(),s.stroke()})),n.src=t.toDataURL();const r=e.isKDE;n.density=(0,p.q)(o,n,r,e.ticks,e.bandwidth),n.summaryStats=(0,m.Z)(n.values),delete n.values}t.biggestBin=f}(e,_,n),!t)return _;t.send(_)}function y(e,t){const n=new Map,s=t.refs.byTermId[e?.term?.id]?.bins;if(s)for(const e of s)n.set(e.label,e);return n}function b(e){return Object.fromEntries(Object.entries(e).sort((([,e],[,t])=>e-t)))}const v={endpoint:"termdb/violin",methods:{get:{init:w,request:{typeId:"getViolinRequest"},response:{typeId:"getViolinResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",devicePixelRatio:2.200000047683716,maxThickness:150,screenThickness:1218,filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{id:"subcohort",type:"categorical"},values:[{key:"ABC",label:"ABC"}]}}]},svgw:227.27272234672367,orientation:"horizontal",datasymbol:"bean",radius:5,strokeWidth:.2,axisHeight:60,rightMargin:50,unit:"abs",termid:"agedx"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:w}}};function w({genomes:e}){return async(t,n)=>{t.query;try{const s=e[t.query.genome],r=s.datasets[t.query.dslabel];if(!s)throw"invalid genome name";const o=await g(t.query,null,r,s);n.send(o)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},6733:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for CNV";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");return-1==r?"gene missing from header":(n[r]="gene",r=s("cnv"),-1==r?"CNV missing from header":(n[r]="cnv",r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.cnv.header=n,t.cnv.loaded=!0,!1))}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.cnv.header.length;e++)i[n.cnv.header[e]]=o[e];if(!i.gene)return void n.cnv.badlines.push([e,"missing gene",o]);if(!i.cnv)return void n.cnv.badlines.push([e,"missing cnv value",o]);switch(i.cnv.toLowerCase()){case"amplification":case"gain":i.class=s.mclasscnvgain;break;case"deletion":case"loss":i.class=s.mclasscnvloss;break;case"loh":i.class=s.mclasscnvloh;break;default:n.cnv.badlines.push([e,"invalid cnv value: "+i.cnv,o]),i.class=null}if(!i.class)return;if(r.EJ(i,n,e,o,n.cnv.badlines))return;i.dt=s.dtcnv,n.good++;const a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}},5558:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for intragenic deletion";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");if(-1==r)return"gene missing from header";if(n[r]="gene",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r)return"isoform missing from header";if(n[r]="isoform",r=s("rnaposition"),-1!=r){if(n[r]="rnaposition",r=s("rnadellength"),-1==r)return"rnadellength is required when rnaPosition is used";n[r]="rnadellength"}if(r=s("chromosome","chr"),-1!=r){if(n[r]="chr",r=s("chr_start"),-1==r)return"chr_start is required when chr is used";if(n[r]="chrpos1",r=s("chr_stop"),-1==r)return"chr_stop is required when chr is used";n[r]="chrpos2"}return r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.del.header=n,t.del.loaded=!0,!1}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.del.header.length&&null!=o[e];e++)i[n.del.header[e]]=o[e];if(i.gene){if(i.rnaposition){let t=Number.parseInt(i.rnaposition);if(Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid rnaPosition value",o]);if(i.rnaposition=t,!i.rnadellength)return void n.del.badlines.push([e,"missing rnaDellength value",o]);if(t=Number.parseInt(i.rnadellength),Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid rnaDellength value",o]);i.rnadellength=t}if(i.chr){let t=Number.parseInt(i.chrpos1);if(Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid chr_start value",o]);if(i.chrpos1=t,t=Number.parseInt(i.chrpos2),Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid chr_stop value",o]);i.chrpos2=t}if(!r.EJ(i,n,e,o,n.del.badlines)){i.dt=s.dtdel,i.class=s.mclassdel,i.mname="DEL",n.good++;var a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}}else n.del.badlines.push([e,"missing gene",o])}},3602:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for ITD";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");if(-1==r)return"gene missing from header";if(n[r]="gene",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r)return"isoform missing from header";if(n[r]="isoform",r=s("rnaposition"),-1!=r){if(n[r]="rnaposition",r=s("rnaduplength"),-1==r)return"rnaduplength is required when rnaposition is present";n[r]="rnaduplength"}if(r=s("chromosome","chr"),-1!=r){if(n[r]="chr",r=s("chr_start"),-1==r)return"chr_start is required when chr is present";if(n[r]="chrpos1",r=s("chr_stop"),-1==r)return"chr_stop is required when chr is present";n[r]="chrpos2"}return r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.itd.header=n,t.itd.loaded=!0,!1}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.itd.header.length&&null!=o[e];e++)i[n.itd.header[e]]=o[e];if(i.gene){if(i.rnaposition){let t=Number.parseInt(i.rnaposition);if(Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid rnaPosition value",o]);if(i.rnaposition=t,!i.rnaduplength)return void n.itd.badlines.push([e,"missing rnaDuplength value",o]);if(t=Number.parseInt(i.rnaduplength),Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid rnaDuplength value",o]);i.rnaduplength=t}if(i.chr){let t=Number.parseInt(i.chrpos1);if(Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid chr_start value",o]);if(i.chrpos1=t,t=Number.parseInt(i.chrpos2),Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid chr_stop value",o]);i.chrpos2=t}if(!r.EJ(i,n,e,o,n.itd.badlines)){i.dt=s.dtitd,i.class=s.mclassitd,i.mname="ITD",n.good++;var a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}}else n.itd.badlines.push([e,"missing gene",o])}},8064:(e,t,n)=>{"use strict";n.d(t,{Dz:()=>r,EJ:()=>o});var s=n(2273);function r(e){if(!e)return null;const t={};for(const e in s.mclass)t[s.mclass[e].label.toUpperCase()]=e;return{genome:e,mclasslabel2key:t,data:{},sample2disease:{},patient2st:{},good:0,geneToUpper:!0,snv:{loaded:!1,header:null,badlines:[],missense:0,silent:0},svjson:{loaded:!1,header:null,badlines:[]},fusion:{loaded:!1,header:null,badlines:[],original:[]},sv:{loaded:!1,header:null,badlines:[],original:[]},cnv:{loaded:!1,header:null,badlines:[]},itd:{loaded:!1,header:null,badlines:[]},del:{loaded:!1,header:null,badlines:[]},truncation:{loaded:!1,header:null,badlines:[]}}}function o(e,t,n,r,o){let i=s.moriginsomatic;if(e.sampletype){switch(e.sampletype.toLowerCase()){case"relapse":i=s.moriginrelapse;break;case"germline":i=s.morigingermline}e.sample?e.patient||(e.patient=e.sample+" "+e.sampletype):e.patient&&(e.sample=e.patient+" "+e.sampletype)}else e.patient?e.sample?e.sampletype=e.sample:e.sample=e.sampletype=e.patient:e.sample&&(e.sampletype=e.sample);if(e.origin){switch(e.origin.toLowerCase()){case"r":case"relapse":i=s.moriginrelapse,e.isrim2=!0;break;case"g":case"germline":i=s.morigingermline,e.isrim1=!0;break;case"gp":case"germline pathogenic":i=s.morigingermlinepathogenic,e.isrim1=!0;break;case"gnp":case"germline nonpathogenic":case"germline non-pathogenic":i=s.morigingermlinenonpathogenic,e.isrim1=!0;break;case"s":case"somatic":case"diagnosis":i=s.moriginsomatic}}if(e.origin=i,!e.sample&&!e.patient)return;const a="no patient/individual name";if(e.patient?(t.patient2st[e.patient]||(t.patient2st[e.patient]={}),t.patient2st[e.patient][e.sampletype]=e.sample):(t.patient2st[a]||(t.patient2st[a]={}),t.patient2st[a][e.sampletype]=e.sample),e.sample&&e.disease)if(e.sample in t.sample2disease){if(e.disease!=t.sample2disease[e.sample])return t.snv.badlines.push([n,'conflict of disease types for sample "'+e.sample+'": '+e.disease+", "+t.sample2disease[e.sample],r]),!0}else t.sample2disease[e.sample]=e.disease;return!1}},5494:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for snv/indel";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("annovar_gene","annovar_sj_gene","gene","genename","gene_symbol","hugo_symbol");return-1==r?"gene missing from header":(n[r]="gene",r=s("annovar_aachange","amino_acid_change","annovar_sj_aachange","aachange","protein_change","variant"),-1==r?"amino_acid_change missing from header":(n[r]="mname",r=s("annovar_class","class","mclass","variant_class","variant_classification","annovar_sj_class"),-1==r?"variant_class missing from header":(n[r]="class",r=s("chromosome","chr"),-1==r?"chromosome missing from header":(n[r]="chr",r=s("wu_hg19_pos","start","start_position","chr_position","position"),-1==r?"start missing from header":(n[r]="pos",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r?"isoform missing from header":(n[r]="isoform",r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("quantitative_measurements"),-1!=r&&(n[r]="qmset"),r=s("mutant_reads_in_case","mutant_in_tumor","tumor_readcount_alt"),-1!=r&&(n[r]="maf_tumor_v1"),r=s("total_reads_in_case","total_in_tumor","tumor_readcount_total"),-1!=r&&(n[r]="maf_tumor_v2"),r=s("mutant_reads_in_control","mutant_in_normal","normal_readcount_alt"),-1!=r&&(n[r]="maf_normal_v1"),r=s("total_reads_in_control","total_in_normal","normal_readcount_total"),-1!=r&&(n[r]="maf_normal_v2"),r=s("cdna_change"),-1!=r&&(n[r]="cdna_change"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("cancer","disease","diagnosis"),-1!=r&&(n[r]="disease"),t.snv.header=n,t.snv.loaded=!0,!1))))))}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.snv.header.length&&null!=o[e];e++)i[n.snv.header[e]]=o[e];if(!i.gene)return void n.snv.badlines.push([e,"missing gene",o]);if("UNKNOWN"==i.gene.toUpperCase())return void n.snv.badlines.push([e,"gene name is UNKNOWN",o]);if(!i.isoform)return void n.snv.badlines.push([e,"missing isoform",o]);if(i.mname)0==i.mname.indexOf("p.")&&(i.mname=i.mname.replace(/^p\./,""));else if(i.mname=i.cdna_change,!i.mname)return void n.snv.badlines.push([e,"missing amino acid change",o]);if(!i.class)return void n.snv.badlines.push([e,"missing mutation class",o]);let a=n.mclasslabel2key[i.class.toUpperCase()];if(a)i.class=a;else{if(a=s.mclasstester(i.class),!a)return void n.snv.badlines.push([e,"wrong mutation class: "+i.class,o]);i.class=a}if(r.EJ(i,n,e,o,n.snv.badlines))return;if(!i.chr)return void n.snv.badlines.push([e,"missing chromosome",o]);if(0!=i.chr.toLowerCase().indexOf("chr")&&(i.chr="chr"+i.chr),!i.pos)return void n.snv.badlines.push([e,"missing chromosome position",o]);const l=Number.parseInt(i.pos);if(Number.isNaN(l))return void n.snv.badlines.push([e,"invalid chromosome position",o]);if(i.pos=l-1,null!=i.maf_tumor_v2&&null!=i.maf_tumor_v1){if(""==i.maf_tumor_v2);else{let t=Number.parseInt(i.maf_tumor_v1),s=Number.parseInt(i.maf_tumor_v2);if(Number.isNaN(t)||Number.isNaN(s))return void n.snv.badlines.push([e,"invalid maf_tumor mutant and/or total read count",o]);i.maf_tumor={f:t/s,v1:t,v2:s}}delete i.maf_tumor_v1,delete i.maf_tumor_v2}if(null!=i.maf_normal_v1&&null!=i.maf_normal_v2){if(""==i.maf_normal_v2);else{let t=Number.parseInt(i.maf_normal_v1),s=Number.parseInt(i.maf_normal_v2);if(Number.isNaN(t)||Number.isNaN(s))return void n.snv.badlines.push([e,"invalid maf_normal mutant and/or total read count",o]);i.maf_normal={f:t/s,v1:t,v2:s}}delete i.maf_normal_v1,delete i.maf_normal_v2}n.good++,"M"==i.class?n.snv.missense++:"S"==i.class&&n.snv.silent++;const c=n.geneToUpper?i.gene.toUpperCase():i.gene;n.data[c]||(n.data[c]=[]),i.dt=s.dtsnvindel,n.data[c].push(i)}},6279:(e,t,n)=>{"use strict";n.r(t),n.d(t,{duplicate:()=>a,parseheader:()=>o,parseline:()=>i});var s=n(8064),r=n(2273);function o(e,t,n){const s=e.toLowerCase().split("\t");if(s.length<=1)return"invalid file header for fusions";const r=(...e)=>{for(const t of e){const e=s.indexOf(t);if(-1!=e)return e}return-1};let o=r("gene_a","gene1","genea");return-1==o?"gene_a missing from header":(s[o]="gene1",o=r("gene_b","gene2","geneb"),-1==o?"gene_b missing from header":(s[o]="gene2",o=r("chr_a","chr1","chra"),-1==o?"chr_a missing from header":(s[o]="chr1",o=r("chr_b","chr2","chrb"),-1==o?"chr_b missing from header":(s[o]="chr2",o=r("pos_a","position_a","position1","posa"),-1==o?"pos_a missing from header":(s[o]="position1",o=r("pos_b","position_b","position2","posb"),-1==o?"pos_b missing from header":(s[o]="position2",o=r("isoform_a","refseq_a","refseq1","isoform1","sv_refseqa"),-1==o?"isoform_a missing from header":(s[o]="isoform1",o=r("isoform_b","refseq_b","refseq2","isoform2","sv_refseqb"),-1==o?"isoform_b missing from header":(s[o]="isoform2",o=r("strand_a","orta"),-1==o?"strand_a missing from header":(s[o]="strand1",o=r("strand_b","ortb"),-1==o?"strand_b missing from header":(s[o]="strand2",o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(s[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(s[o]="patient"),o=r("sampletype","sample type","sample_type"),-1!=o&&(s[o]="sampletype"),o=r("disease"),-1!=o&&(s[o]="disease"),o=r("origin"),-1!=o&&(s[o]="origin"),n?(t.sv.loaded=!0,t.sv.header=s):(t.fusion.loaded=!0,t.fusion.header=s),!1))))))))))}function i(e,t,n,o){if(""==t||"#"==t[0])return;const i=t.split("\t"),a={},l=o?n.sv.header:n.fusion.header,c=o?n.sv.badlines:n.fusion.badlines;for(let e=0;e<l.length;e++)a[l[e]]=i[e];if(!a.chr1)return void c.push([e,"missing chr1",i]);if(0!=a.chr1.toLowerCase().indexOf("chr")&&(a.chr1="chr"+a.chr1),!a.chr2)return void c.push([e,"missing chr2",i]);0!=a.chr2.toLowerCase().indexOf("chr")&&(a.chr2="chr"+a.chr2);let u=a.position1;if(!u)return void c.push([e,"missing position1",i]);let f=Number.parseInt(u);if(Number.isNaN(f)||f<=0)c.push([e,"invalid value for position1",i]);else if(a.position1=f,u=a.position2,u){if(f=Number.parseInt(u),Number.isNaN(f)||f<=0)c.push([e,"invalid value for position2",i]);else if(a.position2=f,!s.EJ(a,n,e,i,c)){if(a.isoform1&&-1!=a.isoform1.indexOf(",")){const e=a.isoform1.split(",");a.isoform1=void 0;for(const t of e)""!=t&&(a.isoform1=t)}if(a.isoform2&&-1!=a.isoform2.indexOf(",")){const e=a.isoform2.split(",");a.isoform2=void 0;for(const t of e)""!=t&&(a.isoform2=t)}if(a.gene1||(a.isoform1=void 0),a.gene2||(a.isoform2=void 0),a.gene1){n.good++;const e={dt:o?r.dtsv:r.dtfusionrna,class:o?r.mclasssv:r.mclassfusionrna,isoform:a.isoform1,mname:a.gene2||a.chr2,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},t=n.geneToUpper?a.gene1.toUpperCase():a.gene1;n.data[t]||(n.data[t]=[]),n.data[t].push(e)}if(a.gene2&&a.gene2!=a.gene1){n.good++;const e={dt:o?r.dtsv:r.dtfusionrna,class:o?r.mclasssv:r.mclassfusionrna,isoform:a.isoform2,mname:a.gene1||a.chr1,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},t=n.geneToUpper?a.gene2.toUpperCase():a.gene2;n.data[t]||(n.data[t]=[]),n.data[t].push(e)}}}else c.push([e,"missing position2",i])}function a(e){const t={};for(const n in e){if("pairlst"==n)continue;const s=e[n];"object"!=typeof s&&(t[n]=s)}if(e.pairlst){t.pairlst=[];for(const n of e.pairlst){const e={};for(const t in n)"a"!=t&&"b"!=t&&"interstitial"!=t&&(e[t]=n[t]);if(n.a){e.a={};for(const t in n.a){const s=n.a[t];"object"!=typeof s&&(e.a[t]=s)}}if(n.b){e.b={};for(const t in n.b){const s=n.b[t];"object"!=typeof s&&(e.b[t]=s)}}if(n.interstitial){e.interstitial={};for(const t in n.interstitial){const s=n.interstitial[t];"object"!=typeof s&&(e.interstitial[t]=s)}}t.pairlst.push(e)}}return t}},8423:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for svjson";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("sample");return-1!=r&&(n[r]="sample"),r=s("sampletype"),-1!=r&&(n[r]="sampletype"),r=s("patient"),-1!=r&&(n[r]="patient"),r=s("json","jsontext"),-1==r?["json missing from header"]:(n[r]="jsontext",[null,n])}function i(e,t,n,o){if(""==t||"#"==t[0])return;const i=t.split("\t"),l={},c=n.svjson.badlines;for(let e=0;e<o.length;e++)l[o[e]]=i[e];if(!l.jsontext)return void c.push([e,"missing jsontext",i]);if(r.EJ(l,n,e,i,c))return;let u;try{u=JSON.parse(l.jsontext)}catch(t){return void c.push([e,"invalid JSON text",i])}if(Array.isArray(u))for(const e of u){if(e.a&&e.a.name&&e.a.isoform){n.good++;const t={dt:s.dtfusionrna,class:s.mclassfusionrna,isoform:e.a.isoform,mname:e.b.name};for(const e in l)"jsontext"!=e&&(t[e]=l[e]);t.pairlst=a(u);const r=e.a.name.toUpperCase();n.data[r]||(n.data[r]=[]),n.data[r].push(t)}if(e.b&&e.b.name&&e.b.isoform){n.good++;const t={dt:s.dtfusionrna,class:s.mclassfusionrna,isoform:e.b.isoform,mname:e.a.name};for(const e in l)"jsontext"!=e&&(t[e]=l[e]);t.pairlst=a(u);const r=e.b.name.toUpperCase();n.data[r]||(n.data[r]=[]),n.data[r].push(t)}}else{switch(u.dt=u.typecode,delete u.typecode,u.dt){case s.dtitd:u.class=s.mclassitd,u.mname="ITD";break;case s.dtnloss:u.class=s.mclassnloss,u.mname="N-loss";break;case s.dtcloss:u.class=s.mclasscloss,u.mname="C-loss";break;case s.dtdel:u.class=s.mclassdel,u.mname="Del";break;case s.dtsv:u.class=s.mclasssv,u.mname="SV";break;default:return void c.push([e,"unknown datatype",i])}if(!u.gene)return void c.push([e,"json.gene missing",i]);n.good++;for(const e in l)"jsontext"!=e&&(u[e]=l[e]);const t=(n.geneToUpper,u.gene.toUpperCase());n.data[t]||(n.data[t]=[]),n.data[t].push(u)}}function a(e){const t=[];for(const n of e){const e={a:{},b:{}};for(const t in n)"a"!=t&&"b"!=t&&(e[t]=n[t]);for(const t in n.a)e.a[t]=n.a[t];for(const t in n.b)e.b[t]=n.b[t];t.push(e)}return t}},8235:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for truncation";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");if(-1==r)return"gene missing from header";if(n[r]="gene",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r)return"isoform missing from header";n[r]="isoform";let o=!1;if(r=s("rnaposition"),-1!=r&&(n[r]="rnaposition",o=!0),r=s("losstype"),-1==r)return"lossType missing from header";n[r]="losstype";let i=!1;if(r=s("chromosome","chr"),-1!=r){if(n[r]="chr",r=s("start","start_position","wu_hg19_pos","chr_position","position"),-1==r)return"genomic position missing from header";n[r]="pos",i=!0}return o||i?(r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.truncation.header=n,t.truncation.loaded=!0,!1):"neither rnaposition nor genomic position is given"}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.truncation.header.length;e++)i[n.truncation.header[e]]=o[e];if(!i.gene)return void n.truncation.badlines.push([e,"missing gene",o]);if(i.rnaposition){const t=Number.parseInt(i.rnaposition);if(Number.isNaN(t)||t<0)return void n.truncation.badlines.push([e,"invalid rnaPosition value",o]);i.rnaposition=t}if(i.pos){const t=Number.parseInt(i.pos);if(Number.isNaN(t)||t<0)return void n.truncation.badlines.push([e,"invalid genomic position",o]);i.pos=t}if(!i.losstype)return void n.truncation.badlines.push([e,"missing lossType value",o]);if("n"!=i.losstype&&"c"!=i.losstype)return void n.truncation.badlines.push([e,'lossType value not "n" or "c"',o]);if(r.EJ(i,n,e,o,n.truncation.badlines))return;"n"==i.losstype?(i.dt=s.dtnloss,i.class=s.mclassnloss,i.mname="N-loss"):(i.dt=s.dtcloss,i.class=s.mclasscloss,i.mname="C-loss"),n.good++;const a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}},2273:(e,t,n)=>{"use strict";n.r(t),n.d(t,{IN_frame:()=>c,OUT_frame:()=>u,alleleInGenotypeStr:()=>he,applyOverrides:()=>B,basecolor:()=>ie,basecompliment:()=>ae,bplen:()=>oe,codon:()=>ne,codon_stop:()=>se,contigNameNoChr:()=>de,contigNameNoChr2:()=>pe,custommdstktype:()=>te,default_text_color:()=>a,defaultcolor:()=>i,dt2color:()=>U,dt2label:()=>k,dtcloss:()=>v,dtcnv:()=>m,dtdel:()=>y,dtfusionrna:()=>d,dtgeneexpression:()=>p,dtitd:()=>g,dtloh:()=>w,dtnloss:()=>b,dtsnvindel:()=>f,dtsv:()=>h,exoncolor:()=>l,fasta2gmframecheck:()=>ue,germlinelegend:()=>J,getColorScheme:()=>qe,getColors:()=>xe,getMax_byiqr:()=>me,gmmode:()=>ge,kernelDensityEstimator:()=>ve,kernelEpanechnikov:()=>we,mclass:()=>q,mclasscloss:()=>A,mclasscnvgain:()=>R,mclasscnvloh:()=>$,mclasscnvloss:()=>F,mclassdel:()=>N,mclassdeletion:()=>G,mclassfusionrna:()=>I,mclassinsertion:()=>P,mclassitd:()=>x,mclassmnv:()=>L,mclassnloss:()=>S,mclassnoncoding:()=>M,mclassnonstandard:()=>T,mclasssnv:()=>D,mclasssv:()=>E,mclasstester:()=>O,mclassutr3:()=>C,mclassutr5:()=>j,mdsvcftype:()=>ee,morigin:()=>H,morigingermline:()=>V,morigingermlinenonpathogenic:()=>X,morigingermlinepathogenic:()=>K,moriginrelapse:()=>Z,moriginsomatic:()=>W,not_annotated:()=>be,nt2aa:()=>re,plotColor:()=>_,proteinChangingMutations:()=>Se,reversecompliment:()=>le,schemeCategory2:()=>ke,schemeCategory20:()=>_e,spliceeventchangegmexon:()=>ce,tkt:()=>Y,truncatingMutations:()=>Ne,validate_vcfinfofilter:()=>fe,validtkt:()=>Q,vcfcopymclass:()=>ye,vepinfo:()=>z});var s=n(1696),r=n(5540),o=n(1868);const i=(0,s.B8)("#8AB1D4").darker(),a=(0,s.B8)("#aaa").darker().darker(),l="#4F8053",c=!0,u=!1,f=1,d=2,p=3,m=4,h=5,g=6,y=7,b=8,v=9,w=10,_="#ce768e",k={[f]:"SNV/indel",[d]:"Fusion RNA",[m]:"CNV",[h]:"SV",[g]:"ITD",[y]:"Deletion",[b]:"N-loss",[v]:"C-loss",[w]:"LOH",[p]:"Gene Expression"},q={M:{label:"MISSENSE",color:"#3987CC",dt:f,desc:"A substitution variant in the coding region resulting in altered protein coding.",key:"M"},E:{label:"EXON",color:"#bcbd22",dt:f,desc:"A variant in the exon of a non-coding RNA.",key:"E"},F:{label:"FRAMESHIFT",color:"#db3d3d",dt:f,desc:"An insertion or deletion variant that alters the protein coding frame.",key:"F"},N:{label:"NONSENSE",color:"#ff7f0e",dt:f,desc:"A variant altering protein coding to produce a premature stopgain or stoploss.",key:"N"},S:{label:"SILENT",color:"#2ca02c",dt:f,desc:"A substitution variant in the coding region that does not alter protein coding.",key:"S"},D:{label:"PROTEINDEL",color:"#7f7f7f",dt:f,desc:"A deletion resulting in a loss of one or more codons from the product, but not altering the protein coding frame.",key:"D"},I:{label:"PROTEININS",color:"#8c564b",dt:f,desc:"An insertion introducing one or more codons into the product, but not altering the protein coding frame.",key:"I"},P:{label:"SPLICE_REGION",color:"#9467bd",dt:f,desc:"A variant in an intron within 10 nt of an exon boundary.",key:"P"},L:{label:"SPLICE",color:"#6633FF",dt:f,desc:"A variant near an exon edge that may affect splicing functionality.",key:"L"},Intron:{label:"INTRON",color:"#656565",dt:f,desc:"An intronic variant.",key:"Intron"},Blank:{label:"Not tested",color:"#fff",dt:f,desc:"This gene is not tested.",key:"Blank"},WT:{label:"Wildtype",color:"#D3D3D3",dt:f,desc:"Wildtype",key:"WT"}},x="ITD";q[x]={label:"ITD",color:"#ff70ff",dt:g,desc:"In-frame internal tandem duplication.",key:x};const N="DEL";q[N]={label:"DELETION, intragenic",color:"#858585",dt:y,desc:"Intragenic deletion.",key:N};const S="NLOSS";q[S]={label:"N-terminus loss",color:"#545454",dt:b,desc:"N-terminus loss due to translocation",key:S};const A="CLOSS";q[A]={label:"C-terminus loss",color:"#545454",dt:v,desc:"C-terminus loss due to translocation",key:A};const C="Utr3";q[C]={label:"UTR_3",color:"#998199",dt:f,desc:"A variant in the 3' untranslated region.",key:C};const j="Utr5";q[j]={label:"UTR_5",color:"#819981",dt:f,desc:"A variant in the 5' untranslated region.",key:j};const T="X";q[T]={label:"NONSTANDARD",color:"black",dt:f,desc:"A mutation class that either does not match our notation, or is unspecified.",key:T};const M="noncoding";function O(e){switch(e.toLowerCase()){case"missense_mutation":return"M";case"nonsense_mutation":case"nonstop_mutation":return"N";case"splice_site":return"L";case"rna":case"3'flank":case"5'flank":return M;case"frame_shift_del":case"frame_shift_ins":return"F";case"in_frame_del":return"D";case"in_frame_ins":return"I";case"translation_start_site":return T;case"3'utr":return C;case"5'utr":return j;case"blank":return"Blank";default:return null}}q[M]={label:"NONCODING",color:"black",dt:f,desc:"Noncoding mutation.",key:M};const I="Fuserna";q[I]={label:"Fusion transcript",color:"#545454",dt:d,desc:"Marks the break points leading to fusion transcripts.<br><span style=\"font-size:150%\">◐</span> - 3' end of the break point is fused to the 5' end of another break point in a different gene.<br><span style=\"font-size:150%\">◑</span> - 5' end of the break point is fused to the 3' end of another break point in a different gene.",key:I};const E="SV";q[E]={label:"Structural variation",color:"#858585",dt:h,desc:"Structural variation detected in genomic DNA.",key:E};const R="CNV_amp";q[R]={label:"Copy number gain",color:"#e9a3c9",dt:m,desc:"Copy number gain",key:R};const F="CNV_loss";q[F]={label:"Copy number loss",color:"#a1d76a",dt:m,desc:"Copy number loss",key:F};const $="CNV_loh";q[$]={label:"LOH",color:"#12EDFC",dt:m,desc:"Loss of heterozygosity",key:$};const D="snv";q[D]={label:"SNV",color:"#92a2d4",dt:f,desc:"Single nucleotide variation",key:D};const L="mnv";q[L]={label:"MNV",color:"#92a2d4",dt:f,desc:"Multiple nucleotide variation",key:L};const P="insertion";q[P]={label:"Sequence insertion",color:"#bd8e91",dt:f,desc:"Sequence insertion",key:P};const G="deletion";q[G]={label:"Sequence deletion",color:"#b5a174",dt:f,desc:"Sequence deletion",key:G};const U={[f]:q.M.color};function B(e={}){if(e.mclass)for(const t in e.mclass){q[t]||(q[t]={});for(const n in e.mclass[t])q[t][n]=e.mclass[t][n]}}const z=function(e){const t=e.toLowerCase().split(",");let n=1;return-1!=t.indexOf("transcript_ablation")?[y,N,n]:(n++,-1!=t.indexOf("splice_acceptor_variant")?[f,"L",n]:(n++,-1!=t.indexOf("splice_donor_variant")?[f,"L",n]:(n++,-1!=t.indexOf("stop_gained")?[f,"N",n]:(n++,-1!=t.indexOf("frameshift_variant")?[f,"F",n]:(n++,-1!=t.indexOf("stop_lost")?[f,"N",n]:(n++,-1!=t.indexOf("start_lost")?[f,"N",n]:(n++,-1!=t.indexOf("transcript_amplification")?[f,T,n]:(n++,-1!=t.indexOf("inframe_insertion")||-1!=t.indexOf("conservative_inframe_insertion")||-1!=t.indexOf("disruptive_inframe_insertion")?[f,"I",n]:(n++,-1!=t.indexOf("inframe_deletion")||-1!=t.indexOf("conservative_inframe_deletion")||-1!=t.indexOf("disruptive_inframe_deletion")?[f,"D",n]:(n++,-1!=t.indexOf("missense_variant")?[f,"M",n]:(n++,-1!=t.indexOf("protein_altering_variant")?[f,"N",n]:(n++,-1!=t.indexOf("splice_region_variant")?[f,"P",n]:(n++,-1!=t.indexOf("incomplete_terminal_codon_variant")?[f,"N",n]:(n++,-1!=t.indexOf("stop_retained_variant")?[f,"S",n]:(n++,-1!=t.indexOf("synonymous_variant")?[f,"S",n]:(n++,-1!=t.indexOf("coding_sequence_variant")?[f,T,n]:(n++,-1!=t.indexOf("mature_mirna_variant")?[f,"E",n]:(n++,-1!=t.indexOf("5_prime_utr_variant")?[f,j,n]:(n++,-1!=t.indexOf("3_prime_utr_variant")?[f,C,n]:(n++,-1!=t.indexOf("non_coding_transcript_exon_variant")?[f,"E",n]:(n++,-1!=t.indexOf("intron_variant")?[f,"Intron",n]:(n++,-1!=t.indexOf("nmd_transcript_variant")?[f,"S",n]:(n++,-1!=t.indexOf("non_coding_transcript_variant")?[f,"E",n]:(n++,-1!=t.indexOf("upstream_gene_variant")?[f,M,n]:(n++,-1!=t.indexOf("downstream_gene_variant")?[f,M,n]:(n++,-1!=t.indexOf("tfbs_ablation")?[f,M,n]:(n++,-1!=t.indexOf("tfbs_amplification")?[f,M,n]:(n++,-1!=t.indexOf("tf_binding_site_variant")?[f,M,n]:(n++,-1!=t.indexOf("regulatory_region_ablation")?[f,M,n]:(n++,-1!=t.indexOf("regulatory_region_amplification")?[f,M,n]:(n++,-1!=t.indexOf("feature_elongation")?[f,M,n]:(n++,-1!=t.indexOf("regulatory_region_variant")?[f,M,n]:(n++,-1!=t.indexOf("feature_truncation")?[f,M,n]:(n++,-1!=t.indexOf("intergenic_variant")?[f,M,n]:(n++,[f,T,n])))))))))))))))))))))))))))))))))))},J='<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="#858585" stroke="none"></path>',H={},W="S";H[W]={label:"Somatic",desc:"A variant found only in a tumor sample. The proportion is indicated by lack of any arc.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle>'};const V="G";H[V]={label:"Germline",desc:"A constitutional variant found in a normal sample. The proportion is indicated by the span of the solid arc within the whole circle.",legend:J},H.germline=H[V],H.somatic=H[W];const Z="R";H[Z]={label:"Relapse",desc:"A somatic variant found only in a relapse sample. The proportion is indicated by the span of the hollow arc within the whole circle.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="none" stroke="#858585"></path>'};const K="GP";H[K]={label:"Germline pathogenic",desc:"A constitutional variant with pathogenic allele.",legend:J};const X="GNP";H[X]={label:"Germline non-pathogenic",desc:"A constitutional variant with non-pathogenic allele.",legend:J,hidden:!0};const Y={usegm:"usegm",ds:"dataset",bigwig:"bigwig",bigwigstranded:"bigwigstranded",junction:"junction",mdsjunction:"mdsjunction",mdscnv:"mdscnv",mdssvcnv:"mdssvcnv",mdsexpressionrank:"mdsexpressionrank",mdsvcf:"mdsvcf",bedj:"bedj",pgv:"profilegenevalue",bampile:"bampile",hicstraw:"hicstraw",expressionrank:"expressionrank",aicheck:"aicheck",ase:"ase",mds2:"mds2",mds3:"mds3",bedgraphdot:"bedgraphdot",bam:"bam",ld:"ld"};function Q(e){for(const t in Y)if(e==Y[t])return!0;return!1}const ee={vcf:"vcf"},te={vcf:"vcf",svcnvitd:"svcnvitd",geneexpression:"geneexpression"},ne={GCT:"A",GCC:"A",GCA:"A",GCG:"A",CGT:"R",CGC:"R",CGA:"R",CGG:"R",AGA:"R",AGG:"R",AAT:"N",AAC:"N",GAT:"D",GAC:"D",TGT:"C",TGC:"C",CAA:"Q",CAG:"Q",GAA:"E",GAG:"E",GGT:"G",GGC:"G",GGA:"G",GGG:"G",CAT:"H",CAC:"H",ATT:"I",ATC:"I",ATA:"I",TTA:"L",TTG:"L",CTT:"L",CTC:"L",CTA:"L",CTG:"L",AAA:"K",AAG:"K",ATG:"M",TTT:"F",TTC:"F",CCT:"P",CCC:"P",CCA:"P",CCG:"P",TCT:"S",TCC:"S",TCA:"S",TCG:"S",AGT:"S",AGC:"S",ACT:"T",ACC:"T",ACA:"T",ACG:"T",TGG:"W",TAT:"Y",TAC:"Y",GTT:"V",GTC:"V",GTA:"V",GTG:"V"},se="*";function re(e){if(!e.genomicseq)return;const t=[];if(e.coding)for(const[n,s]of e.coding.entries()){const n=e.genomicseq.substr(s[0]-e.start,s[1]-s[0]);"-"==e.strand?t.push(le(n)):t.push(n)}const n=t.join(""),s=[];for(let t=e.startCodonFrame?3-e.startCodonFrame:0;t<n.length;t+=3){const e=ne[n.substr(t,3)];s.push(e||se)}return e.cdseq=n,s.join("")}function oe(e,t){return e>=1e9?(e/1e9).toFixed(1)+" Gb":e>=1e7?Math.ceil(e/1e6)+" Mb":e>=1e6?(e/1e6).toFixed(1)+" Mb":e>=1e4?Math.ceil(e/1e3)+" Kb":e>=1e3?(e/1e3).toFixed(1)+" Kb":e+(t?"bytes":" bp")}const ie={A:"#ca0020",T:"#f4a582",C:"#92c5de",G:"#0571b0"};function ae(e){switch(e){case"A":return"T";case"T":return"A";case"C":return"G";case"G":return"C";case"a":return"t";case"t":return"a";case"c":return"g";case"g":return"c";default:return e}}function le(e){const t=[];for(let n=e.length-1;n>=0;n--)t.push(ae(e[n]));return t.join("")}function ce(e,t){const n={chr:e.chr,start:e.start,stop:e.stop,strand:e.strand,coding:[]};if(t.isskipexon||t.isaltexon)for(let s=0;s<e.exon.length;s++){const r=Math.max(e.codingstart,e.exon[s][0]),o=Math.min(e.codingstop,e.exon[s][1]);r>o||-1==t.skippedexon.indexOf(s)&&n.coding.push([r,o])}else if(t.a5ss||t.a3ss){const s=e.exon.map((e=>[e[0],e[1]])),r="+"==e.strand;t.a5ss?r?s[t.exon5idx][1]=t.junctionB.start:s[t.exon5idx+1][0]=t.junctionB.stop:r?s[t.exon5idx+1][0]=t.junctionB.stop:s[t.exon5idx][1]=t.junctionB.start;for(const t of s){const s=Math.max(e.codingstart,t[0]),r=Math.min(e.codingstop,t[1]);s>r||n.coding.push([s,r])}}return n}function ue(e,t){const n=t.split("\n");n.shift(),e.genomicseq=n.join("").toUpperCase();const s=re(e);let r=u;return s.indexOf(se)==s.length-1&&(r=c),r}function fe(e){if(!e.lst)return".lst missing";if(!Array.isArray(e.lst))return"input is not an array";for(const t of e.lst){if(!t.name)return"name missing from a set of .vcfinfofilter.lst";if(t.autocategory||t.categories){if(!t.autocategory)for(const e in t.categories){const n=t.categories[e];if(!t.autocolor&&!n.color)return".color missing for class "+e+" from .categories of set "+t.name;n.label||(n.label=e)}if(t.categoryhidden){for(const e in t.categoryhidden)if(!t.categories[e])return"unknown hidden-by-default category "+e+" from set "+t.name}else t.categoryhidden={}}else if(t.numericfilter){const e=[];for(const n of t.numericfilter)"number"==typeof n?e.push({side:"<",value:n}):e.push({side:n.side||"<",value:n.value});t.numericfilter=e}if(t.altalleleinfo){if(!t.altalleleinfo.key)return".key missing from .altalleleinfo from set "+t.name}else{if(!t.locusinfo)return"neither .altalleleinfo or .locusinfo is available from set "+t.name;if(!t.locusinfo.key)return".key missing from .locusinfo from set "+t.name}}}function de(e,t){for(const n in e.majorchr)if(-1!=t.indexOf(n.replace("chr","")))return!0;if(e.minorchr)for(const n in e.minorchr)if(-1!=t.indexOf(n.replace("chr","")))return!0;return!1}function pe(e,t){let n=0,s=0;for(const r in e.majorchr)t.includes(r)?s++:t.includes(r.replace("chr",""))&&n++;if(e.minorchr)for(const r in e.minorchr)t.includes(r)?s++:t.includes(r.replace("chr",""))&&n++;return[n,s]}function me(e,t){if(0==e.length)return t;e.sort(((e,t)=>e-t));const n=e[e.length-1];if(e.length<=5)return n;const s=e[Math.floor(e.length/4)],r=e[Math.floor(3*e.length/4)];return Math.min(r+1.5*(r-s),n)}function he(e,t){return!!e&&(-1!=e.indexOf("/")?-1!=e.split("/").indexOf(t):-1!=e.split("|").indexOf(t))}const ge={genomic:"genomic",splicingrna:"splicing RNA",exononly:"exon only",protein:"protein",gmsum:"aggregated exons"};function ye(e,t){if(e.csq){let n;if(t.usegm&&(n=e.csq.find((e=>e._isoform==t.usegm.isoform))),!n&&(n=e.csq.find((e=>e.CANONICAL)),!n)){n=e.csq[0];for(const t of e.csq)t._csqrank<n._csqrank&&(n=t)}n&&(e.gene=n._gene,e.isoform=n._isoform,e.class=n._class,e.dt=n._dt,e.mname=n._mname,e.class==M&&delete e.class)}else if(e.ann){let n=null;if(t.usegm){for(const s of e.ann)s._isoform==t.usegm.isoform&&(n?s._csqrank<n._csqrank&&(n=s):n=s);n||t.gmmode!=ge.genomic||(n=e.ann[0])}else{n=e.ann[0];for(const t of e.ann)t._csqrank<n._csqrank&&(n=t)}n&&(e.gene=n._gene,e.isoform=n._isoform,e.class=n._class,e.dt=n._dt,e.mname=n._mname,e.class==M&&delete e.class)}null==e.class&&(q[e.type]?(e.class=e.type,e.dt=q[e.type].dt,e.mname=e.id&&"."!=e.id?e.id:e.ref+">"+e.alt,e.mname.length>15&&(e.mname=e.type)):(e.class=T,e.dt=f,e.mname=e.type)),delete e.type}const be="Unannotated";function ve(e,t){return function(n){return t.map((t=>[t,n.map((n=>e(t-n))).reduce(((e,t)=>e+t),0)/n.length]))}}function we(e){return function(t){return Math.abs(t/=e)<=1?.75*(1-t*t)/e:0}}const _e=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],ke=["#e75480","blue"];function qe(e){return e>12?_e:e>8?o.xHP:e>2?o.XgA:ke}function xe(e){return r.Z(qe(e))}const Ne=["F","N","D","I","L"],Se=["F","N","D","I","L","M","P"]},7027:(e,t,n)=>{"use strict";function s(e,t){e.sort(((e,t)=>e-t));const n=Math.abs(t/100*e.length-1);return Number.isInteger(n)?(e[n]+e[n+1])/2:e[Math.ceil(n)]}n.d(t,{Z:()=>s})},8615:(e,t,n)=>{"use strict";n.d(t,{Z:()=>o});var s=n(7027);function r(e,t){const n=Number(e);return Number.isInteger(n)?n:Math.abs(n)<1?Number(n.toPrecision(t)):Number(n.toFixed(t))}function o(e){let t=e;"string"==typeof e[0]&&(t=e.map(Number));const n=t.length;function o(e){return e.reduce(((e,t)=>e+t))/n}const i=(0,s.Z)(t,50),a=t.map((e=>(e-o(t))**2)).reduce(((e,t)=>e+t),0)/(n-1),l=Math.sqrt(a),c=(0,s.Z)(t,25),u=(0,s.Z)(t,75),f=u-c,d=Math.min(...t),p=Math.max(...t);return{values:[{id:"total",label:"Total",value:n},{id:"min",label:"Minimum",value:r(d,2)},{id:"p25",label:"1st quartile",value:r(c,2)},{id:"median",label:"Median",value:r(i,2)},{id:"mean",label:"Mean",value:r(o(t),2)},{id:"p75",label:"3rd quartile",value:r(u,2)},{id:"max",label:"Maximum",value:r(p,2)},{id:"SD",label:"Standard deviation",value:r(l,2)},{id:"variance",label:"Variance",value:r(a,2)},{id:"IQR",label:"Inter-quartile range",value:r(f,2)}]}}},478:(e,t,n)=>{"use strict";function s(e){if(!e||0==e.length)return;let t=JSON.parse(JSON.stringify(e[0]));if(1==e.length)return t;if(t.lst.length<2){if(""!==t.join)throw'filter.join must be an empty string "" when filter.lst.length < 2';t.join="and"}else if("or"==t.join)t={type:"tvslst",join:"and",in:!0,lst:[t]};else if("and"!=t.join)throw'filter.join must be either "and" or "or" when .lst length > 1';for(let n=1;n<e.length;n++){const s=JSON.parse(JSON.stringify(e[n]));"or"==s.join?t.lst.push(s):t.lst.push(...s.lst)}return 1==t.lst.length&&"tvs"==t.lst[0].type&&(t.join=""),t}n.d(t,{xH:()=>s})},4048:(e,t,n)=>{"use strict";n.d(t,{gp:()=>a});var s=n(670),r=n(2273);function o(e){return!isNaN(parseFloat(e))&&isFinite(e)}function i(e,t,n,s,r){if(s>=1){const t=Math.floor(e*s);return r?`${t}${n.charAt(0)}`:`${t} ${t>1?n+"s":""}`}const o=Math.floor(e*s),i=Math.ceil(e%(1/s));return 0==i?r?`${o}${n.charAt(0)}`:`${o} ${o>1?n+"s":""}`:r?`${o}${n.charAt(0)}${i}${t.charAt(0)}`:`${o} ${o>1?n+"s":""} ${i} ${i>1?t+"s":""}`}function a(e,t,n){const s=e;if(function(e){const t=e;if(!t||"object"!=typeof t)throw"bin schema must be an object";if("type"in t||(t.type="regular-bin"),"custom-bin"==t.type){if(!Array.isArray(t.lst))throw"binconfig.lst must be an array";if(!t.lst.length)throw"binconfig.lst must have entries";const e=t.lst[0],n=t.lst[t.lst.length-1];for(const s of t.lst){if(!("startinclusive"in s)&&!("stopinclusive"in s))throw"custom bin.startinclusive and/or bin.stopinclusive must be defined";if(s==e){if("startunbounded"in s&&!s.startunbounded)throw"a custom first bin must not set bin.startunbounded to false";if(s.startunbounded=!0,"start"in s)throw"a custom first bin must not set a bin.start value";if("start_percentile"in s)throw"the first bin must not set a bin.start_percentile value";if(!("stop"in s))throw"a custom first bin must define a bin.stop value";if(!o(s.stop))throw"a custom first bin.stop value should be numeric"}else if(s==n){if(!("start"in s))throw"a custom last bin must define a bin.start value";if(!o(s.start))throw"a custom last bin.start must be numeric";if("stopunbounded"in s&&!s.stopunbounded)throw"a custom last bin must not set bin.stopunbounded to false";if(s.stopunbounded=!0,"stop"in s)throw"a custom last bin must not set a bin.stop value"}else{if(!o(s.start))throw"bin.start must be numeric for a non-first bin";if(!o(s.stop))throw"bin.stop must be numeric for a non-last bin"}}}else{if("regular-bin"!=t.type)throw`invalid binconfig.type="${t.type}"`;if(!Number.isFinite(t.bin_size))throw"non-numeric bin_size";if(t.bin_size<=0)throw"bin_size must be greater than 0";if(t.startinclusive||t.stopinclusive||(t.startinclusive=1,t.stopinclusive=0),!t.first_bin)throw"first_bin{} missing";if("object"!=typeof t.first_bin)throw"first_bin{} is not an object";if(!Object.keys(t.first_bin).length)throw"first_bin is an empty object";{const e=t.first_bin;if(e.startunbounded=!0,e.stop_percentile){if(!Number.isInteger(e.stop_percentile))throw"first_bin.stop_percentile should be integer";if(e.stop_percentile<=0||e.stop_percentile>=100)throw"first_bin.stop_percentile out of bound (0-100)"}else if(!Number.isFinite(e.stop))throw"first_bin.stop not a number when stop_percentile is not set"}if(t.last_bin){const e=t.last_bin;if(e.start_percentile){if(!Number.isInteger(e.start_percentile))throw"last_bin.start_percentile should be integer";if(e.start_percentile<=0||e.start_percentile>=100)throw"last_bin.start_percentile out of bound (0-100)"}else if(!Number.isFinite(e.start))throw"last_bin.start not a number when start_percentile is not set";if(e.stopunbounded=!0,"stop"in e)throw"a regular last bin must not set a bin.stop value"}}}(s),s.lst){const e=(0,r.getColors)(s.lst.length);for(const t of s.lst)t.color=e(t.label)}if("custom-bin"==s.type)return JSON.parse(JSON.stringify(s.lst));if("function"!=typeof t)throw"summaryfxn required for modules/termdb.bins.js compute_bins()";const i=function(e){const t=[],n=e.first_bin;n&&o(n.start_percentile)&&t.push(n.start_percentile);n&&o(n.stop_percentile)&&t.push(n.stop_percentile);const s=e.last_bin;s&&o(s.start_percentile)&&t.push(s.start_percentile);s&&o(s.stop_percentile)&&t.push(s.stop_percentile);return t}(s),a=t(i);if(!a||"object"!=typeof a)throw"invalid returned value by summaryfxn";s.results={summary:a},s.binLabelFormatter||(s.binLabelFormatter=l(s));const u=Math.floor(100*a.min)/100,f=Math.ceil(100*a.max)/100,d=s.first_bin.startunbounded?u:s.first_bin.start_percentile?a["p"+s.first_bin.start_percentile]:s.first_bin.start;let p,m,h=f;if(s.last_bin)h=s.last_bin.stopunbounded?f:s.last_bin.stop_percentile?a["p"+s.last_bin.stop_percentile]:o(s.last_bin.stop)&&s.last_bin.stop<=a.max?s.last_bin.stop:f,p=o(s.last_bin.start_percentile)?a["p"+s.last_bin.start_percentile]:o(s.last_bin.start)?s.last_bin.start:void 0,m=s.last_bin.stopunbounded?null:s.last_bin.stop_percentile?a["p"+s.last_bin.stop_percentile]:o(s.last_bin.stop)?s.last_bin.stop:null;else if(s.lst){const e=s.lst[s.lst.length-1];p=e.start,m="stop"in e&&!e.stopunbounded?e.stop:f,h=m}else p=f,m=f;const g=o(h),y=o(p),b=o(m);if(!g&&!y)return[];const v=[];let w={startunbounded:s.first_bin.startunbounded,start:s.first_bin.startunbounded?void 0:d,stop:o(s.first_bin.stop_percentile)?+a["p"+s.first_bin.stop_percentile]:o(s.first_bin.stop)?+s.first_bin.stop:d+s.bin_size,startinclusive:s.startinclusive,stopinclusive:s.stopinclusive};if(!o(w.stop))throw"the computed first_bin.stop is non-numeric"+w.stop;for(;(g&&w.stop<=h||w.startunbounded&&!v.length||w.stopunbounded)&&(v.push(w),w.stop>=h&&(w.stopunbounded=!0,v.length>1&&delete w.stop),w.label=c(w,s,n),!w.stopunbounded);){const e=w.stop+s.bin_size,t=w.stop;if(w={startinclusive:s.startinclusive,stopinclusive:s.stopinclusive,start:t,stop:b&&(t==p||e>m)?m:y&&e>p&&t!=p?p:e},w.stop>=h&&(w.stop=h,s.last_bin&&s.last_bin.stopunbounded&&(w.stopunbounded=1),s.last_bin&&s.last_bin.stopinclusive&&(w.stopinclusive=1)),y&&w.start==p&&s.last_bin&&s.last_bin.stopunbounded&&(w.stopunbounded=1),w.start>w.stop){if(!(y&&w.stop==p&&s.last_bin&&s.last_bin.stopunbounded))break;w.stopunbounded=!0}if(v.length+1>=100){s.error="max_num_bins_reached";break}}delete s.binLabelFormatter,v.length>1&&delete v[v.length-1].stop;const _=(0,r.getColors)(v.length);for(const e of v)e.color=_(e.label);return v}function l(e){return"rounding"in e?(0,s.WU)(e.rounding):e=>e}function c(e,t,n){const s=t;s.binLabelFormatter||(s.binLabelFormatter=l(s)),e.startunbounded||e.stopunbounded||"startinclusive"in e||"stopinclusive"in e||(s.startinclusive?e.startinclusive=!0:s.stopinclusive&&(e.stopinclusive=!0));const r="bins"==s.use_as||e.start,o="bins"==s.use_as||e.stop;let a=0;if("label_offset"in s?(s.label_offset_ignored="bin_size"in s&&s.bin_size<s.label_offset,s.label_offset_ignored||(a=s.label_offset)):1===s.bin_size&&"integer"==s.termtype&&(a=1),e.startunbounded){return(e.stopinclusive?"≤":"<")+(n?i(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(o))}if(e.stopunbounded||r===o){return(e.startinclusive?"≥":">")+(n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(r))}if(a&&e.startinclusive&&!e.stopinclusive){if(Number.isInteger(s.bin_size)&&Math.abs(r-o)===a)return""+(n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(r));{const e=n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(r),t=n?i(o-a,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(o-a);return+e>=+t?e.toString():e+" to "+t}}{const t=e.startinclusive?"":">",a=e.stopinclusive?"":"<",l=n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(r)?r:s.binLabelFormatter(r),c=n?i(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(o)?o:s.binLabelFormatter(o);if(+l>=+c){return(e.startinclusive?"≥":">")+l}return t+l+" to "+a+c}}},1575:(e,t,n)=>{"use strict";n.d(t,{CG:()=>r});new Set(["snplst","prs","snplocus","geneVariant","samplelst"]);const s=new Set(["categorical","integer","float","condition","survival","snplst","snplocus","geneVariant","samplelst"]);function r(e,t,n){const r=t||{};if(n&&n.usecase&&use.target in n.usecase)return n.usecase[use.target](e,use);const a=new Set,l=e.child_types||[];switch(r.target){case"barchart":case"summary":case"matrix":return"term0"==r.detail&&"geneVariant"==e.type||("term2"==r.detail&&"geneVariant"==e.type&&"geneVariant"==r.term1type||(e.type&&"survival"!==e.type&&a.add("plot"),o(l)&&a.add("branch"))),a;case"table":return"term"==r.detail&&a.add("plot"),l.length>1&&a.add("branch"),a;case"scatterplot":return"float"!=e.type&&"integer"!=e.type||a.add("plot"),i(l)&&a.add("branch"),a;case"sampleScatter":return"numeric"==r.detail?("float"!=e.type&&"integer"!=e.type||a.add("plot"),i(l)&&a.add("branch")):(s.has(e.type)&&a.add("plot"),e.isleaf||a.add("branch")),a;case"boxplot":return"float"!=e.type&&"integer"!=e.type||a.add("plot"),"term2"===r.detail&&i(l)&&a.add("branch"),a;case"cuminc":if("term"==r.detail)return"condition"==e.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a;if("term2"===r.detail)return e.type&&"survival"!=e.type&&a.add("plot"),o(l)&&a.add("branch"),a;if("term0"==r.detail)return a.add("plot"),a;case"survival":return"term"==r.detail?("survival"==e.type&&a.add("plot"),l.includes("survival")&&a.add("branch"),a):"term2"===r.detail?("survival"!=e.type&&(e.type&&a.add("plot"),o(l)&&a.add("branch")),a):"term0"==r.detail?(e.type&&a.add("plot"),o(l)&&a.add("branch"),a):(e.isleaf?a.add("plot"):a.add("branch"),a);case"regression":if("outcome"==r.detail){if("linear"==r.regressionType)return"float"!=e.type&&"integer"!=e.type||a.add("plot"),i(l)&&a.add("branch"),a;if("logistic"==r.regressionType)return e.type&&"survival"!=e.type&&a.add("plot"),o(l)&&a.add("branch"),a;if("cox"==r.regressionType)return"condition"==e.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a}if("independent"==r.detail)return"float"!=e.type&&"integer"!=e.type&&"categorical"!=e.type||a.add("plot"),function(e,t){for(const n of t)if(e.includes(n))return!0}(l,["categorical","float","integer"])&&a.add("branch"),a;default:return s.has(e.type)&&a.add("plot"),e.isleaf||a.add("branch"),a}}function o(e){return!!e.length&&(e.length>1||"survival"!=e[0])}function i(e){return e.includes("float")||e.includes("integer")}},1881:(e,t,n)=>{"use strict";n.d(t,{N:()=>o});const s="root",r="...";function o(e,t){const n=Object.create(null),o=Object.create(null),a=Object.create(null);for(const s of e)for(const[e,r]of t.entries()){const l=i(s,e,t),c=i(s,e-1,t);if(!s[r.k]){e>0&&(a[c]+=1);break}if(n[l]=c,l in a||(a[l]=0),!(l in o)){const n={lst:[]};r.full&&(n.full=s[r.full]),n.id0=t[0].k,n.v0=s[t[0].k],1==e&&(n.id1=t[1].k,n.v1=s[t[1].k]),2==e&&(n.id2=t[2].k,n.v1=s[t[2].k]),o[l]=n}o[l].lst.push(s),e==t.length-1&&(a[l]+=1)}const l=[{id:s,name:s}];for(const e in n){const t=n[e],s=o[e],i=e.split(r);l.push({id:e,parentId:t,lst:s.lst,value:a[e],name:i[i.length-1],full:s.full,id0:s.id0,v0:s.v0,id1:s.id1,v1:s.v1,id2:s.id2,v2:s.v2})}return l}function i(e,t,n){const o=[s];for(let s=0;s<t;s++)o.push(e[n[s].k]);return t>=0&&o.push(e[n[t].k]),o.join(r)}},4298:(e,t,n)=>{"use strict";n.d(t,{A:()=>r});var s=n(2273);function r(e,t,n){if(!t)return null;for(const r of e.split(",")){const e=r.replace(/&/g,",").split("|"),o={};for(let n=0;n<t.length;n++)e[n]&&(o[t[n].name]=e[n]);if(!o.Allele)continue;let i=null;for(const e of n.mlst||n.alleles)if(e.allele_original==o.Allele){i=e;break}if(!i){if("-"==o.Allele)n.mlst?1==n.mlst.length&&(i=n.mlst[0]):n.alleles&&1==n.alleles.length&&(i=n.alleles[0]);else for(const e of n.mlst||n.alleles)if(e.allele_original.substr(1)==o.Allele){i=e;break}if(!i)continue}if(i.csq||(i.csq=[]),i.csq.push(o),o._gene=o.SYMBOL||o.Gene,o.Feature_type&&"Transcript"==o.Feature_type?o._isoform=o.Feature.split(".")[0]:o._isoform=o._gene,o.Consequence){const[e,t,n]=(0,s.vepinfo)(o.Consequence);o._dt=e,o._class=t,o._csqrank=n}else o._dt=dtsnvindel,o._class=mclassnonstandard;o.HGVSp?o._mname=decodeURIComponent(o.HGVSp.substr(o.HGVSp.indexOf(":")+1)):o.Protein_position&&o.Amino_acids?o._mname=decodeURIComponent(o.Protein_position+o.Amino_acids):o.HGVSc?o._mname=o.HGVSc.substr(o.HGVSc.indexOf(":")+1):o.Existing_variation&&(o._name=o.Existing_variation)}return!0}},9380:(e,t,n)=>{"use strict";function s(e){let t=!1,n=!0,s=0,r=0;const o={};let i;for(;s<e.length;){const a=e[s];n?"="==a?(t=!0,n=!1,i=e.substring(r,s),r=s+1):";"==a&&(o[e.substring(r,s)]=1,r=s+1):t&&";"==a&&(n=!0,t=!1,o[i]=e.substring(r,s),i=null,r=s+1),s++}const a=e.substr(r,s);return i?o[i]=a:o[a]=1,o}n.d(t,{w:()=>s})},6819:(e,t,n)=>{"use strict";n.d(t,{S:()=>d,e:()=>f});var s=n(2273),r=n(9380),o=n(4298);function a(e,t,n){if(!t)return null;for(const r of e.split(",")){const e=r.replace(/&/g,",").split("|"),o={};for(let n=0;n<t.length;n++)e[n]&&(o[t[n].name]=e[n]);if(!o.Allele)continue;let i=null;for(const e of n.alleles)if(e.allele==o.Allele){i=e;break}if(i){if(i.ann||(i.ann=[]),i.ann.push(o),o._gene=o.Gene_Name,o.Feature_Type&&"transcript"==o.Feature_Type&&o.Feature_ID&&(o._isoform=o.Feature_ID.split(".")[0]),o.Annotation){const[e,t,n]=(0,s.vepinfo)(o.Annotation);o._dt=e,o._class=t,o._csqrank=n}else o._dt=dtsnvindel,o._class=mclassnonstandard;o["HGVS.p"]?o._mname=o["HGVS.p"]:o["HGVS.c"]&&(o._mname=o["HGVS.c"])}}return!0}var l=n(736);const c=new RegExp(/<(.+)>/),u={};for(const e in s.mclass)u[s.mclass[e].label.toUpperCase()]=e;function f(e){let t=[],n=[],s={},r=!1,o={},i=!1;for(const a of e)if(a.startsWith("#"))if(a.startsWith("#C"))t=a.split("\t").slice(9);else if(a.startsWith("##INFO")){const e=m(a.substring(8,a.length-1),s);e?n.push("INFO error: "+e):r=!0}else if(a.startsWith("##FORMAT")){const e=m(a.substring(10,a.length-1),o);e?n.push("FORMAT error: "+e):i=!0}const a=[];for(const e of t){const t={name:e};a.push(t)}if(s.CSQ){const e=s.CSQ.Description.split(" Format: ");if(e[1]){const t=e[1].split("|");if(t.length>1){s.CSQ.csqheader=[];for(const e of t){const t={name:e};s.CSQ.csqheader.push(t)}}else n.push("unknown format for CSQ header: "+s.CSQ.Description)}else n.push("unknown format for CSQ header: "+s.CSQ.Description)}if(s.ANN){const e=s.ANN.Description.split("'");if(e[1]){const t=e[1].split(" | ");if(t.length){s.ANN.annheader=[];for(const e of t){const t={name:e};s.ANN.annheader.push(t)}}else n.push('no " | " joined annotation fields for ANN (snpEff annotation): '+s.ANN.Description)}else n.push("no single-quote enclosed annotation fields for ANN (snpEff annotation): "+s.ANN.Description)}return[r?s:null,i?o:null,a,n.length?n:null]}function d(e,t){const n=e.split("\t");if(n.length<8)return["line has less than 8 fields",null,null];const s=Number.parseInt(n[1]);if(!Number.isInteger(s))return["invalid value for genomic position",null,null];const i=n[3],u={vcf_ID:n[2],chr:(t.nochr?"chr":"")+n[0],pos:s-1,ref:i,altstr:n[4],alleles:[{allele:i,sampledata:[]}],info:{},name:"."==n[2]?null:n[2]},f=[];for(const e of n[4].split(",")){const t={ref:u.ref,allele:e,allele_original:e,sampledata:[],_m:u,info:{}};if(u.alleles.push(t),"<"==e[0]){const n=e.match(c);if(!n){f.push(e);continue}t.type=n[1],t.allele=n[1],t.issymbolicallele=!0}else{const[e,n,s]=p(u.pos,u.ref,t.allele);t.pos=e,t.ref=n,t.allele=s}}n[8]&&n[9]&&function(e,t,n){const s=e[8].split(":");for(let r=9;r<e.length;r++){const o=e[r].split(":");{let e=!0;for(const t of o)if("."!=t){e=!1;break}if(e)continue}const i=r-9;for(let e=1;e<t.alleles.length;e++){const s={};if(n.samples&&n.samples[i])for(const e in n.samples[i])s[e]=n.samples[i][e];else s.name="missing_samplename_from_vcf_header";t.alleles[e].sampledata.push({sampleobj:s})}for(let e=0;e<s.length;e++){const r=s[e],i=o[e];if("."==i)continue;if("GT"==r){const e=-1!=i.indexOf("/")?"/":"|";let n=0,s=!1;const r=[];for(const o of i.split(e)){if("."==o){s=!0;continue}const e=Number.parseInt(o);if(Number.isNaN(e)){s=!0;continue}n+=e;const i=t.alleles[e];i&&r.push(i.allele)}let o=!1;s||(o=0==n);const a=r.join(e);for(let e=1;e<t.alleles.length;e++){const n=t.alleles[e].sampledata[t.alleles[e].sampledata.length-1];n.GT=i,n.genotype=a,o&&(n.gtallref=!0),n.__gtalleles=r}continue}const a=n.format?n.format[r]:null;if(!a){for(let e=1;e<t.alleles.length;e++)t.alleles[e].sampledata[t.alleles[e].sampledata.length-1][r]=i;continue}const l="Integer"==a.Type,c="Float"==a.Type;if(a.Number&&"R"==a.Number||"AD"==r){const e=i.split(",").map((e=>l?Number.parseInt(e):c?Number.parseFloat(e):e));for(let n=1;n<t.alleles.length;n++)if(null!=e[n]){const s=t.alleles[n],o=s.sampledata[s.sampledata.length-1];o[r]={},o[r][s.ref]=e[0],o[r][s.allele]=e[n]}}else if(a.Number&&"A"==a.Number){const e=i.split(",").map((e=>l?Number.parseInt(e):c?Number.parseFloat(e):e));for(let n=1;n<t.alleles.length;n++)if(null!=e[n-1]){const s=t.alleles[n],o=s.sampledata[s.sampledata.length-1];o[r]={},o[r][s.allele]=e[n-1]}}else for(let e=1;e<t.alleles.length;e++)t.alleles[e].sampledata[t.alleles[e].sampledata.length-1][r]=i}}for(const e of t.alleles)for(const t of e.sampledata)if(t.AD){t.allele2readcount={};for(const e in t.AD)t.allele2readcount[e]=t.AD[e]}}(n,u,t),u.alleles.shift();const d="."==n[7]?[]:(0,r.w)(n[7]);let m=[];t.info?m=function(e,t,n){const s=[];for(const r in e){if(null==n.info[r]){s.push(r);continue}const i=e[r];if("CSQ"==r){(0,o.A)(i,n.info.CSQ.csqheader,t)||(t.info[r]=i);continue}if("ANN"==r){a(i,n.info.ANN.annheader,t)||(t.info[r]=i);continue}if("Flag"==n.info[r].Type){t.info[r]=r;continue}const l=n.info[r].Number,c="Integer"==n.info[r].Type,u="Float"==n.info[r].Type;if("0"==l){t.info[r]=r;continue}if("A"==l){const e=i.split(",");for(let n=0;n<e.length;n++)t.alleles[n]&&(t.alleles[n].info[r]=c?Number.parseInt(e[n]):u?Number.parseFloat(e[n]):e[n]);continue}if("1"==l){t.info[r]=c?Number.parseInt(i):u?Number.parseFloat(i):i;continue}if(!i.split)continue;const f=i.split(",");t.info[r]=c?f.map(Number.parseInt):u?f.map(Number.parseFloat):f}return s}(d,u,t):u.info=d;const h=[];for(const e of u.alleles){const t={};for(const e in u)"alleles"!=e&&(t[e]=u[e]);for(const n in e)"allele"==n?t.alt=e[n]:"info"==n?t.altinfo=e[n]:t[n]=e[n];t.issymbolicallele||"NON_REF"==t.alt||(t.type=(0,l.P)(t.ref,t.alt)),h.push(t)}return[m.length?"unknown info keys: "+m.join(","):null,h,f.length>0?f:null]}function p(e,t,n){for(;t.length>1&&n.length>1&&t[t.length-1]==n[n.length-1];)t=t.substr(0,t.length-1),n=n.substr(0,n.length-1);for(;t.length>1&&n.length>1&&t[0]==n[0];)t=t.substr(1),n=n.substr(1),e++;return[e,t,n]}function m(e,t){const n={},s=[];let r=0,o=!1,a=null;for(let t=0;t<e.length;t++)if('"'!=e[t])"="!=e[t]?","!=e[t]||(o?o=!1:a?(n[a]=e.substring(r,t),a=null):s.push("k undefined"),r=t+1):(a=e.substring(r,t),r=t+1);else{t++;const r=t;for(;'"'!=e[t];)t++;a?(n[a]=e.substring(r,t),a=null):s.push("k undefined before double quotes"),o=!0}return a&&(n[a]=e.substring(r,i)),n.ID?(t[n.ID]=n,s.length?s.join("\n"):void 0):"no ID"}},736:(e,t,n)=>{"use strict";n.d(t,{P:()=>r});var s=n(2273);function r(e,t){return 1==e.length&&1==t.length?"."==t?s.mclassdeletion:s.mclasssnv:e.length==t.length?s.mclassmnv:e.length<t.length?s.mclassinsertion:e.length>t.length?s.mclassdeletion:s.mclassnonstandard}},7011:(e,t,n)=>{"use strict";n.d(t,{q:()=>o});var s=n(1868);const{bin:r}=n(9724);function o(e,t,n=!1,r=20,o=5){const[a,l]=e.domain(),[c,u]=s.Wem(t.values),f=Math.abs(l-a)/r;if(c==u)return{bins:[{x0:c,x1:u,density:1}],densityMax:u};let d=n?function(e,t,n,r,o){const i=t.map((t=>[t,s.J69(n,(n=>e(t-n)))])),a=[];let l=0;for(const e of i){const t={x0:e[0],x1:e[0]+o,density:e[1]};if(t.density>l&&(l=t.density),0!=t.density||0!=l){if(t.x1>r)break;a.push(t)}}return a.push({x0:r,x1:r,density:0}),{bins:a,densityMax:l}}(function(e){return t=>Math.abs(t/=e)<=1?.75*(1-t*t)/e:0}(o),e.ticks(r),t.values,u,f):i(e,t.values,r,u);return n&&0==d.densityMax&&(console.log("using histogram as max density with KDE is 0"),d=i(e,t.values,r,u)),d.bins.unshift({x0:a,x1:a,density:0}),d}function i(e,t,n,s){const o=r().domain(e.domain()).thresholds(e.ticks(n)).value((e=>e))(t),i=[];let a=0;for(const e of o)if(e.length>a&&(a=e.length),(0!=e.length||0!=a)&&(i.push({x0:e.x0,x1:e.x1,density:e.length}),e.x1>s))break;return i.push({x0:s,x1:s,density:0}),{bins:i,densityMax:a}}},3936:(e,t,n)=>{"use strict";n.d(t,{l2:()=>Jr,LJ:()=>Hr,g_:()=>Pr,U_:()=>$r,lE:()=>Mo,SC:()=>Qr,OG:()=>Zr});var s=n(334),r=n.n(s);const o=require("express");var i=n.n(o),a=n(6464);const l=require("url");var c=n.n(l);const u=require("http");var f=n.n(u);const d=require("https");var p=n.n(d),m=n(7147),h=n.n(m),g=n(1017),y=n.n(g),b=n(6452),v=n.n(b);const w=require("lazy");var _=n.n(w);const k=require("compression");var q=n.n(k),x=n(2081),N=n.n(x),S=n(6718),A=n(1881);const C=require("body-parser");var j=n.n(C),T=n(7219),M=n.n(T),O=n(4521),I=n.n(O),E=n(9344),R=n.n(E),F=n(3345),$=n(2273),D=n(6819),L=n(8064),P=n(5494),G=n(6733),U=n(5558),B=n(3602),z=n(6279),J=n(8423),H=n(8235),W={},V={};function Z(e){return new Function("d","return {"+e.map((function(e,t){return JSON.stringify(e)+": d["+t+'] || ""'})).join(",")+"}")}function K(e){var t=Object.create(null),n=[];return e.forEach((function(e){for(var s in e)s in t||n.push(t[s]=s)})),n}function X(e,t){var n=e+"",s=n.length;return s<t?new Array(t-s+1).join(0)+n:n}function Y(e){var t,n=e.getUTCHours(),s=e.getUTCMinutes(),r=e.getUTCSeconds(),o=e.getUTCMilliseconds();return isNaN(e)?"Invalid Date":((t=e.getUTCFullYear())<0?"-"+X(-t,6):t>9999?"+"+X(t,6):X(t,4))+"-"+X(e.getUTCMonth()+1,2)+"-"+X(e.getUTCDate(),2)+(o?"T"+X(n,2)+":"+X(s,2)+":"+X(r,2)+"."+X(o,3)+"Z":r?"T"+X(n,2)+":"+X(s,2)+":"+X(r,2)+"Z":s||n?"T"+X(n,2)+":"+X(s,2)+"Z":"")}var Q=function(e){var t=new RegExp('["'+e+"\n\r]"),n=e.charCodeAt(0);function s(e,t){var s,r=[],o=e.length,i=0,a=0,l=o<=0,c=!1;function u(){if(l)return V;if(c)return c=!1,W;var t,s,r=i;if(34===e.charCodeAt(r)){for(;i++<o&&34!==e.charCodeAt(i)||34===e.charCodeAt(++i););return(t=i)>=o?l=!0:10===(s=e.charCodeAt(i++))?c=!0:13===s&&(c=!0,10===e.charCodeAt(i)&&++i),e.slice(r+1,t-1).replace(/""/g,'"')}for(;i<o;){if(10===(s=e.charCodeAt(t=i++)))c=!0;else if(13===s)c=!0,10===e.charCodeAt(i)&&++i;else if(s!==n)continue;return e.slice(r,t)}return l=!0,e.slice(r,o)}for(10===e.charCodeAt(o-1)&&--o,13===e.charCodeAt(o-1)&&--o;(s=u())!==V;){for(var f=[];s!==W&&s!==V;)f.push(s),s=u();t&&null==(f=t(f,a++))||r.push(f)}return r}function r(t,n){return t.map((function(t){return n.map((function(e){return i(t[e])})).join(e)}))}function o(t){return t.map(i).join(e)}function i(e){return null==e?"":e instanceof Date?Y(e):t.test(e+="")?'"'+e.replace(/"/g,'""')+'"':e}return{parse:function(e,t){var n,r,o=s(e,(function(e,s){if(n)return n(e,s-1);r=e,n=t?function(e,t){var n=Z(e);return function(s,r){return t(n(s),r,e)}}(e,t):Z(e)}));return o.columns=r||[],o},parseRows:s,format:function(t,n){return null==n&&(n=K(t)),[n.map(i).join(e)].concat(r(t,n)).join("\n")},formatBody:function(e,t){return null==t&&(t=K(e)),r(e,t).join("\n")},formatRows:function(e){return e.map(o).join("\n")},formatRow:o,formatValue:i}}("\t"),ee=Q.parse;Q.parseRows,Q.format,Q.formatBody,Q.formatRows,Q.formatRow,Q.formatValue;function te(e){delete e.mclasslabel2key,delete e.sample2disease,delete e.patient2ori2sample}function ne(e){return null==e?null:function(e){if("function"!=typeof e)throw new Error;return e}(e)}function se(e){var t=0,n=e.children,s=n&&n.length;if(s)for(;--s>=0;)t+=n[s].value;else t=1;e.value=t}function re(e,t){e instanceof Map?(e=[void 0,e],void 0===t&&(t=ie)):void 0===t&&(t=oe);for(var n,s,r,o,i,a=new ce(e),l=[a];n=l.pop();)if((r=t(n.data))&&(i=(r=Array.from(r)).length))for(n.children=r,o=i-1;o>=0;--o)l.push(s=r[o]=new ce(r[o])),s.parent=n,s.depth=n.depth+1;return a.eachBefore(le)}function oe(e){return e.children}function ie(e){return Array.isArray(e)?e[1]:null}function ae(e){void 0!==e.data.value&&(e.value=e.data.value),e.data=e.data.data}function le(e){var t=0;do{e.height=t}while((e=e.parent)&&e.height<++t)}function ce(e){this.data=e,this.depth=this.height=0,this.parent=null}ce.prototype=re.prototype={constructor:ce,count:function(){return this.eachAfter(se)},each:function(e,t){let n=-1;for(const s of this)e.call(t,s,++n,this);return this},eachAfter:function(e,t){for(var n,s,r,o=this,i=[o],a=[],l=-1;o=i.pop();)if(a.push(o),n=o.children)for(s=0,r=n.length;s<r;++s)i.push(n[s]);for(;o=a.pop();)e.call(t,o,++l,this);return this},eachBefore:function(e,t){for(var n,s,r=this,o=[r],i=-1;r=o.pop();)if(e.call(t,r,++i,this),n=r.children)for(s=n.length-1;s>=0;--s)o.push(n[s]);return this},find:function(e,t){let n=-1;for(const s of this)if(e.call(t,s,++n,this))return s},sum:function(e){return this.eachAfter((function(t){for(var n=+e(t.data)||0,s=t.children,r=s&&s.length;--r>=0;)n+=s[r].value;t.value=n}))},sort:function(e){return this.eachBefore((function(t){t.children&&t.children.sort(e)}))},path:function(e){for(var t=this,n=function(e,t){if(e===t)return e;var n=e.ancestors(),s=t.ancestors(),r=null;e=n.pop(),t=s.pop();for(;e===t;)r=e,e=n.pop(),t=s.pop();return r}(t,e),s=[t];t!==n;)t=t.parent,s.push(t);for(var r=s.length;e!==n;)s.splice(r,0,e),e=e.parent;return s},ancestors:function(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t},descendants:function(){return Array.from(this)},leaves:function(){var e=[];return this.eachBefore((function(t){t.children||e.push(t)})),e},links:function(){var e=this,t=[];return e.each((function(n){n!==e&&t.push({source:n.parent,target:n})})),t},copy:function(){return re(this).eachBefore(ae)},[Symbol.iterator]:function*(){var e,t,n,s,r=this,o=[r];do{for(e=o.reverse(),o=[];r=e.pop();)if(yield r,t=r.children)for(n=0,s=t.length;n<s;++n)o.push(t[n])}while(o.length)}};var ue={depth:-1},fe={},de={};function pe(e){return e.id}function me(e){return e.parentId}function he(){var e,t=pe,n=me;function s(s){var r,o,i,a,l,c,u,f,d=Array.from(s),p=t,m=n,h=new Map;if(null!=e){const t=d.map(((t,n)=>function(e){e=`${e}`;let t=e.length;ye(e,t-1)&&!ye(e,t-2)&&(e=e.slice(0,-1));return"/"===e[0]?e:`/${e}`}(e(t,n,s)))),n=t.map(ge),r=new Set(t).add("");for(const e of n)r.has(e)||(r.add(e),t.push(e),n.push(ge(e)),d.push(de));p=(e,n)=>t[n],m=(e,t)=>n[t]}for(i=0,r=d.length;i<r;++i)o=d[i],c=d[i]=new ce(o),null!=(u=p(o,i,s))&&(u+="")&&(f=c.id=u,h.set(f,h.has(f)?fe:c)),null!=(u=m(o,i,s))&&(u+="")&&(c.parent=u);for(i=0;i<r;++i)if(u=(c=d[i]).parent){if(!(l=h.get(u)))throw new Error("missing: "+u);if(l===fe)throw new Error("ambiguous: "+u);l.children?l.children.push(c):l.children=[c],c.parent=l}else{if(a)throw new Error("multiple roots");a=c}if(!a)throw new Error("no root");if(null!=e){for(;a.data===de&&1===a.children.length;)a=a.children[0],--r;for(let e=d.length-1;e>=0&&(c=d[e]).data===de;--e)c.data=null}if(a.parent=ue,a.eachBefore((function(e){e.depth=e.parent.depth+1,--r})).eachBefore(le),a.parent=null,r>0)throw new Error("cycle");return a}return s.id=function(e){return arguments.length?(t=ne(e),s):t},s.parentId=function(e){return arguments.length?(n=ne(e),s):n},s.path=function(t){return arguments.length?(e=ne(t),s):e},s}function ge(e){let t=e.length;if(t<2)return"";for(;--t>1&&!ye(e,t););return e.slice(0,t)}function ye(e,t){if("/"===e[t]){let n=0;for(;t>0&&"\\"===e[--t];)++n;if(0==(1&n))return!0}return!1}const be=require("express-basic-auth");var ve=n.n(be),we=n(2826),_e=n(1271),ke=n(1696);async function qe(e,t,n,s,r,o,i,a){const l=xe().height(e.query.barheight).min(s).max(r),c=t.width/(t.stop-t.start);await F.UE({args:[o,t.chr+":"+t.start+"-"+t.stop],dir:i,callback:o=>{const i=o.split("\t"),u=Number.parseInt(i[1]);if(Number.isNaN(u))return;const f=Number.parseInt(i[2]);if(Number.isNaN(f))return;const d=Number.parseFloat(i[3]);if(Number.isNaN(d))return;a.fillStyle=d>0?e.query.pcolor:e.query.ncolor;const p=l(d),m=n+(Math.max(u,t.start)-t.start)*c,h=n+(Math.min(f,t.stop)-t.start)*c,g=Math.max(1,h-m);a.fillRect(m,p.y,g,p.h),d>r?(a.fillStyle=e.query.pcolor2,a.fillRect(m,0,g,2)):d<s&&(a.fillStyle=e.query.ncolor2,a.fillRect(m,e.query.barheight-2,g,2))}})}function xe(){var e=50,t=0,n=100;function s(s){var r,o=!1,i=0;return 0==t&&0==n||t<=0&&n>=0&&(o=!0,i=e*n/(n-t)),o?s>=n?{y:0,h:i}:s>=0?{y:i-(r=i*s/n),h:r}:s<=t?{y:i,h:e-i}:{y:i,h:r=(e-i)*s/t}:s<=t?{y:e,h:0}:{y:e-(r=e*(s-t)/(n-t)),h:r}}return s.height=function(t){return e=t,s},s.min=function(e){return t=e,s},s.max=function(e){return n=e,s},s}function Ne(e,t,n){return new Promise(((s,o)=>{const i=(0,x.spawn)(r().bigwigsummary,["-udcDir="+r().cachedir,n,t.chr,t.start,t.stop,Math.ceil(t.width*(e.query.dotplotfactor||1))]),a=[],l=[];i.stdout.on("data",(e=>a.push(e))),i.stderr.on("data",(e=>l.push(e))),i.on("close",(e=>{const t=l.join("");t.length?t.startsWith("no data")?s():o("Cannot read bigWig file"):s(a.join(""))}))}))}function Se(e,t,n,s,r){const[o,i]=function(e,t){let n=e.width/t.size,s=0;n>40&&(n=40,s=(e.width-n*t.size)/2);const r=new Map,o=e.reverse?[...t].sort(((e,t)=>t-e)):[...t].sort(((e,t)=>e-t));let i=s;for(const e of o)r.set(e,i+n/2),i+=n;return[n,r]}(e,n),a=new Map;{const t=(e.stop-e.start)/e.width;for(const s of n)e.reverse?a.set(s,(e.stop-s)/t):a.set(s,(s-e.start)/t)}let l=0;for(const e of t)l=Math.max(l,(i.get(e.stop)-i.get(e.start))/2);const c=s+l+o/2,u=(0,S.createCanvas)(e.width*r,c*r),f=u.getContext("2d");r>1&&f.scale(r,r),f.strokeStyle="black";for(const e of n)f.beginPath(),f.moveTo(a.get(e),0),f.lineTo(i.get(e),s),f.closePath(),f.stroke();for(const e of t){const t=i.get(e.start),n=i.get(e.stop),r=(t+n)/2,a=s+Math.abs(n-t)/2,l=Math.floor(255*(1-e.r2));f.fillStyle="rgb(255,"+l+","+l+")",f.beginPath(),f.moveTo(r,a-o/2),f.lineTo(r-o/2,a),f.lineTo(r,a+o/2),f.lineTo(r+o/2,a),f.lineTo(r,a-o/2),f.closePath(),f.fill()}return{height:c,src:u.toDataURL()}}var Ae=n(938);async function Ce(e,t,n){const s={rglst:[]};let r=0,o=0;if(e.autoscale){for(const s of e.rglst){const i=(n?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop;await F.UE({args:[e.file,i],dir:t,callback:e=>{const[t,n,s,i]=e.split("\t");for(const e of i.split(",")){const t=Number(e);r=Math.min(r,t),o=Math.max(o,t)}}})}s.minv=r,s.maxv=o}else r=e.minv,o=e.maxv;const i=app.makeyscale().height(e.barheight).min(r).max(o);for(const a of e.rglst){const l={chr:a.chr,start:a.start,stop:a.stop,width:a.width,reverse:a.reverse,xoff:a.xoff},c=(0,S.createCanvas)(a.width,e.barheight),u=c.getContext("2d"),f=(n?a.chr.replace("chr",""):a.chr)+":"+a.start+"-"+a.stop;await F.UE({args:[e.file,f],dir:t,callback:t=>{const[n,s,l,c]=t.split("\t"),f=Math.max(Number.parseInt(s),a.start),d=Math.min(Number.parseInt(l),a.stop),p=(a.reverse?a.stop-d:f-a.start)*a.width/(a.stop-a.start),m=(a.reverse?a.stop-f:d-a.start)*a.width/(a.stop-a.start);for(const t of c.split(",")){const n=Number(t);u.fillStyle=n>0?e.pcolor:e.ncolor;const s=i(n),a=Math.max(1,m-p);u.fillRect(p,s.y,a,2),n>o?(u.fillStyle=req.query.pcolor2,u.fillRect(p,0,a,2)):n<r&&(u.fillStyle=req.query.ncolor2,u.fillRect(p,e.barheight-2,a,2))}}}),l.img=c.toDataURL(),s.rglst.push(l)}return s}var je=n(2781);const Te="all",Me="support_ref",Oe="support_alt",Ie="support_no",Ee="support_amb",Re="support_sv";function Fe(e){const t={};if(e.variant)if(e.grouptype)t[e.grouptype]={partstack:e.partstack};else{t[Me]={},t[Ie]={},t[Ee]={};for(let n=0;n<e.variant.length;n++)t[Oe+n.toString()]={}}else{if(!e.sv)throw"q.variant or q.sv missing";e.grouptype?t[e.grouptype]={partstack:e.partstack}:(t[Re]={},t[Me]={})}for(const n in t){const s=t[n];s.type=n,s.templates=[],s.regions=$e(e.regions),s.messages=[]}return t}function $e(e){return e.map((e=>({x:e.x,scale:e.scale,ntwidth:e.ntwidth})))}var De=n(6113),Le=n.n(De),Pe=n(4314);require("jstat"),r().features,r().clustalo;function Ge(e){return e>1e9?(e/1e9).toFixed(2)+" GB":e>1e6?(e/1e6).toFixed(2)+" MB":e>1e3?(e/1e3).toFixed(2)+" KB":e+" Bytes"}const Ue={end_point:"files/",fields:["id","file_size","data_type","experimental_strategy","cases.submitter_id","associated_entities.entity_submitter_id","associated_entities.case_id","cases.samples.sample_type","analysis.workflow_type"],size:100},Be={end_point:"cases/",fields:["case_id"]},ze=[{type:"case",field:"cases.case_id"},{type:"case",field:"cases.submitter_id"},{type:"sample",field:"cases.samples.submitter_id"},{type:"sample",field:"cases.samples.sample_id"},{type:"aliquot",field:"cases.samples.portions.analytes.aliquots.submitter_id"},{type:"aliquot",field:"cases.samples.portions.analytes.aliquots.aliquot_id"}],Je="STAR 2-Pass Transcriptome",He=100,We=1e3;let Ve;async function Ze(e,t,n,s){for(const r of ze)if(await Ke(e,r.field,n,s))return t.isCaseSample=r.type,await Xe(e,r.field,10,s);const r=await Ye(e,"file_id",s);if(r.data.hits.length)return t.is_file_uuid=!0,r;const o=await Ye(e,"file_name",s);return o.data.hits.length&&(t.is_file_id=!0),o}async function Ke(e,t,n,s){const r={op:"and",content:[{op:"=",content:{field:t,value:e}}]};return(await Ve(r,Be,null,n,s)).data.hits.length>0}async function Xe(e,t,n,s){const r={op:"and",content:[{op:"=",content:{field:"data_category",value:"Sequencing Reads"}},{op:"=",content:{field:"index_files.data_format",value:"bai"}},{op:"=",content:{field:"data_type",value:"Aligned Reads"}},{op:"=",content:{field:"data_format",value:"bam"}}]};return e&&t&&r.content.push({op:"in",content:{field:t,value:e}}),await Ve(r,Ue,n,null,s)}async function Ye(e,t,n){const s={op:"and",content:[{op:"in",content:{field:t,value:e}}]},r=await Ve(s,Ue,null,null,n),o=r.data.hits[0];if(o&&"Aligned Reads"!=o.data_type)throw"Requested file is not a BAM file.";return r}async function Qe(e,t,n){const{host:s,headers:r}=t.getHostHeaders(n);r.Range="bytes=0-0";const o=s.rest+"/data/"+e;try{const e=await v()(o,{headers:r,decompress:!1});if(!(e.statusCode>=200&&e.statusCode<400))throw console.log(`gdcCheckPermission() error for got(${o})`,e),"Invalid status code: "+e.statusCode}catch(e){throw console.log("gdcCheckPermission error: ",e?.code||e),"Permission denied"}}const et=r().clustalo,tt=(0,a.promisify)(je.pipeline),nt="rgb(120,120,120)",st="rgb(230,230,230)",rt=(0,Pe.ZP)(st,nt),ot="#d48b37",it=(0,Pe.ZP)("#dbc6ad",ot),at="#3B7A57",lt=(0,Pe.ZP)("#E5FFCC",at),ct="#d13232",ut="#ffdbdd",ft=(0,Pe.ZP)(ut,ct),dt="#4888bf",pt="#c9e6ff",mt=(0,Pe.ZP)(pt,dt),ht="#6B4423",gt=(0,Pe.ZP)("#987654",ht),yt="#fc6df3",bt=(0,Pe.ZP)("#dea4da",yt),vt="#47FFFC",wt="#B2D7D7",_t=(0,Pe.ZP)(wt,vt),kt=12,qt=7,xt="black",Nt="#ededed",St="blue",At="#e0e0e0",Ct="#FF0000",jt="#6cc24a",Tt="#ffff00",Mt="#DEB887",Ot="#CD853F",It="#9a92ec",Et="#47C8FF",Rt=1,Ft=1,$t=.4,Dt=.9,Lt=7,Pt=7,Gt=10,Ut=7,Bt=40,zt=.5,Jt=2,Ht=5,Wt=7e3,Vt=1500,Zt=2e3,Kt=7,Xt=200,Yt=20,Qt=(new Set(["A","T","C","G"]),Math.random.toString()),en=3e5;function tn(e){const t=e.hg38?.datasets?.GDC;if(!t)throw"hg38.datasets.GDC missing";return t}async function nn(e,t,n,s,r){const o=e.diff_score_plotwidth/(s-r),i=s*o-r*o,a=(0,S.createCanvas)(i*e.devicePixelRatio,t.canvasheight*e.devicePixelRatio),l=a.getContext("2d");e.devicePixelRatio>1&&l.scale(e.devicePixelRatio,e.devicePixelRatio);const c=n.map((e=>e.__tempscore)),u=t.canvasheight/c.length;let f=0;const d=t.stackspace/t.canvasheight;for(const e of c){let t=0;for(const n of e)"alt0"==n?l.fillStyle=Ct:"ref"==n?l.fillStyle=Et:"alt1"==n?l.fillStyle=jt:"alt2"==n?l.fillStyle=Tt:"alt3"==n?l.fillStyle=Mt:"alt4"==n?l.fillStyle=Ot:"alt5"==n&&(l.fillStyle=It),l.fillRect(o*t,f*u,o,u-d*u),t+=1;f+=1}return{height:t.canvasheight,width:i,src:a.toDataURL(),read_height:u}}function sn(e,t,n,s){for(const r of n)for(const n of r.segments)if(!(n.ridx!=e||Math.max(n.segstart,t.start)>Math.min(n.segstop,t.stop)))for(const e of n.boxes)if(t.ntwidth>=1){if(("S"==e.opr||"X"==e.opr)&&e.s)for(let t=0;t<e.s.length;t++){const n=e.start+t,r=s.find((e=>e.position==n));if(!r)continue;const o=e.s[t];r[o]=1+(r[o]||0),"S"==e.opr&&r.total++}}else if("S"==e.opr){const n=Math.floor((e.start-t.start)*t.ntwidth),r=Math.floor((e.start+e.len-t.start)*t.ntwidth);for(let e=n;e<=r;e++){const t=s[e];t&&(t.softclip=1+(t.softclip||0),t.total++)}}}async function rn(e){if(e.query.gdcFileUUID){const t=y().join(r().cachedir_bam,e.query.file);return await async function(e,t){try{if(!await F.yE(t))return;const n=e.query.regions,s=e.query.gdcFilePosition.split(".");e.query.regions=[{chr:s[0],start:Number(s[1]),stop:Number(s[2])}],await Sn(e),e.query.regions=n}catch(e){throw e}}(e,t),[t,null]}const[t,n,s]=F.ZX(e);if(t)throw t;return[n,s?await F.d1(n,e.query.indexURL||n+".bai"):null]}async function on(e,t,n,s,r){const o=e.map((e=>e.segments[0].seq)),i=e.map((e=>e.segments[0].qual));let a="",l="";r&&(a+=">seq\n"+r.replace("\n","")+"\n");let c=0;for(const e of o){if(!(c<Xt))break;a+=">seq\n"+e.replace("\n","")+"\n",l+=yn(i[c].replace("\n",""))+"\n",c+=1}return await function(e,t,n,s,r,o,i,a){return new Promise(((n,l)=>{const c=(0,x.spawn)(et,["-i","-","-t","DNA","--outfmt=clu","--wrap=5000","--maxnumseq="+(t+1),"--maxseqlen=1000"]),u=[],f=[];je.Readable.from(e).pipe(c.stdin),c.stdout.on("data",(e=>u.push(e))),c.stderr.on("data",(e=>f.push(e))),c.on("error",(e=>{console.log("stderr (clustalo):",f),l(e)})),c.on("close",(e=>{let t=0;const c=[],f={final_read_align:[],qual_r:[],qual_g:[],qual_b:[]};let d=0;for(const e of u.toString().split("\n"))if(e.includes("seq ")){let n=0,l="",u=0,p="";0!=t&&a?p=s.split("\n")[t-1].split(","):a||(p=s.split("\n")[t].split(","));let m="",h="",g="";for(const s of e.replace("seq ",""))if(","!=s){if("-"!=s){if(n+=1,l+=s,0==t&&a)c.push(s);else if(s==c[u]&&a||!a){const e=rt(p[n-1]/Bt).replace("rgb(","").replace(")","").split(",");m+=e[0]+",",h+=e[1]+",",g+=e[2]+","}else if(s!=c[u]&&a){const e=ft(p[n-1]/Bt).replace("rgb(","").replace(")","").split(",");m+=e[0]+",",h+=e[1]+",",g+=e[2]+","}}else n>0&&n<e.replace(/-/g,"").replace(/,/g,"").replace("seq ","").length?(l+=s,0==t&&(c.push(s),u<r&&(d+=1))):(l+=" ",0==t&&c.push(s)),m+="255,",h+="255,",g+="255,";u+=1}t+=1,f.gaps_before_variant=d,f.read_count=a?t-1:t,f.qual_r.push(m),f.qual_g.push(h),f.qual_b.push(g),f.final_read_align.push(l),0!=o&&0!=i&&(f.partstack_start=o,f.partstack_stop=i)}else(e.includes("FATAL:")||e.includes("ERROR:"))&&(console.log(e),l(e));n(f)}))}))}(a,Xt,o.length,l,t,n,s,r)}async function an(e,t){let n=0;for(const s of t){const t=["view","-c",e.file];e.gdc_case_id||t.push((e.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop),await F.UE({isbam:!0,args:t,dir:e.dir,callback:e=>{const t=Number(e);if(!Number.isInteger(t))throw"total number of reads from a region not integer";n+=t}})}if(n<1.1*Wt)return;const s=(n-Wt)/(.1*Wt);e.downsample={keep:10,skip:Math.floor(s),pointer:0},e.read_limit_reached=n}async function ln(e,t){e.lines=[];const n=["view",t.file];t.gdc_case_id||n.push((t.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop),await F.UE({isbam:!0,args:n,dir:t.dir,callback:(n,s)=>{const r=n.split("\t")[1];if(!(1024&r&&t.drop_pcrduplicates||2048&r&&t.drop_supplementary_alignments)){if(t.downsample){const e=t.downsample;if(e.pointer++,e.pointer>=e.keep&&e.pointer<e.keep+e.skip)return;e.pointer>=e.keep+e.skip&&(e.pointer=0)}e.lines.push(n)}}})}async function cn(e,t){const n=[],s=["depth","-r",(e.nochr?t.chr.replace("chr",""):t.chr)+":"+(t.start+1)+"-"+t.stop,"-g","DUP",e.file||e.url];if(e.drop_pcrduplicates&&(s.push("-G"),s.push("0x400")),e.drop_supplementary_alignments&&(s.push("-G"),s.push("0x800")),await F.UE({isbam:!0,args:s,dir:e.dir,callback:e=>{const s=e.split("\t"),r=Number.parseInt(s[1])-1,o=Number.parseInt(s[2]);if(t.ntwidth>=1)return void n.push({position:r,total:o});const i=Math.floor((r-t.start)*t.ntwidth);n[i]||(n[i]={position:r,sum:0,count:0}),n[i].sum+=o,n[i].count++}}),t.ntwidth<1)for(const e of n)e&&(e.total=e.sum/e.count,delete e.sum,delete e.count);return n}async function un(e,t){for(const e of t.regions)e.lines.length>0&&e.ntwidth>=Dt&&(e.to_checkmismatch=!0,e.referenceseq=await hn(t.genome,e.chr+":"+(e.start+1)+"-"+e.stop));for(const n of e)for(const e of n.segments){const n=t.regions[e.ridx];if(!n.to_checkmismatch)continue;const s=[];for(const t of e.boxes)null!=t.cidx&&"M"==t.opr&&(t.s=e.seq.substr(t.cidx,t.len),vn(s,n,t,t.s));s.length&&e.boxes.push(...s)}for(const e of t.regions)delete e.to_checkmismatch,delete e.referenceseq}function fn(e,t){if(!e.asPaired){const n=[];for(let s=0;s<e.regions.length;s++){const r=e.regions[s];for(const o of t.templates){o.ridx=s;const t=dn(o,r,e);t&&n.push({x1:t.x1,x2:t.x2,__tempscore:t.tempscore,segments:[t]})}}return n}const n=new Map;for(let s=0;s<e.regions.length;s++){const r=e.regions[s];for(const o of t.templates){o.ridx=s;const t=dn(o,r,e);if(!t||!t.qname)continue;const i=n.get(t.qname);i?(i.segments.push(t),i.x2=Math.max(i.x2,t.x2)):n.set(t.qname,{x1:Math.max(t.x1,r.x),x2:Math.min(t.x2,r.x+r.width),__tempscore:t.tempscore,segments:[t]})}}return[...n.values()]}function dn(e,t,n){const{sam_info:s,tempscore:r,ridx:o,keepallboxes:i,keepmatepos:a,keepunmappedread:l}=e,c=s.trim().split("\t");if(c.length<11)return;const u=c[0],f=c[1],d=Number.parseInt(c[3]),p=c[5],m=c[6],h=c[7],g=Number.parseInt(c[8]),y=c[9],b=c[10];if(Number.isNaN(d)||d<=0)return;const v=d-1,w={qname:u,segstart:v,segstart_original:v,segstop:v,boxes:[],forward:!(16&f),ridx:o,seq:y,qual:b,cigarstr:p,tlen:g,flag:f,tempscore:r};if(function(e,t,n,s,r,o){const i=e.flag;if(!(1&i))return;64&i?e.isfirst=!0:128&i&&(e.islast=!0);if("="!=t&&"*"!=t&&t!=s.chr)return e.rnext=t,void(e.pnext=n);if(8&i)return void(e.discord_unmapped2=!0);32&i&&!(16&i)&&64&i||16&i&&!(32&i)&&128&i||16&i&&!(32&i)&&64&i||32&i&&!(16&i)&&128&i||(e.discord_orientation=!0,r&&(16&i?32&i?e.discord_orientation_direction="R1R2":n>o&&(e.discord_orientation_direction="R1F2"):32&i?n<o&&(e.discord_orientation_direction="R1F2"):e.discord_orientation_direction="F1F2")),2&i||(e.discord_wrong_insertsize=!0,r&&(e.pnext=n))}(w,m,h,t,a,d),4&f)return l?(w.boxes.push({opr:p,start:v,len:y.length,cidx:0,qual:b}),w.discord_unmapped1=!0,w):void 0;if("*"!=p){let e=v,s=0,r=0;for(let n=0;n<p.length;n++){const o=p[n];if(o.match(/[0-9]/))continue;const a=Number.parseInt(p.substring(s,n));if("H"!=o)if("N"==o||"P"==o||"D"==o||(r+=a),s=n+1,"="!=o&&"M"!=o)if("I"!=o)if("N"!=o&&"D"!=o)if("X"!=o)if("S"!=o){if("P"!=o)console.log("unknown cigar: "+o);else if(i||e>t.start&&e<t.stop){const t={opr:"P",start:e,len:a,cidx:r-a};w.boxes.push(t)}}else{const n={opr:o,start:e,len:a,cidx:r-a};0==w.boxes.length?(n.start-=a,(i||Math.max(e,t.start)<=Math.min(e+a-1,t.stop))&&w.boxes.push(n)):w.boxes.push(n)}else{if(i||Math.max(e,t.start)<Math.min(e+a-1,t.stop)){const t={opr:o,start:e,len:a,cidx:r-a};w.boxes.push(t)}e+=a}else(e>=t.start&&e<=t.stop||e+a-1>=t.start&&e+a-1<=t.stop||i)&&w.boxes.push({opr:o,start:e,len:a}),e+=a;else(i||e>t.start&&e<t.stop)&&a*t.ntwidth>=Rt&&w.boxes.push({opr:"I",start:e,len:a,cidx:r-a});else(i||Math.max(e,t.start)<=Math.min(e+a-1,t.stop))&&w.boxes.push({opr:o,start:e,len:a,cidx:r-a}),e+=a;else{const l={opr:o,start:e,len:a,cidx:r-a};0==w.boxes.length?(l.start-=a,l.cidx=0,(i||Math.max(e,t.start)<=Math.min(e+a-1,t.stop))&&w.boxes.push(l)):w.boxes.push(l),s=n+1}}if(0==w.boxes.length)return void(n&&n.readcount_skipped++);w.segstop=e,w.x1=t.x+t.scale(w.boxes[0].start),w.x2=t.x+t.scale((_=w.boxes,Math.max(..._.map((e=>e.start+e.len)))))}var _;return w}async function pn(e,t,n){const[s,r]=function(e,t){let n=(t.groups.length>1?Vt/2:Vt)/e;return n>10?[Math.min(15,Math.floor(n)),1]:n>7?[Math.floor(n),1]:n>3?[Math.ceil(n),0]:n>1?[Math.floor(n),0]:[n,0]}(e.stacks.length,t);e.stackheight=s,e.stackspace=r;for(const t of e.regions)t.to_printnt=e.stackheight>7&&t.ntwidth>=7,t.to_qual=t.ntwidth>=Ft;if(e.stacks.length&&(e.stackheight>=Kt&&n.length<Zt?e.returntemplatebox=[]:e.partstack||(e.allowpartstack=!0)),e.stackheight>=Lt){let t=0;for(const e of n)for(const n of e.segments)t=Math.max(t,n.x2-n.x1);t>.7*e.stackheight&&(e.canClipArrowhead=!0)}}function mn(e,t,n){if(t.asPaired){e.stacks=[];const s=[],r=[];for(const e of n){let n=e.segments[0].ridx;1==e.segments.length||2==e.segments.length&&e.segments[0].ridx==e.segments[1].ridx?(e.x1=Math.max(t.regions[n].x,e.x1),e.x2=Math.min(t.regions[n].x+t.regions[n].width,e.x2),s.push(e)):2==e.segments.length&&e.segments[0].ridx!=e.segments[1].ridx&&(e.x1=e.x1,e.x2=e.x2,r.push(e))}if(s.sort(((e,t)=>e.x1-t.x1)),r.sort(((e,t)=>e.x1-t.x1)),r.length>0){const e=[],t=[],o=r[0];for(const n of s)n.x1<o.x1&&n.x2<o.x1?e.push(n):t.push(n);n=[...e,...r,...t]}for(const s of n){let n=s.segments[0].ridx,r=null;if(!t.variant)for(let o=0;o<e.stacks.length;o++){if(s.x2==t.regions[n].x+t.regions[n].width&&e.stacks[o]<s.x1){r=o,e.stacks[o]=s.x2;break}if(e.stacks[o]+t.stacksegspacing<s.x1){r=o,e.stacks[o]=s.x2;break}}null==r&&(r=e.stacks.length,e.stacks[r]=s.x2),s.y=r}}else{n.sort(((e,t)=>e.x1-t.x1)),e.stacks=[];for(let s=0;s<t.regions.length;s++)for(const r of n)if(r.segments[0].ridx==s){let n=null;if(!t.variant&&!t.sv)for(let o=0;o<e.stacks.length;o++)if(e.stacks[o]+t.stacksegspacing<r.x1&&e.stacks[o]+t.stacksegspacing<t.regions[s].x+t.regions[s].width){n=o,e.stacks[o]=r.x2;break}null==n&&(n=e.stacks.length,e.stacks[n]=r.x2),r.y=n}}return n=function(e,t,n){if(!e.partstack)return t;const s=t.filter((t=>t.y>=e.partstack.start&&t.y<=e.partstack.stop));s.forEach((t=>t.y-=e.partstack.start)),t=s,e.stacks=[];for(let t=e.partstack.start;t<=e.partstack.stop;t++)e.stacks.push(0);return e.returntemplatebox=[],t}(e,n),n}async function hn(e,t){const n=(await F.Kf(e,t)).split("\n");return n.shift(),n.join("").toUpperCase()}function gn(e,t,n){const s=function(e,t,n){const s=[];for(let t=0;t<e.stacks.length;t++)s.push(e.stackheight);if(function(e,t){if(!t.asPaired)return;for(const t of e.regions)if(t.ntwidth<=$t)return;e.overlapRP_multirows=!0,e.overlapRP_hlline=e.stackspace>0}(e,n),e.overlapRP_multirows)for(const n of t)n.segments.length<=1||n.segments[0].ridx!=n.segments[1].ridx||(n.height=bn(n,e.stackheight),s[n.y]=Math.max(s[n.y],n.height));const r=[];let o=e.stackspace;for(const t of s)r.push(o),o+=t+e.stackspace;return e.canvasheight=o,r}(e,t,n);for(const n of t){n.y=s[n.y];for(const t of n.segments){const n=e.regions[t.ridx].to_qual?yn(t.qual):null;for(const e of t.boxes)null!=e.cidx&&"H"!=e.opr&&(n&&(e.qual=n.slice(e.cidx,e.cidx+e.len)),"I"==e.opr?e.s=t.seq.substr(e.cidx,e.len):"X"!=e.opr&&"S"!=e.opr||(e.s=t.seq.substr(e.cidx,e.len)),delete e.cidx);delete t.seq,delete t.qual}}}function yn(e){if("*"==e)return null;const t=[];for(let n=0;n<e.length;n++){const s=e[n].charCodeAt(0)-33;t.push(s)}return t}function bn(e,t){if(2==e.segments.length){const[n,s]=e.segments;return n.x2>s.x1?(s.shiftdownrow=1,2*t):t}console.log("more than 2 segments",e.segments.length);const n=[];for(const t of e.segments){let e=null;for(let s=0;s<n.length;s++)if(n[s]<t.x1){e=s,n[s]=t.x2;break}null==e&&(e=n.length,n[e]=t.x2),t.shiftdownrow=e}return t*n.length}function vn(e,t,n,s){for(let r=0;r<s.length;r++){if(n.start+r<t.start||n.start+r>t.stop)continue;const o=s[r];if(t.referenceseq[n.start+r-t.start]!=o.toUpperCase()){const t={opr:"X",start:n.start+r,len:1,s:o,cidx:n.cidx+r};e.push(t)}}}function wn(e,t,n,s){if(n.returntemplatebox){const e=n.regions[t.segments[0].ridx];let r;if(e.width=n.widths[t.segments[0].ridx],s.asPaired)if(2==t.segments.length)r=t.segments[0].ridx!=t.segments[1].ridx?{qname:t.segments[0].qname,x1:t.x1,x2:t.x2,y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop))),multi_region:!0}:{qname:t.segments[0].qname,x1:Math.max(e.x,t.x1),x2:Math.min(t.x2,e.width),y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop)))};else{const e=t.segments[0],s=n.regions[e.ridx];s.width=n.widths[e.ridx],r={qname:t.segments[0].qname,x1:Math.max(s.x,t.x1),x2:Math.min(t.x2,s.width),y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop)))}}else r={qname:t.segments[0].qname,x1:Math.max(e.x,t.x1),x2:Math.min(t.x2,e.x+e.width),y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop)))},t.segments[0].isfirst&&(r.isfirst=!0),t.segments[0].islast&&(r.islast=!0);n.returntemplatebox.push(r)}for(let r=0;r<t.segments.length;r++){const o=t.segments[r],i=n.regions[o.ridx];if(i.width=n.widths[o.ridx],0==r){_n(e,o,t.y,n,s);continue}const a=t.segments[r-1],l=n.regions[a.ridx];if(l.width=n.widths[a.ridx],a.x2<=o.x1||t.segments[0].ridx!=t.segments[1].ridx){_n(e,o,t.y,n,s);const r=Math.floor(t.y+n.stackheight/2)+.5;if(e.strokeStyle=n.stackheight<=2?Nt:nt,e.setLineDash([5,3]),e.beginPath(),l.x==i.x?(e.moveTo(a.x2,r),e.lineTo(o.x1,r)):l.x<a.x2&&o.x1<i.width&&(e.moveTo(Math.min(a.x2,l.width),r),e.lineTo(Math.max(o.x1,i.x),r)),e.stroke(),n.overlapRP_hlline){const s=a.boxes.reduce(((e,t)=>e.start+e.len>t.start+t.len?e:t));if(s.start+s.len==o.boxes[0].start){e.strokeStyle=St,e.setLineDash([]),e.beginPath();const s=Math.floor(o.x1)+.5;e.moveTo(s,t.y),e.lineTo(s,t.y+n.stackheight),e.stroke()}}}else if(n.overlapRP_multirows){if(_n(e,o,t.y+n.stackheight,n,s),n.overlapRP_hlline){const s=Math.floor(t.y+n.stackheight)+.5;e.strokeStyle=St,e.setLineDash([]),e.beginPath(),l.x<=a.x2&&o.x1<=i.width&&(e.moveTo(Math.max(o.x1,i.x),s),e.lineTo(Math.min(a.x2,l.width),s)),e.stroke()}}else _n(e,o,t.y,n,s)}null!=t.__tempscore&&r().features.indel_read_alignment_scores&&(e.fillStyle="blue",e.font=n.stackheight+"pt Arial",e.fillText(t.__tempscore,s.regions[0].width-100,t.y+n.stackheight/2))}function _n(e,t,n,s,r){const o=s.regions[t.ridx];o.width=s.widths[t.ridx];for(const r of t.boxes){const i=o.x+o.scale(r.start);if("P"!=r.opr&&"I"!=r.opr)if("H"!=r.opr)if("D"!=r.opr&&"N"!=r.opr)if("*"!=r.opr){if("X"!=r.opr&&"S"!=r.opr){if("M"!=r.opr&&"="!=r.opr)throw"unknown opr at rendering: "+r.opr;if(o.to_qual&&r.qual){let a=i;r.qual.forEach((r=>{t.rnext?e.fillStyle=it(r/Bt):t.discord_orientation?e.fillStyle=bt(r/Bt):t.discord_wrong_insertsize?e.fillStyle=lt(r/Bt):t.discord_unmapped2?e.fillStyle=gt(r/Bt):e.fillStyle=rt(r/Bt),a+o.ntwidth+zt<o.width&&o.x<=a?e.fillRect(a,n,o.ntwidth+zt,s.stackheight):a<o.width&&a+o.ntwidth+zt>=o.width&&o.x<=a?e.fillRect(a,n,o.width-a,s.stackheight):a<=o.x&&a+o.ntwidth+zt>o.x&&e.fillRect(o.x,n,o.ntwidth+zt+a-o.x,s.stackheight),a+=o.ntwidth}))}else r.qual?t.rnext?e.fillStyle=ot:t.discord_orientation?e.fillStyle=yt:t.discord_wrong_insertsize?e.fillStyle=at:t.discord_unmapped2?e.fillStyle=ht:e.fillStyle=nt:o.to_printnt?e.fillStyle="white":t.rnext?e.fillStyle=ot:t.discord_orientation?e.fillStyle=yt:t.discord_wrong_insertsize?e.fillStyle=at:t.discord_unmapped2?e.fillStyle=ht:e.fillStyle=nt,i+r.len*o.ntwidth+zt<o.width&&i<o.width&&o.x<i+zt?e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight):i+r.len*o.ntwidth+zt<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+zt+i-o.x,s.stackheight):i+r.len*o.ntwidth+zt>=o.width&&o.x<i?e.fillRect(i,n,o.width-i,s.stackheight):i+r.len*o.ntwidth+zt>=o.width&&o.x>=i&&e.fillRect(o.x,n,o.width-i,s.stackheight);if(o.to_printnt){e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial",r.qual?e.fillStyle="white":e.fillStyle="black";for(let t=0;t<r.s.length;t++)i+o.ntwidth*(t+.5)<o.width&&i<o.width&&o.x<=i+o.ntwidth*(t+.5)&&e.fillText(r.s[t],i+o.ntwidth*(t+.5),n+s.stackheight/2)}}else if(o.to_qual&&r.qual){o.to_printnt&&(e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial");let t=i;for(let i=0;i<r.qual.length;i++){const a=r.qual[i]/Bt;e.fillStyle="S"==r.opr?mt(a):ft(a),t+o.ntwidth+zt<o.x+o.width&&o.x<=t?e.fillRect(t,n,o.ntwidth+zt,s.stackheight):t<o.x+o.width&&t+o.ntwidth+zt>=o.x+o.width&&o.x<=t?e.fillRect(t,n,o.width+o.x-t,s.stackheight):t<=o.x&&t+o.ntwidth+zt>o.x&&e.fillRect(o.x,n,o.ntwidth+zt+t-o.x,s.stackheight),o.to_printnt&&(r.qual?e.fillStyle="white":e.fillStyle="black",t+o.ntwidth/2<o.width&&t<o.width&&o.x<=t+o.ntwidth/2&&e.fillText(r.s[i],t+o.ntwidth/2,n+s.stackheight/2)),t+=o.ntwidth}}else if(e.fillStyle="S"==r.opr?dt:ct,i+r.len*o.ntwidth+zt<o.width&&o.x<i?e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight):i+r.len*o.ntwidth+zt<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+zt+i-o.x,s.stackheight):i+r.len*o.ntwidth+zt<=o.width&&o.x<i&&e.fillRect(i,n,o.width-i,s.stackheight),o.to_printnt&&!r.qual){e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial",r.qual?e.fillStyle="white":e.fillStyle="black";for(let t=0;t<r.s.length;t++)i+o.ntwidth*(t+.5)<o.width&&i<o.width&&o.x<=i+o.ntwidth*(t+.5)&&e.fillText(r.s[t],i+o.ntwidth*(t+.5),n+s.stackheight/2)}}else{if(o.to_qual&&r.qual){let a=i;r.qual.forEach((r=>{t.discord_unmapped2&&(e.fillStyle=gt(r/Bt)),e.fillRect(a,n,o.ntwidth+zt,s.stackheight),a+=o.ntwidth}))}else t.discord_unmapped2&&(e.fillStyle=ht),e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight);o.to_printnt&&(e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial")}else{"D"==r.opr?e.strokeStyle=xt:e.strokeStyle=s.stackheight<=2?Nt:nt,e.setLineDash([]);const t=Math.floor(n+s.stackheight/2)+.5;if(e.beginPath(),e.moveTo(Math.max(i,o.x),t),e.lineTo(Math.min(i+r.len*o.ntwidth,o.x+o.width),t),e.stroke(),s.stackheight>Pt){const t=Math.max(o.x,i),a=Math.min(o.x+o.width,i+r.len*o.ntwidth);if(a-t>=50){const i=Math.min(Gt,Math.max(Ut,s.stackheight-2));e.font=i+"pt Arial";const l=e.measureText(r.len+" bp").width;l<a-t-20&&(e.fillStyle="white",(a+t)/2+l/2<o.width&&o.x<(a+t)/2-l/2?(e.fillRect((a+t)/2-l/2,n,l,s.stackheight),e.fillStyle=nt,e.fillText(r.len+" bp",(a+t)/2,n+s.stackheight/2)):(a+t)/2+l/2<o.width&&o.x>=(a+t)/2-l/2?(e.fillRect(o.x,n,l+(a+t)/2-l/2-o.x,s.stackheight),e.fillStyle=nt,e.fillText(r.len+" bp",(a+t)/2,n+s.stackheight/2)):(a+t)/2+l/2>=o.width&&o.x<(a+t)/2-l/2&&(e.fillRect((a+t)/2-l/2,n,o.width-(a+t)/2+l/2,s.stackheight),e.fillStyle=nt,e.fillText(r.len+" bp",(a+t)/2,n+s.stackheight/2)))}}}else e.fillStyle="white",i+r.len*o.ntwidth+zt<o.width&&o.x<i?e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight):i+r.len*o.ntwidth+zt<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+zt+i-o.x,s.stackheight):i+r.len*o.ntwidth+zt<=o.width&&o.x<i&&e.fillRect(i,n,o.width-i,s.stackheight)}!function(e,t,n,s,r){if(!n.canClipArrowhead)return;if(t.x2-t.x1<5)return;if(t.forward){const o=Math.ceil(t.x2+zt);o<=s.width+n.stackheight/2&&(e.fillStyle="white",e.beginPath(),e.moveTo(o-n.stackheight/2,r),e.lineTo(o,r),e.lineTo(o,r+n.stackheight/2),e.lineTo(o-n.stackheight/2,r),e.closePath(),e.fill(),e.beginPath(),e.moveTo(o-n.stackheight/2,r+n.stackheight),e.lineTo(o,r+n.stackheight),e.lineTo(o,r+n.stackheight/2),e.lineTo(o-n.stackheight/2,r+n.stackheight),e.closePath(),e.fill())}else{const o=t.x1;o>=s.x&&(e.fillStyle="white",e.beginPath(),e.moveTo(o+n.stackheight/2,r),e.lineTo(o,r),e.lineTo(o,r+n.stackheight/2),e.lineTo(o+n.stackheight/2,r),e.closePath(),e.fill(),e.beginPath(),e.moveTo(o+n.stackheight/2,r+n.stackheight),e.lineTo(o,r+n.stackheight),e.lineTo(o,r+n.stackheight/2),e.lineTo(o+n.stackheight/2,r+n.stackheight),e.closePath(),e.fill())}}(e,t,s,o,n),t.rnext&&(o.to_qual||t.x2-t.x1>=20&&s.stackheight>=7&&(e.font=Math.min(kt,Math.max(qt,s.stackheight-4))+"pt Arial",e.fillStyle="white",e.fillText((r.nochr?"chr":"")+t.rnext,(t.x1+t.x2)/2,n+s.stackheight/2,t.x2-t.x1)))}function kn(e,t,n,s){for(const[e,n]of t.regions.entries()){if(!n.to_printnt)continue;const t=new Set;for(const r of s)for(const s of r.segments){if(s.ridx!=e)continue;const r=s.boxes.filter((e=>"I"==e.opr));if(r.length)for(const e of r)t.add(n.x+n.scale(e.start))}}for(const n of s)for(const s of n.segments){const r=t.regions[s.ridx],o=s.boxes.filter((e=>"I"==e.opr));if(o.length){e.font=Math.max(kt,t.stackheight-2)+"pt Arial";for(const i of o){const o=r.x+r.scale(i.start);let a;i.qual?e.fillStyle=_t(i.qual.reduce(((e,t)=>e+t),0)/i.qual.length/Bt):e.fillStyle=vt,a=""==i.s?i.len:1==i.s.length?i.s:i.s.length,e.fillText(a,o,n.y+t.stackheight*(s.on2ndrow||0)+t.stackheight/2)}}}}async function qn(e,t,n){const s=yn(e.qual),r=['<td style="color:black;text-align:left">Read</td>'];for(const t of e.boxes)for(let n=0;n<t.len;n++){e.seq[t.cidx+n];r.push('<td style="background:'+rt(s[t.cidx+n]/Bt)+'">'+e.seq[t.cidx+n]+"</td>")}const o=[];o.push('<li><span style="background:'+ht+';color:white">This segment in template is unmapped</span></li>'),1&e.flag&&o.push("<li>Template has multiple segments</li>"),2&e.flag&&o.push("<li>Each segment properly aligned</li>"),16&e.flag&&o.push("<li>Reverse complemented</li>"),32&e.flag&&o.push("<li>Next segment in the template is reverse complemented</li>"),64&e.flag&&o.push("<li>This is the first segment in the template</li>"),128&e.flag&&o.push("<li>This is the last segment in the template</li>"),256&e.flag&&o.push("<li>Secondary alignment</li>"),512&e.flag&&o.push("<li>Not passing filters</li>"),1024&e.flag&&o.push("<li>PCR or optical duplicate</li>"),2048&e.flag&&o.push("<li>Supplementary alignment</li>");let i={seq:e.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center">\n\t\t\t <tr style="color:white">${r.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE</span>: ${Math.abs(e.seq.length)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${e.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${e.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${e.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${o.join("")}</ul>`};return e.discord_unmapped2&&(i.unmapped_mate=!0),i}async function xn(e,t,n){const s=e.boxes[0].start,r=e.boxes[e.boxes.length-1],o=r.start+r.len,i=await hn(t,n.chr+":"+(s+1)+"-"+o),a=yn(e.qual);let l,c;if("*"==e.seq)l=["<td>Nucleotide sequence not available for this read</td>"],c=["<td></td>"];else{l=["<td>Reference</td>"],c=['<td style="color:black;text-align:left">Read</td>'];for(const t of e.boxes)if("H"!=t.opr)if("I"!=t.opr)if("D"!=t.opr&&"N"!=t.opr)if("S"!=t.opr)if("M"!=t.opr&&"="!=t.opr&&"X"!=t.opr&&"*"!=t.opr);else for(let n=0;n<t.len;n++){const r=i[t.start-s+n],o=e.seq[t.cidx+n];l.push("<td>"+r+"</td>"),"*"==e.qual?c.push('<td style="color:black;background:'+(r.toUpperCase()==o.toUpperCase()?rt:ft)+'">'+e.seq[t.cidx+n]+"</td>"):c.push('<td style="background:'+(r.toUpperCase()==o.toUpperCase()?rt:ft)(a[t.cidx+n]/Bt)+'">'+e.seq[t.cidx+n]+"</td>")}else for(let n=0;n<t.len;n++)l.push("<td>"+i[t.start-s+n]+"</td>"),"*"==e.qual?c.push('<td style="background:'+mt(1)+'">'+e.seq[t.cidx+n]+"</td>"):c.push('<td style="background:'+mt(a[t.cidx+n]/Bt)+'">'+e.seq[t.cidx+n]+"</td>");else if(t.len>=Yt)l.push('<td style="font-size:.8em;opacity:.5;white-space:nowrap">'+t.len+" bp</td>"),c.push('<td style="color:black;white-space:nowrap">-----------</td>');else for(let e=0;e<t.len;e++)l.push("<td>"+i[t.start-s+e]+"</td>"),c.push('<td style="color:black">-</td>');else for(let n=t.cidx;n<t.cidx+t.len;n++)l.push("<td>-</td>"),"*"==e.qual?c.push('<td style="color:'+vt+';background:white">'+e.seq[n]+"</td>"):c.push('<td style="color:'+vt+";background:"+rt(a[n]/Bt)+'">'+e.seq[n]+"</td>")}let u=0,f=0,d=[],p=[],m=0;for(const t of e.boxes)u=f,f+=t.len,"S"==t.opr&&(m=1,d.push(u),p.push(f));const h=[];e.rnext&&h.push('<li>Next segment on <span style="background:'+ot+'">'+(n.nochr?"chr":"")+e.rnext+", "+e.pnext+"</span></li>"),e.discord_wrong_insertsize&&e.discord_orientation?h.push('<li><span style="background:'+at+';color:white">Wrong insert size</span> mate position: '+e.pnext+'</li><li><span style="background:'+yt+';color:white">Segments also having wrong orientation</span> '+e.discord_orientation_direction+"</li>"):e.discord_wrong_insertsize?h.push('<li><span style="background:'+at+';color:white">Wrong insert size</span> mate position: '+e.pnext+"</li>"):e.discord_orientation?h.push('<li><span style="background:'+yt+';color:white">Segments having wrong orientation</span> '+e.discord_orientation_direction+"</li>"):e.discord_unmapped2&&h.push('<li><span style="background:'+ht+';color:white">Other segment in template is unmapped</span></li>'),1&e.flag&&h.push("<li>Template has multiple segments</li>"),2&e.flag&&h.push("<li>Each segment properly aligned</li>"),16&e.flag&&h.push("<li>Reverse complemented</li>"),32&e.flag&&h.push("<li>Next segment in the template is reverse complemented</li>"),64&e.flag&&h.push("<li>This is the first segment in the template</li>"),128&e.flag&&h.push("<li>This is the last segment in the template</li>"),256&e.flag&&h.push("<li>Secondary alignment</li>"),512&e.flag&&h.push("<li>Not passing filters</li>"),1024&e.flag&&h.push("<li>PCR or optical duplicate</li>"),2048&e.flag&&h.push("<li>Supplementary alignment</li>");let g={seq:e.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center;font-family:courier">\n\t\t\t <tr style="opacity:.6">${l.join("")}</tr>\n\t\t\t <tr style="color:white">${c.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">CHR</span>: ${n.chr.replace("chr","")},\n\t\t\t<span style="opacity:.5;font-size:.7em">START</span>: ${e.segstart_original+1},\n\t\t\t<span style="opacity:.5;font-size:.7em">STOP</span>: ${o},\n\t\t\t<span style="opacity:.5;font-size:.7em">READ LENGTH</span>: ${e.seq.length} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE LENGTH</span>: ${Math.abs(e.tlen)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${e.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${e.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${e.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${h.join("")}</ul>`,start_readpos:s+1,boxes:e.boxes,readpanel_DN_maxlength:Yt};return 1==m&&(g.soft_starts=d,g.soft_stops=p),e.discord_unmapped2&&(g.unmapped_mate=!0),g}function Nn(e){const t=Le().createHmac("md5",Qt),n=[e.get("X-Auth-Token")||e.cookies.sessionid,e.query.gdcFileUUID,e.query.gdcFilePosition];return t.update(n.join("")).digest("hex")+".bam"}async function Sn(e){if(!e.query.gdcFileUUID||!e.query.gdcFilePosition||!e.query.file)throw"cannot download GDC BAM slice: request is unauthorized";const t=e.query.regions;if(!Array.isArray(t)||0==t.length)throw"req.query.regions[] not non-empty array";const n=[];for(const s of t){const t=await Rn(s.chr,s.start,s.stop,e.query.gdcFileUUID,Nn(e),e);n.push({filesize:t})}return n}const An=r().features?.bamCache||{},Cn=An.maxAge||72e5,jn=An.maxSize||5e9,Tn=An.checkWait||6e4;let Mn,On=0;function In(e=0){const t=Date.now()+e;if(Mn){if(On&&On<=t+5)return;clearTimeout(Mn),Mn=void 0}On=t,console.log(`will trigger mayDeleteCacheFiles() in ${e} ms`),Mn=setTimeout(En,e)}async function En(){console.log("checking for cached bam files to delete ...");try{const e=Date.now()-Cn,t=await h().promises.readdir(r().cachedir_bam),n=[];let s=0,o=0,i=0,a=0;for(const l of t){if(!l.endsWith(".bam")&&!l.endsWith(".bai"))continue;i++;const t=y().join(r().cachedir_bam,l),c=await h().promises.stat(t);if(!c.isFile())continue;const u=c.mtimeMs;u<e?(await h().promises.unlink(t),a++,o+=c.size):(n.push({path:t,time:u,size:c.size}),s+=c.size)}if(n.sort(((e,t)=>t.time-e.time)),s>=jn){const e=Date.now()-Tn;for(const t of n){if(t.time>e)break;if(await h().promises.unlink(t.path),t.deleted=!0,a++,o+=t.size,s-=t.size,s<jn)break}}console.log(`deleted ${a} of ${i} cached bam files (${o} bytes deleted, ${s} remaining)`),Mn=void 0,On=0;const l=s&&n.find((e=>!e.deleted));if(l){In(Tn+Math.round(s>=jn?0:Math.max(0,l.time+Cn-Date.now())))}}catch(e){console.error("Error in mayDeleteCacheFiles(): "+e)}}async function Rn(e,t,n,s,o,i){In(Tn);const{host:a,headers:l}=tn(i.query.__genomes).getHostHeaders(i.query);l.compression=!1;const c=y().join(r().cachedir_bam,o),u=a.rest+"/slicing/view/"+s+"?region="+e+":"+t+"-"+n;try{const e=Math.round(Date.now()/1e3);if(await F.yE(c)){if(await tt(v().stream(u,{method:"GET",headers:l}),h().createWriteStream(c)),await F.yE(c))throw"BAM file slice is not found after downloading"}else await h().promises.utimes(c,e,e);const t=c+".bai";if(await F.yE(t)){if(await async function(e){await F.UE({isbam:!0,args:["index",e],callback:()=>{}})}(c),await F.yE(t))throw"index file is missing after indexing"}else await h().promises.utimes(t,e,e);const n=await h().promises.stat(c);return(0,$.bplen)(n.size,!0)}catch(e){throw e.stack&&console.log(e.stack),"Error with BAM slicing: "+(e.message||e)}}r().features?.bamCache&&In(Tn);const Fn="Unannotated";function $n(e){return e.file?e.file:e.file2?e.file2:e.url}function Dn(e,t,n,s){const r=[];for(const o of e.samples)if(Number.isFinite(o.readcount)&&(o.readcount=Math.floor(o.readcount),!(o.readcount<=0||t.readcountCutoff&&o.readcount<t.readcountCutoff))){if(s.samples&&n.cohort&&n.cohort.annotation){const e=s.samples[o.i];if(!e)continue;const r=n.cohort.annotation[e];if(o.anno=r,t.cohortOnlyAttr&&n.cohort&&n.cohort.annotation){if(!r)continue;let e=!1;for(const n in t.cohortOnlyAttr){const s=r[n];if(s&&t.cohortOnlyAttr[n][s]){e=!0;break}}if(!e)continue}if(t.cohortHiddenAttr&&n.cohort&&n.cohort.annotation&&n.cohort.attributes){if(!r)continue;let e=!1;for(const s in t.cohortHiddenAttr){n.cohort.attributes.lst.find((e=>e.key==s)).isNumeric;const o=r[s];if(o){if(t.cohortHiddenAttr[s][o]){e=!0;break}}else if(t.cohortHiddenAttr[s][Fn]){e=!0;break}}if(e)continue}}if(o.events&&t.spliceEventPercentage){let n=!1;for(const s in o.events){if(!e.events[s])continue;const r=e.events[s].attrValue,i=t.spliceEventPercentage[r];if(!i)continue;const a=o.events[s].percentage;if(null!=a)if(">"==i.side){if(a<=i.value){n=!0;break}}else if(a>=i.value){n=!0;break}}if(n)continue}r.push(o)}return r}function Ln(e,...t){if(0==e.length)return 0;const n=e.sort(((e,t)=>e.readcount-t.readcount)),s=[];return t.forEach((e=>{!Number.isFinite(e)||e<0||e>1?s.push(null):s.push(n[Math.floor(n.length*e)].readcount)})),s}var Pn=n(4555);function Gn(e){return new Promise(((t,n)=>{const s=I().createInterface({input:h().createReadStream(e.file,{encoding:"utf8"})}),r=[];let o=!0;s.on("line",(t=>{if(o)return void(o=!1);const n=t.split("\t"),[i,a,l,c,u,f]=n[0].split(/[:,]/);if(i!=e.chr)return;const d=Number.parseInt(a),p=Number.parseInt(u);if(Number.isNaN(d)||Number.isNaN(p))return;const m=d-1,h=p-1;if(m>e.start&&m<e.stop||h>e.start&&h<e.stop){const e=Number.parseInt(n[1]),t=n[2];r.push({chr:i,start:m,stop:h,type:t,rawdata:[e]})}else m>e.stop&&s.close()})),s.on("close",(()=>{t(r)}))}))}const Un=new Set(["-1","0","1","2"]);function Bn(e,t){e[0];const n=Number(e[1]),s=(e[2],e[3].split(".")[0]),r=e[5];if("+"!=r&&"-"!=r)return{name:s};const o="+"==r,i=Number(e[6]),a=Number(e[7]);if(!Number.isInteger(i)||!Number.isInteger(a))return{name:s,strand:r};const l=[],c=[],u=[],f=[],d=[],p=e[15],m=e[17],h=e[20];if(!e[10].includes(",")||!e[11].includes(","))return{name:s,strand:r};const g=e[10].split(",");g.pop();const y=g.map(Number),b=e[11].split(",");b.pop();const v=b.map(Number);if(y.includes(NaN)||v.includes(NaN))return{name:s,strand:r};let w=null,_=0,k=0;for(const[e,t]of y.entries()){_+=t;const s=n+v[e],r=s+t;o?d.push([s,r]):d.unshift([s,r]),e>0&&(o?f.push([w,s]):f.unshift([w,s])),w=r,s<i?r<i?o?c.push([s,r]):l.unshift([s,r]):(o?c.push([s,i]):l.unshift([s,i]),r>a?(i<a&&(o?u.push([i,a]):u.unshift([i,a]),k+=a-i),o?l.push([a,r]):c.unshift([a,r])):i<r&&(o?u.push([i,r]):u.unshift([i,r]),k+=r-i)):s<a?r<=a?s<r&&(o?u.push([s,r]):u.unshift([s,r]),k+=r-s):(s<a&&(o?u.push([s,a]):u.unshift([s,a]),k+=a-s),o?l.push([a,r]):c.unshift([a,r])):o?l.push([s,r]):c.unshift([s,r])}const q={name:m,isoform:s,strand:r,exon:d,rnalen:_};26==e.length&&(q.category=h),t&&t.has(s)&&(q.description=t.get(s)),f.length>0&&(q.intron=f),i==a||(q.cdslen=k,q.codingstart=i,q.codingstop=a,q.coding=u,c.length&&(q.utr5=c),l.length&&(q.utr3=l));const x=p.split(",");return x.pop(),x.length<1||x.some((e=>!Un.has(e)))||function(e,t){if(!e.codingstart)return;const n="+"==e.strand?e.codingstart:e.codingstop;let s=e.exon.findIndex((e=>e[1]>=n&&e[0]<=n));if(-1==s)throw"start codon not matched to an exon: "+JSON.stringify(e);"-"==e.strand&&(s=e.exon.length-s-1);const r=t.split(",")[s];if("-1"==r)throw"start codon frame is -1: "+e.isoform;if("0"!=r){if("1"!=r&&"2"!=r)throw"start codon frame not 0/1/2: "+r+" "+e.isoform;e.startCodonFrame=Number.parseInt(r)}}(q,p),q}const zn=1,Jn=10,Hn=400,Wn=600,Vn=50,Zn="rgba(122,103,44,.7)",Kn="red",Xn="#edad0c",Yn="rgba(255,0,0,.5)",Qn="#ccc";function es(e,t,n,s,r){if(!e)return;if(!r.name&&!r.isoform)return;const o=[];r.name&&o.push(r.name),r.isoform&&o.push(r.isoform),e.push({chr:r.chr,start:r.start,stop:r.stop,x1:t,x2:n,y:s,isoform:r.isoform,name:o.join(" ")})}function ts(e,t,n,s,r,o){const i=o/2,a=o/2,l=Math.max(o/2,6);if(r-2*i<a)return;const c=Math.ceil((r-2*i)/(a+l));if(c<=0)return;const u="+"==t;let f=Math.ceil(n+(r-a*c-l*(c-1))/2);for(let t=0;t<c;t++)e.beginPath(),u?(e.moveTo(f,s),e.lineTo(f+a,s+o/2),e.moveTo(f+a,s+o/2+1),e.lineTo(f,s+o)):(e.moveTo(f+a,s),e.lineTo(f,s+o/2),e.moveTo(f,s+o/2+1),e.lineTo(f+a,s+o)),e.stroke(),f+=a+l}function ns(e,t){return new Promise(((n,s)=>{const o=(0,x.spawn)(r().gfServer,["status",t.blat.host,t.blat.port]),i=[],a=[];o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("close",(t=>{a.join("").trim()&&n(e+" OFF");const s=i.join("").trim().split("\n");let r=0;for(const e of s)e.startsWith("blat requests")&&(r=e.split(" ")[2]);n(e+" ON, "+r+" requests")}))}))}function ss(e,t){const n=y().join(r().cachedir,Math.random().toString());return new Promise(((s,o)=>{const i=(0,x.spawn)(r().gfClient,[e.blat.host,e.blat.port,e.blat.seqDir,t,n,"-q=dna","-nohead","-minScore=20","-minIdentity=0","-out=psl"]),a=[];i.stderr.on("data",(e=>a.push(e))),i.on("close",(e=>{const t=a.join("");t&&(console.log("BLAT error",t),o("blat server problem")),s(n)}))}))}var rs=n(8877),os=n(1575);const is="ssm_occurrence_centrics";async function as(e){const t=new Map,{host:n,headers:s}=e.getHostHeaders(),o=y().join(n.rest,"ssm_occurrences/_mapping");let i;try{const{body:e}=await(0,F.fk)(o,{headers:s});i=e}catch(e){throw console.log(e),"failed to get GDC API _mapping: "+(e.message||e)}if(!i._mapping)throw"returned data does not have ._mapping";if(!Array.isArray(i.fields))throw".fields not array";if(!Array.isArray(i.nested))throw".nested not array";const a=new Set(i.nested);let l=0,c=0,u=0,f=0,d=0,p=0;for(const e of i.fields){if(ds(e)){l++;continue}const n=e.split(".");for(let e=1;e<n.length;e++){const s=n.slice(0,e).join("."),r=s+"."+n[e],o=n[e][0].toUpperCase()+n[e].slice(1).replace(/_/g," "),l={id:r.toLowerCase(),name:o,included_types_set:new Set,child_types_set:new Set};if(e==n.length-1){l.isleaf=!0;const e=i._mapping[is+"."+r];e&&("keyword"==e.type?(l.type="categorical",u++):"long"==e.type?(l.type="integer",f++):"double"==e.type?(l.type="float",d++):console.log("GDC !!! ERR !!! Unknown variable type: "+e.type)),l.type||c++,ls(l)}if(1==e);else if(l.parent_id=s,l.type){l.included_types_set.add(l.type);let e=t.get(s);for(;e&&(e.included_types_set.add(l.type),e.child_types_set.add(l.type),e.parent_id);)e=t.get(e.parent_id)}a.has(r)&&(l.isObjectList=!0),t.set(r,l)}}try{await async function(e,t){const n=[],s=new Map;for(const t of e.values()){if("integer"!=t.type&&"float"!=t.type)continue;if(us[t.id]){t.bins=us[t.id];continue}const e=t.id.replace("case.","").replace(/\./g,"__");s.set(e,t.id),n.push(e+" {\n\t\t stats {\n\t\t\t\tMin : min\n\t\t\t\tMax: max\n\t\t\t\tMean: avg\n\t\t\t\tSD: std_deviation\n\t\t\t\tcount\n\t\t\t}\n\t\t\trange(ranges: $filters2) {\n\t\t\t buckets {\n\t\t\t\tdoc_count\n\t\t\t\tkey\n\t\t\t }\n\t\t\t}\n\t\t}")}if(0==n.length)throw"GDC: no numeric terms, should not happen";const r=`\n\t query ContinuousAggregationQuery($caseFilters: FiltersArgument, $filters: FiltersArgument, $filters2: FiltersArgument) {\n\t viewer {\n\t\texplore {\n\t\t cases {\n\t\t\taggregations(case_filters: $caseFilters, filters: $filters) {\n\t\t\t\t${n.join("\n")}\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t}`,o={caseFilters:{},filters:{},filters2:{op:"range",content:[{ranges:[{from:0,to:1}]}]}};let i=0,a=0;const{host:l,headers:c}=t.getHostHeaders(),{body:u}=await(0,F.fk)(l.graphql,{method:"POST",body:{query:r,variables:o}});if("object"!=typeof u.data?.viewer?.explore?.cases?.aggregations)throw"return not object: re.data.viewer.explore.cases.aggregations{}";for(const[t,n]of s){const s=e.get(n);if(!(t in u.data.viewer.explore.cases.aggregations)){console.log("GDC: no stats object returned for numeric term",n),s.bins=cs,a++;continue}const r=u.data.viewer.explore.cases.aggregations[t].stats;if("object"!=typeof r){console.log("GDC: aggregations[facet].stats{} is not object"),s.bins=cs,a++;continue}if(!Number.isFinite(r.Max)||!Number.isFinite(r.Min)){s.bins=cs,a++;continue}if(r.Max<=r.Min){s.bins=cs,a++;continue}const o=(r.Max-r.Min)/5,l="integer"==s.type?Math.ceil(o):o;s.bins={default:{mode:"discrete",type:"regular-bin",bin_size:l,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:r.Min+l}}},i++}console.log(`GDC default binning: ${i} assigned, ${a} unassigned`)}(t,e)}catch(e){throw console.log(e),"assignDefaultBins() failed: "+(e.message||e)}for(const e of t.values())e.type||p++,e.included_types=[...e.included_types_set],e.child_types=[...e.child_types_set],delete e.included_types_set,delete e.child_types_set;console.log("GDC dictionary:",t.size,"total variables,",l,"lines skipped,",c,"lines with unknown term type,","categorical="+u,"integer="+f,"float="+d,"parent="+p),Object.freeze(t),function(e,t){const n=e.cohort.termdb.q={};async function s(t,n){if(0==t.length||!n)return;const s=await e.termdb.termid2totalsize2.get(t.map((e=>e.id)),JSON.parse(n));for(const e of t)if(e){const t=s.get(e.id);"categorical"==e.type&&t?t.length?e.samplecount=t.map((e=>e[1])).reduce(((e,t)=>e+t)):(e.disabled=!0,e.samplecount=0):"integer"!=e.type&&"float"!=e.type||(e.samplecount=t.total,0==t.total&&(e.disabled=!0))}}n.getRootTerms=async(e,n=null)=>{const r=[];for(const e of t.values())null==e.parent_id&&r.push(JSON.parse(JSON.stringify(e)));return await s(r,n),r},n.getTermChildren=async(e,n=null,r=null)=>{const o=[];for(const n of t.values())n.parent_id==e&&o.push(JSON.parse(JSON.stringify(n)));return await s(o,r),o},n.findTermByName=async(e,n,r=null,o=null)=>{(e=e.toLowerCase()).includes(" ")&&(e=e.replace(/\s/g,"_"));const i=[];for(const n of t.values())o&&!(0,os.CG)(n,o)||n.id.includes(e)&&i.push(JSON.parse(JSON.stringify(n)));return await s(i,r),i},n.getAncestorIDs=e=>{if(!t.has(e))return;const n=e.split("."),s=[];for(let e=1;e<n.length;e++)s.push(n.slice(0,e+1).join("."));return s},n.getAncestorNames=n.getAncestorIDs,n.termjsonByOneid=e=>{const n=t.get(e);return n?JSON.parse(JSON.stringify(n)):null},n.getSupportedChartTypes=()=>{const e={},n={};for(const s of t.values())s.type&&(s.cohort in e||(e[s.cohort]=["barchart","table","regression"],n[s.cohort]=0),"survival"!=s.type||e[s.cohort].includes("survival")||e[s.cohort].push("survival"),"condition"!=s.type||e[s.cohort].includes("cuminc")||e[s.cohort].push("cuminc"),"float"!=s.type&&"integer"!=s.type||(n[s.cohort]+=s.samplecount));for(const t in n)n[t]>0&&e[t].push("boxplot"),n[t]>1&&e[t].push("scatterplot");return e}}(e,t),e.cohort.termdb.termtypeByCohort=[],u&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"categorical"}),f&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"integer"}),d&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"float"}),e.__gdc={aliquot2submitter:{cache:new Map,get:async t=>e.__gdc.aliquot2submitter.cache.has(t)?e.__gdc.aliquot2submitter.cache.get(t):t},map2caseid:{cache:new Map,get:t=>e.__gdc.map2caseid.cache.get(t)},caseid2submitter:new Map,caseIds:new Set,casesWithExpData:new Set,gdcOpenProjects:new Set,doneCaching:0};try{await async function(e){const t={filters:{op:"and",content:[{op:"=",content:{field:"access",value:"open"}},{op:"=",content:{field:"data_type",value:"Masked Somatic Mutation"}}]},facets:"cases.project.project_id",size:0},{host:n,headers:s}=e.getHostHeaders(),{body:r}=await(0,F.fk)(y().join(n.rest,"files"),{method:"POST",headers:s,body:t});if(!Array.isArray(r?.data?.aggregations?.["cases.project.project_id"]?.buckets))return void console.log("getting open project_id but return is not re.data.aggregations['cases.project.project_id'].buckets[]");for(const t of r.data.aggregations["cases.project.project_id"].buckets)t.key&&e.__gdc.gdcOpenProjects.add(t.key);console.log("GDC open-access projects:",e.__gdc.gdcOpenProjects.size)}(e)}catch(e){throw console.log(e),"getOpenProjects() failed: "+(e.message||e)}!async function(e){await async function(e){const{host:t,headers:n}=e.getHostHeaders();try{{const e=y().join(t.rest,"ssms"),n=await ps(e);if(n)throw`${e} returns error code: ${n}`}{const e=y().join(t.rest,"ssm_occurrences"),n=await ps(e);if(n)throw`${e} returns error code: ${n}`}{const e=y().join(t.rest,"cases"),n=await ps(e);if(n)throw`${e} returns error code: ${n}`}{const e=y().join(t.rest,"files"),n=await ps(e);if(n)throw`${e} returns error code: ${n}`}{const e=y().join(t.rest,"analysis/top_mutated_genes_by_project"),n=await ps(e);if(n)throw`${e} returns error code: ${n}`}{const e=await async function(e,t){const n=new Date;try{const n="query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\tprimary_site {buckets { doc_count, key }}\n\t\t\t\t}\n\t\t\t}\n\t\t}}",s=await v().post(e,{headers:t,body:JSON.stringify({query:n,variables:{}})});if(s.statusCode>399)return s.statusCode}catch(t){if(console.log(t),t.code)return t.code;throw"see above error from graphql API "+e}console.log("GDC GraphQL API okay: "+e,new Date-n,"ms")}(t.graphql,JSON.parse(JSON.stringify(n)));if(e)throw`${t.graphql} returns error code: ${e}`}}catch(e){throw console.log(e),`\n##########################################\n#\n# Some GDC API unavailable, see error above\n# ${t.rest}\n# ${t.graphql}\n#\n##########################################`}}(e);try{await async function(e){if("stopGdcCacheAliquot"in r().features){if(!Number.isInteger(r().features.stopGdcCacheAliquot))return void console.log("GDC: sample IDs are not cached!");console.log("GDC: running limited sample ID caching")}else console.log("GDC: caching complete sample ID mapping");const t=1e3,n=await ms(e,1,0);if(!Number.isInteger(n))throw"totalCases not integer";const s=new Date;console.log("GDC: Start to cache sample IDs of",n,"cases...");for(let s=0;s<Math.ceil(n/t)&&(await ms(e,t,1e3*s),!(Number.isInteger(r().features.stopGdcCacheAliquot)&&s>=r().features.stopGdcCacheAliquot));s++);await async function(e){const{host:t,headers:n}=e.getHostHeaders(),s=`${t.geneExp}/gene_expression/availability`;try{const t=[...e.__gdc.caseIds],{body:r}=await(0,F.fk)(s,{method:"post",headers:n,body:{case_ids:t,gene_ids:["ENSG00000141510"]}});if(!Array.isArray(r.cases?.details))throw"re.cases.details[] not array";for(const t of r.cases.details)t.has_gene_expression_values&&e.__gdc.casesWithExpData.add(t.case_id);delete e.__gdc.caseIds}catch(e){console.log("You don't have access to /gene_expression/availability/, you cannot run GDC hierCluster")}}(e),e.__gdc.doneCaching=!0,console.log("GDC: Done caching sample IDs. Time:",Math.ceil((new Date-s)/1e3),"s"),console.log("\t",e.__gdc.aliquot2submitter.cache.size,"aliquot IDs to sample submitter id,"),console.log("\t",e.__gdc.caseid2submitter.size,"case uuid to submitter id,"),console.log("\t",e.__gdc.map2caseid.cache.size,"different ids to case uuid,"),console.log("\t",e.__gdc.casesWithExpData.size,"cases with gene expression data.")}(e)}catch(e){throw e.stack&&console.log(e.stack),"cacheSampleIdMapping() failed: "+(e.message||e)}}(e)}function ls(e){"case.diagnoses.age_at_diagnosis"!=e.id||(e.valueConversion={scaleFactor:1/365,fromUnit:"day",toUnit:"year"})}const cs={default:{mode:"discrete",type:"regular-bin",bin_size:1,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:0},last_bin:{start:1,stopunbounded:!0}}},us={"case.diagnoses.age_at_diagnosis":{default:{type:"custom-bin",mode:"discrete",lst:[{startunbounded:!0,stop:10950,stopinclusive:!0,label:"<=30 years"},{start:10950,stop:21900,stopinclusive:!0,label:"30-60 years"},{start:21900,stopunbounded:!0,startinclusive:!1,label:">60years"}]}}};const fs=new Set(["case.consent_type","case.days_to_consent","case.days_to_index"]);function ds(e){return!!(e.startsWith("ssm")||e.startsWith("case.observation")||e.startsWith("case.available_variation_data"))||(!(!e.endsWith("_id")||e.endsWith("project_id"))||(!!fs.has(e)||void 0))}async function ps(e){try{const t=new Date,n=await v()(e);if(n.statusCode>399)return n.statusCode;console.log("GDC API okay: "+e,new Date-t,"ms")}catch(t){if(console.log("See error from",e),console.log(t),t.code)return t.code;throw"gdc api down: "+e}}async function ms(e,t,n,s){const r=["fields=submitter_id,samples.portions.analytes.aliquots.aliquot_id,samples.submitter_id"];if(s)r.push('filters={"op":"and","content":[{"op":"=","content":{"field":"samples.portions.analytes.aliquots.aliquot_id","value":["'+s+'"]}}]}');else{if(!Number.isInteger(t)||!Number.isInteger(n))throw"size and from not integers";r.push("size="+t),r.push("from="+n)}const{host:o,headers:i}=e.getHostHeaders(),{body:a}=await(0,F.fk)(o.rest+"/cases?"+r.join("&"),{headers:i});if(!Array.isArray(a?.data?.hits))throw"re.data.hits[] not array";for(const t of a.data.hits){const n=t.id;if(!n)throw"h.id (case uuid) missing";e.__gdc.caseIds.add(n);const s=t.submitter_id;if(!s)throw"h.submitter_id missing";if(e.__gdc.caseid2submitter.set(n,s),e.__gdc.map2caseid.cache.set(s,n),Array.isArray(t.samples))for(const s of t.samples){const t=s.submitter_id;if(!t)throw"sample.submitter_id missing";if(e.__gdc.map2caseid.cache.set(t,n),Array.isArray(s.portions))for(const r of s.portions)if(Array.isArray(r.analytes))for(const s of r.analytes)if(Array.isArray(s.aliquots))for(const r of s.aliquots){const s=r.aliquot_id;if(!s)throw"aliquot.aliquot_id missing";e.__gdc.aliquot2submitter.cache.set(s,t),e.__gdc.map2caseid.cache.set(s,n)}}}return a.data?.pagination?.total}var hs=n(4973),gs=n(3625),ys=n(478),bs=n(8907),vs=n(394);function ws(e,t){if(t.updateAttr&&!e.label){for(const n of t.updateAttr){let t=e;for(const e of n)if(t)if("object"==typeof e)for(const n in e)t[n]=e[n];else t=t[e]}e.label&&delete t.updateAttr}}function _s(e,t,n){if(!e.cohort?.db?.refresh)return;const s=e.cohort.db.refresh;delete e.cohort.db.refresh,t.get(`${n}/${s.route}`,(async(t,n)=>{n.send({label:e.label,files:[]})})),t.post(`${n}/${s.route}`,(async(t,n)=>{try{const s=e.cohort.db?.file?.startsWith(r().tpmasterdir)?e.cohort.db.file:y().join(r().tpmasterdir,e.cohort.db.file||""),o=t.body;if(!o.dbfile)throw"Updating input text files via the termdb-refresh page has been deprecated.Please use the buildTermdb.bundle.js. pipeline before triggering this route to replace the db file.";{const t=y().join(r().tpmasterdir,o.dbfile);if(!await h().stat(t))throw`dbfile not found: '${t}'`;const n=e.cohort.db.file_fullpath||s;if(t===n)throw"db file source and target are the same";console.log(`copying ${t} to ${n}`),await h().copyFile(t,n)}await Is(e),n.send({status:"ok"})}catch(e){console.log(e),n.send({error:e.error||e})}}))}var ks=n(2188),qs=n(2974),xs=n(3795),Ns=n(7934),Ss=n(5057),As=n(3677),Cs=n(4924),js=n(901);const Ts="Unannotated";async function Ms(e,t,n,s=null,o=null){await Is(e),e.queries&&(await async function(e,t){const n=e.queries.snvindel;if(!n)return;if(n.url){if(!n.url.base)throw".snvindel.url.base missing";if(!n.url.key)throw".snvindel.url.key missing"}if(!n.byisoform&&!n.byrange)throw"byisoform and byrange are both missing on queries.snvindel";if(n.byrange)if(n.byrange.gdcapi)Pn.xq(e);else if(n.byrange.bcffile)n.byrange.bcffile=n.byrange.bcffile.startsWith(r().tpmasterdir)?n.byrange.bcffile:y().join(r().tpmasterdir,n.byrange.bcffile),n.byrange._tk={file:n.byrange.bcffile},n.byrange.get=await Fs(e,t),n.byrange._tk?.samples.length||delete n.byrange._tk.samples,Rs(e,n.byrange._tk.samples,"snvindel.byrange.bcffile");else{if(!n.byrange.chr2bcffile)throw"unknown query method for queries.snvindel.byrange";n.byrange._tk={chr2files:{}};for(const e in n.byrange.chr2bcffile)n.byrange._tk.chr2files[e]={file:y().join(r().tpmasterdir,n.byrange.chr2bcffile[e])};delete n.byrange.chr2bcffile,n.byrange.get=await Fs(e,t),n.byrange._tk.samples.length||delete n.byrange._tk.samples,Rs(e,n.byrange._tk.samples,"snvindel.byrange.bcffile")}if(n.byisoform){if(!n.byisoform.gdcapi)throw"unknown query method for queries.snvindel.byisoform";Pn.CN(e)}if(n.m2csq){if(!n.m2csq.by)throw".by missing from queries.snvindel.m2csq";if("ssm_id"!=n.m2csq.by)throw"unknown value of queries.snvindel.m2csq.by";if(!n.m2csq.gdcapi)throw"unknown query method for queries.snvindel.m2csq";Pn.wm(e)}}(e,t),await async function(e,t){const n=e.queries.svfusion;if(!n)return;if(!n.byrange)throw"byrange missing from queries.svfusion";if(n.byrange){if(!n.byrange.file)throw"unknown query method for svfusion.byrange";n.byrange.file=n.byrange.file.startsWith(r().tpmasterdir)?n.byrange.file:y().join(r().tpmasterdir,n.byrange.file),n.byrange.get=await async function(e,t){const n=e.queries.svfusion.byrange;if(n.file)await F.LC(n.file);else{if(!n.url)throw"file and url both missing on svfusion.byrange{}";n.dir=await F.d1(n.url,n.indexURL)}n.nochr=await F.Jy(n.file||n.url,null,t);{const e=await F.ZD(n.file);if(!e[0])throw"header line missing from "+n.file;const t=e[0].split(" ");if("#sample"!=t[0])throw"header line not starting with #sample: "+n.file;n.samples=t.slice(1).map((e=>({name:e})))}return async t=>{if(!Array.isArray(t.rglst))throw"q.rglst[] is not array";if(0==t.rglst.length)throw"q.rglst[] blank array";const s=$s(t),r=await(0,js.T)(t,n.samples,e);if(0==r?.size)return[];const o=new Map;for(const e of t.rglst)await F.UE({args:[n.file||n.url,(n.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop],dir:n.dir,callback:n=>{const i=n.split("\t"),a=Number(i[1]);let l,c,u,f,d;try{l=JSON.parse(i[3])}catch(e){return}if(l.dt!=$.dtfusionrna&&l.dt!=$.dtsv)return;if(l.class=l.dt==$.dtsv?$.mclasssv:$.mclassfusionrna,t.hiddenmclass&&t.hiddenmclass.has(l.class))return;if(l.sample&&r&&!r.has(l.sample))return;if(l.chrA)c=1,u=l.geneA||l.chrA,f=l.strandA,d=[{a:{chr:l.chrA,pos:l.posA,strand:l.strandA,name:l.geneA},b:{chr:e.chr,pos:a,strand:l.strandB,name:l.geneB}}];else if(l.chrB)c=0,u=l.geneB||l.chrB,f=l.strandB,d=[{a:{chr:e.chr,pos:a,strand:l.strandA,name:l.geneA},b:{chr:l.chrB,pos:l.posB,strand:l.strandB,name:l.geneB}}];else{if(!l.pairlst)throw"missing chrA and chrB";{d=l.pairlst;const e=l.pairlst.findIndex((e=>e.chr==chr&&e.pos==a));if(-1==e)throw"current point missing from pairlst";c=e}}const p=[l.dt,e.chr,a,f,c,encodeURIComponent(u)].join(hs.dq);let m;if(l.sample&&(m={sample_id:l.sample},l.mattr)){if(s)for(const e in s){const t=e in l.mattr?l.mattr[e]:Ts;if(s[e].has(t))return}t.addFormatValues&&(m.formatK2v=l.mattr)}o.has(p)||o.set(p,{ssm_id:p,dt:l.dt,class:l.class,chr:e.chr,pos:a,strand:f,pairlstIdx:c,mname:u,pairlst:d,samples:[]}),m&&o.get(p).samples.push(m)}});return[...o.values()]}}(e,t),Rs(e,n.byrange.samples,"svfusion.byrange")}}(e,t),await async function(e,t){const n=e.queries.geneCnv;if(!n)return;if(!n.bygene)throw"geneCnv.bygene missing";n.bygene.gdcapi&&Pn.IK(e)}(e),await async function(e,t){const n=e.queries.cnv;if(!n)return;if(!n.byrange)throw"queries.cnv.byrange{} missing";if("native"==n.byrange.src){if(!n.byrange.file)throw"cnv.byrange.file missing when src=native";return n.byrange.file=n.byrange.file.startsWith(r().tpmasterdir)?n.byrange.file:y().join(r().tpmasterdir,n.byrange.file),n.byrange.get=await async function(e,t){const n=e.queries.cnv.byrange;if(n.file)await F.LC(n.file);else{if(!n.url)throw"file and url both missing on cnv.byrange{}";n.dir=await F.d1(n.url,n.indexURL)}n.nochr=await F.Jy(n.file||n.url,null,t);{const e=await F.ZD(n.file);if(!e[0])throw"header line missing from "+n.file;const t=e[0].split(" ");if("#sample"!=t[0])throw"header line not starting with #sample: "+n.file;n.samples=t.slice(1).map((e=>({name:e})))}return async t=>{if(!Array.isArray(t.rglst))throw"q.rglst[] is not array";if(0==t.rglst.length)throw"q.rglst[] blank array";if(t.cnvMaxLength&&!Number.isInteger(t.cnvMaxLength))throw"cnvMaxLength is not integer";if(t.cnvGainCutoff&&!Number.isFinite(t.cnvGainCutoff))throw"cnvGainCutoff is not finite";if(t.cnvLossCutoff&&!Number.isFinite(t.cnvLossCutoff))throw"cnvLossCutoff is not finite";const s=$s(t),r=await(0,js.T)(t,n.samples,e);if(0==r?.size)return[];const o=[];for(const e of t.rglst)await F.UE({args:[n.file||n.url,(n.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop],dir:n.dir,callback:n=>{const i=n.split("\t"),a=Number(i[1]),l=Number(i[2]);if(t.cnvMaxLength&&l-a>=t.cnvMaxLength)return;let c;try{c=JSON.parse(i[3])}catch(e){return}if(c.dt==$.dtcnv){if(c.chr=e.chr,c.start=a,c.stop=l,Number.isFinite(c.value)){if(c.value>0&&t.cnvGainCutoff&&c.value<t.cnvGainCutoff)return;if(c.value<0&&t.cnvLossCutoff&&c.value>t.cnvLossCutoff)return;c.class=c.value>0?$.mclasscnvgain:$.mclasscnvloss}else if(c.class!=$.mclasscnvgain&&c.class!=$.mclasscnvloss)return;if(c.ssm_id=[e.chr,c.start,c.stop,c.class].join(hs.dq),(!t.hiddenmclass||!t.hiddenmclass.has(c.class))&&(!c.sample||!r||r.has(c.sample))){if(c.sample){const e={sample_id:c.sample};if(c.mattr){if(s)for(const e in s){const t=e in c.mattr?c.mattr[e]:Ts;if(s[e].has(t))return}t.addFormatValues&&(e.formatK2v=c.mattr)}delete c.sample,c.samples=[e]}o.push(c)}}}});return o}}(e,t),void Rs(e,n.byrange.samples,"cnv.byrange")}throw"unknown cnv.byrange.src"}(e,t),await async function(e,t){const n=e.queries.ld;if(!n)return;if(!Array.isArray(n.tracks)||!n.tracks.length)throw"ld.tracks[] not nonempty array";for(const e of n.tracks){if(!e.name)throw"name missing from one of ld.tracks[]";if(!e.file)throw".file missing from one of ld.tracks[]";e.file0=e.file,e.file=y().join(r().tpmasterdir,e.file),await F.LC(e.file),e.nochr=await F.Jy(e.file,null,t)}if(!n.overlay)throw"ld.overlay{} missing";if(!n.overlay.color_0)throw"ld.overlay.color_0 missing";if(!n.overlay.color_1)throw"ld.overlay.color_1 missing"}(e,t),await(0,Cs.validate_query_geneExpression)(e,t),await async function(e,t){const n=e.queries.rnaseqGeneCount;if(!n)return;if(!n.file)throw"unknown data type for rnaseqGeneCount";n.file=y().join(r().tpmasterdir,n.file);{const t=(await(s=n.file,new Promise(((e,t)=>{const n=[],r=[],o=(0,x.spawn)("head",["-1",s]);o.stdout.on("data",(e=>n.push(e.toString()))),o.stderr.on("data",(e=>r.push(e.toString()))),o.on("error",(e=>{r.length&&t(r.join(""))})),o.on("close",(s=>{0!=s&&t("head command exited with non-zero status and this error: "+r.join("")),e(n.join(""))}))})))).trim().split("\t").slice(4);n.allSampleSet=new Set(t);const r=[];for(const t of n.allSampleSet)e.cohort.termdb.q.sampleName2id(t)||r.push(t);console.log(n.allSampleSet.size,`rnaseqGeneCount samples from ${e.label}`)}var s;n.get=async function(t){if(2!=t.samplelst?.groups?.length)throw".samplelst.groups.length!=2";if(t.samplelst.groups[0].values?.length<1)throw"samplelst.groups[0].values.length<1";if(t.samplelst.groups[1].values?.length<1)throw"samplelst.groups[1].values.length<1";const s=[];let o=0;for(const r of t.samplelst.groups[0].values){if(!Number.isInteger(r.sampleId))continue;const t=e.cohort.termdb.q.id2sampleName(r.sampleId);t&&(n.allSampleSet.has(t)?s.push(t):o+=1)}const i=[];let a=0;for(const s of t.samplelst.groups[1].values){if(!Number.isInteger(s.sampleId))continue;const t=e.cohort.termdb.q.id2sampleName(s.sampleId);t&&(n.allSampleSet.has(t)?i.push(t):a+=1)}const l=s.length,c=i.length;if(l<1)throw"sample size of group1 < 1";if(c<1)throw"sample size of group2 < 1";const u={case:s.map((e=>e)).join(","),control:i.map((e=>e)).join(","),input_file:n.file,output_path:y().join(r().binpath,"utils")},f=8;let d;if(s.length<=f&&i.length<=f||"edgeR"==t.method){const e=new Date,n=(await async function(e,t){return new Promise(((n,s)=>{y().join(r().Rscript,e);const o=(0,x.spawn)(r().Rscript,[e]),i=[],a=[];try{je.Readable.from(t).pipe(o.stdin)}catch(t){o.kill();let n=t;a.length&&(n+=`killed edgeR('${e}'), stderr: ${a.join("").trim()}`),s(n)}o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("error",(t=>{a.length&&console.log(`edgeR('${e}') ps.on('error') stderr:`,a),s(t)})),o.on("close",(t=>{0!==t?s(`spawned '${e}' exited with a non-zero status and this stderr:\n${a.join("")}`):n(i.toString())}))}))}(y().join(r().binpath,"utils","edge.R"),JSON.stringify(u)),new Date);console.log("Time taken to run edgeR:",n-e,"ms"),t.method="edgeR";const s=y().join(r().binpath,"utils","r_output.txt");d=JSON.parse(h().readFileSync(s,"utf8")),h().unlink(s,(()=>{}))}else if("wilcoxon"==t.method){const e=new Date,n=await(0,_e.run_rust)("DEanalysis",JSON.stringify(u)),s=new Date;for(const e of n.split("\n"))e.startsWith("adjusted_p_values:")&&(d=JSON.parse(e.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",s-e,"ms"),t.method="wilcoxon"}else{const e=new Date,n=await(0,_e.run_rust)("DEanalysis",JSON.stringify(u)),s=new Date;for(const e of n.split("\n"))e.startsWith("adjusted_p_values:")&&(d=JSON.parse(e.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",s-e,"ms"),t.method="wilcoxon"}return{data:d,sample_size1:l,sample_size2:c,method:t.method}}}(e),await(0,As.validate_query_singleSampleMutation)(e,t),await async function(e,t){const n=e.queries.singleSampleGenomeQuantification;if(!n)return;for(const s in n){if(!Number.isFinite(n[s].min))throw"min not a number";if(!Number.isFinite(n[s].max))throw"max not a number";if(n[s].min>=n[s].max)throw"min>=max";if(!n[s].folder)throw"unknown query method for singleSampleGenomeQuantification";n[s].get=async(o,i)=>{let a=o;if(e.cohort?.termdb?.q?.sampleName2id&&(a=e.cohort.termdb.q.sampleName2id(o),null==a))return[];const l=y().join(r().tpmasterdir,n[s].folder,a.toString());try{await h().promises.stat(l)}catch(e){if("EACCES"==e.code)throw"cannot read file, permission denied";if("ENOENT"==e.code)throw"no data for this sample";throw"failed to load data"}return await Us(l,t,n[s],i)}}}(e,t),await async function(e,t){const n=e.queries.singleSampleGbtk;if(!n)return;for(const t in n){if(!Number.isFinite(n[t].min))throw"min not a number";if(!Number.isFinite(n[t].max))throw"max not a number";if(n[t].min>=n[t].max)throw"min>=max";if(!n[t].folder)throw"unknown query method for singleSampleGbtk";n[t].get=async s=>{let o=s;if(e.cohort?.termdb?.q?.sampleName2id&&(o=e.cohort.termdb.q.sampleName2id(s),null==o))return{};const i=y().join(n[t].folder,o+".gz");try{return await h().promises.stat(y().join(r().tpmasterdir,i)),{path:i}}catch(e){return{}}}}}(e),await(0,Ns.validate_query_singleCell)(e,t),await(0,Ss.validate_query_TopVariablyExpressedGenes)(e,t),await(0,hs.uK)(e),await function(e){if(!e.ssm2canonicalisoform)return;if(e.ssm2canonicalisoform.gdcapi)return void Pn.vK(e.ssm2canonicalisoform,e.getHostHeaders);throw"ssm2canonicalisoform.gdcapi is false"}(e),await function(e,t){if(!t.genedb.hasTable_refseq2ensembl)return;e.refseq2ensembl_query=t.genedb.db.prepare("select ensembl from refseq2ensembl where refseq=?")}(e,t),await function(e,t){if(!e.queries.snvindel&&!e.queries.svfusion&&!e.queries.geneCnv)return;e.mayGetGeneVariantData=async(n,s)=>{if("object"!=typeof n.term)throw"tw.term{} is not object";if("geneVariant"!=n.term.type)throw"tw.term.type is not geneVariant";if("string"!=typeof n.term.name)throw"tw.term.name is not string";if(!n.term.name)throw"tw.term.name should be gene symbol but is empty string";const r=[];if("snp"==n.term.subtype){if(!e.queries.snvindel?.allowSNPs)throw"snvindel does not allow snp";const o=(await Js(e,n.term,t,s)).find((e=>n.term.alleles.includes(e.ref)&&n.term.alleles.includes(e.alt)));if(o){const e=[];for(const t of o.samples){if(!t.formatK2v?.GT)continue;const n=[];for(const e of t.formatK2v.GT.split("/"))0==e?n.push(o.ref):1==e?n.push(o.alt):console.log("unknown allele idx");n.join("/"),n.join("/");e.push({sample_id:t.sample_id,GT:n.join("/")})}const t={samples:e};r.push(t)}}else{if(e.queries.snvindel){const o=await Js(e,n.term,t,s);r.push(...o)}if(e.queries.svfusion){const o=await async function(e,t,n,s){const r={addFormatValues:!0,filter0:s.filter0,filterObj:s.filter,sessionid:s.sessionid};if(e.queries.svfusion.byrange)return await zs(t,n),r.rglst=[t],await e.queries.svfusion.byrange.get(r);throw"unknown queries.svfusion method"}(e,n.term,t,s);r.push(...o)}if(e.queries.cnv){const o=await async function(e,t,n,s){const r={addFormatValues:!0,filter0:s.filter0,filterObj:s.filter,cnvMaxLength:t?.q?.cnvMaxLength,cnvGainCutoff:t?.q?.cnvGainCutoff,cnvLossCutoff:t?.q?.cnvLossCutoff,sessionid:s.sessionid};if(e.queries.cnv.byrange)return await zs(t.term,n),r.rglst=[t.term],await e.queries.cnv.byrange.get(r);throw"unknown queries.cnv method"}(e,n,t,s);r.push(...o)}if(e.queries.geneCnv){const t=await async function(e,t,n,s){const r={filter0:s.filter0,sessionid:s.sessionid};if(e.queries.geneCnv.bygene)return t.name?(r.gene=t.name,await e.queries.geneCnv.bygene.get(r)):[];throw"unknown queries.geneCnv method"}(e,n.term,0,s);r.push(...t)}}const o=new Map;for(const e of r)if(Array.isArray(e.samples))for(const t of e.samples){o.has(t.sample_id)||o.set(t.sample_id,{sample:t.sample_id}),o.get(t.sample_id)[n.term.name]||(o.get(t.sample_id)[n.term.name]={key:n.term.name,label:n.term.name,values:[]});const s={gene:n.term.name,isoform:e.isoform,dt:e.dt,chr:n.term.chr,class:e.class,pos:e.pos||(e.start?e.start+"-"+e.stop:""),mname:e.mname};if("value"in e&&(s.value=e.value),t.formatK2v)for(const e in t.formatK2v)s[e]=t.formatK2v[e];e.dt==$.dtsnvindel?t.GT&&(s.value=t.GT,s.key=t.GT):e.dt!=$.dtfusionrna&&e.dt!=$.dtsv||(s.pairlst=e.pairlst),o.get(t.sample_id)[n.term.name].values.push(s)}return await async function(e,t,n,s){if(!t.assayAvailability?.byDt)return;const r=e.filter?new Set((await(0,bs.cf)(e.filter,t)).map((e=>e.id))):null;for(const e in t.assayAvailability.byDt){const o=t.assayAvailability.byDt[e];if(o.byOrigin)for(const t in o.byOrigin){Bs(e,o.byOrigin[t],n,s,t,r)}else Bs(e,o,n,s,!1,r)}}(s,e,o,n.term.name),o}}(e,t)),await function(e){if(!e.assayAvailability)return;if(e.assayAvailability.byDt)for(const t in e.assayAvailability.byDt){const n=e.assayAvailability.byDt[t];if(n.byOrigin)for(const t in n.byOrigin){const s=n.byOrigin[t];if(!s.yes||!s.no||!s.term_id)throw"ds.assayAvailability.byDt.*.byOrigin properties require .term_id .yes{} .no{}";Hs(e,s)}else{if(!n.yes||!n.no||!n.term_id)throw"ds.assayAvailability.byDt properties require .term_id .yes{} .no{}";Hs(e,n)}}}(e),await function(e){if(!e.viewModes)return;if(!Array.isArray(e.viewModes))throw"ds.viewModes[] not array";for(const t of e.viewModes)if(t.byInfo){if(!e?.queries?.snvindel?.info)throw"view mode byInfo but queries.snvindel.info missing";const n=e.queries.snvindel.info[t.byInfo];if(!n)throw"unknown INFO field for viewmode byInfo";if("Float"!=n.Type&&"Integer"!=n.Type)throw"viewmode byInfo Type is not numeric";t.type="numeric",t.label=t.byInfo}else if(!t.byAttribute)throw"view mode not byInfo or byAttribute"}(e),e.cohort?.db?.refresh&&s&&await _s(e,s,o)}function Os(e){const t={isMds3:!0,label:e.label};if(e.viewModes&&(t.skewerModes=e.viewModes),e.noGenomicMode4lollipopTk&&(t.noGenomicMode4lollipopTk=!0),function(e,t){if(!e.queries)return;const n={};e.queries.singleSampleMutation&&(n.singleSampleMutation={sample_id_key:e.queries.singleSampleMutation.sample_id_key,discoSkipChrM:e.queries.singleSampleMutation.discoSkipChrM});if(e.queries.singleSampleGenomeQuantification){n.singleSampleGenomeQuantification={};for(const t in e.queries.singleSampleGenomeQuantification)n.singleSampleGenomeQuantification[t]=JSON.parse(JSON.stringify(e.queries.singleSampleGenomeQuantification[t])),delete n.singleSampleGenomeQuantification[t].folder}if(e.queries.singleSampleGbtk){n.singleSampleGbtk={};for(const t in e.queries.singleSampleGbtk)n.singleSampleGbtk[t]=JSON.parse(JSON.stringify(e.queries.singleSampleGbtk[t])),delete n.singleSampleGbtk[t].folder}const s=e.queries.snvindel;s&&(t.has_skewer=!0,n.snvindel={forTrack:s.forTrack,vcfid4skewerName:s.vcfid4skewerName,skewerRim:s.skewerRim,ssmUrl:s.ssmUrl},s.m2csq&&(n.snvindel.m2csq={by:s.m2csq.by}),s.info&&(t.bcf={info:s.info}),s.format&&(t.bcf||(t.bcf={}),t.bcf.format=s.format));if(e.queries.ld){n.ld=JSON.parse(JSON.stringify(e.queries.ld));for(const e of n.ld.tracks)delete e.file}t.queries=n}(e,t),e.cohort?.termdb&&(t.termdb={},e.cohort.termdb.allowCaseDetails&&(t.termdb.allowCaseDetails={sample_id_key:e.cohort.termdb.allowCaseDetails.sample_id_key})),e.variant2samples){const n=e.variant2samples;t.variant2samples={sunburst_twLst:n.sunburst_twLst,twLst:n.twLst,type_samples:n.type_samples,type_summary:n.type_summary,type_sunburst:n.type_sunburst,variantkey:n.variantkey}}return t}async function Is(e){if(e.cohort){if(!e.cohort.termdb)throw"ds.cohort is set but cohort.termdb{} missing";if(!e.cohort.db)throw"ds.cohort is set but cohort.db{} missing";if(!e.cohort.db.file&&!e.cohort.db.file_fullpath)throw"ds.cohort.db.file missing"}else{if(!e.termdb)return;e.cohort={},e.cohort.termdb=e.termdb,delete e.termdb}const t=e.cohort.termdb;if(t?.dictionary?.gdcapi)await as(e);else if(t?.dictionary?.dbFile)e.cohort.db={file:t.dictionary.dbFile},delete t.dictionary.dbFile,(0,vs.JV)(e);else{if(!e.cohort.db)throw"unknown method to initiate dictionary";(0,vs.JV)(e)}if(t.termid2totalsize2&&(t.termid2totalsize2.gdcapi,t.termid2totalsize2.get=async(n,s={},r=null)=>t.termid2totalsize2.gdcapi?await Pn.ws(n,s,r,e):await async function(e,t,n,s){const r=Es(t,s),o=new Map;for(const t of e)if(t.term&&"categorical"==t.term.type){const e={term1_id:t.id,term1_q:{type:"values"},filter:r},n=await(0,Ae.e8)(e,s,s.cohort.termdb);if(!n?.data?.charts?.[0])continue;const i=[];for(const e of n.data.charts[0].serieses)i.push([e.seriesId,e.total]);o.set(t.id,i)}return n?[o,n]:o}(n,s,r,e)),function(e){const t=e.selectCohort;if(!t)return;if("object"!=typeof t)throw"selectCohort{} not object";if(!t.term)throw"term{} missing from termdb.selectCohort";if(!t.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof t.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=t.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';{const n=e.q.termjsonByOneid(t.term.id);if(!n)throw"termdb.selectCohort.term.id is invalid";if("categorical"!=n.type)throw"termdb.selectCohort.term type is not categorical"}if(!t.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(t.values))throw"termdb.selectCohort.values is not array";if(0==t.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const e of t.values){if(!e.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(e.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==e.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}(t),await async function(e){if(!e.restrictAncestries)return;if(!Array.isArray(e.restrictAncestries)||0==e.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const t of e.restrictAncestries){if(!t.name)throw"name missing from one of restrictAncestries";if("object"!=typeof t.tvs)throw".tvs{} missing from one of restrictAncestries";if(!t.tvs.term)throw"tvs.term{} missing from an ancestry";if(!t.tvs.term.id)throw"tvs.term.id missing from an ancestry";{const n=e.q.termjsonByOneid(t.tvs.term.id);if(!n)throw"tvs.term.id is invalid from an ancestry";if("categorical"!=n.type)throw"tvs.term.type is not categorical from an ancestry"}if(!Number.isInteger(t.PCcount))throw"PCcount is not integer";if(t.PCcount<=1)throw"PCcount must be greater than 1";if(t.PCTermId){t.pcs=new Map;for(let n=1;n<=t.PCcount;n++){const s=t.PCTermId+n,r=e.q.termjsonByOneid(s);if(!r)throw"a PC term is not found in termdb";const o=e.q.getAllValues4term(s);if(!o||!o.size)throw"no sample PC values are retrieved by restrictAncestries term: "+s;t.pcs.set(r.name,o)}}else{if(!t.PCBySubcohort)throw"unknown PC source and configuration for restrictAncestries";for(const n in t.PCBySubcohort){let s=!0;for(const t of e.selectCohort.values)if(n==t.keys.sort().join(",")){s=!1;break}if(s)throw"unknown subcohort from PCBySubcohort";const r=t.PCBySubcohort[n];if(!r.termId)throw"termId missing from a subcohort of PCBySubcohort";r.pcs=new Map;for(let n=1;n<=t.PCcount;n++){const t=r.termId+n,s=e.q.termjsonByOneid(t);if(!s)throw"a PC term is not found in termdb";const o=e.q.getAllValues4term(t);if(!o||!o.size)throw"no sample PC values are retrieved by restrictAncestries.PCBySubcohort.<>.termId";r.pcs.set(s.name,o)}}}}}(t),await(0,ks.wz)(e),await(0,qs.te)(e),"minTimeSinceDx"in t){if(!Number.isFinite(t.minTimeSinceDx))throw"termdb.minTimeSinceDx not number";if(t.minTimeSinceDx<=0)throw"termdb.minTimeSinceDx<=0"}if("ageEndOffset"in t){if(!Number.isFinite(t.ageEndOffset))throw"termdb.ageEndOffset not number";if(t.ageEndOffset<=0)throw"termdb.ageEndOffset<=0"}if(t.convertSampleId){if(!t.convertSampleId.gdcapi)throw"unknown implementation of tdb.convertSampleId";Pn.Ak(t,e)}if(await async function(e){if(!e.cohort?.cumburden)return;e.cohort.cumburden.files;const t=e.cohort.cumburden.files;for(const e of["fit","surv","sample"]){const n=t[e];if(!n)throw`missing ds.cohort.burden.files.${e}`;const s=(0,x.spawnSync)(r().Rscript,["-e",`load('${r().tpmasterdir}/${n}')`],{encoding:"utf-8"});if(s?.status||s?.stderr)throw console.log(s),`error with ds.cohort.cumburden.files.${e}`}}(e),e.cohort?.db?.connection){e.sampleName2Id=new Map,e.sampleId2Name=new Map;const t="SELECT * FROM sampleidmap",n=e.cohort.db.connection.prepare(t).all();for(const t of n)e.sampleId2Name.set(t.id,t.name),e.sampleName2Id.set(t.name,t.id);e.getSampleIdMap=t=>{const n={};for(const s in t)n[sampleId]=e.sampleId2Name.get(+sampleId);return n}}if(e.cohort.mutationset){const{mayGetGeneVariantData:t,getTermTypes:s,mayGetMatchingGeneNames:r}=n(7833);e.mayGetGeneVariantData=t,e.getTermTypes=s,e.mayGetMatchingGeneNames=r}}function Es(e,t){const n=[];if(e.filterObj&&n.push(e.filterObj),e.tid2value&&n.push((0,js.w)(e.tid2value,t)),0!=n.length)return 1==n.length?n[0]:(0,ys.xH)(n)}function Rs(e,t,n){if(!t)return;let s;if(e?.cohort?.termdb){for(const e of t){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer sample id from "+n;e.name=t}s=", all integer IDs"}console.log(t.length,"samples from "+n+" of "+e.label+s)}async function Fs(e,t){const n=e.queries.snvindel.byrange;if(n._tk.file)await F._H(n._tk,t,!0);else if(n._tk.chr2files){let e;for(const s in n._tk.chr2files){if("chr17"!=s)continue;const r=n._tk.chr2files[s];try{await F._H(r,t,!0);const o=JSON.stringify(r.samples);if(e){if(o!=e)throw"Different samples found in bcf file of "+s}else e=o,n._tk.samples=r.samples,n._tk.format=r.format,n._tk.info=r.info,n._tk.nochr=r.nochr}catch(e){console.log("missing file ignored:",r.file)}}}if(n._tk?.samples.length){if(!n._tk.format)throw"bcf file has samples but no FORMAT"}else if(n._tk.format)throw"bcf file has FORMAT but no samples";if(n._tk.format){for(const e in n._tk.format)"GT"==e&&(n._tk.format[e].isGT=!0);if(e.queries.snvindel.format4filters){if(!Array.isArray(e.queries.snvindel.format4filters))throw"snvindel.format4filters[] is not array";for(const t of e.queries.snvindel.format4filters)n._tk.format[t]&&(n._tk.format[t].isFilter=!0);delete e.queries.snvindel.format4filters}}if(n._tk.info){if(n.infoFields){for(const e of n.infoFields){if(!e.key)throw".key missing from one of snvindel.byrange.infoFields[]";e.name||(e.name=e.key);const t=n._tk.info[e.key];if(!t)throw"invalid key from one of snvindel.byrange.infoFields[]";t.categories=e.categories,t.name=e.name,t.separator=e.separator}delete n.infoFields}if(e.queries.snvindel.infoUrl){for(const t of e.queries.snvindel.infoUrl){const e=n._tk.info[t.key];if(!e)throw"invalid key from one of snvindel.infoUrl[]";e.urlBase=t.base}delete e.queries.snvindel.infoUrl}}return e.queries.snvindel.info=n._tk.info,e.queries.snvindel.format=n._tk.format,async t=>{if(!Array.isArray(t.rglst))throw"q.rglst[] is not array";if(0==t.rglst.length)throw"q.rglst[] blank array";const s=$s(t);let r;if(n._tk.chr2files){const e=n._tk.chr2files[t.rglst[0].chr];if(!e)throw"unknown chr for chr2files";r=e.file}else r=n._tk.file||n._tk.url;const o=["query",r,"-r",t.rglst.map((e=>(n._tk.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+(e.stop+1))).join(","),"-f","%ID\t%CHROM\t%POS\t%REF\t%ALT\t%INFO\t%FORMAT\n"],i=await(0,js.T)(t,n._tk.samples,e);if(i){if(0==i.size)return[];o.push("-s",[...i].join(","))}t.variantFilter&&(0,xs.u)(t.variantFilter,o);const a=[];return await F.UE({isbcf:!0,args:o,dir:n._tk.dir,callback:r=>{const o=r.split("\t"),l=o[0],c=o[1],u=Number(o[2]),f=o[3],d=o[4].split(","),p=o[5],m={pos:u-1};(0,gs.H)(n._tk,f,d,m,p,l,t.isoform);for(const r of m.mlst)t.hiddenmclass&&t.hiddenmclass.has(r.class)||Ds(r,t)||m.mlst.length>1&&t.variantFilter?.lst&&Ls(r,t)||(r.chr=(n._tk.nochr?"chr":"")+c,r.ssm_id=[r.chr,r.pos,r.ref,r.alt].join(hs.dq),n._tk?.samples?.length&&(Ps(n,r,o,t.addFormatValues,e,i,s),!r.samples)||a.push(r))}}),a}}function $s(e){const t=e.formatFilter||{};return"format"==e.skewerRim?.type&&e.skewerRim.hiddenvalues?.size&&(t[e.skewerRim.formatKey]=e.skewerRim.hiddenvalues),Object.keys(t).length?t:void 0}function Ds(e,t){if(!t.infoFilter)return!1;for(const n in t.infoFilter){const s=e.info[n];if(s)if(Array.isArray(s)){for(const e of t.infoFilter[n])if(s.includes(e))return!0}else if(t.infoFilter[n].includes(s))return!0}return!1}function Ls(e,t){for(const n of t.variantFilter.lst){const t=e.info[n.tvs.term.id];if(null==t)return!0;if("integer"==n.tvs.term.type||"float"==n.tvs.term.type){const e=Number(t);if(Number.isNaN(e))return!0;const s=n.tvs.ranges?.[0];if(s){if("start"in s)if(s.startinclusive){if(e<s.start)return!0}else if(e<=s.start)return!0;if("stop"in s)if(s.stopinclusive){if(e>s.stop)return!0}else if(e>=s.stop)return!0}}}return!1}function Ps(e,t,n,s,r,o,i){if(!n[6]||"."==n[6])return;const a=[];for(const t of n[6].split(":")){const n=e._tk.format[t];if(!n)throw"invalid format field: "+n;a.push(n)}const l=[];let c=e._tk.samples;o&&(c=[...o].map((e=>({name:e}))));for(const[e,t]of c.entries()){const r=n[e+7];if(!r||"."==r)continue;const o=Gs(r.split(":"),a,t,s);if(o){if(i){let e=!1;for(const t in i){const n=t in o.formatK2v?o.formatK2v[t]:Ts;if(i[t].has(n)){e=!0;break}}if(e)continue}l.push(o)}}l.length&&(t.samples=l)}function Gs(e,t,n,s){const r={};for(const[n,s]of t.entries()){const t=e[n];if(t&&"."!=t)if(s.isGT){if("./."==t||".|."==t)continue;r.GT=t}else r[s.ID]=t}if(0==Object.keys(r).length)return null;const o={sample_id:n.name};return s&&(o.formatK2v=r),o}function Us(e,t,n,s=1){s=Number(s);const r=200,o=20;let i=0;for(const e in t.majorchr)i+=t.majorchr[e];const a=800/i,l={};let c=0;const u=[];for(const e in t.majorchr){const n=t.majorchr[e];l[e]=(0,rs.Z)().domain([0,n]).range([a*c,a*(c+n)]),c+=n,u.push({chr:e,chrLen:n,xStart:a*(c-n),xStop:a*c})}const f=(0,rs.Z)().domain([n.min,n.max]).range([r,0]),d=(0,S.createCanvas)(890*s,240*s),p=d.getContext("2d");s>1&&p.scale(s,s),g(n.max),g(0),g(n.min);const m=I().createInterface({input:h().createReadStream(e)});return new Promise(((e,s)=>{m.on("line",(e=>{const t=e.split("\t"),s=t[0];if(!s)return;if(!l[s])return;const r=Number(t[1]);if(!Number.isInteger(r))return;const i=Number(t[2]);if(!Number.isFinite(i))return;if(i<n.min||i>n.max)return;p.fillStyle=i>0?n.positiveColor:n.negativeColor;const a=l[s](r),c=o+f(i);p.fillRect(70+a,c,1,1)})),m.on("close",(()=>{!function(){p.strokeStyle="black",p.beginPath();{const e=220-f(0);p.moveTo(70,e),p.lineTo(870,e),p.stroke()}let e=!0;p.fillStyle="black",p.font="12px Arial",p.textAlign="center";for(const n in l){if(p.fillText(n.replace("chr",""),70+l[n](t.majorchr[n]/2),234),e){e=!1;continue}const s=Math.floor(70+l[n](0))+.5;p.moveTo(s,o),p.lineTo(s,220),p.stroke()}p.closePath()}(),e({src:d.toDataURL(),canvasWidth:890,canvasHeight:240,xoff:70,chrLst:u})}))}));function g(e){p.fillStyle="black",p.font="12px Arial",p.textAlign="right";const t=o+f(e);p.fillText(e,64,t+5),p.strokeStyle="black",p.beginPath(),p.moveTo(66,t),p.lineTo(70,t),p.stroke(),p.closePath()}}function Bs(e,t,n,s,r,o){for(const i of t.yesSamples){if(o&&!o.has(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:Number.parseInt(e),class:"WT",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:Number.parseInt(e),class:"WT",_SAMPLEID_:i})}for(const i of t.noSamples){if(o&&!o.has(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:Number.parseInt(e),class:"Blank",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:Number.parseInt(e),class:"Blank",_SAMPLEID_:i})}}async function zs(e,t){if(e.chr&&Number.isInteger(e.start)&&Number.isInteger(e.stop))return;if(!e.name)throw"both term.name and term.chr/start/stop missing";const n=t.genedb.getjsonbyname.all(e.name);if(0==n.length)throw"unknown gene name";const s=n.find((e=>e.isdefault))||n[0],r=JSON.parse(s.genemodel);if(!r.chr||!Number.isInteger(r.start)||!Number.isInteger(r.stop))throw"invalid chr/start/stop from returned gm";return e.chr=r.chr,e.start=r.start,e.stop=r.stop,r.isoform}async function Js(e,t,n,s){const r={addFormatValues:!0,filter0:s.filter0,filterObj:s.filter,sessionid:s.sessionid,gdcUseCaseuuid:!0};if(e.queries.snvindel.byisoform)return await async function(e,t){if(e.isoform&&"string"==typeof e.isoform)return;if(!e.name)throw"both term.name and term.isoform";const n=t.genedb.getjsonbyname.all(e.name);if(0==n.length)return;const s=n.find((e=>e.isdefault))||n[0],r=JSON.parse(s.genemodel);if(!r.isoform)throw"isoform missing from returned gm";e.isoform=r.isoform}(t,n),t.isoform?(r.isoform=t.isoform,await e.queries.snvindel.byisoform.get(r)):[];if(e.queries.snvindel.byrange)return r.isoform=await zs(t,n),r.rglst=[t],await e.queries.snvindel.byrange.get(r);throw"unknown queries.snvindel method"}function Hs(e,t){t.yesSamples=new Set,t.noSamples=new Set;const n=`SELECT sample, value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = '${t.term_id}'`,s=e.cohort.db.connection.prepare(n).all();for(const e of s)t.yes.value.includes(e.value)?t.yesSamples.add(e.sample):t.no.value.includes(e.value)&&t.noSamples.add(e.sample)}function Ws(e,t,n){if(t.skewerRim){if("format"!=t.skewerRim.type)throw"unknown skewerRim.type";e.rim1count=0;for(const n of e.samples)n.formatK2v?.[t.skewerRim.formatKey]==t.skewerRim.rim1value&&e.rim1count++}}function Vs(e,t){if(t.queries.snvindel?.format)for(const n in t.queries.snvindel.format)if(t.queries.snvindel.format[n].isFilter){e.formatK2count||(e.formatK2count={}),e.formatK2count[n]||(e.formatK2count[n]={v2c:{},unannotatedCount:0});for(const t of e.samples){const s=t.formatK2v?.[n];null==s?e.formatK2count[n].unannotatedCount++:e.formatK2count[n].v2c[s]=1+(e.formatK2count[n].v2c[s]||0)}}}function Zs(e,t){if(e.startunbounded){if(e.stopunbounded)throw"both start & stop are unbounded from "+t;if(!Number.isFinite(e.stop))throw".stop undefined when start is unbounded from "+t}else if(e.stopunbounded){if(!Number.isFinite(e.start))throw".start undefined when stop is unbounded from "+t}else{if(!Number.isFinite(e.start))throw".start undefined when start is not unbounded from "+t;if(!Number.isFinite(e.stop))throw".stop undefined when stop is not unbounded from "+t;if(e.start>=e.stop)throw".start is not lower than stop from "+t}}const Ks="Ancestry_PC_";async function Xs(e,t=null,s=null){if(!e.cohort.termdb)throw"cohort.termdb missing when cohort.db is used";await async function(e){if(e.phewas){if(e.phewas.samplefilter4termtype&&e.phewas.samplefilter4termtype.condition&&!e.phewas.samplefilter4termtype.condition.filter)throw"filter{} missing from tdb.phewas.samplefilter4termtype.condition";if(e.phewas.comparison_groups){if(!Array.isArray(e.phewas.comparison_groups))throw"tdb.phewas.comparison_groups is not array";if(0==e.phewas.comparison_groups.length)throw"tdb.phewas.comparison_groups[] cannot be empty"}}if(e.selectCohort){if(!e.selectCohort.term)throw"term{} missing from termdb.selectCohort";if(!e.selectCohort.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof e.selectCohort.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=e.selectCohort.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';if(!e.selectCohort.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(e.selectCohort.values))throw"termdb.selectCohort.values is not array";if(0==e.selectCohort.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const t of e.selectCohort.values){if(!t.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(t.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==t.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}if(e.restrictAncestries){if(!Array.isArray(e.restrictAncestries)||0==e.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const t of e.restrictAncestries){if(!t.name)throw"name missing from one of restrictAncestries";if("object"!=typeof t.tvs)throw".tvs{} missing from one of restrictAncestries";if(!Number.isInteger(t.PCcount))throw"PCcount is not integer";if(t.PCfile)t.pcs=await Qs(t.PCfile,t.PCcount);else if(t.PCfileBySubcohort)for(const e in t.PCfileBySubcohort){const n=t.PCfileBySubcohort[e];if(!n.file)throw".file missing for a subcohort in PCfileBySubcohort";n.pcs=await Qs(n.file,t.PCcount)}}}}(e.cohort.termdb),await async function(e){if("scatterplots"in e)for(const t of e.scatterplots.plots){const e=y().join(r().tpmasterdir,t.file);await F.Ic(e)}}(e.cohort),(0,vs.JV)(e),function(e){e.sampleName2Id=new Map,e.sampleId2Name=new Map;const t="SELECT * FROM sampleidmap",n=e.cohort.db.connection.prepare(t).all();for(const t of n)e.sampleId2Name.set(t.id,t.name),e.sampleName2Id.set(t.name,t.id);e.getSampleIdMap=t=>{const n={};for(const s in t)n[s]=e.sampleId2Name.get(+s);return n}}(e);const{mayGetGeneVariantData:o,getTermTypes:i,mayGetMatchingGeneNames:a}=n(7833);e.mayGetGeneVariantData=o,e.getTermTypes=i,e.mayGetMatchingGeneNames=a,e.cohort?.db?.refresh&&t&&_s(e,t,s)}async function Ys(e,t){if(!e.track)throw"no mds2 track; missing ds.track{}";const n=e.track;n.name||(n.name=e.label),function(e){if(!e.populations)return;if(!Array.isArray(e.populations))throw"populations should be array";for(const t of e.populations){if(!t.key)throw"key missing from a population";if(t.label||(t.label=t.key),!Array.isArray(t.sets))throw".sets is not an array in population: "+t.key;for(const e of t.sets){if(!e.infokey_AC)throw"infokey_AC missing from a set of population: "+t.key;if(!e.infokey_AN)throw"infokey_AN missing from a set of population: "+t.key;if(t.termfilter&&!e.termfilter_value)throw"termfilter_value missing from a set of population where termfilter is set: "+t.key}}}(n),await async function(e,t,n){if(!e)return;if(!e.chr2bcffile)throw"vcftk.chr2bcffile is missing";{if("object"!=typeof e.chr2bcffile)throw"chr2bcffile not an object";for(const t in e.chr2bcffile)e.chr2bcffile[t]=y().join(r().tpmasterdir,e.chr2bcffile[t]);const n={file:e.chr2bcffile[t.defaultcoord.chr]};if(!n.file)throw"default chr missing from chr2bcffile";await F._H(n,t,!0),e.info=n.info,e.format=n.format,e.samples=n.samples,e.nochr=n.nochr}if(e.AD&&e.AD.chr2bcffile){if("object"!=typeof e.AD.chr2bcffile)throw"AD.chr2bcffile not an object";for(const t in e.AD.chr2bcffile)e.AD.chr2bcffile[t]=y().join(r().tpmasterdir,e.AD.chr2bcffile[t]);const s={file:e.AD.chr2bcffile[t.defaultcoord.chr]};if(!s.file)throw"default chr missing from AD.chr2bcffile";await F._H(s,t,!0),e.AD.info=s.info,e.AD.format=s.format,e.AD.samples=s.samples,e.AD.nochr=s.nochr,console.log(n.label+" vcf: AD: "+e.AD.samples.length+" samples");for(const t of e.AD.samples){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer vcf sample: "+t.name;t.name=e}}if(e.samples){for(const t of e.samples){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer vcf sample: "+t.name;t.name=e}console.log(n.label+" vcf: "+e.samples.length+" samples")}else console.log(n.label+" vcf: no samples");if(e.numerical_axis&&e.numerical_axis.info_keys){if(!Array.isArray(e.numerical_axis.info_keys))throw"numerical_axis.info_keys should be an array";for(const t of e.numerical_axis.info_keys){const n=e.info[t.key];if(!n)throw'INFO field "'+t.key+'" not found for numerical_axis';if("Float"!=n.Type&&"Integer"!=n.Type)throw'INFO field "'+t.key+'" from numerical_axis not of integer or float type';if("1"!=n.Number&&"A"!=n.Number)throw'for numerical axis, INFO field "'+t.key+'" only allows to be Number=1 or Number=A'}}if(e.plot_mafcov){if(!e.AD)throw".plot_mafcov enabled but .AD{} missing from vcf";if(!e.AD.samples)throw".plot_mafcov enabled but no samples from vcf";if(!e.AD.format)throw".plot_mafcov enabled but no FORMAT fields from vcf";if(!e.AD.format.AD)throw".plot_mafcov enabled but the AD FORMAT field is missing";if("R"!=e.AD.format.AD.Number)throw"AD FORMAT field Number=R is not true";if("Integer"!=e.AD.format.AD.Type)throw"AD FORMAT field Type=Integer is not true";if(e.plot_mafcov.overlay_term){if(!n.cohort)throw"ds.cohort missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb)throw"ds.cohort.termdb missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb.q)throw"ERR: termdb.q{} missing while trying to access termdb helper functions";if(!n.cohort.termdb.q.termjsonByOneid)throw"ERR: q.termjsonByOneid missing";const t=n.cohort.termdb.q.termjsonByOneid(e.plot_mafcov.overlay_term);if(!t)throw'unknown term id "'+e.plot_mafcov.overlay_term+'" from vcftk.plot_mafcov.overlay_term';e.plot_mafcov.overlay_term=t}}if(e.termdb_bygenotype){if(!e.samples)throw".termdb_bygenotype enabled but no samples from vcf";if(!e.format)throw".termdb_bygenotype enabled but no FORMAT fields from vcf";if(!e.format.GT)throw".termdb_bygenotype enabled but the GT FORMAT field is missing";if(!n.cohort)throw"termdb_bygenotype but ds.cohort missing";if(!n.cohort.termdb)throw"termdb_bygenotype but ds.cohort.termdb missing";if(e.termdb_bygenotype.getAF){if(!e.termdb_bygenotype.termid_sex)throw"termid_sex missing for getAF at termdb_bygenotype";if(!e.termdb_bygenotype.value_male)throw"value_male missing for getAF at termdb_bygenotype";const t=n.cohort.termdb.q.getSample2value(e.termdb_bygenotype.termid_sex);e.termdb_bygenotype.male_samples=new Set;for(const n of t)n.value==e.termdb_bygenotype.value_male&&e.termdb_bygenotype.male_samples.add(n.sample);if(!e.termdb_bygenotype.sex_chrs)throw"sex_chrs missing for getAF at termdb_bygenotype";if(!Array.isArray(e.termdb_bygenotype.sex_chrs))throw"sex_chrs is not array";e.termdb_bygenotype.sex_chrs=new Set(e.termdb_bygenotype.sex_chrs)}}if(e.samples){e.sample2arrayidx=new Map;for(const[t,n]of e.samples.entries())e.sample2arrayidx.set(n.name,t)}}(n.vcf,t,e),function(e){if(!e.info_fields)return;if(!Array.isArray(e.info_fields))throw"tk.info_fields is not array";for(const t of e.info_fields){if(!t.key)throw".key missing from one of tk.info_fields[]";if(e.vcf&&e.vcf.info&&!e.vcf.info[t.key])throw`info field ${t.key} missing from tk.vcf.info{}`;if(t.label||(t.label=t.key),t.iscategorical){if(!Array.isArray(t.values))throw".values[] not an array of categorical INFO field: "+t.key;for(const e of t.values){if(!e.key)throw"key missing from a value of categorical INFO: "+t.key;e.label||(e.label=e.key)}}else if(t.isfloat||t.isinteger){if(!t.range)throw".range{} missing from a numerical INFO: "+t.key;Zs(t.range,"tk.info_fields[]")}else if(!t.isflag)throw"tk.info_fields unknown type: "+t.key}}(n),await async function(e,t,n){if(!e)return;if(!Array.isArray(e.tracks))throw"ld.tracks[] not an array";if(0==e.tracks.length)throw"ld.tracks[] is empty array";for(const n of e.tracks){if(!n.name)throw".name missing from a ld track";if(!Number.isInteger(n.viewrangelimit))throw'viewrangelimit missing from ld track "'+n.name+'"';if(n.file)n.file.startsWith(r().tpmasterdir)||(n.file=y().join(r().tpmasterdir,n.file)),await F.LC(n.file),n.nochr=await F.Jy(n.file,null,t),console.log(n.file+": "+(n.nochr?"no chr":"has chr"));else if(!n.chr2file)throw"ld tk has no file or chr2file"}}(n.ld,t),await async function(e,t){if(!e)return}(n.svcnv,0),function(e){const t=new Set;if(e.vcf&&e.vcf.samples)for(const n of e.vcf.samples)t.add(n.name);e.svcnv;t.size&&(e.samples=[...t])}(n),n.samples&&console.log(e.label+": mds2: "+n.samples.length+" samples")}async function Qs(e,t){const n=new Map;for(let e=1;e<=t;e++)n.set(Ks+e,new Map);let s=0;for(const o of(await F.b5(y().join(r().tpmasterdir,e))).trim().split("\n")){s++;const e=o.split("\t"),r=Number(e[0]);if(!Number.isInteger(r))throw"non-integer sample id from a line of restrictAncestries pc file";for(let s=1;s<=t;s++){const t=Ks+s,o=Number(e[s]);if(Number.isNaN(o))throw"non-numeric PC value from restrictAncestries file";n.get(t).set(r,o)}}return console.log(s,"samples loaded from "+e),Object.freeze(n)}var er=n(9157);const tr=n(334),nr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO";async function sr(e,t,n,s){if(!e.rglst)throw".rglst[] missing";const r=n.track.vcf;if(!r)throw"ds.track.vcf missing";const o={info:r.info,format:r.format,samples:r.samples};await async function(e,t,n){if(e.querymode={},e.AFtest){if(n.iscustom)throw"custom track does not support AFtest";for(const t of e.AFtest.groups)if(!t.is_infofield)if(t.is_termdb)t.columnidx=await rr(t.filter,n);else{if(!t.is_population)throw"Cannot set query mode: unknown group type";{if(!n.track.populations)throw"ds.track.populations missing";const s=n.track.populations.find((e=>e.key==t.key));if(!s)throw"unknown population key: "+t.key;if(t.population=JSON.parse(JSON.stringify(s)),e.AFtest.termfilter&&e.AFtest.termfilter[0].term.id==t.population.termfilter){const n=t.population.sets.find((t=>t.termfilter_value==e.AFtest.termfilter[0].values[0].key));if(!n)throw"no matching set found for a termfilter from a population";t.population.sets=[n]}}}if(e.AFtest.testby_fisher&&e.AFtest.groups.find((e=>e.is_infofield)))throw"cannot do fisher test for an INFO field";{const t=e.AFtest.groups.find((e=>e.is_population));if(t&&t.adjust_race){const s=e.AFtest.groups.find((e=>e.is_termdb));if(!s)throw"cannot adjust race: termdb group missing";s.pop2average=await async function(e,t,n,s){const r=new Map;let o=0;for(const t of e){const e={infokey_AC:t.infokey_AC,infokey_AN:t.infokey_AN,average:0},s=await bs.J4({ds:n,key:t.key});for(const t of s){if(!n.track.vcf.sample2arrayidx.has(t.sample))continue;const s=Number(t.value);Number.isFinite(s)&&(e.average+=s,o+=s)}r.set(t.key,e)}for(const[e,t]of r)t.average/=o;return r}(t.population.sets,s.columnidx,n)}}return void(e.querymode.range_AFtest=!0)}e.querymode.range_variantonly=!0}(e,0,n),function(e,t){if(t.querymode.range_variantonly||t.querymode.range_AFtest){delete e.samples;for(const e of t.rglst)e.variants=[]}t.bcfformat=nr,t.exportgenotype||t.querymode.range_AFtest?t.bcfformat+="\t%FORMAT\n":t.querymode.range_variantonly&&(t.querymode.slicecolumnindex||(t.bcfformat+="\\n"))}(o,e),e.exportgenotype&&(s.mlst=[]),function(e,t){const n=(s=e.rglst[0],s.usegm_isoform?{gmmode:"protein",usegm:{isoform:s.usegm_isoform}}:{});var s;e.m_is_filtered=s=>{let r=!1;if(e.info_fields)for(const n of e.info_fields){const e=t.info_fields[n.key];let o;if(s.info&&(o=s.info[n.key]),null==o&&s.altinfo&&(o=s.altinfo[n.key]),n.iscategorical)null==o?(e.unannotated_count=1+(e.unannotated_count||0),n.unannotated_ishidden&&(r=!0)):(e.value2count[o]=1+(e.value2count[o]||0),n.hiddenvalues[o]&&(r=!0));else if(n.isnumerical)null==o&&null!=n.missing_value&&(o=n.missing_value),n.range.startunbounded||(n.range.startinclusive?o<n.range.start&&(r=!0):o<=n.range.start&&(r=!0)),n.range.stopunbounded||(n.range.stopinclusive?o>n.range.stop&&(r=!0):o>=n.range.stop&&(r=!0)),r&&e.filteredcount++;else{if(!n.isflag)throw"unknown info type";o?e.count_yes++:e.count_no++,(n.remove_yes&&o||n.remove_no&&!o)&&(r=!0)}}return!!r||($.vcfcopymclass(s,n),t.mclass2count[s.class]=(t.mclass2count[s.class]||0)+1,e.hidden_mclass&&e.hidden_mclass.has(s.class)&&(r=!0),r)}}(e,s);for(const t of e.rglst){if(r.viewrangeupperlimit&&t.stop-t.start>=r.viewrangeupperlimit){t.rangetoobig="Zoom in under "+$.bplen(r.viewrangeupperlimit)+" to view VCF data";continue}const n=(r.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop,s=r.chr2bcffile[t.chr];if(!s)throw"chr not found in chr2bcffile";await F.UE({isbcf:!0,args:["query",s,"-r",n,"-f",e.bcfformat],dir:r.dir,callback:i(t)})}function i(t){return n=>{if(e.exportgenotype){const t=n.split("\t"),[r,i,a]=D.S(t.slice(0,8).join("\t"),o);for(const n of i){if(e.m_is_filtered(n))continue;const r=[n.chr+"."+(n.pos+1)+"."+n.ref+"."+n.alt,n.name||""];for(let e=9;e<t.length;e++){const s=t[e].split(":",1)[0];if("."==s){r.push(".");continue}const o=s.split(-1==s.indexOf("/")?"|":"/");r.push(("0"==o[0]?n.ref:n.alt)+("0"==o[1]?n.ref:n.alt))}s.mlst.push(r.join("\t"))}return}let i;if(e.querymode.range_variantonly)if(e.querymode.slicecolumnindex);else{const[t,s,r]=D.S(n,o);i=[];for(const t of s)e.m_is_filtered(t)||i.push(t)}else e.querymode.range_AFtest&&(i=function(e,t,n,s){const r=e.split("\t"),[o,i,a]=D.S(r.slice(0,8).join("\t"),n),l=i.filter((e=>!t.m_is_filtered(e)));if(0==l.length)return;const c=[r[3],...r[4].split(",")],u=[];for(const e of l){const n=ir(r,e,c,t);if(or(n)){if(u.push(e),t.AFtest.testby_AFdiff){for(const e of n)if(e.is_infofield)e.v=e.infofieldvalue;else{if(!e.is_termdb&&!e.is_population)throw"unknown group type";e.v=e.altcount/(e.refcount+e.altcount)}e.AFtest_group_values=[n[0].v,n[1].v],e.nm_axis_value=n[0].v-n[1].v}else t.AFtest.testby_fisher&&(e.contigencytable=[n[0].altcount,n[0].refcount,n[1].altcount,n[1].refcount]);{const s=t.AFtest.groups.find((e=>e.is_population));if(s&&s.adjust_race){const t=n.find((e=>e.is_population));e.popsetadjvalue=[];for(const[n,s]of t.set2value)e.popsetadjvalue.push([n,s.ACraw,s.ANraw-s.ACraw,Number.parseInt(s.ACadj),Number.parseInt(s.ANadj-s.ACadj)])}}}}return u}(n,e,o));if(i)for(const e of i)e.csq&&(e.csq_count=e.csq.length,delete e.csq),delete e._m,delete e.vcf_ID,delete e.sampledata,r.nochr&&(e.chr="chr"+e.chr),t.variants.push(e)}}await async function(e){if(!e.querymode.range_AFtest)return;if(!e.AFtest.testby_fisher)return;const t=[],n={};for(const s of e.rglst)if(s.variants)for(const e of s.variants)if(e.contigencytable){const s=e.chr+"."+e.pos+"."+e.ref+"."+e.alt;t.push(s+"\t"+e.contigencytable.join("\t")),n[s]=e}if(0==t.length)return;const s=await er(y().join(tr.binpath,"/utils/fisher.R"),t);for(const e of s){const t=e.split("\t"),s=n[t[0]];if(s){const e=Number.parseFloat(t[5]);s.AFtest_pvalue=e,s.nm_axis_value=Number.isNaN(e)?0:-Math.log10(e)}}}(e),function(e,t,n,s){if(t.exportgenotype)return e.exportgenotype="variant\tSNP\t"+n.samples.map((e=>s.cohort.termdb.id2sampleName(e.name))).join("\t")+"\n"+e.mlst.join("\n"),void delete e.mlst;e.vcf={rglst:[]};for(const n of t.rglst){const t={chr:n.chr,start:n.start,stop:n.stop,width:n.width,reverse:n.reverse,xoff:n.xoff};e.vcf.rglst.push(t),n.rangetoobig?(t.rangetoobig=n.rangetoobig,delete n.rangetoobig):n.variants?(t.variants=n.variants,delete n.variants):n.canvas&&(t.img=n.canvas.toDataURL(),delete n.canvas)}if(t.AFtest&&t.AFtest.groups.find((e=>e.is_termdb))){e.AFtest_termdbgroup=[];let n=t.AFtest.groups[0];if(n.is_termdb&&(e.AFtest_termdbgroup[0]={samplecount:n.columnidx.length},n.pop2average)){e.AFtest_termdbgroup[0].popsetaverage=[];for(const[t,s]of n.pop2average)e.AFtest_termdbgroup[0].popsetaverage.push([t,s.average])}if(n=t.AFtest.groups[1],n.is_termdb&&(e.AFtest_termdbgroup[1]={samplecount:n.columnidx.length},n.pop2average)){e.AFtest_termdbgroup[1].popsetaverage=[];for(const[t,s]of n.pop2average)e.AFtest_termdbgroup[1].popsetaverage.push([t,s.average])}}}(s,e,r,n)}async function rr(e,t){if(!t.track)throw"ds.track{} missing";return(await bs.cf(e,t)).reduce(((e,n)=>{const s=t.track.vcf.sample2arrayidx.get(n);return s>=0&&e.push(s),e}),[])}function or(e){if(e.find((e=>e.is_infofield)))return!0;return e[0].altcount+e[1].altcount>0}function ir(e,t,n,s){return s.AFtest.groups.reduce(((r,o)=>{if(o.is_infofield)r.push({is_infofield:!0,infofieldvalue:ar(t,o)});else if(o.is_termdb){const s=function(e,t,n){let s=!0;const r=new Map;for(const t of e)r.set(t,0);for(const o of n){if(!t[9+o])continue;const n=t[9+o].split(":")[0];"."!=n&&n.split(-1==n.indexOf("/")?"|":"/").forEach((t=>{const n=Number.parseInt(t);if(Number.isNaN(n))return;const o=e[n];o&&(0!=n&&(s=!1),r.set(o,1+r.get(o)))}))}return{allref:s,alleles:r}}(n,e,o.columnidx);r.push({is_termdb:!0,allref:s.allref,refcount:s.alleles.get(t.ref)||0,altcount:s.alleles.get(t.alt)||0})}else{if(!o.is_population)throw"unknown group type";{const e=new Map;for(const n of o.population.sets)e.set(n.key,{ACraw:ar(t,{key:n.infokey_AC,missing_value:0}),ANraw:ar(t,{key:n.infokey_AN,missing_value:0})});let n=0,i=0;if(o.adjust_race)[n,i]=function(e,t){if(!t)throw"group_termdb missing";if(!t.pop2average)throw"group_termdb.pop2average missing";let n=0;for(const t of e.values())n+=t.ANraw;let s=0,r=0;for(const[o,i]of e)i.ANadj=n*t.pop2average.get(o).average,i.ACadj=0==i.ANadj?0:i.ACraw*i.ANadj/i.ANraw,s+=i.ACadj,r+=i.ANadj;return[r-s,s]}(e,s.AFtest.groups.find((e=>e.is_termdb)));else for(const t of e.values())i+=t.ACraw,n+=t.ANraw-t.ACraw;r.push({is_population:!0,refcount:n,altcount:i,set2value:e})}}return r}),[])}function ar(e,t){if(e.info){const n=e.info[t.key];if(null!=n)return n}if(e.altinfo){const n=e.altinfo[t.key];if(null!=n)return n}return t.missing_value}var lr=n(5540);const cr=(0,n(4090).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),ur="#aaa",fr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO\t%FORMAT\n";async function dr(e,t,n,s,r){const o=s.track.ld.tracks.find((t=>t.name==e.name));if(!o)throw"ld track not found by name: "+e.name;if(!t.rglst)throw"rglst missing";r.ld[o.name]={rglst:[]};const i=t.trigger_ld.connheight||50;for(const e of t.rglst){const t={chr:e.chr,start:e.start,stop:e.stop,width:e.width,reverse:e.reverse,xoff:e.xoff};if(r.ld[o.name].rglst.push(t),e.stop-e.start>=o.viewrangelimit){t.rangetoobig="Zoom in under "+(0,$.bplen)(o.viewrangelimit)+" to view LD data";continue}const n=[],s=new Set,a=(o.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;await F.UE({args:[o.file,a],dir:o.dir,callback:t=>{const o=t.split("\t"),i=Number.parseInt(o[1]);if(i<e.start)return;const a=Number.parseInt(o[2]);if(a>e.stop)return;if(r.__mposset){if(!r.__mposset.has(i))return;if(!r.__mposset.has(a))return}const l=Number.parseFloat(o[5]);n.push({start:i,stop:a,r2:l}),s.add(i),s.add(a)}}),t.img=pr(e,n,s,i)}}function pr(e,t,n,s){const[r,o]=function(e,t){let n=e.width/t.size,s=0;n>40&&(n=40,s=(e.width-n*t.size)/2);const r=new Map,o=e.reverse?[...t].sort(((e,t)=>t-e)):[...t].sort(((e,t)=>e-t));let i=s;for(const e of o)r.set(e,i+n/2),i+=n;return[n,r]}(e,n),i=new Map;{const t=(e.stop-e.start)/e.width;for(const s of n)e.reverse?i.set(s,(e.stop-s)/t):i.set(s,(s-e.start)/t)}let a=0;for(const e of t)a=Math.max(a,(o.get(e.stop)-o.get(e.start))/2);const l=s+a+r/2,c=(0,S.createCanvas)(e.width,l),u=c.getContext("2d");u.strokeStyle="black";for(const e of n)u.beginPath(),u.moveTo(i.get(e),0),u.lineTo(o.get(e),s),u.closePath(),u.stroke();for(const e of t){const t=o.get(e.start),n=o.get(e.stop),i=(t+n)/2,a=s+Math.abs(n-t)/2,l=Math.floor(255*(1-e.r2));u.fillStyle="rgb(255,"+l+","+l+")",u.beginPath(),u.moveTo(i,a-r/2),u.lineTo(i-r/2,a),u.lineTo(i,a+r/2),u.lineTo(i+r/2,a),u.lineTo(i,a-r/2),u.closePath(),u.fill()}return{height:l,src:c.toDataURL()}}var mr=n(6191);function hr(e,t){const{filename:n,route:s,dslabel:o,embedder:i}=e,a=t.email.replace("@","_at_");return`${r().cachedir}/sessionsByCred/${i}/${a}/${s}/${o}`}const gr=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];function yr(e){const t=e.toString(16);return 1==t.length?"0"+t:t}function br(e,t,n){return yr(e)+yr(t)+yr(n)}function vr(e){if(!e.cellfile)throw"cellfile missing";{const[t,n,s]=F.ZX({query:{file:e.cellfile}});if(t)throw"cellfile error: "+t;e.cellfile=n}if(!e.delimiter)throw"delimiter missing";if(!Number.isInteger(e.barcodecolumnidx))throw"barcodecolumnidx missing";if(!Number.isInteger(e.categorycolumnidx))throw"categorycolumnidx missing";return new Promise(((t,n)=>{const s=new Map,r=I().createInterface({input:h().createReadStream(e.cellfile)});let o=!0;r.on("line",(t=>{if(o)return void(o=!1);const n=t.split(e.delimiter);s.set(n[e.barcodecolumnidx],{category:n[e.categorycolumnidx],expvalue:0})})),r.on("close",(()=>{t(s)}))}))}const wr=r().fimo||"fimo";async function _r(e,t,n){const s=y().join(r().cachedir,Math.random().toString());return await F.Sf(s,n),new Promise(((n,r)=>{const o=["--parse-genomic-coord","--verbosity",1,"--text"];e.fimo_thresh&&(o.push("--thresh"),o.push(e.fimo_thresh)),o.push(t.fimo_motif.db),o.push(s);const i=(0,x.spawn)(wr,o),a=[];i.stdout.on("data",(e=>a.push(e))),i.on("close",(r=>{h().unlink(s,(()=>{}));const o=a.join("").trim();o||n([]);const i=[],l=o.split("\n");for(let n=1;n<l.length;n++){const s=l[n].split("\t"),r=s[0].split("_")[0],o=Number.parseInt(s[3]),a=Number.parseInt(s[4]);if(o>e.m.pos||a<e.m.pos+1)continue;const c=Number.parseFloat(s[7]),u={start:o,stop:a,strand:s[5],name:r,pvalue:c,score:Number.parseFloat(s[6]),logpvalue:-Math.log10(c)};t.fimo_motif.tf2attr&&(u.attr=t.fimo_motif.tf2attr[u.name]),i.push(u)}n(i)}))}))}function kr(e){!function(e){if(!e.sample2term)throw".sample2term missing";if(!e.terms)throw".terms[] missing";if(!e.config)throw".config{} missing"}(e);const t=function(e){const t=new Map;for(const n of e.sample2term.values())for(const e of n.keys())t.set(e,1+(t.get(e)||0));if(e.config.termidorder){const n=[];for(const s of e.config.termidorder){const e=t.get(s);null!=e&&n.push({id:s,samplecount:e})}return n}return[...t].sort(((e,t)=>t[1]-e[1])).map((e=>({id:e[0],samplecount:e[1]})))}(e),n=function(e,t){const n=[];for(const[s,r]of e.sample2term)t.find((e=>r.has(e.id)))&&n.push(s);return n}(e,t);return function(e,t,n){for(const[s,r]of t.entries()){const o=0==s?[{samples:n}]:t[s-1].blocks;r.blocks=qr(o,r.id,e)}}(e,t,n),function(e,t){for(const n of e){const e=t.terms.find((e=>e.id==n.id));n.name=e.name;for(const t of n.blocks)t.samplecount=t.samples.length,delete t.samples,t.value&&(t.color=e.values[t.value].color)}}(t,e),function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];for(const e of n.blocks){let t=0;for(const n of e.children)t+=n.symbolwidth;const n=e.isgap?1:e.samplecount.toString().length;e.symbolwidth=Math.max(n,t)}}let t=0;for(const n of e[0].blocks){n.x=t;let e=t;for(const t of n.children)t.x=e,e+=t.symbolwidth;t+=n.symbolwidth}for(let t=1;t<e.length;t++)for(const n of e[t].blocks){let e=n.x;for(const t of n.children)t.x=e,e+=t.symbolwidth}for(const t of e)delete t.children}(t),t}function qr(e,t,n){const s=[];for(const r of e){const e=new Map,o=[];for(const s of r.samples){const r=n.sample2term.get(s);if(r){const n=r.get(t);null==n?o.push(s):(e.has(n)||e.set(n,[]),e.get(n).push(s))}else o.push(s)}const i=[...e].sort(((e,t)=>t[1].length-e[1].length));for(const e of i){const t={value:e[0],samples:e[1],children:[]};s.push(t),r.children&&r.children.push(t)}if(o.length){const e={isgap:!0,samples:o,children:[]};s.push(e),r.children&&r.children.push(e)}}return s}async function xr(e){const t=["futime\tfustat\trx"];for(const[n,s]of e.entries())for(const e of s.lst)t.push(e.serialtime+"\t"+e.censored+"\t"+n);const n=await(0,er.default)(y().join(r().binpath,"/utils/km.R"),t);return Number(n.join(""))}async function Nr(e,t,n,s){const r=new Set(e.map((e=>e.name))),o=t.samplerule.set;let i,a;for(const e in n.queries){const t=n.queries[e];t.type==$.tkt.mdsvcf?i=t:t.type==$.tkt.mdssvcnv&&(a=t)}const l=new Set;if(o.cnv||o.loh||o.sv||o.fusion||o.itd){if(!a)throw"no svcnv found in ds.queries";if(s)return await Sr(a,r,t,!0);const e=await Sr(a,r,t);for(const t of e)l.add(t)}if(o.snvindel){if(!i)throw"no vcf found in ds.queries";for(const e of i.tracks)await Ar(i,e,r,l,t)}return e.filter((e=>l.has(e.name)))}async function Sr(e,t,n,s){const o=n.samplerule.set,i=e.url?await F.d1(e.url,e.indexURL):null,a=new Set,l=new Set,c=new Set;return await F.UE({args:[e.file?y().join(r().tpmasterdir,e.file):e.url,(e.nochr?o.chr.replace("chr",""):o.chr)+":"+o.start+"-"+(o.stop+1)],dir:i,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),i=Number.parseInt(n[2]),u=JSON.parse(n[3]);if(t.has(u.sample)){if(u.dt==$.dtcnv){if(!o.cnv)return;if(o.cnv.focalsizelimit&&i-r>=o.cnv.focalsizelimit)return;if(o.cnv.valuecutoff&&Math.abs(u.value)<o.cnv.valuecutoff)return;return s?u.value>0?a.add(u.sample):l.add(u.sample):c.add(u.sample),void o.samples_cnv.add(u.sample)}if(u.dt==$.dtloh){if(!o.loh)return;if(o.loh.focalsizelimit&&i-r>=o.loh.focalsizelimit)return;if(o.loh.valuecutoff&&u.segmean<o.loh.valuecutoff)return;return c.add(u.sample),void o.samples_loh.add(u.sample)}if(u.dt==$.dtsv){if(!o.sv)return;return c.add(u.sample),void o.samples_sv.add(u.sample)}if(u.dt==$.dtfusionrna){if(!o.fusion)return;return c.add(u.sample),void o.samples_fusion.add(u.sample)}if(u.dt==$.dtitd){if(!o.itd)return;return c.add(u.sample),void o.samples_itd.add(u.sample)}}}}),s?[a,l]:c}async function Ar(e,t,n,s,o){const i=o.samplerule.set,a=t.url?await F.d1(t.url,t.indexURL):null;await F.UE({args:[t.file?y().join(r().tpmasterdir,t.file):t.url,(t.nochr?i.chr.replace("chr",""):i.chr)+":"+i.start+"-"+(i.stop+1)],dir:a,callback:r=>{if(t.type==$.mdsvcftype.vcf){const[o,a,l]=D.S(r,{nochr:t.nochr,samples:t.samples,info:e.info,format:t.format});for(const e of a)if(e.sampledata&&!(i.snvindel.ref&&(e.ref!=i.snvindel.ref||e.alt!=i.snvindel.alt)||i.snvindel.hiddenclass&&($.vcfcopymclass(e,{}),i.snvindel.hiddenclass[e.class])))for(const t of e.sampledata)n.has(t.sampleobj.name)&&(s.add(t.sampleobj.name),i.samples_snvindel.add(t.sampleobj.name))}}})}async function Cr(e,t,n){if(!n.queries)throw".queries{} missing from ds";let s;for(const e in n.queries)n.queries[e].isgenenumeric&&(s=n.queries[e]);if(!s)throw"no gene numeric query from ds";const o=s.url?await F.d1(s.url,s.indexURL):null,i=t.samplerule.set,a=new Map;await F.UE({args:[s.file?y().join(r().tpmasterdir,s.file):s.url,i.chr+":"+i.start+"-"+i.stop],dir:o,callback:e=>{const t=JSON.parse(e.split("\t")[3]);t.sample&&Number.isFinite(t.value)&&t.gene==i.gene&&a.set(t.sample,t.value)}});const l=[];for(const t of e)a.has(t.name)&&(t.genevalue=a.get(t.name),l.push(t));return l.sort(((e,t)=>e.genevalue-t.genevalue)),[s,l]}function jr(e){e.lst.sort(((e,t)=>e.serialtime-t.serialtime));let t=e.lst.length,n=[],s=0;e.steps=[];for(const r of e.lst){if(0==r.censored){n.push(r.serialtime);continue}const o=1*(1-s)/(t-n.length);e.steps.push({x:r.serialtime,y:s,drop:o,censored:n}),s+=o,t-=n.length+1,n=[]}n.length>0&&e.steps.push({x:e.lst[e.lst.length-1].serialtime,y:s,drop:0,censored:n})}exports.do_plot=jr;const Tr={};function Mr(e,t,n){const s=+new Date;if(e.ip in Tr||(Tr[e.ip]={time:s,count:0}),s-Tr[e.ip].time>3e4)delete Tr[e.ip];else{if(Tr[e.ip].count>10)return void t.send({error:"busy"});Tr[e.ip].count++}throw t.send({error:n}),new Date+" "+n}const Or={genome(e){if("string"!=typeof e)throw"genome should be a non-empty string";if(/\s+/.test(e))throw"invalid genome character";return e},chr(e){if("string"!=typeof e)throw"chr should be a string";if(/\s+/.test(e))throw"invalid chr character";return e},start:e=>Number(e),term(e){const t="string"==typeof e?JSON.parse(e):e;if(!("id"in t))throw"missing termWrapper.id";if(!("q"in t))throw"missing termWrapper.q";return t}},Ir=require("cookie-parser");var Er=n.n(Ir),Rr=n(2062);function Fr(e){return!isNaN(parseFloat(e))&&isFinite(e)&&""!==e}var $r=n(5708);const Dr=e=>e.startsWith("[E::idx_test_and_fetch]"),Lr=(new Map,Object.freeze(r().features||{})),Pr={},Gr=r().tabix,Ur=r().samtools,Br=r().bcftools,zr=(r().bigwigsummary,r().hicstraw,"Unannotated"),Jr=i()();Jr.disable("x-powered-by"),r().users&&Jr.use(ve()({users:r().users,challenge:!0}));const Hr=r().basepath||"";function Wr(e){e.header("Vary","Origin"),e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS, HEAD"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, origin, x-requested-with, content-type, accept, authorization, X-Auth-Token, X-Ds-Access-Token, X-SjPPDs-Sessionid, x-auth-token, x-ds-access-token, x-sjppds-sessionid")}if(!r().backend_only){const e=i().static(y().join(process.cwd(),"./public"),{setHeaders:Wr});Jr.use(e)}function Vr(e){const t={};for(const n in e.query)"jwt"!=n&&(t[n]=e.query[n]);console.log("%s\t%s\t%s\t%s",c().parse(e.url).pathname,new Date,e.header("x-forwarded-for")||e.connection.remoteAddress,JSON.stringify(t).replace(/\\"/g,'"'))}async function Zr(){try{if(r().preListenScript){const{cmd:e,args:t}=r().preListenScript,n=N().spawnSync(e,t,{encoding:"utf-8"});if(n.stderr.trim())throw n.stderr.trim();console.log(n.stdout)}r().appEnable&&r().appEnable.forEach((e=>Jr.enable(e)));const e=r().port,t=`STANDBY AT PORT ${e}`;if(r().ssl){const n={key:h().readFileSync(r().ssl.key),cert:h().readFileSync(r().ssl.cert)},s=await p().createServer(n,Jr);return s.listen(e,"0.0.0.0",(()=>{console.log(`HTTPS ${t}`)})),s}{const n=await f().createServer(Jr);return n.listen(e,"0.0.0.0",(()=>{process.send&&process.send("ready"),console.log(t)})),n}}catch(e){throw e}}function Kr(e){const t=Pr[e],n={species:t.species,name:e,hasSNP:!!t.snp,hasIdeogram:t.genedb.hasIdeogram,fimo_motif:!!t.fimo_motif,blat:!!t.blat,geneset:t.geneset,defaultcoord:t.defaultcoord,isdefault:t.isdefault,majorchr:t.majorchr,majorchrorder:t.majorchrorder,minorchr:t.minorchr,tracks:t.tracks,hicenzymefragment:t.hicenzymefragment,datasets:{}};if(t.termdbs){n.termdbs={};for(const e in t.termdbs)n.termdbs[e]={label:t.termdbs[e].label}}for(const e in t.datasets){const s=t.datasets[e];s.isMds3?n.datasets[s.label]={isMds3:!0,noHandleOnClient:s.noHandleOnClient,label:s.label}:s.isMds?n.datasets[s.label]={isMds:!0,mdsIsUninitiated:!0,noHandleOnClient:s.noHandleOnClient,label:s.label}:n.datasets[s.label]={isofficial:!0,legacyDsIsUninitiated:!0,noHandleOnClient:s.noHandleOnClient,label:s.label}}if(t.hicdomain){n.hicdomain={groups:{}};for(const e in t.hicdomain.groups){const s=t.hicdomain.groups[e];n.hicdomain.groups[e]={name:s.name,reference:s.reference,sets:{}};for(const t in s.sets)n.hicdomain.groups[e].sets[t]={name:s.sets[t].name,longname:s.sets[t].longname}}}return n}function Xr(e){const t={noHandleOnClient:e.noHandleOnClient,sampleselectable:e.sampleselectable,label:e.label,dsinfo:e.dsinfo,stratify:e.stratify,cohort:e.cohort,vcfinfofilter:e.vcfinfofilter,info2table:e.info2table,info2singletable:e.info2singletable,url4variant:e.url4variant,itemlabelname:e.itemlabelname};if(e.snvindel_attributes){t.snvindel_attributes=[];for(const n of e.snvindel_attributes){const e={};for(const t in n)if("lst"==t){e.lst=[];for(const t of n.lst){const n={};for(const e in t)n[e]=t[e];e.lst.push(n)}}else e[t]=n[t];t.snvindel_attributes.push(e)}}e.snvindel_legend&&(t.snvindel_legend=e.snvindel_legend);const n={};let s=!1;for(const t of e.queries)t.vcf&&(s=!0,n[t.vcf.vcfid]=t.vcf);return s&&(t.id2vcf=n),t}function Yr(e){const t={isMds:!0,noHandleOnClient:e.noHandleOnClient,label:e.label,version:e.version,annotationsampleset2matrix:e.annotationsampleset2matrix,mutationAttribute:e.mutationAttribute,locusAttribute:e.locusAttribute,alleleAttribute:e.alleleAttribute,hide_genotypedownload:e.hide_genotypedownload,hide_phewas:e.hide_phewas,sample2bam:e.sample2bam};if(e.queries&&(t.queries={}),e.track&&(t.track=function(e){const t=e.track,n={name:t.name,info_fields:t.info_fields,sample_termfilter:t.sample_termfilter};return t.vcf&&(n.vcf={numerical_axis:t.vcf.numerical_axis,format:t.vcf.format,info:t.vcf.info,check_pecanpie:t.vcf.check_pecanpie},t.vcf.plot_mafcov&&(n.vcf.plot_mafcov={},e.cohort&&e.cohort.termdb&&(n.vcf.plot_mafcov.overlay_term=t.vcf.plot_mafcov.overlay_term||{})),t.vcf.termdb_bygenotype&&(n.vcf.termdb_bygenotype=!0),t.populations&&(n.populations=t.populations)),t.ld&&(n.ld={tracks:t.ld.tracks.map((e=>({name:e.name,shown:e.shown}))),overlay:t.ld.overlay}),n}(e)),e.singlesamplemutationjson&&(t.singlesamplemutationjson=1),e.gene2mutcount&&(t.gene2mutcount=!0,t.mutCountType=e.gene2mutcount.mutationTypes),e.assayAvailability&&(t.assayAvailability=1),e.cohort&&e.cohort.sampleAttribute){const n={};for(const t in e.cohort.sampleAttribute.attributes){const s=e.cohort.sampleAttribute.attributes[t];s.clientnoshow||(n[t]=s)}t.sampleAttribute={attributes:n}}if(e.cohort){if(e.cohort.termdb&&(t.termdb={selectCohort:e.cohort.termdb.selectCohort}),e.cohort.attributes&&e.cohort.attributes.defaulthidden&&(t.cohortHiddenAttr=e.cohort.attributes.defaulthidden),e.cohort.survivalplot){t.survivalplot={samplegroupattrlst:e.cohort.survivalplot.samplegroupattrlst,plots:[]};for(const n in e.cohort.survivalplot.plots){const s=e.cohort.survivalplot.plots[n];t.survivalplot.plots.push({key:n,name:s.name,timelabel:s.timelabel})}}if(e.cohort.mutation_signature){const n={};for(const t in e.cohort.mutation_signature.sets){const s=e.cohort.mutation_signature.sets[t];n[t]={name:s.name,signatures:s.signatures}}t.mutation_signature={sets:n}}}for(const n in e.queries){const s=e.queries[n],r={name:s.name,hideforthemoment:s.hideforthemoment};if(s.istrack){if(r.istrack=!0,r.type=s.type,r.isfull=s.isfull,null!=s.nochr&&(r.nochr=s.nochr),s.infoFilter&&(r.infoFilter=s.infoFilter),s.readcountCutoff&&(r.readcountCutoff=s.readcountCutoff),s.valueLabel&&(r.valueLabel=s.valueLabel),s.valueCutoff&&(r.valueCutoff=s.valueCutoff),s.bplengthUpperLimit&&(r.bplengthUpperLimit=s.bplengthUpperLimit),s.segmeanValueCutoff&&(r.segmeanValueCutoff=s.segmeanValueCutoff),s.lohLengthUpperLimit&&(r.lohLengthUpperLimit=s.lohLengthUpperLimit),s.type==$.tkt.mdssvcnv){if(s.groupsamplebyattr&&(r.groupsamplebyattr=s.groupsamplebyattr),r.multihidelabel_fusion=s.multihidelabel_fusion,r.multihidelabel_sv=s.multihidelabel_sv,r.multihidelabel_vcf=s.multihidelabel_vcf,r.showfullmode=s.showfullmode,r.legend_vorigin=s.legend_vorigin,r.no_loh=s.no_loh,s.expressionrank_querykey){const t=e.queries[s.expressionrank_querykey];if(r.checkexpressionrank={querykey:s.expressionrank_querykey,datatype:t.datatype},t.boxplotbysamplegroup&&t.boxplotbysamplegroup.additionals){const e=[];t.boxplotbysamplegroup.attributes&&e.push(t.boxplotbysamplegroup.attributes.map((e=>e.label)).join(", "));for(const n of t.boxplotbysamplegroup.additionals)e.push(n.label);r.checkexpressionrank.boxplotgroupers=e}}if(s.vcf_querykey){r.checkvcf={querykey:s.vcf_querykey,info:e.queries[s.vcf_querykey].info,format:{}};for(const t of e.queries[s.vcf_querykey].tracks)if(t.format)for(const e in t.format)r.checkvcf.format[e]=t.format[e]}}}else{if(!s.isgenenumeric)continue;r.isgenenumeric=!0,r.datatype=s.datatype,r.no_ase=s.no_ase}t.queries[n]=r}return t}async function Qr(e,t){if(!t)throw"invalid genome";if(!t.snp)throw"snp is not configured for this genome";const n=[];if(e.byCoord){if(t.genomicNameRegexp.test(e.chr))throw"invalid chr name";if(!Array.isArray(e.ranges))throw"ranges not an array";for(const s of e.ranges){if(!Number.isInteger(s.start)||!Number.isInteger(s.stop)||s.start<0||s.stop<s.start)throw"invalid start/stop";if(s.stop-s.start>=100)throw"range too big";const r=await F.z5(t.snp.bigbedfile,e.chr,s.start,s.stop);for(const t of r){const s=eo(t);if(e.alleleLst){let t=!1;for(const n of e.alleleLst)if(n&&!s.alleles.includes(n)){t=!0;break}if(t)continue}n.push(s)}}}else{if(!e.byName)throw"unknown query method";if(!Array.isArray(e.lst))throw".lst[] missing";for(const s of e.lst){if(t.genomicNameRegexp.test(s))continue;const e=await F.mr(t.snp.bigbedfile,s);for(const t of e){const e=eo(t);n.push(e)}}}return n}function eo(e){const t=e.split("\t"),n=t[4],s=t[6].split(",").filter(Boolean),r=n+"/"+s.join("/");return{chrom:t[0],chromStart:Number(t[1]),chromEnd:Number(t[2]),name:t[3],observed:r,alleles:[n,...s]}}function to(e,t,n){if(n.query.isoform&&Pr[n.query.genome].genomicNameRegexp.test(n.query.isoform))return;const[s,r]=t.makequery(n.query);if(!s)return;const o=e.newconn.prepare(s).all(r);let i;i=t.tidy?o.map((e=>t.tidy(e))):o;const a={};if(t.isgeneexpression){a.lst=i,a.isgeneexpression=!0,a.config=t.config;for(const t of e.queries)if(t.dsblocktracklst)for(const e of t.dsblocktracklst)e.type==$.tkt.junction&&(a.config.dsjunctiontk=e)}else a.lst=i;return a}function no(e,t){const n=[y().join(r().tpmasterdir,e.vcffile),(e.vcf.nochr?t.query.range.chr.replace("chr",""):t.query.range.chr)+":"+t.query.range.start+"-"+t.query.range.stop];return new Promise(((t,s)=>{const r=(0,x.spawn)(Gr,n),o=[],i=[];r.stdout.on("data",(e=>o.push(e))),r.stderr.on("data",(e=>i.push(e))),r.on("close",(n=>{""!=i.join("").trim()&&s("error querying vcf file");const r=o.join("").trim();t({lines:""==r?[]:r.split("\n"),vcfid:e.vcf.vcfid})}))}))}function so(e){if(!e.genome)return["no genome"];const t=Pr[e.genome];if(!t)return["invalid genome"];if(!t.datasets)return["genome is not equipped with datasets"];if(!e.dslabel)return["dslabel missing"];const n=t.datasets[e.dslabel];if(!n)return["invalid dslabel"];if(!n.queries)return["dataset is not equipped with queries"];if(!e.querykey)return["querykey missing"];const s=n.queries[e.querykey];return s?[null,t,n,s]:["invalid querykey"]}async function ro(e,t,n,s,o,i){const a=await async function(e,t,n,s){const o=e.checkvcf.tracks[0],i={file:o.file,url:o.url,indexURL:o.indexURL,dir:o.dir,nochr:o.nochr,samples:o.samples,info:e.checkvcf.info,format:o.format},a=await yo(i.file?y().join(r().tpmasterdir,i.file):i.url,(i.nochr?t.replace("chr",""):t)+":"+n+"-"+s,i.dir),l=[];for(const e of a||[]){const[t,n,s]=D.S(e,i);for(const e of n)$.basecolor[e.ref]&&$.basecolor[e.alt]&&e.sampledata&&l.push(e)}return l}(o,t,n,s),l=[];for(const e in o.checkrnabam.samples){const n=o.checkrnabam.samples[e];n.hetsnps=[];for(const t of a){const s=ho(t,e,o.checkrnabam);s&&s.dnacount.ishet&&n.hetsnps.push(s)}if(n.url?n.dir=await F.d1(n.url,n.indexURL||n.url+".bai"):n.file&&(n.file=y().join(r().tpmasterdir,n.file)),n.hetsnps.length>0){await ao(n,n.hetsnps,t,o.checkrnabam);for(const t of n.hetsnps)t.rnacount.nocoverage||t.rnacount.ref+t.rnacount.alt<o.checkrnabam.rna_mintotalreads||l.push(e+"."+t.pos+"."+t.ref+"."+t.alt+"\t\t\t\t\t\t\t\t"+t.rnacount.ref+"\t"+t.rnacount.alt)}}l.length>0&&await async function(e,t){const n=await function(e){const t=y().join(r().cachedir,Math.random().toString());return new Promise(((n,s)=>{h().writeFile(t,e.join("\n")+"\n",(e=>{e&&s("cannot write"),n(t)}))}))}(e),s=await po(n);await function(e,t){return new Promise(((n,s)=>{h().readFile(e,"utf8",((e,r)=>{if(e&&s("cannot read binom pvalue"),r){for(const e of r.trim().split("\n")){const n=e.split("\t"),s=n[0].split("."),r=t[s[0]];if(!r)continue;const o=r.hetsnps.find((e=>e.pos+"."+e.ref+"."+e.alt==s[1]+"."+s[2]+"."+s[3]));o&&(o.rnacount.pvalue=Number.parseFloat(n[10]))}n()}else n()}))}))}(s,t),h().unlink(n,(()=>{})),h().unlink(s,(()=>{}))}(l,o.checkrnabam.samples),i.checkrnabam=[];for(const n in o.checkrnabam.samples){const s=o.checkrnabam.samples[n],r=[];for(const[n,i]of e){const e={gene:n,chr:t,start:i.start,stop:i.stop},a=s.hetsnps.filter((e=>e.pos>=i.start&&e.pos<=i.stop)),l=a.filter((e=>!e.rnacount.nocoverage));if(l.length>0){const t=l.reduce(((e,t)=>e+Math.abs(t.rnacount.f-.5)),0);let n=null,s=0;for(const e of l)null!=e.rnacount.pvalue&&(null==n?n=e.rnacount.pvalue:n*=e.rnacount.pvalue,e.rnacount.pvalue<=o.checkrnabam.binompvaluecutoff&&s++);null!=n&&(e.ase={markers:a.filter((e=>e.dnacount.ishet)).length,ase_markers:s,mean_delta:t/l.length,geometricmean:Math.pow(n,1/l.length)})}let c;c=s.pairedend?await io(s,t,i):await oo(s,t,i),e.fpkm=1e9*c/(s.totalreads*i.exonlength),e.snps=a,r.push(e)}r.length&&i.checkrnabam.push({sample:n,genes:r})}}async function oo(e,t,n){const s=["view","-c","-M",e.url||e.file];for(const r of n.exonunion)s.push((e.nochr?t.replace("chr",""):t)+":"+(r[0]+1)+"-"+(r[1]+1));let r;return await F.UE({isbam:!0,args:s,dir:e.dir,callback:e=>r=e}),Number.parseInt(r)}function io(e,t,n){return new Promise(((s,r)=>{const o=["view","-M",e.url||e.file];for(const s of n.exonunion)o.push((e.nochr?t.replace("chr",""):t)+":"+(s[0]+1)+"-"+(s[1]+1));const i=(0,x.spawn)(Ur,o,{cwd:e.dir}),a=(0,x.spawn)("cut",["-f1"],{cwd:e.dir}),l=(0,x.spawn)("sort",["-u"],{cwd:e.dir}),c=(0,x.spawn)("wc",["-l"],{cwd:e.dir});i.stdout.pipe(a.stdin),a.stdout.pipe(l.stdin),l.stdout.pipe(c.stdin);const u=[],f=[];c.stdout.on("data",(e=>u.push(e))),c.stderr.on("data",(e=>f.push(e))),c.on("close",(()=>{s(Number.parseInt(u.join("")))}))}))}function ao(e,t,n,s){const r=[];for(const s of t)s.rnacount={nocoverage:1},r.push((e.nochr?n.replace("chr",""):n)+":"+(s.pos+1)+"-"+(s.pos+1));return new Promise(((n,o)=>{const i=(0,x.spawn)(Br,["mpileup","--no-reference","-a","INFO/AD","-d",999999,"-r",r.join(","),"-q",s.rnapileup_q,"-Q",s.rnapileup_Q,e.url||e.file],{cwd:e.dir});I().createInterface({input:i.stdout}).on("line",(e=>{if("#"==e[0])return;const n=mo(e);if(!n)return;const s=t.find((e=>e.pos==n.pos));if(s){const e=n.allele2count[s.ref]||0,t=n.allele2count[s.alt]||0;e+t>0&&(s.rnacount={ref:e,alt:t,f:t/(e+t)})}})),i.on("close",(()=>{n()}))}))}function lo(e,t,n,s,r,o){t.hideLOHwithCNVoverlap&&co(r);const i=[];if(o){const e=new Map;for(const[t,n]of r){const s=o.sample2group.get(t);e.has(s)||e.set(s,[]),e.get(s).push({samplename:t,items:n})}if(s)for(const t of s)if(t.dt!=$.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+t.dt);else for(const n of t.sampledata){const t=o.sample2group.get(n.sampleobj.name);e.has(t)||e.set(t,[]),e.get(t).find((e=>e.samplename==n.sampleobj.name))||e.get(t).push({samplename:n.sampleobj.name,items:[]})}for(const[t,n]of e)i.push({name:t,samples:n})}else if(e.cohort&&e.cohort.annotation&&t.groupsamplebyattr){const n=new Map,o=[];for(const[s,i]of r)uo(s,i,n,o,e,t);if(s)for(const r of s)if(r.dt!=$.dtsnvindel)console.log("unknown dt when grouping samples from vcf data: "+r.dt);else for(const s of r.sampledata)uo(s.sampleobj.name,[],n,o,e,t);for(const e of n.values())if(i.push(e),t.groupsamplebyattr.key2group){const n=t.groupsamplebyattr.key2group.get(e.name);n&&(e.sampletotalnum=n.samples.length)}o.length&&i.push({name:"Unannotated",samples:o});for(const t of i)for(const n of t.samples)e.cohort.annotation[n.samplename]&&(n.sampletype=e.cohort.annotation[n.samplename].sample_type)}else{const e=[];for(const[t,n]of r)e.push({samplename:t,items:n});if(s)for(const t of s)if(t.dt!=$.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+t.dt);else for(const n of t.sampledata){let t=!0;for(const s of e)if(s.samplename==n.sampleobj.name){t=!1;break}t&&e.push({samplename:n.sampleobj.name,items:[]})}e.length&&i.push({samples:e})}return i}function co(e){for(const[t,n]of e){const s=new Map,r=new Map,o=[];for(const e of n)e.dt!=$.dtloh?(e.dt==$.dtcnv&&(r.has(e.chr)||r.set(e.chr,[]),r.get(e.chr).push(e)),o.push(e)):(s.has(e.chr)||s.set(e.chr,[]),s.get(e.chr).push(e));if(0!=s.size){for(const[e,t]of s){const n=r.get(e);if(n)for(const e of t){let t=!0;for(const s of n)if(Math.max(e.start,s.start)<Math.min(e.stop,s.stop)){t=!1;break}t&&o.push(e)}else for(const e of t)o.push(e)}e.set(t,o)}}}function uo(e,t,n,s,r,o){const i=r.cohort.annotation[e];if(!i)return void s.push({samplename:e,items:t});const a=i[o.groupsamplebyattr.attrlst[0].k];if(null==a)return void s.push({samplename:e,items:t});const l=[];for(let e=1;e<o.groupsamplebyattr.attrlst.length;e++){const t=i[o.groupsamplebyattr.attrlst[e].k];if(null==t)break;l.push(t)}l.unshift(a);const c=l.join(o.groupsamplebyattr.attrnamespacer);if(!n.has(c)){const e=[];for(const t of o.groupsamplebyattr.attrlst){const n=i[t.k];if(null==n)break;const s={k:t.k,kvalue:n};t.full&&(s.full=t.full,s.fullvalue=i[t.full]),e.push(s)}const t=[];for(const e of o.groupsamplebyattr.attrlst){const n=i[e.k];if(null==n)break;const s=(e.full?i[e.full]:null)||n;t.push(s)}n.set(c,{name:c,samples:[],attributes:e})}let u=!0;for(const s of n.get(c).samples)if(s.samplename==e){for(const e of t)s.items.push(e);u=!1;break}u&&n.get(c).samples.push({samplename:e,items:t})}function fo(e){return Number.isFinite(e.dna_mintotalreads)?Number.isFinite(e.rna_mintotalreads)?Number.isFinite(e.hetsnp_minbaf)?Number.isFinite(e.hetsnp_maxbaf)?Number.isFinite(e.rnapileup_q)?Number.isFinite(e.rnapileup_Q)?void 0:"invalid value for rnapileup_Q":"invalid value for rnapileup_q":"invalid value for hetsnp_maxbaf":"invalid value for hetsnp_minbaf":"invalid value for rna_mintotalreads":"invalid value for dna_mintotalreads"}function po(e){const t=e+".pvalue";return new Promise(((n,s)=>{const o=(0,x.spawn)("Rscript",[y().join(r().binpath,"utils/binom.R"),e,t]);o.on("close",(()=>{n(t)})),o.on("error",(e=>{s(`cannot do binom test: ${e}`)})),o.stderr.on("data",(e=>{s(`cannot do binom test: ${e}`)}))}))}function mo(e){const t=e.split("\t");if(t.length<8)return;const n={pos:Number.parseInt(t[1])-1},s=[t[3],...t[4].split(",")],r={};for(const e of t[7].split(";")){const t=e.split("=");r[t[0]]=t[1]}if(r.DP&&(n.DP=Number.parseInt(r.DP)),r.AD){n.allele2count={};const e=r.AD.split(",");for(const[t,r]of s.entries())n.allele2count[r]=Number.parseInt(e[t])}return n}function ho(e,t,n){const s=e.sampledata.find((e=>e.sampleobj.name==t));if(s){if(s.AD){const t=s.AD[e.ref]||0,r=s.AD[e.alt]||0,o={chr:e.chr,pos:e.pos,ref:e.ref,alt:e.alt,dnacount:{ref:t,alt:r}};return o.dnacount.f=r+t==0?0:r/(r+t),t+r>=n.dna_mintotalreads&&o.dnacount.f>=n.hetsnp_minbaf&&o.dnacount.f<=n.hetsnp_maxbaf&&(o.dnacount.ishet=!0),o}return null}}async function go(e,t,n,s,o){const i=await yo(y().join(r().tpmasterdir,t.file),n+":"+s+"-"+o),a=new Map;if(i)for(const e of i){const t=e.split("\t"),n=JSON.parse(t[3]),s=Number.parseInt(t[1]),r=Number.parseInt(t[2]);if(a.has(n.name)){const e=a.get(n.name);e.start=Math.min(e.start,s),e.stop=Math.max(e.stop,r)}else a.set(n.name,{gene:n.name,start:s,stop:r,exonunion:[]});const o=a.get(n.name);if(n.exon)for(const e of n.exon){const t=o.exonunion.find((t=>Math.max(t[0],e[0])<Math.min(t[1],e[1])));t?(t[0]=Math.min(e[0],t[0]),t[1]=Math.max(e[1],t[1])):o.exonunion.push([e[0],e[1]])}}for(const[e,t]of a)t.exonlength=t.exonunion.reduce(((e,t)=>e+t[1]-t[0]),0);return a}async function yo(e,t,n){return new Promise(((s,r)=>{const o=(0,x.spawn)(Gr,[e,t],{cwd:n}),i=[],a=[];o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("close",(()=>{const e=a.join("");e&&r(e);const t=i.join("").trim();t||s(),s(t.split("\n"))}))}))}function bo(e,t){return new Promise(((n,s)=>{const r=(0,x.spawn)(Gr,["-H",e],{cwd:t}),o=[],i=[];r.stdout.on("data",(e=>o.push(e))),r.stderr.on("data",(e=>i.push(e))),r.on("close",(()=>{const e=i.join("");e&&s(e);const t=o.join("").trim();t||s("cannot list vcf meta lines"),n(t.split("\n"))}))}))}function vo(e,t){const n=t.findIndex((t=>t.value>=e));return-1==n||n==t.length-1?100:0==n?0:Math.ceil(100*n/t.length)}function wo(e,t,n){if(!e.key)return[".key missing"];if(!t.cohort)return["ds.cohort missing"];if(!t.cohort.annotation)return["ds.cohort.annotation missing"];return[null,Promise.resolve().then((()=>{const s=[];for(const r in t.cohort.annotation){if(n&&!n.has(r))continue;const o=t.cohort.annotation[r][e.key];null!=o&&s.push({sample:r,value:o})}return{id:e.id,items:s}}))]}function _o(e,t,n,s){if(!e.genename)return["genename missing"];const o=e.genename.toLowerCase();if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["gene feature too long (> 10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((t=>new Promise(((i,a)=>{const l=[],c=(0,x.spawn)(Gr,[n.file?y().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});I().createInterface({input:c.stdout}).on("line",(e=>{const t=e.split("\t"),n=JSON.parse(t[3]);n.gene&&n.gene.toLowerCase()==o&&n.sample&&(s&&!s.has(n.sample)||l.push(n))}));const u=[];c.stderr.on("data",(e=>u.push(e))),c.on("close",(t=>{const n=u.join("");!n||Dr(n)?i({id:e.id,items:l}):a(n)}))}))))]}function ko(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];if(null!=e.valuecutoff&&!Number.isFinite(e.valuecutoff))return["invalid value for valuecutoff"];if(null!=e.focalsizelimit&&!Number.isInteger(e.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,x.spawn)(Gr,[n.file?y().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});I().createInterface({input:l.stdout}).on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);r.dt==$.dtcnv&&(e.valuecutoff&&Math.abs(r.value)<e.valuecutoff||(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.focalsizelimit&&r.stop-r.start>=e.focalsizelimit||r.sample&&(s&&!s.has(r.sample)||a.push(r))))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||Dr(n)?o({id:e.id,items:a}):i(n)}))}))))]}function qo(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];if(null!=e.valuecutoff&&!Number.isFinite(e.valuecutoff))return["invalid value for valuecutoff"];if(null!=e.focalsizelimit&&!Number.isInteger(e.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,x.spawn)(Gr,[n.file?y().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});I().createInterface({input:l.stdout}).on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);r.dt==$.dtloh&&(e.valuecutoff&&r.segmean<e.valuecutoff||(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.focalsizelimit&&r.stop-r.start>=e.focalsizelimit||r.sample&&(s&&!s.has(r.sample)||a.push(r))))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||Dr(n)?o({id:e.id,items:a}):i(n)}))}))))]}function xo(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,x.spawn)(Gr,[n.file?y().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});I().createInterface({input:l.stdout}).on("line",(e=>{const t=e.split("\t"),n=JSON.parse(t[3]);n.dt==$.dtitd&&(n.chr=t[0],n.start=Number.parseInt(t[1]),n.stop=Number.parseInt(t[2]),n.sample&&(s&&!s.has(n.sample)||a.push(n)))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||Dr(n)?o({id:e.id,items:a}):i(n)}))}))))]}function No(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,x.spawn)(Gr,[n.file?y().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});I().createInterface({input:l.stdout}).on("line",(e=>{const t=e.split("\t"),n=JSON.parse(t[3]);n.dt!=$.dtsv&&n.dt!=$.dtfusionrna||n.sample&&(s&&!s.has(n.sample)||(n._chr=t[0],n._pos=Number.parseInt(t[1]),n.chrA?(n.chrB=n._chr,n.posB=n._pos):(n.chrA=n._chr,n.posA=n._pos),a.push(n)))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||Dr(n)?o({id:e.id,items:a}):i(n)}))}))))]}function So(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,x.spawn)(Gr,[n.file?y().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});I().createInterface({input:l.stdout}).on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);if(r.sample&&(!s||s.has(r.sample))){if(r.dt==$.dtsv||r.dt==$.dtfusionrna){if(r.dt==$.dtsv&&e.sv&&e.sv.hidden)return;if(r.dt==$.dtfusionrna&&e.fusion&&e.fusion.hidden)return;r._chr=n[0],r._pos=Number.parseInt(n[1]),r.chrA?(r.chrB=r._chr,r.posB=r._pos):(r.chrA=r._chr,r.posA=r._pos)}else if(r.dt==$.dtcnv){if(e.cnv&&e.cnv.hidden)return;if(e.cnv&&e.cnv.valuecutoff&&Math.abs(r.value)<e.cnv.valuecutoff)return;if(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.cnv&&e.cnv.focalsizelimit&&r.stop-r.start>=e.cnv.focalsizelimit)return}else if(r.dt==$.dtloh){if(e.loh&&e.loh.hidden)return;if(e.loh&&e.loh.valuecutoff&&r.segmean<e.loh.valuecutoff)return;if(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.loh&&e.loh.focalsizelimit&&r.stop-r.start>=e.loh.focalsizelimit)return}else{if(r.dt!=$.dtitd)return void console.error("unknown datatype",r.dt);if(e.itd&&e.itd.hidden)return;r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2])}a.push(r)}}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const s=c.join("");if(s&&!Dr(s))return void i(s);const r=new Map;for(const e of a)r.has(e.sample)||r.set(e.sample,[]),r.get(e.sample).push(e);n.hideLOHwithCNVoverlap&&co(r);const l=[];for(const[e,t]of r)for(const e of t)l.push(e);o({id:e.id,items:l})}))}))))]}function Ao(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];const r=[];for(const o of n)if(o.type==$.tkt.mdsvcf){const[n,i]=Co(e,t,o,s);if(n)return[n];r.push(i)}else{if(o.type!=$.tkt.mdssvcnv)return["unsupported track type: "+o.type];{const[t,n]=So(e,0,o,s);if(t)return[t];r.push(n)}}return[null,Promise.all(r).then((e=>{const t=[];for(const n of e)for(const e of n.items)t.push(e);return{id:e[0].id,items:t}}))]}function Co(e,t,n,s){if(!n.tracks)return"tracks[] missing from dsquery";if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>3e6)return["look range too big (>3Mb)"];const o=[];for(const t of n.tracks){const i=Promise.resolve().then((()=>{if(!t.file)return F.d1(t.url,t.indexURL)})).then((o=>new Promise(((i,a)=>{const l=[],c=(0,x.spawn)(Gr,[t.file?y().join(r().tpmasterdir,t.file):t.url,(t.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+(e.stop+1)],{cwd:o});I().createInterface({input:c.stdout}).on("line",(r=>{if(n.iscustom)l.push(r);else if(t.type==$.mdsvcftype.vcf){const[o,i,a]=D.S(r,{nochr:t.nochr,samples:t.samples,info:n.info,format:t.format});for(const t of i)if(t.sampledata&&($.vcfcopymclass(t,{}),!(e.snvindel&&e.snvindel.excludeclasses&&e.snvindel.excludeclasses[t.class]))){if(s){const e=[];for(const n of t.sampledata)s.has(n.sampleobj.name)&&e.push(n);if(0==e.length)continue;t.sampledata=e}for(const e of t.sampledata)delete e.allele2readcount;delete t._m,delete t.vcf_ID,delete t.name,t.dt=$.dtsnvindel,l.push(t)}}else console.error("type not one of mdsvcftype: "+t.type)}));const u=[];c.stderr.on("data",(e=>u.push(e))),c.on("close",(e=>{const t=u.join("");!t||Dr(t)?i(l):a(t)}))}))));o.push(i)}return[null,Promise.all(o).then((t=>{const n=[];for(const e of t)for(const t of e)n.push(t);return{id:e.id,items:n}}))]}function jo(e){if(!e.endsWith(".gz"))return["no .gz suffix (file should be compressed by bgzip)"];const t=y().join(r().tpmasterdir,e);return h().existsSync(t)?h().existsSync(t+".tbi")||h().existsSync(t+".csi")?[null,t]:[".tbi/.csi index missing"]:[".gz file not found"]}Jr.use(q()()),Jr.use(((e,t,n)=>{"POST"==e.method.toUpperCase()&&(e.headers["content-type"]="application/json");try{e.query.encoding;!function(e){const t=e.encoding;for(const[n,s]of Object.entries(e))("json"==t||"null"==s||"true"==s||"false"==s||Fr(s)||s.startsWith('"')&&s.endsWith('"')||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))&&(e[n]=JSON.parse(s))}(e.query)}catch(e){return void t.send({error:e})}n()})),Jr.use(Er()()),Jr.use(j().json({limit:"5mb"})),Jr.use(j().text({limit:"5mb"})),Jr.use(j().urlencoded({extended:!0})),Jr.use(((e,t,n)=>{"POST"==e.method.toUpperCase()&&e.body&&"application/json"!=e.headers["content-type"]?t.send({error:"invalid HTTP request.header['content-type'], must be 'application/json'"}):("application/json"==e.headers["content-type"]&&(e.query||(e.query={}),Object.assign(e.query,e.body)),Vr(e),e.query.__protected__={},e.cookies?.sessionid&&(e.query.__protected__.sessionid=e.cookies.sessionid),Object.freeze(e.query.__protected__),Wr(t),t.header("Access-Control-Allow-Origin",e.get("origin")||e.get("referrer")||e.protocol+"://"+e.get("host").split(":")[0]||"*"),t.header("Access-Control-Allow-Credentials",!0),"GET"!=e.method||e.path.includes(".")&&!e.path.endsWith("proteinpaint.js")||t.header("Cache-control",`immutable,max-age=${r().responseMaxAge||1}`),n())})),Jr.catch=Mr,Jr.use((function(e,t,n){try{const t=e.query;for(const e in t)e in Or&&(t[e]=Or[e](t[e]));n()}catch(n){Mr(e,t,n.message||n)}})),Jr.use(((e,t,n,s)=>{Vr(t),e&&(e&&"entity.parse.failed"==e.type?n.send({error:"invalid request body, must be a valid JSON-encoded object"}):n.send({error:e}))})),r().jwt&&(console.log("JWT is activated"),Jr.use(((e,t,n)=>{let s={};e.body&&"POST"==e.method&&(s=e.body);const o=s.jwt?s.jwt:e.headers&&e.headers.authorization&&e.headers.authorization.startsWith("Bearer ")?e.headers.authorization.split(" ")[1]:null;if(!o)return t.send({error:"json web token missing"});R().verify(o,r().jwt.secret,((e,s)=>e?t.send({error:"Invalid token"}):s[r().jwt.permissioncheck]?void n():t.send({error:"Not authorized"})))}))),function(){if(!r().routeSetters)return;for(const e of r().routeSetters)if(e.endsWith(".js")){require(e)(Jr,Hr)}}(),mr.i.maySetAuthRoutes(Jr,Hr,r()),Jr.get(Hr+"/cardsjson",(async function(e,t){try{if(e.query.datafile&&e.query.tabixCoord)return new Promise(((n,s)=>{const o=(0,x.spawn)(Gr,[y().join(r().tpmasterdir,e.query.datafile),e.query.tabixCoord]),i=[],a=[];o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("close",(e=>{""!=a.join("").trim()&&s("error querying bedj file");const r=i.join("").trim();n(t.send({file:r.split("\n")}))}))})).catch((e=>{e.stack&&console.error(e.stack)}));throw"invalid cards request"}catch(e){t.send({error:e.message||e})}})),Jr.post(Hr+"/mdsjsonform",(async function(e,t){if(!Lr.mdsjsonform)return t.send({error:"This feature is not enabled on this server."});if(e.query.deposit){const n=Math.random().toString(),s=await function(){const e=y().join(r().cachedir,"mdsjsonform");return new Promise(((t,n)=>{h().stat(e,((s,r)=>{if(s){if("ENOENT"==s.code)return void h().mkdir(e,(s=>{s&&n("error creating dir"),t(e)}));n("error checking directory")}else r.isDirectory()?t(e):n('"mdsjsonform" exists but not directory')}))}))}(),o=y().join(s,n);return await F.Sf(o,JSON.stringify(e.query.deposit)),void t.send({id:n})}if(e.query.draw){const n=y().join(r().cachedir,"mdsjsonform",e.query.draw),s=await F.b5(n);try{const e=JSON.parse(s);t.send({json:e})}catch(e){t.send({error:"Invalid JSON"})}return}t.send({})})),Jr.get(Hr+"/genomes",(async function(e,t){try{await h().promises.stat(r().tpmasterdir)}catch(e){let n="Error with TP directory ("+e.code+")";const s=r().maintenance||{};if("start"in s&&"stop"in s&&s.tpMessage){const e=+new Date(s.start),t=+new Date(s.stop),r=+new Date;e<=r&&r<=t&&(n=s.tpMessage)}return void t.send({error:n})}const n={};if(e.query&&e.query.genome)n[e.query.genome]=Kr(e.query.genome);else for(const e in Pr)n[e]=Kr(e);let s=!1;for(const e in Pr)Pr[e].blat&&(s=!0);t.send({genomes:n,debugmode:r().debugmode,headermessage:r().headermessage,base_zindex:r().base_zindex,codedate:Rr.A.codedate,launchdate:Rr.A.launchdate,hasblat:s,features:Lr,dsAuth:mr.i.getDsAuth(e),commonOverrides:r().commonOverrides,targetPortal:r().targetPortal,cardsPath:r().cards?.path})})),Jr.get(Hr+"/getDataset",(function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"unknown genome";if(!n.datasets)throw"genomeobj.datasets{} missing";let s;for(const t in n.datasets)if(t.toLowerCase()==e.query.dsname.toLowerCase()){s=n.datasets[t];break}if(!s)throw"invalid dsname";return s.isMds3?t.send({ds:Os(s)}):s.isMds?t.send({ds:Yr(s)}):t.send({ds:Xr(s)})}catch(e){t.send({error:e.message||e})}})),Jr.all(Hr+"/ntseq",(async function(e,t){try{if(!e.query.coord)throw"coord missing";const n=Pr[e.query.genome];if(!n)throw"invalid genome";if(!n.genomefile)throw"no sequence file available";const s=await F.Kf(n,e.query.coord);t.send({seq:s.split("\n").slice(1).join("")})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.post(Hr+"/pdomain",(function(e,t){try{const n=e.query.genome;if(!n)throw"no genome";const s=Pr[n];if(!s)throw"invalid genome "+n;if(!s.proteindomain)return t.send({lst:[]});if(!Array.isArray(e.query.isoforms))throw"isoforms[] missing";const r=[];for(const t of e.query.isoforms){if(s.genomicNameRegexp.test(t))continue;const e=s.proteindomain.getbyisoform.all(t);r.push({name:t,pdomains:e.map((e=>{const n=JSON.parse(e.data);return n.refseq=t,n}))})}t.send({lst:r})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.post(Hr+"/tkbedj",function(e){return async(t,n)=>{try{n.send(await async function(e,t){const[n,s,r]=F.ZX(e);if(n)throw n;let o,i,a,l,c;if(e.query.fileIsBigbed=await F.aS(s),e.query.getdata)e.query.getBED;else{if(o=Number(e.query.stackheight),i=Number(e.query.stackspace),a=Number(e.query.regionspace),l=Number(e.query.width),Number.isNaN(o))throw"stackheight is not integer";if(c=Math.max(10,o-2),Number.isNaN(i))throw"stackspace is not integer";if(Number.isNaN(a))throw"regionspace is not integer";if(Number.isNaN(l))throw"width is not a number"}if(e.query.usevalue){if(!e.query.usevalue.key)throw".key missing from .usevalue";if(e.query.usevalue.dropBelowCutoff&&(e.query.usevalue.dropBelowCutoff=Number(e.query.usevalue.dropBelowCutoff),Number.isNaN(e.query.usevalue.dropBelowCutoff)))throw".usevalue.dropBelowCutoff is not number"}if(e.query.bplengthUpperLimit&&(e.query.bplengthUpperLimit=Number(e.query.bplengthUpperLimit),Number.isNaN(e.query.bplengthUpperLimit)))throw"bplengthUpperLimit not number";if(!e.query.rglst)throw"no rglst[]";if(!Array.isArray(e.query.rglst))throw"rglst is not an array";if(0==e.query.rglst.length)throw"empty rglst";for(const t of e.query.rglst)t.reverse?t.scale=e=>Math.ceil(t.width*(t.stop-e)/(t.stop-t.start)):t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start));const u=e.query.color||"#3D7A4B",f=e.query.gmregion||null,d=e.query.isoform,p=e.query.onerow,m=e.query.categories||null,h=e.query.__isgene;let g;!e.query.fileIsBigbed&&r&&(g=await F.d1(s,e.query.indexURL));const y=await async function(e,t,n,s,r){let o;if(s){const i=[];if(e.fileIsBigbed){const n=await F.z5(t,s.chr,s.start,s.stop);for(const t of n){const n=t.split("\t"),s=Bn(n);s.chr=n[0],s.start=Number(n[1]),s.stop=Number(n[2]),s.rglst=[];for(let t=0;t<e.rglst.length;t++){const n=e.rglst[t];Math.max(s.start,n.start)<Math.min(s.stop,n.stop)&&s.rglst.push({idx:t})}0!=s.rglst.length&&i.push(s)}}else await F.UE({args:[t,s.chr+":"+s.start+"-"+s.stop],dir:n,callback:t=>{const n=t.split("\t");let s={};if(e.getBED)s.rest=n.slice(3);else if(n[3])try{s=JSON.parse(n[3])}catch(e){return void(o=t)}if(!s.isoformonly||s.isoformonly==r){s.chr=n[0],s.start=Number(n[1]),s.stop=Number(n[2]),s.rglst=[];for(let t=0;t<e.rglst.length;t++){const n=e.rglst[t];Math.max(s.start,n.start)<Math.min(s.stop,n.stop)&&s.rglst.push({idx:t})}0!=s.rglst.length&&i.push(s)}}});if(o)throw"Line with invalid JSON: "+o;return[i]}const i=[];for(const[s,r]of e.rglst.entries()){const a=[];if(e.fileIsBigbed){const e=await F.z5(t,r.chr,r.start,r.stop);for(const t of e){const e=t.split("\t"),n=Bn(e);n.chr=e[0],n.start=Number(e[1]),n.stop=Number(e[2]),n.rglst=[{idx:s}],a.push(n)}}else await F.UE({args:[t,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:t=>{const n=t.split("\t");let r={};if(e.getBED)r.rest=n.slice(3);else if(n[3])try{r=JSON.parse(n[3])}catch(e){return void(o=t)}r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[{idx:s}],a.push(r)}});i.push(a)}if(o)throw"Line with invalid JSON: "+o;return i}(e.query,s,g,f,d);let b;e.query.filterByName&&(b=new Set(e.query.filterByName.split(/[\s\n]/).map((e=>e.trim()))));const v=[];for(const t of y)for(const n of t){if(e.query.usevalue){const t=n[e.query.usevalue.key];if(!Number.isFinite(t))continue;if(e.query.usevalue.dropBelowCutoff&&t<e.query.usevalue.dropBelowCutoff)continue}if(!(e.query.bplengthUpperLimit&&n.stop-n.start>e.query.bplengthUpperLimit)){if(b)if(n.isoform){if(!b.has(n.isoform))continue}else{if(!n.name)continue;if(!b.has(n.name))continue}v.push(n)}}if(e.query.getdata)return{items:v};if(0==v.length){const t=(0,S.createCanvas)(l*e.query.devicePixelRatio,o*e.query.devicePixelRatio),n=t.getContext("2d");return e.query.devicePixelRatio>1&&n.scale(e.query.devicePixelRatio,e.query.devicePixelRatio),n.font=o+"px Arial",n.fillStyle="#aaa",n.textAlign="center",n.textBaseline="middle",n.fillText("No data in view range",l/2,o/2),{src:t.toDataURL(),height:o}}const w=Math.ceil(o/4)-1;if(p||v.length>=Wn){const t=v.length<200,n=(0,S.createCanvas)(l*e.query.devicePixelRatio,o*e.query.devicePixelRatio),s=n.getContext("2d");e.query.devicePixelRatio>1&&s.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);const r=v.length<=200?[]:null;for(const n of v){const i=m&&n.category&&m[n.category]?m[n.category].color:n.color||u;s.fillStyle=i;for(const i of n.rglst){let l=0;for(let t=0;t<i.idx;t++)l+=e.query.rglst[t].width+a;const c=e.query.rglst[i.idx],u=[];n.utr5&&u.push(...n.utr5),n.utr3&&u.push(...n.utr3),!n.exon||n.coding&&0!=n.coding.length||u.push(...n.exon);for(const e of u){const t=Math.max(c.start,e[0]),i=Math.min(c.stop,e[1]),a=l+c.scale(c.reverse?i:t),u=l+c.scale(c.reverse?t:i);s.fillRect(a,w,Math.max(1,u-a),o-2*w),es(r,a,u,1,n)}const f=[];n.exon?n.coding&&n.coding.length>0&&f.push(...n.coding):f.push([n.start,n.stop]);for(const e of f){const i=Math.max(c.start,e[0]),a=Math.min(c.stop,e[1]),u=l+c.scale(c.reverse?a:i),f=l+c.scale(c.reverse?i:a);s.fillRect(u,0,Math.max(1,f-u),o),es(r,u,f,1,n),n.strand&&t&&(s.strokeStyle="white",ts(s,n.strand,u,w,f-u,o-2*w))}}}return{src:n.toDataURL(),height:o,mapisoform:r}}if(e.query.hideItemNames)for(const e of v)delete e.name;let _=null;if(h&&v.length<Vn){_=[];for(const e of v){const t={};for(const n in e)"canvas"!=n&&"rglst"!=n&&(t[n]=e[n]);_.push(t)}}const k=e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0),q=e.query.translatecoding&&k<3*l;let x;if(q){if(!e.query.genome)throw"genome missing for translating genes";if(x=t[e.query.genome],!x)throw"invalid genome"}const N=[],A=(0,S.createCanvas)(10,10);let C=A.getContext("2d");e.query.devicePixelRatio>1&&C.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);C.font="bold "+c+"px Arial";const j=v.length<Hn,T=v.length<Hn?[]:null;let M=!1;f&&(M=f.reverse);for(const t of e.query.rglst)t.reverse&&(M=!0);v.sort(((e,t)=>M?e.stop==t.stop?e.start-t.start:t.stop-e.stop:e.start==t.start?t.stop-e.stop:e.start-t.start));const O=v.some((e=>e.exon)),I=[0];let E=1,R=null;for(const t of v){let n=null,s=null;for(const r of t.rglst){let o=0;for(let t=0;t<r.idx;t++)o+=e.query.rglst[t].width+a;const i=e.query.rglst[r.idx],l=Math.max(t.start,i.start),c=Math.min(t.stop,i.stop);if(l<c){const e=o+i.scale(i.reverse?c:l),t=o+i.scale(i.reverse?l:c);null==n?(n=e,s=t):(n=Math.min(n,e),s=Math.max(s,t))}}if(null==n)continue;t.canvas={start:n,stop:s,stranded:null!=t.strand},t.coding&&q&&(t.willtranslate=!0,N.push(t));let r=n,o=s;if(j){const e=t.name;if(e){t.canvas.namestr=e;const n=C.measureText(e).width;t.canvas.namewidth=n,O?t.canvas.start>=n+zn?(t.canvas.namestart=t.canvas.start-zn,r=t.canvas.namestart-n,t.canvas.textalign="right"):t.canvas.stop+n+zn<=l?(t.canvas.namestart=t.canvas.stop+zn,o=t.canvas.namestart+n,t.canvas.textalign="left"):n>t.canvas.stop-t.canvas.start?t.canvas.start>l-t.canvas.stop?(t.canvas.namestart=t.canvas.start-zn,r=t.canvas.namestart-n,t.canvas.textalign="right"):(t.canvas.namestart=t.canvas.stop+zn,o=t.canvas.namestart+n,t.canvas.textalign="left"):(t.canvas.namehover=!0,t.canvas.textalign="left"):Math.min(l,t.canvas.stop)-Math.max(0,t.canvas.start)>=n+2*Jn?t.canvas.namein=!0:t.canvas.start>=n+zn?(t.canvas.namestart=t.canvas.start-zn,r=t.canvas.namestart-n,t.canvas.textalign="right"):t.canvas.stop+n+zn<=l?(t.canvas.namestart=t.canvas.stop+zn,o=t.canvas.namestart+n,t.canvas.textalign="left"):t.canvas.namein=!0}}t.canvas.stop-t.canvas.start>.3*l&&(R=[]);for(let e=1;e<=E;e++)if(null==I[e]||I[e]<r){t.canvas.stack=e,I[e]=o;break}null==t.canvas.stack&&(E++,I[E]=o,t.canvas.stack=E),es(T,r,o,t.canvas.stack,t)}A.width=l*e.query.devicePixelRatio;const D=(o+i)*E-i;A.height=D*e.query.devicePixelRatio,C=A.getContext("2d"),e.query.devicePixelRatio>1&&C.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);C.font="bold "+c+"px Arial",C.textBaseline="middle",C.lineWidth=1;for(const t of v){const n=t.canvas;if(!n)continue;const s=m&&t.category&&m[t.category]?m[t.category].color:t.color||u,r=(o+i)*(n.stack-1);C.fillStyle=s,(t.exon||t.rglst.length>1)&&(C.strokeStyle=s,C.beginPath(),C.moveTo(n.start,Math.floor(r+o/2)+.5),C.lineTo(n.stop,Math.floor(r+o/2)+.5),C.stroke());for(const i of t.rglst){let l=0;for(let t=0;t<i.idx;t++)l+=e.query.rglst[t].width+a;const c=e.query.rglst[i.idx],u=[];t.utr3&&u.push(...t.utr3),t.utr5&&u.push(...t.utr5),!t.exon||t.coding&&0!=t.coding.length||u.push(...t.exon);for(const e of u){const n=Math.max(e[0],c.start),i=Math.min(e[1],c.stop);if(n<i){if(t.exon2color)for(const e of t.exon2color)if(n>=e.start&&i<=e.stop){C.fillStyle=e.color;break}const e=l+c.scale(c.reverse?i:n),a=l+c.scale(c.reverse?n:i);C.fillRect(e,r+w,Math.max(1,a-e),o-2*w),t.exon2color&&(C.fillStyle=s)}}const f=[];t.exon?t.coding&&t.coding.length>0&&f.push(...t.coding):f.push([t.start,t.stop]);let d=t.strand;n.stranded&&c.reverse&&(d="+"==t.strand?"-":"+");for(const e of f){const i=Math.max(e[0],c.start),a=Math.min(e[1],c.stop);if(i<a){if(t.exon2color)for(const e of t.exon2color)if(i>=e.start&&a<=e.stop){C.fillStyle=e.color;break}const e=l+c.scale(c.reverse?a:i),u=l+c.scale(c.reverse?i:a);if(C.fillRect(e,r,Math.max(1,u-e),o),t.exon2color&&(C.fillStyle=s),n.stranded&&!t.willtranslate)if(C.strokeStyle="white",n.namein){const t=(u-e-n.namewidth)/2;ts(C,d,e,r+w,t,o-2*w),ts(C,d,e+t+n.namewidth,r+w,t,o-2*w)}else ts(C,d,e,r+w,u-e,o-2*w)}}if(n.stranded&&t.intron){C.strokeStyle=s;for(const e of t.intron){const t=Math.max(e[0],c.start),n=Math.min(e[1],c.stop);if(t<n){const e=l+c.scale(c.reverse?n:t);ts(C,d,e,r+w,l+c.scale(c.reverse?t:n)-e,o-2*w)}}}if(R&&t.exon){for(let e=0;e<t.exon.length;e++){const s=t.exon[e];if(s[1]<=c.start||s[0]>=c.stop)continue;const r=Math.max(s[0],c.start),o=Math.min(s[1],c.stop);if(r<o){const i=l+c.scale(c.reverse?o:r),a=l+c.scale(c.reverse?r:o);R.push({chr:t.chr,start:Math.min(s[0],s[1]),stop:Math.max(s[0],s[1]),x1:i,x2:a,y:n.stack,name:"Exon "+(e+1)+"/"+t.exon.length})}}for(let e=1;e<t.exon.length;e++){const s=t.exon["+"==t.strand?e-1:e][1],r=t.exon["+"==t.strand?e:e-1][0];if(r<=c.start||s>=c.stop)continue;const o=Math.max(s,c.start),i=Math.min(r,c.stop);if(o<i){const a=l+c.scale(c.reverse?i:o),u=l+c.scale(c.reverse?o:i);if(u<0)continue;R.push({chr:t.chr,start:s,stop:r,x1:a,x2:u,y:n.stack,name:"Intron "+e+"/"+(t.exon.length-1)})}}}}if(null!=n.namestart)C.textAlign=n.textalign,C.fillStyle=s,C.fillText(n.namestr,n.namestart,r+o/2);else if(n.namehover&&!e.query.noNameHover){const e=Math.max(10,n.start+10);C.fillStyle="white",C.fillRect(e,r,n.namewidth+10,o),C.strokeStyle=s,C.strokeRect(e+1.5,r+.5,n.namewidth+10-3,o-2),C.fillStyle=s,C.textAlign="center",C.fillText(n.namestr,e+n.namewidth/2+5,r+o/2)}else n.namein&&(C.textAlign="center",C.fillStyle="white",C.fillText(n.namestr,(Math.max(0,n.start)+Math.min(l,n.stop))/2,r+o/2))}const L={height:D,mapisoform:T,mapexon:R,returngmdata:_};if(0==N.length)return L.src=A.toDataURL(),L;const P=[];C.textAlign="center",C.textBaseline="middle";for(const[t,n]of N.entries()){const t=m&&n.category&&m[n.category]?m[n.category].color:n.color||u,s=n.canvas,r=(o+i)*(s.stack-1);n.genomicseq=(await F.Kf(x,n.chr+":"+(n.start+1)+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase();const l=(0,$.nt2aa)(n);for(const t of n.rglst){const i=e.query.rglst[t.idx];let c=0;for(let n=0;n<t.idx;n++)c+=e.query.rglst[n].width+a;const u=i.width/(i.stop-i.start),f=Math.min(o,3*u),d=f<8?null:f;let p=!1;s.stranded&&"-"==n.strand&&(p=!0);let m=0;d&&(C.font=d+"px Arial");for(const[e,t]of n.coding.entries()){let[s,a]=t;if(p){if(s>=i.stop){m+=a-s,0==e&&n.startCodonFrame&&(m-=3-n.startCodonFrame);continue}if(a<=i.start)break}else{if(a<=i.start){m+=a-s,0==e&&n.startCodonFrame&&(m-=3-n.startCodonFrame);continue}if(s>=i.stop)break}if(0==e&&n.startCodonFrame){p?a-=3-n.startCodonFrame:s+=3-n.startCodonFrame;let e=Math.max(t[0],i.start),l=Math.min(t[1],i.stop);if(p?e=Math.max(a,i.start):l=Math.min(s,i.stop),e<l){C.fillStyle=Qn;const t=c+i.scale(i.reverse?l:e),n=c+i.scale(i.reverse?e:l);C.fillRect(t,r,Math.max(1,n-t),o)}}const f=Math.max(i.start,s),h=Math.min(i.stop,a);m+=p?a-h:f-s;let g=0;for(let e=0;e<h-f;e++){let t;if(m++,g++,m%3==0)t=m/3-1;else{if(e<h-f-1)continue;t=Math.floor(m/3)}let s=l[t],a=Math.ceil(m/3)%2==0?Zn:null;s?"M"==s?a=Xn:"*"==s&&(a=Yn):(s=4,a=Kn);let y,b=u*g;if(p){const t=h-1-e;y=c+i.scale(t)}else{const t=f+e+1-g;y=c+i.scale(t)}i.reverse&&(y-=b),g=0,y>=c&&y<=c+i.width&&(a&&(C.fillStyle=a,C.fillRect(y,r,b,o)),d&&(C.fillStyle="white",C.fillText(s,y+b/2,r+o/2)),P.push({x1:y,x2:y+b,y:n.canvas.stack,name:s+(t+1)+' <span style="font-size:.7em;color:#858585">AA residue</span>'}))}}}if(s.namehover&&!e.query.noNameHover){C.font="bold "+c+"px Arial";const e=Math.max(10,s.start+10);C.fillStyle="white",C.fillRect(e,r,s.namewidth+10,o),C.strokeStyle=t,C.strokeRect(e+1.5,r+.5,s.namewidth+10-3,o-2),C.fillStyle=t,C.fillText(s.namestr,e+s.namewidth/2+5,r+o/2)}}return L.src=A.toDataURL(),L.mapaa=P,L}(t,e))}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Pr)),Jr.post(Hr+"/tkbedgraphdot",function(e){return async(t,n)=>{try{const s=t.query,o=e[s.genome];if(!o)throw"unknown genome";let i=null;if(s.file)s.file=y().join(r().tpmasterdir,s.file);else{if(!s.url)throw"file or url missing";i=await F.d1(s.url,s.indexURL)}const a=await F.Jy(s.file||s.url,i,o),l=await Ce(s,i,a);n.send(l)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Pr)),Jr.all(Hr+"/tkbam",function(e){return async(t,n)=>{try{if(t.query.gdcFileUUID){if("string"!=typeof t.query.gdcFileUUID)throw"gdcFileUUID not string";!function(e){if(!e.query.gdcFilePosition)throw"gdcFileUUID is present but gdcFilePosition is missing";if("string"!=typeof e.query.gdcFilePosition)throw"gdcFilePosition is not string";if("unmapped"==e.query.gdcFilePosition)return;const t=e.query.gdcFilePosition.split(/[.:-]/);if(3!=t.length)throw"gdcFilePosition not 3 fields";const n=Number(t[1]),s=Number(t[2]);if(!Number.isInteger(n)||!Number.isInteger(s)||n>s)throw"gdcFilePosition invalid start/stop";if(e.query.stream2download)return;if(s-n>en)throw`Slice range exceeds ${Ge(en)} limit. Please choose a smaller range.`}(t),t.query.__genomes=e;const s=t.get("X-Auth-Token");if(s&&(t.query.token=s),await Qe(t.query.gdcFileUUID,tn(e),t.query),t.query.stream2download)return void await async function(e,t){const{host:n,headers:s}=tn(e.query.__genomes).getHostHeaders(e.query);s.compression=!1;const r=y().join(n.rest,"/slicing/view/",e.query.gdcFileUUID+"?region="+e.query.gdcFilePosition);t.statusCode=200;try{await tt(v().stream(r,{method:"get",headers:s}),t)}catch(e){if("ERR_STREAM_PREMATURE_CLOSE"==e.code)return;e.stack&&console.log(e.stack),t.send({error:e.message||e})}}(t,n);t.query.file=Nn(t)}if(t.query.downloadgdc)return void n.send(await Sn(t));if(t.query.clientdownloadgdcslice)return void await async function(e,t){if(!e.query.gdcFileUUID||!e.query.gdcFilePosition||!e.query.file)throw"clientdownloadgdcslice: unauthorized access";const n=y().join(r().cachedir_bam,e.query.file),s=await h().promises.readFile(n);t.writeHead(200,{"Content-Type":"application/octet-stream","Content-Disposition":"attachment; filename=gdc.bam","Content-Length":s.length}),t.end(Buffer.from(s,"binary"))}(t,n);if(!t.query.genome)throw".genome missing";const s=e[t.query.genome];if(!s)throw"invalid genome";if(t.query.getread)return void n.send(await async function(e,t){if(!t.query.chr)throw".chr missing";if(!t.query.qname)throw".qname missing";if(t.query.qname=decodeURIComponent(t.query.qname),!Number.isInteger(t.query.start))throw".start is not integer";if(!Number.isInteger(t.query.stop))throw".stop is not integer";const n={chr:t.query.chr,start:t.query.start,stop:t.query.stop,scale:()=>{},ntwidth:10},s=await async function(e,t){const[n,s]=await rn(e);let r,o,i,a,l;if(e.query.unknownorder){if(!Number.isInteger(e.query.readstart)||!Number.isInteger(e.query.readstop))throw"readstart/stop not provided for read with unknown order";i=e.query.readstart,a=e.query.readstop}if(await F.UE({isbam:!0,args:["view",n,(e.query.nochr?e.query.chr.replace("chr",""):e.query.chr)+":"+t.start+"-"+t.stop],dir:s,callback:(n,s)=>{if(n.split("\t")[0]!=e.query.qname)return;const c=dn({sam_info:n,keepallboxes:!0,keepmatepos:!0,keepunmappedread:!0},t);if(c&&(!e.query.show_unmapped||!c.discord_unmapped2)&&(e.query.start==c.segstart_original&&e.query.stop==c.segstop||e.query.paired||e.query.show_unmapped))if(e.query.show_unmapped&&e.query.getfirst){if(c.islast)return s.kill(),void(l=[c])}else if(e.query.show_unmapped&&e.query.getlast){if(c.isfirst)return s.kill(),void(l=[c])}else if(e.query.getfirst){if(c.isfirst)return s.kill(),void(l=[c])}else if(e.query.getlast){if(c.islast)return s.kill(),void(l=[c])}else if(e.query.unknownorder){if(c.segstart==i&&c.segstop==a)return s.kill(),void(l=[c])}else if(c.isfirst?r=c:c.islast&&(o=c),r&&o)return s.kill(),void(l=[r,o])}}),l){if(e.query.altseqs){const t={query_seq:l[0].seq,refseqs:e.query.refseqs,altseqs:e.query.altseqs,cigar_seq:l[0].cigarstr,start_position:l[0].segstart,ref_positions:e.query.ref_positions,refalleles:e.query.refalleles,altalleles:e.query.altalleles},n=(await(0,_e.run_rust)("align",JSON.stringify(t))).split("\n");let s;for(let e of n)e.includes("Final_output:")?s=JSON.parse(e.replace("Final_output:","")):console.log(e);l.alignments=s}return l}l=[],r&&l.push(r);o&&l.push(o);return l.length?l:null}(t,n);if(!s){if(t.query.show_unmapped)throw"mate not found";throw"read not found"}const r=[];for(const n of s)n.discord_unmapped1?r.push(await qn(n,e,t.query)):r.push(await xn(n,e,t.query));s.alignments&&(r[0].alignments=s.alignments);return{lst:r}}(s,t));const o=r().debugmode?new Date:null,i=await async function(e,t){const[n,s]=await rn(t),r={genome:e,file:n,dir:s,asPaired:t.query.asPaired,getcolorscale:t.query.getcolorscale,devicePixelRatio:t.query.devicePixelRatio?Number(t.query.devicePixelRatio):1};if(t.query.pileupheight&&(r.pileupheight=Number(t.query.pileupheight),Number.isNaN(r.pileupheight)))throw".pileupheight is not integer";t.query.drop_pcrduplicates&&(r.drop_pcrduplicates=!0);t.query.drop_supplementary_alignments&&(r.drop_supplementary_alignments=!0);if(t.query.variant){r.diff_score_plotwidth=Number(t.query.diff_score_plotwidth),t.query.max_diff_score&&(r.max_diff_score=Number(t.query.max_diff_score),r.min_diff_score=Number(t.query.min_diff_score));const e=t.query.variant.split(".");if(r.strictness=t.query.strictness,!Number.isInteger(e.length%4))throw"invalid variant, not chr.pos.ref.alt";r.alleleAlreadyUpdated=t.query.alleleAlreadyUpdated,r.alleleAlreadyUpdated&&(r.altseqs=t.query.altseqs,r.refseqs=t.query.refseqs,r.altalleles=t.query.altalleles,r.refalleles=t.query.refalleles,r.leftflankseqs=t.query.leftflankseqs,r.rightflankseqs=t.query.rightflankseqs,r.ref_positions=t.query.ref_positions);const n=e.length/4,s=[];for(let t=0;t<n;t++)s.push({chr:e[4*t],pos:Number(e[4*t+1]),ref:e[4*t+2],alt:e[4*t+3]});if(r.variant=s,t.query.alignOneGroup&&(r.alignOneGroup=t.query.alignOneGroup),Number.isNaN(r.variant.pos))throw"variant pos not integer"}else if(t.query.sv){const e=t.query.sv.split(".");if(e.length<6)throw"invalid sv, not chrA.posA.chrB.posB";if(r.sv={chrA:e[0],startA:Number(e[1]),strandA:Number(e[2]),chrB:e[3],startB:Number(e[4]),strandB:Number(e[5])},Number.isNaN(r.sv.startA))throw"sv.startA not integer";if(Number.isNaN(r.sv.startB))throw"sv.startB not integer"}if(Number.isFinite(Number(t.query.stackstart))){if(!t.query.stackstop)throw".stackstop missing";if(r.partstack={start:Number(t.query.stackstart),stop:Number(t.query.stackstop)},Number.isNaN(r.partstack.start))throw".stackstart not integer";if(Number.isNaN(r.partstack.stop))throw".stackstop not integer";if(!t.query.grouptype)throw".grouptype required for partstack";r.grouptype=t.query.grouptype}t.query.gdc||(t.query.nochr?r.nochr="string"==typeof t.query.nochr?JSON.parse(t.query.nochr):t.query.nochr:r.nochr=await F.Dp(r.file,e,r.dir));if(r.regions=t.query.regions,!Array.isArray(r.regions)||0==r.regions.length)throw"q.regions[] not non-empty array";let o=0;for(const e of r.regions){if(!e.chr)throw".chr missing from a region";if(!Number.isInteger(e.start))throw".start not integer of a region";if(!Number.isInteger(e.stop))throw".stop not integer of a region";e.scale=t=>Math.ceil(e.width*(t-e.start)/(e.stop-e.start)),e.ntwidth=e.width/(e.stop-e.start),o=Math.max(o,e.ntwidth)}return r.stacksegspacing=Math.max(Jt,Ht*o),r.readcount_skipped=0,r}(s,t);n.send(await async function(e){await async function(e){if(e.variant){let t=0,n=0,s=0,r=e.variant[0].pos,o=e.variant[0].pos+Math.max(e.variant[0].ref.length,e.variant[0].alt.length);for(const i of e.variant){const e=Math.abs(i.pos-Math.max(i.ref.length,i.alt.length));e>t&&(t=e,n=s),r>i.pos&&(r=i.pos),o<i.pos+Math.max(i.ref.length,i.alt.length)&&(o=i.pos+Math.max(i.ref.length,i.alt.length)),s+=1}t=Math.floor(1.5*Math.max(e.variant[n].ref.length,e.variant[n].alt.length));const i={chr:e.variant[0].chr,start:r-t,stop:o+t};return await an(e,[i]),await ln(i,e),void(e.regions[0].lines=i.lines)}await an(e,e.regions);for(const t of e.regions)await ln(t,e)}(e),e.totalnumreads=e.regions.reduce(((e,t)=>e+t.lines.length),0);const t={nochr:e.nochr,count:{r:e.totalnumreads},groups:[]};e.read_limit_reached&&(t.count.read_limit_reached=e.read_limit_reached);e.canvaswidth=e.regions[e.regions.length-1].x+e.regions[e.regions.length-1].width;{const n=await async function(e){const t=[],n=[];let s=0;for(const r of e.regions){for(const e of r.lines)t.push({sam_info:e,tempscore:""});s=r.x+r.width,n.push(s)}if(0==t.length)return{groups:[{type:Te,regions:$e(e.regions),templates:t,messages:[],partstack:e.partstack,widths:n}]};if(e.variant){if(1==e.regions.length)return await async function(e,t,n){const s=e.regions[0].lines[0].split("\t")[9].length;let r=!1,o=[],i=[],a=[],l=[],c=[],u=[],f=[];if(e.alleleAlreadyUpdated)o=e.leftflankseqs,i=e.rightflankseqs,u=e.refseqs,f=e.altseqs,a=e.refalleles,l=e.altalleles,c=e.ref_positions,0!=u[0].toUpperCase().localeCompare((o[0]+a[0]+i[0]).toUpperCase())&&(console.log("Reference allele is not correct for variant 0"),r=!0);else{let t,n,r=0;for(const o of e.variant){let i="",u="";if(!(0!=o.ref.length&&"-"!=o.ref||"-"!=o.alt&&0!=o.alt.length))throw"Both Ref and Alt alleles are missing";if(0==o.ref.length||"-"==o.ref)i=(await F.Kf(e.genome,o.chr+":"+o.pos+"-"+o.pos)).split("\n").slice(1).join("").toUpperCase(),u=i+o.alt,o.pos-=1;else if("-"==o.alt||0==o.alt.length){const t=(await F.Kf(e.genome,o.chr+":"+o.pos+"-"+o.pos)).split("\n").slice(1).join("").toUpperCase();i=t+o.ref,u=t,o.pos-=1}else u=o.alt,i=o.ref;const f=o.pos,d=i.toUpperCase(),p=u.toUpperCase();0==r?(t=f-s,n=f+i.length+1+s):(f-s<t&&(t=f-s),f+i.length+1+s>n&&(n=f+i.length+1+s)),a.push(d),l.push(p),c.push(f),r+=1}r=0;for(const s of e.variant){const d=(await F.Kf(e.genome,s.chr+":"+t+"-"+c[r])).split("\n").slice(1).join("").toUpperCase(),p=(await F.Kf(e.genome,s.chr+":"+(c[r]+a[r].length+1)+"-"+n)).split("\n").slice(1).join("").toUpperCase(),m=d+a[r]+p,h=d+l[r]+p;console.log(s.chr+"."+c[r]+"."+a[r]+"."+l[r]),r+=1,o.push(d),i.push(p),u.push(m),f.push(h)}}const d=[];for(let e=0;e<t.length;e++){const n=t[e].sam_info.split("\t");d.push({read_sequence:n[9],start_position:Number(n[3]),cigar:n[5],flag:Number(n[1])})}const p=[];for(let e=0;e<a.length;e++)p.push({ref_position:Number(c[e]),refallele:a[e],altallele:l[e],refseq:u[e],altseq:f[e],leftflankseq:o[e],rightflankseq:i[e]});Number.isFinite(Number(e.strictness))||(e.strictness=1);const m={reads:d,alleles:p,strictness:Number(e.strictness)},h=new Date,g=await(0,_e.run_rust)("indel",JSON.stringify(m)),y=new Date;console.log("Time taken to run rust indel pipeline:",y-h,"ms");const b=g.split("\n");let v,w,_,k,q,x,N=0;for(let e of b)e.includes("Final_output:")?v=JSON.parse(JSON.parse(e.replace("Final_output:",""))):1==a.length&&e.includes("fisher_strand:")?(w=JSON.parse(e.replace("fisher_strand:","")),_=w.alternate_forward_count,k=w.alternate_reverse_count,q=w.reference_forward_count,x=w.reference_reverse_count,N=w.p_value):console.log(e);if(0==v.length)throw"No reads available for variant typing";let S=!1;1==e.variant.length&&N>60&&(S=!0);const A=Fe(e);e.variant.length;let C=1;for(let n=0;n<v.length;n++){const s=v[n],r=s.read_number,o=s.categories,i=s.categories[0],a=[];if(o.length>1){for(let e=1;e<o.length;e++)a.push(o[e]);o.length-1>C&&(C=o.length-1)}if(i.includes("alt"))for(let n=0;n<e.variant.length;n++)i=="alt"+n.toString()&&A[Oe+n.toString()]&&(t[r].tempscore=["alt"+n.toString()],A[Oe+n.toString()].templates.push(t[r]));else"ref"==i?A[Me]&&(t[r].tempscore=["ref"],A[Me].templates.push(t[r])):"none"==i?A[Ie]&&(t[r].tempscore=a,A[Ie].templates.push(t[r])):"amb"==i?A[Ee]&&(t[r].tempscore=a,A[Ee].templates.push(t[r])):console.log("Unaccounted group, please check")}const j=[];for(const t in A){const s=A[t];if(0!=s.templates.length){if(t.includes(Oe))for(let n=0;n<e.variant.length;n++)t==Oe+n.toString()&&(1==e.variant.length?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read supporting the alternative allele"}):s.messages.push({isheader:!0,t:s.templates.length+" reads supporting the alternative allele"}):1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read support the alternative allele with "+l[n]+" sequence"}):s.messages.push({isheader:!0,t:s.templates.length+" reads support the alternative allele with "+l[n]+" sequence"}));else t==Ee?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" ambiguous read"}):s.messages.push({isheader:!0,t:s.templates.length+" ambiguous reads"}):t==Me?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read supporting the reference allele"}):s.messages.push({isheader:!0,t:s.templates.length+" reads supporting the reference allele"}):t==Ie?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read supporting neither reference nor alternative alleles"}):s.messages.push({isheader:!0,t:s.templates.length+" reads supporting neither reference nor alternative alleles"}):console.log("Unaccounted group, please check");s.widths=n,j.push(s)}}const T=[];for(let e=0;e<j.length;e++)j[e].type.includes("support_alt")&&T.push(j[e]);for(let e=0;e<j.length;e++)"support_ref"==j[e].type&&T.push(j[e]);for(let e=0;e<j.length;e++)"support_no"==j[e].type&&T.push(j[e]);for(let e=0;e<j.length;e++)"support_amb"==j[e].type&&T.push(j[e]);return{groups:T,refalleleerror:r,ref_positions:c,refalleles:a,altalleles:l,max_diff_score:C,min_diff_score:0,strand_probability:N,strand_significance:S,refseqs:u,altseqs:f,leftflankseqs:o,rightflankseqs:i,alternate_forward_count:_,alternate_reverse_count:k,reference_forward_count:q,reference_reverse_count:x}}(e,t,n);console.log("Indel pipeline works only in single region. Please check!")}if(e.sv&&e.regions.length>1)return async function(e,t,n){const s=Fe(t),r=[];for(let e=0;e<t.regions.length;e++){const n=t.regions[e],s=(await F.Kf(t.genome,n.chr+":"+n.start+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase(),o=[];for(const t of n.lines)o.push({sam_info:t,tempscore:"",ridx:e});const i={refseq:s,start:n.start,stop:n.stop,entries:o};0==e?(i.chr=t.sv.chrA,i.pos=t.sv.startA):1==e?(i.chr=t.sv.chrB,i.pos=t.sv.startB):console.log("More than two regions, please check"),r.push(i)}const o=new Date,i=(await(0,_e.run_rust)("sv",JSON.stringify(r))).split("\n"),a=new Date;let l,c;console.log("Time taken to run rust SV pipeline:",a-o,"ms");for(let e of i)e.includes("multi_region_templates:")?l=JSON.parse(e.replace("multi_region_templates:","")):e.includes("single_region_templates:")&&(c=JSON.parse(e.replace("single_region_templates:","")));if(!t.grouptype||"support_sv"==t.grouptype)for(const e of l)s[Re].templates.push(e);if(!t.grouptype||"support_ref"==t.grouptype)for(const e of c)s[Me].templates.push(e);const u=[];for(const e in s){const t=s[e];0!=t.templates.length&&(e==Re?1==t.templates.length?t.messages.push({isheader:!0,t:t.templates.length+" read supporting SV/fusion"}):t.messages.push({isheader:!0,t:t.templates.length+" reads supporting SV/fusion"}):e==Me&&t.messages.push({isheader:!0,t:t.templates.length+" reads supporting reference allele"}),t.widths=n,u.push(t))}return{groups:u}}(0,e,n);return{groups:[{type:Te,regions:$e(e.regions),templates:t,messages:[],partstack:e.partstack,widths:n}]}}(e);e.groups=n.groups,e.variant&&(t.ref_alleles=n.refalleles,t.alt_alleles=n.altalleles,t.allele_positions=n.ref_positions,t.strand_probability=n.strand_probability,t.alternate_forward_count=n.alternate_forward_count,t.reference_forward_count=n.reference_forward_count,t.alternate_reverse_count=n.alternate_reverse_count,t.reference_reverse_count=n.reference_reverse_count,1==n.strand_significance&&(t.strand_significance=!0),e.alleleAlreadyUpdated||(t.refseqs=n.refseqs,t.altseqs=n.altseqs,t.leftflankseqs=n.leftflankseqs,t.rightflankseqs=n.rightflankseqs,t.ref_positions=n.ref_positions,t.refalleles=n.refalleles,t.altalleles=n.altalleles)),Number.isFinite(e.max_diff_score)&&e.variant?(t.max_diff_score=e.max_diff_score,t.min_diff_score=e.min_diff_score):Number.isFinite(n.max_diff_score)&&(t.max_diff_score=n.max_diff_score,t.min_diff_score=n.min_diff_score),n.refalleleerror&&(t.refalleleerror=n.refalleleerror)}if(0==t.count.r)throw"No reads in view range.";if(e.alignOneGroup){const t=e.groups.find((t=>t.type==e.alignOneGroup));if(!t)throw"cannot find group for realignment";let n=fn(e,t);return n=mn(t,e,n),await async function(e,t,n){let s;if(t.variant)if("support_ref"==e.type){let r=t.leftflankseqs[0].length;s=e.partstack?await on(n,r,e.partstack.start,e.partstack.stop,t.refseqs[0]):await on(n,r,0,0,t.refseqs[0])}else if("support_no"==e.type){let r=t.leftflankseqs[0].length;s=e.partstack?await on(n,r,e.partstack.start,e.partstack.stop):await on(n,r)}else{if("support_amb"==e.type)throw"Realignment of reads in ambiguous group is not currently implemented.";if(e.type.includes("support_alt")){for(let r=0;r<t.variant.length;r++)if(e.type=="support_alt"+r.toString()){let o=t.leftflankseqs[r].length;s=e.partstack?await on(n,o,e.partstack.start,e.partstack.stop,t.altseqs[r]):await on(n,o,0,0,t.altseqs[r])}}else console.log("Unaccounted group, please check")}return{alignmentData:s}}(t,e,n)}let n=[];for(const s of e.groups){let r=fn(e,s);r=mn(s,e,r),await pn(s,e,r),await un(r,e),gn(s,r,e);const o={type:s.type,width:e.canvaswidth,height:s.canvasheight,stackheight:s.stackheight,stackcount:s.stacks.length,allowpartstack:s.allowpartstack,templatebox:s.returntemplatebox,count:{r:r.reduce(((e,t)=>e+t.segments.length),0)}},i=(0,S.createCanvas)(e.canvaswidth*e.devicePixelRatio,s.canvasheight*e.devicePixelRatio),a=i.getContext("2d");e.devicePixelRatio>1&&a.scale(e.devicePixelRatio,e.devicePixelRatio),a.textAlign="center",a.textBaseline="middle",o.messages=s.messages,o.messagerowheights=0;for(const t of r)wn(a,t,s,e);kn(a,s,e,r),e.asPaired&&(o.count.t=r.length),e.variant&&(o.diff_scores_img=await nn(e,s,r,t.max_diff_score,t.min_diff_score),"support_alt0"==o.type?o.group_color=Ct:"support_alt1"==o.type?o.group_color=jt:"support_alt2"==o.type?o.group_color=Tt:"support_alt3"==o.type?o.group_color=Mt:"support_alt4"==o.type?o.group_color=Ot:"support_alt5"==o.type?o.group_color=It:"support_ref"==o.type&&(o.group_color=Et)),o.src=i.toDataURL(),t.groups.push(o),n=[...n,...r]}e.readcount_skipped&&(t.count.skipped=e.readcount_skipped);e.getcolorscale&&(t.colorscale=function(e){const t=160,n=20,s=1,r=12,o=5,i=100,a=4,l=i+t+10,c=2*r+o+a+4*(n+s),u=(0,S.createCanvas)(e.devicePixelRatio*l,e.devicePixelRatio*c),f=u.getContext("2d");e.devicePixelRatio>1&&f.scale(e.devicePixelRatio,e.devicePixelRatio);f.fillStyle="black",f.font=r+"pt Arial",f.textAlign="center",f.fillText("Base quality",i+t/2,r);let d=2*r+o;function p(e,s,r){const o=i,a=f.createLinearGradient(o,r,o+t,r);a.addColorStop(0,s),a.addColorStop(1,e),f.fillStyle=a,f.fillRect(o,r,t,n)}return f.strokeStyle="black",f.beginPath(),f.moveTo(i,d),f.lineTo(i,d+a),f.moveTo(i+t/4,d),f.lineTo(i+t/4,d+a),f.moveTo(i+t/2,d),f.lineTo(i+t/2,d+a),f.moveTo(i+3*t/4,d),f.lineTo(i+3*t/4,d+a),f.moveTo(i+t,d),f.lineTo(i+t,d+a),f.closePath(),f.stroke(),f.fillText(40,i,d),f.fillText(30,i+t/4,d),f.fillText(20,i+t/2,d),f.fillText(10,i+3*t/4,d),f.fillText(0,i+t,d),f.textAlign="left",f.textBaseline="middle",d+=a,f.fillText("Match",0,d+n/2),p(st,nt,d),d+=n+s,f.fillStyle="black",f.fillText("Mismatch",0,d+n/2),p(ut,ct,d),d+=n+s,f.fillStyle="black",f.fillText("Softclip",0,d+n/2),p(pt,dt,d),d+=n+s,f.fillStyle="black",f.fillText("Insertion",0,d+n/2),p(wt,vt,d),{width:l,height:c,src:u.toDataURL()}}(e));if(!e.partstack)if(0==t.count.r);else{if(!e.pileupheight)throw"pileupheight missing";t.pileup_data=await async function(e,t){const n=(0,S.createCanvas)(e.canvaswidth*e.devicePixelRatio,e.pileupheight*e.devicePixelRatio),s=n.getContext("2d");e.devicePixelRatio>1&&s.scale(e.devicePixelRatio,e.devicePixelRatio);const r=[];let o=0;for(const[n,s]of e.regions.entries()){r[n]=await cn(e,s),sn(n,s,t,r[n]);for(const e of r[n])e&&(o=Math.max(o,e.total))}for(const[t,n]of e.regions.entries()){const i=e.pileupheight/o;for(const o of r[t]){if(!o)continue;const t=(o.position-n.start)*n.ntwidth+n.x,r=n.ntwidth>=1?t:Math.floor(t),a=Math.max(1,n.ntwidth);{s.fillStyle=At;const t=o.total*i;s.fillRect(r,e.pileupheight-t,a,t)}let l=0;if(o.A){s.fillStyle=$.basecolor.A;const t=o.A*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.C){s.fillStyle=$.basecolor.C;const t=o.C*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.G){s.fillStyle=$.basecolor.G;const t=o.G*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.T){s.fillStyle=$.basecolor.T;const t=o.T*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.softclip){s.fillStyle=dt;const t=o.softclip*i;s.fillRect(r,e.pileupheight-l-t,a,t)}}}return{width:e.canvaswidth,maxValue:o,src:n.toDataURL()}}(e,n)}return t}(i)),r().debugmode&&console.log("bam.js time ms",new Date-o)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Pr)),Jr.get(Hr+"/gdcbam",function(e){return async function(t,n){try{const s=e.hg38;if(!s)throw"hg38 missing";const r=s.datasets.GDC;if(!r)throw"hg38 GDC missing";if(Ve||(Ve=function(e){if(Ve)throw"The gdc queryApi has already been set.";return async function(t,n,s,r,o){const{host:i,headers:a}=e.getHostHeaders(o),l=y().join(i.rest,n.end_point),c={filters:t,case_filters:r,size:s||10,fields:n.fields.join(",")},u=await v()(l,{method:"POST",headers:a,body:JSON.stringify(c)});let f;try{f=JSON.parse(u.body)}catch(e){throw"invalid JSON from "+n.end_point}if(!Array.isArray(f.data?.hits))throw"data structure not re.data.hits[]";return f}}(r)),t.query.gdc_id){const e=await async function(e){const{gdc_id:t,filter0:n}=e,s={file_metadata:[],isCaseSample:"",numFilesSkippedByWorkflow:0},r=await Ze(t,s,n,e);if(!r.data.hits.length){if(s.isCaseSample)throw`No bam files available for this ${s.isCaseSample}.`;if(n){if((await Ze(t,s,null,e)).data.hits.length)throw"Case not in current cohort.";throw"Invalid input ID."}throw"Invalid input ID."}for(const e of r.data.hits){if(e.analysis.workflow_type==Je){s.numFilesSkippedByWorkflow++;continue}const t={};t.file_uuid=e.id,t.file_size=Ge(e.file_size),t.experimental_strategy=e.experimental_strategy,t.entity_id=e.associated_entities[0].entity_submitter_id,t.case_id=e.associated_entities[0].case_id,t.sample_type=e.cases[0].samples[0].sample_type,s.file_metadata.push(t)}return s}(t.query);await async function(e,t,n){if(!e.file_metadata?.length)return;const s=t.cookies.sessionid;if(!s)return;try{await Qe(e.file_metadata[0].file_uuid,n,t.query)}catch(t){"Permission denied"==t&&(e.userHasNoAccess=!0)}}(e,t,r),n.send(e)}else{const e=await async function(e,t){const n=await async function(e,t){const n=await Ve(null,Be,He,e,t);return n.data.hits.map((e=>e.id))}(e,t);if(0==n.length)throw"No cases available";const s=await Xe(n,"cases.case_id",We,t),r={};if(!Array.isArray(s.data?.hits))throw"re.data.hits[] not array";for(const e of s.data.hits){if(e.analysis.workflow_type==Je)continue;const t=e.cases?.[0]?.submitter_id;t&&(r[t]||(r[t]=[]),r[t].push({file_uuid:e.id,sample_type:e.cases?.[0].samples?.[0].sample_type,experimental_strategy:e.experimental_strategy,file_size:Ge(Number.parseFloat(e.file_size))}))}return{case2files:r,total:s.data?.pagination?.total,loaded:We}}(t.query.filter0,t.query);n.send(e)}}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Pr)),Jr.get(Hr+"/tkaicheck",(async(e,t)=>{try{t.send(await async function(e){const[t,n,s]=F.ZX(e);if(t)throw t;const r=Number(e.query.coveragemax)||100;if(!Number.isInteger(r))throw"invalid coveragemax";const o=Number(e.query.vafheight);if(!Number.isInteger(o))throw"invalid vafheight";const i=Number(e.query.coverageheight);if(!Number.isInteger(i))throw"invalid coverageheight";const a=Number(e.query.rowspace);if(!Number.isInteger(a))throw"invalid rowspace";const l=Number(e.query.dotsize)||1;if(!Number.isInteger(l))throw"invalid dotsize";if(!e.query.rglst)throw".rglst missing";"string"==typeof e.query.rglst&&(e.query.rglst=JSON.parse(e.query.rglst));const c=e.query.gtotalcutoff,u=e.query.gmafrestrict,f=(0,S.createCanvas)(e.query.width*e.query.devicePixelRatio,(3*o+4*a+2*i)*e.query.devicePixelRatio),d=f.getContext("2d");let p;e.query.devicePixelRatio>1&&d.scale(e.query.devicePixelRatio,e.query.devicePixelRatio),d.fillStyle="#f1f1f1",d.fillRect(0,0,e.query.width,o/2),d.fillRect(0,2*a+o+i,e.query.width,o/2),d.fillStyle="#FAFAD9",d.fillRect(0,o/2,e.query.width,o/2),d.fillRect(0,2*a+1.5*o+i,e.query.width,o/2),s&&(p=await F.d1(n,e.query.indexURL));let m=0;for(const t of e.query.rglst)t.x=m,m+=e.query.regionspace+t.width;const h="#786312",g="#122778",y="#858585",b="red";for(const t of e.query.rglst){const e=t.width/(t.stop-t.start);await F.UE({args:[n,t.chr+":"+t.start+"-"+t.stop],dir:p,callback:n=>{const s=n.split("\t"),f=Number.parseInt(s[1]),p=Number.parseInt(s[2]),m=Number.parseInt(s[3]),v=Number.parseInt(s[4]),w=Number.parseInt(s[5]);if(Number.isNaN(p)||Number.isNaN(m)||Number.isNaN(v)||Number.isNaN(w))return;if(c&&w<c)return;const _=Math.ceil(t.x+e*(t.reverse?t.stop-f:f-t.start)-l/2);d.fillStyle=h;const k=p/m;d.fillRect(_,o*(1-k),l,2);const q=v/w;if(u&&(q<u||q>1-u))return;d.fillRect(_,o+a+i+a+o*(1-q),l,2),d.fillStyle=g;const x=Math.abs(k-q);d.fillRect(_,2*o+4*a+2*i+o*(1-x),l,2),d.fillStyle=y;let N=(m>=r?r:m)*i/r,S=i-N;d.fillRect(_,S+o+a,l,N),d.fillStyle=y,N=(w>=r?r:w)*i/r,S=i-N,d.fillRect(_,S+3*a+2*o+i,l,N),m>=r&&(d.fillStyle=b,d.fillRect(_,o+a,l,2)),w>=r&&(d.fillStyle=b,d.fillRect(_,3*a+2*o+i,l,2))}})}return{src:f.toDataURL(),coveragemax:r}}(e))}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.get(Hr+"/blat",function(e){return async(t,n)=>{try{if(t.query.serverstat){const t=[];for(const n in e){const s=e[n];s.blat&&t.push(await ns(n,s))}if(0==t.length)throw"found no genome with blat";return void n.send({lst:t})}if(!t.query.genome)throw".genome missing";const s=e[t.query.genome];if(!s)throw"invalid genome";if(!s.blat)throw"blat not enabled";if(!t.query.seq)throw".seq missing";n.send(await async function(e,t,n,s){const o=y().join(r().cachedir,await(0,F.tG)(">query\n"+t+"\n")),i=await ss(e,o),a=(await(0,F.b5)(i)).trim();if(h().unlink(i,(()=>{})),h().unlink(o,(()=>{})),""==a)return{nohit:1};const l=a.split("\n"),c=[];for(const e of l){const t={},n=e.split(" ").filter((function(e){return""!=e}))[0].split("\t");t.query_match=n[0],t.query_startpos=(parseInt(n[11])+1).toString(),t.query_stoppos=n[12],t.query_strand=n[8],t.query_totallen=n[10],t.query_alignlen=Math.abs(parseInt(n[11])-parseInt(n[12])).toString(),t.ref_chr=n[13],t.ref_startpos=(parseInt(n[15])+1).toString(),t.ref_stoppos=n[16],t.ref_alignlen=Math.abs(n[16]-n[15]).toString(),t.ref_totallen=n[14],c.push(t)}return c.sort(((e,t)=>t.query_match-e.query_match)),{hits:c}}(s,t.query.seq,t.query.soft_starts,t.query.soft_stops))}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Pr)),Jr.all(Hr+"/mds3",function(e){return async(t,n)=>{try{if(!t.query.genome)throw".genome missing";const s=e[t.query.genome];if(!s)throw"invalid genome";const r=function(e,t){const n=e.query;e.get("X-Auth-Token")&&(n.token=e.get("X-Auth-Token"));(0,F.Y5)(n,e.cookies),n.hiddenmclasslst&&(n.hiddenmclass=new Set(n.hiddenmclasslst.split(",")),delete n.hiddenmclasslst);return n}(t),o=await async function(e,t){if(e.dslabel){if(!t.datasets)throw".datasets{} missing from genome";const n=t.datasets[e.dslabel];if(!n)throw"invalid dslabel";return n}const n={queries:{}};if(e.bcffile||e.bcfurl){const[s,r,o]=(0,F.ZX)({query:{file:e.bcffile,url:e.bcfurl}});if(s)throw s;const i={};o?(i.url=r,i.indexURL=e.bcfindexURL):i.file=r,n.queries.snvindel={byrange:{_tk:i}},n.queries.snvindel.byrange.get=await Fs(n,t)}return n}(r,s);!function(e,t){if(e.filter0){const n="object"==typeof e.filter0?e.filter0:JSON.parse("string"==typeof e.filter0&&e.filter0.startsWith("%")?decodeURIComponent(e.filter0):e.filter0);e.filter0=t.validate_filter0(n)}e.filterObj&&"string"==typeof e.filterObj&&(e.filterObj=JSON.parse("string"==typeof e.filterObj&&e.filterObj.startsWith("%")?decodeURIComponent(e.filterObj):e.filterObj));if(e.skewerRim){if("format"!=e.skewerRim.type)throw"unknown skewerRim.type";if(!e.skewerRim.formatKey)throw"skewerRim.formatKey missing when type=format";if(!t.queries?.snvindel?.format)throw"snvindel.format{} not found when type=format";if(!t.queries.snvindel.format[e.skewerRim.formatKey])throw"invalid skewerRim.formatKey";if(e.skewerRim.hiddenvalues=new Set,e.skewerRim.hiddenvaluelst){if(!Array.isArray(e.skewerRim.hiddenvaluelst))throw"query.skewerRim.hiddenvaluelst is not array";for(const t of e.skewerRim.hiddenvaluelst)e.skewerRim.hiddenvalues.add(t);delete e.skewerRim.hiddenvaluelst}}if(e.formatFilter){if("object"!=typeof e.formatFilter)throw"formatFilter{} not object";if(!t.queries?.snvindel?.format)throw"snvindel.format{} not found when formatFilter is used";const n={};for(const s in e.formatFilter){if(!t.queries.snvindel.format[s])throw"invalid format key from formatFilter";if(!Array.isArray(e.formatFilter[s]))throw"formatFilter[k] value is not array";n[s]=new Set(e.formatFilter[s])}e.formatFilter=n}("format"==e.skewerRim?.type||e.formatFilter)&&(e.addFormatValues=!0)}(r,o);const i=await async function(e,t){if(e.singleSampleGenomeQuantification){if(!t.queries.singleSampleGenomeQuantification)throw"not supported on this dataset";const n=t.queries.singleSampleGenomeQuantification[e.singleSampleGenomeQuantification.dataType];if(!n)throw"invalid dataType";return await n.get(e.singleSampleGenomeQuantification.sample,e.devicePixelRatio)}if(e.singleSampleGbtk){if(!t.queries.singleSampleGbtk)throw"not supported on this dataset";const n=t.queries.singleSampleGbtk[e.singleSampleGbtk.dataType];if(!n)throw"invalid dataType";return await n.get(e.singleSampleGbtk.sample)}if(e.ssm2canonicalisoform){if(!t.ssm2canonicalisoform)throw"ssm2canonicalisoform not supported on this dataset";return{isoform:await t.ssm2canonicalisoform.get(e)}}if(e.variant2samples){if(!t.variant2samples)throw"not supported by server";return{variant2samples:await t.variant2samples.get(e)}}if(e.m2csq){if(t.queries&&t.queries.snvindel&&t.queries.snvindel.m2csq)return{csq:await t.queries.snvindel.m2csq.get(e)};throw"m2csq not supported on this dataset"}if(e.forTrack){const n={};if(e.skewer){if(n.skewer=[],t.queries.snvindel){const s=await async function(e,t){if(e.isoform&&t.queries.snvindel.byisoform)return await t.queries.snvindel.byisoform.get(e);if(e.rglst){if(!t.queries.snvindel.byrange)throw"q.rglst[] provided but .byrange{} is missing";return await t.queries.snvindel.byrange.get(e)}throw"insufficient query parameters for snvindel"}(e,t);n.skewer.push(...s)}if(t.queries.svfusion){const s=await async function(e,t){if(e.rglst){if(!t.queries.svfusion.byrange)throw"q.rglst provided but svfusion.byrange missing";return await t.queries.svfusion.byrange.get(e)}throw"insufficient query parameters for svfusion"}(e,t);n.skewer.push(...s)}if(t.queries.geneCnv){const s=await async function(e,t){if(e.gene){if(!t.queries.geneCnv.bygene)throw"q.gene provided but geneCnv.bygene missing";return await t.queries.geneCnv.bygene.get(e)}}(e,t);n.geneCnv=s}t.queries.cnv&&(n.cnv=await async function(e,t){if(e.rglst){if(!t.queries.cnv.byrange)throw"q.rglst provided but cnv.byrange missing";return await t.queries.cnv.byrange.get(e)}throw"insufficient query parameters for cnv"}(e,t)),function(e,t){if(t.skewer){const n=[];for(const s of t.skewer)e.rglst&&!e.rglst.find((e=>s.chr==e.chr&&s.pos>=e.start&&s.pos<=e.stop))||n.push(s);t.skewer=n}t.genecnvAtsample}(e,n),n.mclass2variantcount=function(e){const t=new Map;for(const n of e){const e=n.class||n.dt;t.set(e,1+(t.get(e)||0))}return[...t].sort(((e,t)=>t[1]-e[1]))}(n.skewer)}return function(e,t,n){const s=new Set;if(n.skewer)for(const r of n.skewer)if(r.samples){r.occurrence=r.samples.length,Ws(r,e,t),Vs(r,t);for(const e of r.samples)s.add(e.sample_id);delete r.samples}if(n.cnv)for(const e of n.cnv)if(e.samples)for(const n of e.samples)if(s.add(n.sample_id),t.cohort?.termdb?.q?.id2sampleName){const e=t.cohort.termdb.q.id2sampleName(n.sample_id);e&&(n.sample_id=e)}s.size&&(n.sampleTotalNumber=s.size)}(e,t,n),n}throw"do not know what client wants"}(r,o);n.send(i)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Pr)),Jr.get(Hr+"/tkbampile",(async function(e,t){try{const[n,s,r]=F.ZX(e);if(n)throw n;let o=e.query.usegrade;const i=Number(e.query.allheight),a=Number(e.query.fineheight),l=Number(e.query.fineymax),c=Number(e.query.midpad),u=Number(e.query.regionspace),f=Number(e.query.width);if(!Number.isInteger(i))throw"allheight is not integer";if(!Number.isInteger(a))throw"fineheight is not integer";if(!Number.isInteger(l))throw"fineymax is not integer";if(!Number.isInteger(c))throw"midpad is not integer";if(!Number.isInteger(u))throw"regionspace is not integer";if(!Number.isFinite(f))throw"width is not a number";const d="string"==typeof e.query.rglst?JSON.parse(e.query.rglst):e.query.rglst;if(!d)throw"no rglst[]";if(!Array.isArray(d))throw"rglst is not an array";if(0==d.length)throw"empty rglst";for(const e of d)e.reverse?e.scale=t=>Math.ceil(e.width*(e.stop-t)/(e.stop-e.start)):e.scale=t=>Math.ceil(e.width*(t-e.start)/(e.stop-e.start));let p;r&&(p=await F.d1(s,e.query.indexURL));for(const e of d){e.items=[];let t=0;await F.UE({args:[s,e.chr+":"+e.start+"-"+e.stop],dir:p,callback:n=>{const s=n.split("\t");let r;try{r=JSON.parse(s[2])}catch(e){return void t++}const o=Number.parseInt(s[1]);e.items.push({pos:o,data:r})}})}const m=i+c+a,h=(0,S.createCanvas)(f,m),g=d.reduce(((e,t)=>e+t.items.length),0),y=h.getContext("2d");if(0==g)return y.font="15px Arial",y.fillStyle="#aaa",y.textAlign="center",y.textBaseline="middle",y.fillText("No data in view range",f/2,m/2),void t.send({src:h.toDataURL()});let b=null;if(!o){const e=new Set;for(const t of d)for(const n of t.items)for(const t in n.data)e.add(t);if(b=[...e],b.length>0&&(o=b[0]),!o)return void t.send({src:h.toDataURL()})}let v=0;for(const e of d)for(const t of e.items)if(t.data[o]){let e=0;for(const n in t.data[o])e+=t.data[o][n];v=Math.max(v,e)}const w="#ededed";let _=0;const k=i/v,q=a/l;for(const e of d){const t=e.width/(e.stop-e.start);for(const n of e.items){const s=n.data[o];if(!s)continue;const r=e.scale(n.pos);let a=0;const u=[];for(const e in s)u.push({nt:e,v:s[e]}),a+=s[e];y.fillStyle=w;const f=k*(v-a);if(y.fillRect(_+r,f,t,k*a),u.length>1){u.sort(((e,t)=>t.v-e.v));for(let e=1;e<u.length;e++){let n=0;for(let t=0;t<e;t++)n+=u[t].v;y.fillStyle=$.basecolor[u[e].nt],y.fillRect(_+r,f+k*n,t,k*u[e].v)}}y.fillStyle=w;const d=i+c+q*(l-Math.min(a,l));if(y.fillRect(_+r,d,t,q*Math.min(a,l)),u.length>1)for(let e=1;e<u.length;e++){let n=0;for(let t=0;t<e;t++)n+=u[t].v;y.fillStyle=$.basecolor[u[e].nt],y.fillRect(_+r,d+q*(l-Math.min(l,a-n)),t,q*Math.min(l,u[e].v))}}_+=e.width+u}t.send({src:h.toDataURL(),allgrades:b,usegrade:o,allmax:v})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/dsdata",(async function(e,t){try{if(!Pr[e.query.genome])throw"invalid genome";if(!e.query.dsname)throw".dsname missing";const n=Pr[e.query.genome].datasets[e.query.dsname];if(!n)throw"invalid dsname";const s=[];for(const t of n.queries)if((!e.query.expressiononly||t.isgeneexpression)&&!(e.query.noexpression&&t.isgeneexpression||t.dsblocktracklst))if(t.vcffile){const n=await no(t,e);s.push(n)}else{if(!t.makequery)throw"unknow type from one of ds.queries[]";{const r=to(n,t,e);s.push(r)}}t.send({data:s})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/tkbigwig",(async function(e,t){try{let n,s,o,i,a=!1,l=!1;const[c,u,f]=F.ZX(e);if(c)throw c;if(u.endsWith(".gz")&&(l=!0,f&&(i=await F.d1(u,e.query.indexURL))),e.query.autoscale)a=!0;else if(e.query.percentile){if(o=e.query.percentile,!Number.isFinite(o))throw"invalid percentile"}else{if(n=e.query.minv,s=e.query.maxv,!Number.isFinite(n))throw"invalid minv";if(!Number.isFinite(s))throw"invalid maxv"}if(!Number.isFinite(e.query.barheight))throw"invalid barheight";if(!Number.isFinite(e.query.regionspace))throw"invalid regionspace";if(!Number.isFinite(e.query.width))throw"invalid width";if(!e.query.rglst)throw"region list missing";if(e.query.dotplotfactor&&!Number.isInteger(e.query.dotplotfactor))throw"dotplotfactor value should be positive integer";if(l)return await async function(e,t,n,s,r,o){if(null==n||null==s)throw"Y axis scale must be defined for bedgraph track";const i=(0,S.createCanvas)(e.query.width*e.query.devicePixelRatio,e.query.barheight*e.query.devicePixelRatio),a=i.getContext("2d");e.query.devicePixelRatio>1&&a.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);let l=0;for(let t of e.query.rglst)await qe(e,t,l,n,s,r,o,a),l+=t.width+e.query.regionspace;t.send({src:i.toDataURL()})}(e,t,n,s,u,i);for(const t of e.query.rglst){let n;if(r().features.bigwig_rust){const s=u+","+t.chr+","+t.start+","+t.stop+","+Math.ceil(t.width*(e.query.dotplotfactor||1));n=await(0,_e.run_rust)("bigwig",s)}else n=await Ne(e,t,u);n&&(t.values=n.trim().split("\t").map(Number.parseFloat),e.query.dividefactor&&(t.values=t.values.map((t=>t/e.query.dividefactor))))}let d=!0;for(const t of e.query.rglst)t.values&&(d=!1);const p=(0,S.createCanvas)(e.query.width*e.query.devicePixelRatio,e.query.barheight*e.query.devicePixelRatio),m=p.getContext("2d");if(e.query.devicePixelRatio>1&&m.scale(e.query.devicePixelRatio,e.query.devicePixelRatio),d)return m.font="14px Arial",m.fillStyle="#858585",m.textAlign="center",m.textBaseline="middle",m.fillText(e.query.name+": no data in view range",e.query.width/2,e.query.barheight/2),void t.send({src:p.toDataURL(),nodata:!0});const h=1,g=e.query.dotplotfactor?1/e.query.dotplotfactor:1;let y=0,b=0;const v={};if(a||o){const t=[],n=[];for(const s of e.query.rglst)if(s.values)for(const e of s.values)Number.isNaN(e)||(e>=0&&t.push(e),e<=0&&n.push(e));t.length&&(t.sort(((e,t)=>e-t)),y=a?t[t.length-1]:t[Math.floor(t.length*o/100)]),n.length&&(n.sort(((e,t)=>t-e)),b=a?n[n.length-1]:n[Math.floor(n.length*o/100)]),v.minv=b,v.maxv=y}else b=n,y=s;if(e.query.barheight<10){let t=(0,ke.B8)(e.query.pcolor);const n=t.r+","+t.g+","+t.b;t=(0,ke.B8)(e.query.ncolor);const s=t.r+","+t.g+","+t.b;let r=0;for(const t of e.query.rglst){if(t.values)for(let o=0;o<t.values.length;o++){const i=t.values[o];if(Number.isNaN(i))continue;m.fillStyle=i>=y?e.query.pcolor2:i>=0?"rgba("+n+","+i/y+")":i<=b?e.query.ncolor2:"rgba("+s+","+i/b+")";const a=Math.ceil(r+(t.reverse?t.width-g*o:g*o));m.fillRect(a,0,h,e.query.barheight)}r+=t.width+e.query.regionspace}}else{const t=xe().height(e.query.barheight).min(b).max(y);let n=0;for(const s of e.query.rglst){if(s.values)for(let r=0;r<s.values.length;r++){const o=s.values[r];if(Number.isNaN(o))continue;m.fillStyle=o>0?e.query.pcolor:e.query.ncolor;const i=Math.ceil(n+(s.reverse?s.width-g*r:g*r)),a=t(o);if(o>0)m.fillRect(i,a.y,h,e.query.dotplotfactor?Math.min(2,a.h):a.h);else if(e.query.dotplotfactor){const e=Math.min(2,a.h);m.fillRect(i,a.y+a.h-e,h,e)}else m.fillRect(i,a.y,h,a.h);o>y?(m.fillStyle=e.query.pcolor2,m.fillRect(i,0,h,2)):o<b&&(m.fillStyle=e.query.ncolor2,m.fillRect(i,e.query.barheight-2,h,2))}n+=s.width+e.query.regionspace}}v.src=p.toDataURL(),t.send(v)}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/tkld",function(e){return async(t,n)=>{try{const s=e[t.query.genome];if(!s)throw"unknown genome";n.send(await async function(e,t){const[n,s,r]=F.ZX(e);if(n)throw n;let o;r&&(o=await F.d1(s,e.query.indexURL));if(!e.query.rglst)throw"rglst missing";const i=await F.Jy(s,o,t),a=e.query.connheight||50,l={rglst:[]};for(const t of e.query.rglst){const n={chr:t.chr,start:t.start,stop:t.stop,width:t.width,reverse:t.reverse,xoff:t.xoff};l.rglst.push(n);const r=[],c=new Set,u=(i?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;await F.UE({args:[s,u],dir:o,callback:e=>{const n=e.split("\t"),s=Number.parseInt(n[1]);if(s<t.start)return;const o=Number.parseInt(n[2]);if(o>t.stop)return;const i=Number.parseFloat(n[5]);r.push({start:s,stop:o,r2:i}),c.add(s),c.add(o)}}),n.img=Se(t,r,c,a,e.query.devicePixelRatio||1)}return l}(t,s))}catch(e){n.send({error:e.message||e})}}}(Pr)),Jr.get(Hr+"/tabixheader",(async function(e,t){try{const[n,s,r]=F.ZX(e);if(n)throw n;const o=r?await F.d1(s,e.query.indexURL):null,i=await F.ZD(s,o);t.send({lines:i})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.all(Hr+"/snp",(async function(e,t){try{const n=e.query.genome;if(!n)throw"no genome";t.send({results:await Qr(e.query,Pr[n])})}catch(e){return e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/isoformlst",(function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"invalid genome";if(!Array.isArray(e.query.lst))throw".lst missing";const s=[];for(const t of e.query.lst){if(n.genomicNameRegexp.test(t))continue;const e=n.genedb.getjsonbyisoform.all(t);s.push(e.map((e=>{const t=JSON.parse(e.genemodel);return e.isdefault&&(t.isdefault=!0),t})))}t.send({lst:s})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.post(Hr+"/dbdata",(function(e,t){})),Jr.get(Hr+"/img",(async function(e,t){const[n,s,r]=F.ZX(e);try{if(n)throw"invalid image file";const e=await h().promises.readFile(s);t.send({src:"data:image/jpeg;base64,"+new Buffer.from(e).toString("base64"),size:M()(s)})}catch(n){t.send({error:n.message||n})}})),Jr.post(Hr+"/svmr",(function(e,t){if(e.query.file){const[n,s,r]=F.ZX(e);if(n)return void t.send({error:"illegal file name"});h().readFile(s,"utf8",((e,n)=>{e?t.send({error:"cannot read file"}):t.send({raw:n})}))}else t.send({error:"missing file"})})),Jr.post(Hr+"/study",(async function(e,t){try{if(F.lY(e.query.file))throw"invalid file path";const n=y().join(r().tpmasterdir,e.query.file.endsWith(".json")?e.query.file:e.query.file+".json"),s=JSON.parse(await F.b5(n));if(!s.genome)throw"genome missing";const o={};let i=0;for(const e of s.mutationset||[]){const t=L.Dz(s.genome);if(!t)throw"init_bulk_flag() failed";if(s.mutationset.length>1&&(t.tpsetname=e.name?e.name:"set"+ ++i),o[Math.random()]=t,e.snvindel){const n=(await F.b5(y().join(r().tpmasterdir,e.snvindel))).trim().split(/\r?\n/),s=P.parseheader(n[0],t);if(s)throw"snvindel header line error: "+s;for(let e=1;e<n.length;e++)P.parseline(e,n[e],t)}if(e.sv){const n=(await F.b5(y().join(r().tpmasterdir,e.sv))).trim().split(/\r?\n/),s=z.parseheader(n[0],t,!0);if(s)throw"sv header line error: "+s;for(let e=1;e<n.length;e++)z.parseline(e,n[e],t,!0)}if(e.fusion){const n=(await F.b5(y().join(r().tpmasterdir,e.fusion))).trim().split(/\r?\n/),s=z.parseheader(n[0],t,!1);if(s)throw"fusion header line error: "+s;for(let e=1;e<n.length;e++)z.parseline(e,n[e],t,!1)}if(e.svjson){const n=(await F.b5(y().join(r().tpmasterdir,e.svjson))).trim().split(/\r?\n/),[s,o]=J.parseheader(n[0],t);if(s)throw"svjson header line error: "+s;for(let e=1;e<n.length;e++)J.parseline(e,n[e],t,o)}if(e.cnv){const n=(await F.b5(y().join(r().tpmasterdir,e.cnv))).trim().split(/\r?\n/),s=G.parseheader(n[0],t);if(s)throw"cnv header line error: "+s;for(let e=1;e<n.length;e++)G.parseline(e,n[e],t)}if(e.itd){const n=(await F.b5(y().join(r().tpmasterdir,e.itd))).trim().split(/\r?\n/),s=B.parseheader(n[0],t);if(s)throw"itd header line error: "+s;for(let e=1;e<n.length;e++)B.parseline(e,n[e],t)}if(e.deletion){const n=(await F.b5(y().join(r().tpmasterdir,e.deletion))).trim().split(/\r?\n/),s=U.parseheader(n[0],t);if(s)throw"deletion header line error: "+s;for(let e=1;e<n.length;e++)U.parseline(e,n[e],t)}if(e.truncation){const n=(await F.b5(y().join(r().tpmasterdir,e.truncation))).trim().split(/\r?\n/),s=H.parseheader(n[0],t);if(s)throw"Truncation header line error: "+s;for(let e=1;e<n.length;e++)H.parseline(e,n[e],t)}}if(s.annotations){const e=s.annotations.idkey?s.annotations.idkey:"sample";s.annotations.data={};for(const t of s.annotations.files){const n=await F.b5(y().join(r().tpmasterdir,t));ee(n).forEach((t=>{const n=t[e].trim();s.annotations.data[n]||(s.annotations.data[n]=[]),s.annotations.data[n].push(t)}))}}for(const e in o)te(o[e]);delete s.mutationset,t.send({cohort:s,flagset:o})}catch(e){return void t.send({error:e.message||e})}})),Jr.post(Hr+"/textfile",(function(e,t){if(!e.query.file)return t.send({error:"no file"});if(F.lY(e.query.file))return t.send({error:"invalid file name"});const n=y().join(r().tpmasterdir,e.query.file);if(null!=e.query.from){if(!Number.isInteger(e.query.from))return void t.send({error:"invalid value for from"});if(!Number.isInteger(e.query.to))return void t.send({error:"invalid value for to"});const s=[];_()(h().createReadStream(n)).on("end",(()=>{t.send({text:s.join("\n")})})).lines.map(String).skip(e.query.from-1).take(e.query.to).forEach((e=>{s.push(e)}))}else h().readFile(n,{encoding:"utf8"},((e,n)=>{e?t.send({error:"error reading file"}):t.send({text:n})}))})),Jr.post(Hr+"/urltextfile",(async function(e,t){const n=e.query.url.replace(r().URL,`http://127.0.0.1:${r().port}`);try{const e=await v()(n);switch(e.statusCode){case 200:return void t.send({text:F.cl(e.body)});case 404:return void t.send({error:"File not found: "+n});default:t.send({error:"unknown status code: "+e.status})}}catch(e){return t.send({error:"Error downloading file: "+n})}})),Jr.get(Hr+"/junction",(async function(e,t){try{const[n,s,o]=F.ZX(e);if(n)throw n;if(!e.query.rglst)throw"rglst[] missing";if("string"==typeof e.query.rglst&&(e.query.rglst=JSON.parse(e.query.rglst)),!Array.isArray(e.query.rglst))throw"rglst[] not an array";if(e.query.rglst.reduce(((e,t)=>t.stop-t.start+e),0)>1e6)throw"Zoom in below 1 Mb to show junctions";let i;if(e.query.isrnapeg){if(!r().features.junctionrnapeg)throw"rnapeg not supported on this server";if(o)throw"rnapeg file from url is not supported";i=await async function(e,t){try{await h().promises.stat(t)}catch(e){if("EACCES"==e.code)throw"permission denied for rnapeg file";if("ENOENT"==e.code)throw"rnapeg file not found";throw"cannot access rnapeg file ("+e.code+")"}const n=[];for(const s of e.rglst){const e=await Gn({file:t,chr:s.chr,start:s.start,stop:s.stop});for(const t of e)n.push(t)}return n}(e.query,s)}else{const t=o?await F.d1(s,e.query.indexURL):null;i=await async function(e,t,n){const s=[];for(const r of e.rglst)await F.UE({args:[t,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:e=>{const t=e.split("\t"),n=Number.parseInt(t[1]),o=Number.parseInt(t[2]);if(n>=r.start&&n<=r.stop||o>=r.start&&o<=r.stop){const e={chr:r.chr,start:n,stop:o,type:t[4],rawdata:[]};for(let n=5;n<t.length;n++)e.rawdata.push(Number.parseInt(t[n]));s.push(e)}}});return s}(e.query,s,t)}t.send({lst:i})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/mdsjunction",function(e){return async(t,n)=>{try{const[s,o,i]=await async function(e,t){const n=e.query;if(!n.genome)throw"genome missing";const s=t[n.genome];if(!s)throw"invalid genome";let o={},i={};if(n.iscustom)if(i.listsamples=!0,n.url)i.url=n.url,i.dir=await F.d1(n.url,n.indexURL);else if(n.file)i.file=y().join(r().tpmasterdir,n.file);else{if(!n.file2)throw"no file or url given";i.file2=y().join(r().tpmasterdir,n.file2)}else{if(!s.datasets)throw"genome is not equipped with datasets";if(!n.dslabel)throw"dslabel missing";if(o=s.datasets[n.dslabel],!o)throw"invalid dslabel";if(!o.queries)throw"dataset is not equipped with queries";if(!n.querykey)throw"querykey missing";if(i=o.queries[n.querykey],!i)throw"invalid querykey"}return[n,o,i]}(t,e),a=await async function(e,t,n){if(e.junction)return await async function(e,t,n){const s=e.junction;if(!s.chr||!Number.isInteger(s.start)||!Number.isInteger(s.stop))throw"incomplete/invalid info about querying junction";let r;if(await F.UE({args:[$n(n),s.chr+":"+s.start+"-"+s.stop],dir:n.dir,callback:o=>{const i=o.split("\t"),a=Number.parseInt(i[1]),l=Number.parseInt(i[2]);if(a==s.start&&l==s.stop)if(n.file2){r=[];for(let e=5;e<i.length;e++){const t=i[e];if(!t)continue;const n=Number.parseInt(t);Number.isNaN(n)||(n<=0||r.push({i:e-5,readcount:n}))}}else{const s=JSON.parse(i[5]);r=Dn(s,e,t,n)}}}),0==r.length)throw"no sample passing filters";const o={};if(n.listsamples){const e=r.map((e=>{const t={readcount:e.readcount};return e.anno?t.sample_name=e.anno.sample_name:t.i=e.i,t}));e.sort(((e,t)=>t.readcount-e.readcount)),e.length>100?(o.samples=e.slice(0,100),o.sampletotalnumber=e.length):o.samples=e}else if(n.singlejunctionsummary&&n.singlejunctionsummary.readcountboxplotpercohort){o.readcountboxplotpercohort=[];for(const e of n.singlejunctionsummary.readcountboxplotpercohort.groups){const t=new Map;for(const n of r){if(!n.anno)continue;const s=n.anno[e.key];null!=s&&(t.has(s)||t.set(s,[]),t.get(s).push(n))}if(0==t.size)continue;const n=[...t].sort(((e,t)=>t[1].length-e[1].length)),s=[];for(const[e,t]of n){let n=t[0].readcount,r=n;t.forEach((e=>{n=Math.min(n,e.readcount),r=Math.max(r,e.readcount)}));const o=Ln(t,.05,.25,.5,.75,.95);s.push({label:e,samplecount:t.length,percentile:{p05:o[0],p25:o[1],p50:o[2],p75:o[3],p95:o[4]},minvalue:n,maxvalue:r})}o.readcountboxplotpercohort.push({label:e.label,boxplots:s})}}return o}(e,t,n);if(e.readcountByjBsamples)return await async function(e,t,n){if(!e.junctionAposlst)throw".junctionAposlst[] missing";let s,r=e.junctionB.start,o=e.junctionB.stop;e.junctionAposlst.forEach((e=>{r=Math.min(r,e[0]),o=Math.max(o,e[1])}));let i=[];if(await F.UE({args:[n.file||n.url,e.junctionB.chr+":"+r+"-"+o],dir:n.dir,callback:t=>{const n=t.split("\t"),r=Number.parseInt(n[1]),o=Number.parseInt(n[2]);if(r==e.junctionB.start&&o==e.junctionB.stop)s=JSON.parse(n[5]);else for(const[t,s]of e.junctionAposlst)if(t==r&&s==o){const e=JSON.parse(n[5]);e.start=r,e.stop=o,i.push(e);break}}}),!s)throw"jB not found";if(0==i.length)throw"none of jA is found";const a=Dn(s,e,t,n);if(0==a.length)throw"no sample passing filters for junctionB";const l=new Set;a.forEach((e=>l.add(e.i)));const c=[];for(const t of i){const n=[];for(const s of t.samples)l.has(s.i)&&(e.readcountCutoff&&s.readcount<e.readcountCutoff||n.push(s));c.push({start:t.start,stop:t.stop,v:Math.floor(Ln(n,.5))})}return{lst:c}}(e,t,n);const s={};if(e.iscustom&&e.getsamples){const e=await F.ZD($n(n),n.dir);if(e[0]){const t=e[0].split("\t");t.length>5&&(s.sample2client=t.slice(5))}}if(!e.rglst)throw"rglst missing";if(n.viewrangeupperlimit){if(e.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=n.viewrangeupperlimit)throw"zoom in under "+common.bplen(n.viewrangeupperlimit)+" to view details"}let r=0,o=0;const i=[],a=new Set,l=new Set;for(const s of e.rglst)await F.UE({args:[$n(n),s.chr+":"+s.start+"-"+s.stop],dir:n.dir,callback:c=>{const u=c.split("\t"),f=Number.parseInt(u[1]),d=Number.parseInt(u[2]);if(n.file2){u[3];const t=u[4];let n;if("known"==t)n="canonical";else{if("novel"!=t)throw"unknown rnapeg type: "+t;n=Fn}if(e.infoFilter&&e.infoFilter.type&&e.infoFilter.type[n])return;const a={chr:s.chr,start:f,stop:d,info:{type:{lst:[{attrValue:n}]}}},l=[];for(let e=5;e<u.length;e++){const t=u[e];if(!t)continue;const n=Number.parseInt(t);Number.isNaN(n)||(n<=0||(l.push({readcount:n}),r=Math.max(r,n)))}if(0==l.length)return;if(o++,a.sampleCount=l.length,1==a.sampleCount)a.medianReadCount=l[0].readcount;else{const e=Ln(l,.05,.25,.5,.75,.95);a.medianReadCount=e[2],a.readcountBoxplot={percentile:e}}i.push(a)}else{u[3],u[4];if(!(f>=s.start&&f<=s.stop||d>=s.start&&d<=s.stop))return;o++;const c={chr:s.chr,start:f,stop:d,info:{type:{lst:[]}}},p=JSON.parse(u[5]);if(p.sv){c.sv=p.sv;const e=c.chr+"."+c.start+"."+c.sv.mate.chr+"."+c.sv.mate.start;if(a.has(e))return;a.add(e),a.add(c.sv.mate.chr+"."+c.sv.mate.start+"."+c.chr+"."+c.start)}if(p.canonical&&c.info.type.lst.push({attrValue:"canonical"}),p.events)for(const e in p.events){const t=p.events[e];t.__ek=e,c.info.type.lst.push(t)}else p.canonical||c.info.type.lst.push({attrValue:Fn});if(e.infoFilter&&e.infoFilter.type)for(const t of c.info.type.lst)if(e.infoFilter.type[t.attrValue])return;const m=Dn(p,e,t,n);if(0==m.length)return;if((p.exonleft||p.exonright||p.exonleftin||p.exonrightin||p.intronleft||p.intronright||p.leftout||p.rightout)&&(c.ongene={},p.exonleft&&(c.ongene.exonleft=p.exonleft),p.exonright&&(c.ongene.exonright=p.exonright),p.exonleftin&&(c.ongene.exonleftin=p.exonleftin),p.exonrightin&&(c.ongene.exonrightin=p.exonrightin),p.intronleft&&(c.ongene.intronleft=p.intronleft),p.intronright&&(c.ongene.intronright=p.intronright),p.leftout&&(c.ongene.leftout=p.leftout),p.rightout&&(c.ongene.rightout=p.rightout)),m.forEach((e=>{l.add(e.i),r=Math.max(r,e.readcount)})),c.sampleCount=m.length,1==c.sampleCount)c.medianReadCount=m[0].readcount;else{const e=Ln(m,.05,.25,.5,.75,.95);c.medianReadCount=e[2],c.readcountBoxplot={percentile:e}}i.push(c)}}});s.lst=i,s.maxreadcount=r,s.junctiontotalnumber=o,l.size;return s}(s,o,i);n.send(a)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Pr)),Jr.post(Hr+"/mdscnv",(function(e,t){const[n,s,o,i]=so(e.query);if(n)return t.send({error:n});if(!e.query.rglst)return t.send({error:"rglst missing"});if(!e.query.gain)return t.send({error:".gain missing"});if(!e.query.loss)return t.send({error:".loss missing"});if(i.viewrangeupperlimit){if(e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=i.viewrangeupperlimit)return t.send({error:"zoom in under "+$.bplen(i.viewrangeupperlimit)+" to view details"})}if(e.query.permanentHierarchy){const n=function(e,t){if(!t.cohort)return".cohort missing from ds";if(!t.cohort.hierarchies)return".hierarchies missing from ds.cohort";if(!t.cohort.hierarchies.lst)return".hierarchies.lst[] missing from ds.cohort";const n=t.cohort.hierarchies.lst.find((t=>t.name==e.permanentHierarchy.hierarchyname));if(!n)return"unknown hierarchy "+e.permanentHierarchy.hierarchyname;if(!n.levels)return".levels[] missing in hierarchy "+n.name;const s=n.levels[e.permanentHierarchy.levelidx];if(!s)return"level not found by array idx "+e.permanentHierarchy.levelidx;const r=s.k;return delete e.cohortHiddenAttr,e.cohortOnlyAttr={},e.cohortOnlyAttr[r]={},e.cohortOnlyAttr[r][e.permanentHierarchy.valuekey]=1,null}(e.query,o);if(n)return t.send({error:"permanentHierarchy error: "+n})}const a=[],l={count:0,samples:new Set},c={count:0,samples:new Set};for(const t of e.query.rglst){const n=new Promise(((n,s)=>{const a=(0,x.spawn)(Gr,[i.file?y().join(r().tpmasterdir,i.file):i.url,t.chr+":"+t.start+"-"+t.stop],{cwd:i.usedir}),u=I().createInterface({input:a.stdout}),f=(t.stop-t.start)/t.width,d=[];for(let e=0;e<t.width;e++)d.push({positive:0,negative:0});u.on("line",(n=>{const s=n.split("\t"),r=Number.parseInt(s[1]),i=Number.parseInt(s[2]);if(e.query.bplengthUpperLimit&&i-r>e.query.bplengthUpperLimit)return;const a=JSON.parse(s[3]);if(e.query.valueCutoff&&Math.abs(a.value)<e.query.valueCutoff)return;if(a.sample&&o.cohort&&o.cohort.annotation){const t=o.cohort.annotation[a.sample];if(!t)return;if(e.query.cohortOnlyAttr&&o.cohort&&o.cohort.annotation){let n=!1;for(const s in e.query.cohortOnlyAttr){const r=t[s];if(r&&e.query.cohortOnlyAttr[s][r]){n=!0;break}}if(!n)return}if(e.query.cohortHiddenAttr&&o.cohort.attributes){let n=!1;for(const s in e.query.cohortHiddenAttr){o.cohort.attributes.lst.find((e=>e.key==s)).isNumeric;const r=t[s];if(r){if(e.query.cohortHiddenAttr[s][r]){n=!0;break}}else if(e.query.cohortHiddenAttr[s][zr]){n=!0;break}}if(n)return}}a.value>0?(l.count++,l.samples.add(a.sample)):a.value<0&&(c.count++,c.samples.add(a.sample));const u=Math.max(t.start,r),p=Math.min(t.stop,i);let m,h;t.reverse?(m=Math.floor((t.stop-p)/f),h=Math.floor((t.stop-u)/f)):(m=Math.floor((u-t.start)/f),h=Math.floor((p-t.start)/f));for(let e=m;e<h;e++)a.value>0?d[e].positive++:a.value<0&&d[e].negative++}));const p=[];a.stderr.on("data",(e=>p.push(e))),a.on("close",(e=>{const t=p.join("");!t||Dr(t)?n(d):s(t)}))}));a.push(n)}Promise.all(a).then((n=>{const s=e.query.rglst.reduce(((t,n)=>t+n.width+e.query.regionspace),0)-e.query.regionspace,r=(0,S.createCanvas)(s,e.query.gain.barheight+e.query.loss.barheight),a=r.getContext("2d"),u={gain:{count:l.count,samplenumber:l.samples.size},loss:{count:c.count,samplenumber:c.samples.size},maxvalue:0};if(l.count+c.count==0)return a.font="15px Arial",a.fillStyle="#aaa",a.textAlign="center",a.textBaseline="middle",a.fillText("No data in view range",s/2,e.query.gain.barheight),u.src=r.toDataURL(),void t.send(u);for(const e of n)for(const t of e)u.maxvalue=Math.max(u.maxvalue,t.positive,t.negative);const f=e.query.maxvalue||u.maxvalue;let d=0;for(const t of n){for(const n of t){if(n.positive){a.fillStyle=e.query.gain.color||"#67a9cf";const t=Math.ceil(e.query.gain.barheight*Math.min(f,n.positive)/f),s=e.query.gain.barheight-t;a.fillRect(d,s,1,t)}if(n.negative){a.fillStyle=e.query.loss.color||"#ef8a62";const t=Math.ceil(e.query.loss.barheight*Math.min(f,n.negative)/f),s=e.query.gain.barheight;a.fillRect(d,s,1,t)}d++}d+=e.query.regionspace}if(u.src=r.toDataURL(),l.samples.size||c.samples.size){const e=new Set([...l.samples,...c.samples]),[t,n]=function(e,t,n){if(!e.cohort||!e.cohort.annotation||0==n.length)return[null,null];const s=[];for(const t of n){const n=e.cohort.annotation[t];n&&s.push(n)}if(0==s.length)return[null,null];let r,o;if(e.cohort.attributes){r=[];for(const n of e.cohort.attributes.lst){const o={label:n.label,key:n.key};if(n.isNumeric){o.isNumeric=!0;continue}const i=new Map;let a=0;for(const t of s){const s=t[n.key];null!=s?(i.has(s)||i.set(s,new Set),i.get(s).add(t[e.cohort.samplenamekey])):a++}const l=[...i];a&&l.push([zr,a]),l.sort(((e,t)=>t[1]-e[1])),o.values=[];for(const[e,s]of l){const r={name:e,sampleset:s};if(n.values&&n.values[e])for(const t in n.values[e])r[t]=n.values[e][t];t.attributeSummary&&t.attributeSummary[n.key]&&t.attributeSummary[n.key][e]&&(r.totalCount=t.attributeSummary[n.key][e]),o.values.push(r)}r.push(o)}}if(e.cohort.hierarchies){o={};for(const n of e.cohort.hierarchies.lst){const r=he()((0,A.N)(s,n.levels));r.sum((e=>e.value));const i=[];r.eachBefore((s=>{const r={id:s.data.id,name:s.data.name,label:s.data.full,depth:s.depth};if(s.data.lst){r.sampleset=new Set;for(const t of s.data.lst)r.sampleset.add(t[e.cohort.samplenamekey])}s.children||(r.isleaf=1),t.hierarchySummary&&t.hierarchySummary[n.name]&&(r.totalCount=t.hierarchySummary[n.name][s.id]),i.push(r)})),o[n.name]=i}}return[r,o]}(o,i,[...e]);if(t){for(const e of t)for(const t of e.values){t.gain=0,t.loss=0;for(const e of t.sampleset)l.samples.has(e)&&t.gain++,c.samples.has(e)&&t.loss++;delete t.sampleset}u.attributeSummary=t}if(n){for(const e in n)for(const t of n[e])if(t.sampleset){t.gain=0,t.loss=0;for(const e of t.sampleset)l.samples.has(e)&&t.gain++,c.samples.has(e)&&t.loss++}u.hierarchySummary=n}}t.send(u)})).catch((e=>{t.send({error:e}),e.stack&&console.error(e.stack)}))})),Jr.post(Hr+"/mdssvcnv",(async function(e,t){let n,s,o,i,a,l,c,u,f;if(e.query.iscustom){if(n=Pr[e.query.genome],!n)return t.send({error:"invalid genome"});if(s={},o={iscustom:1,file:e.query.file,url:e.query.url,indexURL:e.query.indexURL,allow_getallsamples:!0},e.query.checkexpressionrank){if(!e.query.checkexpressionrank.file&&!e.query.checkexpressionrank.url)return t.send({error:"no file or url for checkexpressionrank"});o.checkexpressionrank={file:e.query.checkexpressionrank.file,url:e.query.checkexpressionrank.url,indexURL:e.query.checkexpressionrank.indexURL}}if(e.query.checkvcf){let n;try{n=JSON.parse(e.query.checkvcf)}catch(e){return t.send({error:"invalid JSON for VCF object"})}if(!n.file&&!n.url)return t.send({error:"no file or url for custom VCF track"});n.type=$.mdsvcftype.vcf,o.checkvcf={info:n.info,tracks:[n]}}if(e.query.checkrnabam){if(!e.query.checkrnabam.samples)return t.send({error:"samples{} missing from checkrnabam"});let n=0;for(const t in e.query.checkrnabam.samples)n++;if(n>13)return t.send({error:"no more than 13 BAM files allowed"});const s=fo(e.query.checkrnabam);if(s)return t.send({error:s});o.checkrnabam=e.query.checkrnabam}}else{if(n=Pr[e.query.genome],!n)return t.send({error:"invalid genome"});if(!n.datasets)return t.send({error:"genome is not equipped with datasets"});if(s=n.datasets[e.query.dslabel],!s)return t.send({error:"invalid dslabel"});if(e.query.getsample4disco)return function(e,t,n,s){if(e.query.iscustom)return t.send({error:"not for custom track"});if(!s.singlesamplemutationjson)return t.send({error:"singlesamplemutationjson not available for this dataset"});const o=e.query.getsample4disco,i=s.singlesamplemutationjson.samples[o];if(!i)return t.send({error:"no data"});const a=y().join(r().tpmasterdir,i);h().readFile(a,{encoding:"utf8"},((e,n)=>{if(e)return t.send({error:"error getting data for this sample"});t.send({text:n})}))}(e,t,0,s);if(e.query.gettrack4singlesample)return function(e,t,n){const s=e.query.gettrack4singlesample;if(e.query.iscustom)return t.send({error:"no server-side config available for custom track"});if(!n.sampleAssayTrack)return t.send({});return t.send({tracks:n.sampleAssayTrack.samples.get(s)})}(e,t,s);if(e.query.findsamplename)return function(e,t,n){if(e.query.iscustom)return t.send({error:"cannot search sample by name in custom track"});const s=e.query.findsamplename.toLowerCase(),r=[];if(!n.cohort.__samplelst){n.cohort.__samplelst=[];for(const e in n.cohort.annotation)n.cohort.__samplelst.push({name:e,low:e.toLowerCase()})}o(n.cohort.__samplelst);for(const e in n.queries){const t=n.queries[e];if(t.type==$.tkt.mdssvcnv&&t.groupsamplebyattr)for(const e of r){const s=n.cohort.annotation[e.name];if(!s)continue;const r=[];for(const e of t.groupsamplebyattr.attrlst){const t=s[e.k];t&&r.push({k:e.k,kvalue:t})}r.length&&(e.attributes=r,e.grouplabel=r.map((e=>e.kvalue)).join(t.groupsamplebyattr.attrnamespacer))}}if(n.cohort&&n.cohort.sampleAttribute&&n.cohort.sampleAttribute.attributes&&n.cohort.annotation)for(const e of r){const t=n.cohort.annotation[e.name];if(!t)continue;const s=[];for(const e in n.cohort.sampleAttribute.attributes){if(n.cohort.sampleAttribute.attributes[e].clientnoshow)continue;const r=t[e];null!=r&&s.push({k:e,v:r})}s.length&&(e.attr=s)}if(n.sampleAssayTrack)for(const e of r){const t=n.sampleAssayTrack.samples.get(e.name);t&&(e.num_assay_tracks=t.length)}if(n.cohort&&n.cohort.mutation_signature)for(const e in n.cohort.mutation_signature.sets){const t=n.cohort.mutation_signature.sets[e];if(t.samples)for(const e of r)t.samples.map.has(e.name)&&(e.mutation_signature=1)}if(n.singlesamplemutationjson)for(const e of r)n.singlesamplemutationjson.samples[e.name]&&(e.disco=1);return t.send({result:r});function o(e){for(const t of e){if(r.length>10)return;-1!=t.low.indexOf(s)&&(r.find((e=>e.name==t.name))||r.push(t))}}}(e,t,s);if(e.query.assaymap)return async function(e,t,n){try{if(!n.assayAvailability)throw"assay availability not enabled for this dataset";const s=new Set(e.query.skip_termids||[]),r=new Map;for(const t in n.cohort.annotation){if(e.query.key){if(n.cohort.annotation[t][e.query.key]!=e.query.value)continue}r.set(t,new Map)}for(const[e,t]of r){const r=n.assayAvailability.samples.get(e);if(r)for(const e of n.assayAvailability.assays)s.has(e.id)||r[e.id]&&t.set(e.id,"yes")}for(const e of r.keys())0==r.get(e).size&&r.delete(e);const o={};o.totalsample=r.size,o.terms=kr({sample2term:r,terms:n.assayAvailability.assays,config:{termidorder:e.query.termidorder}}),t.send(o)}catch(e){t.send({error:e.message||e})}}(e,t,s);if(!s.queries)return t.send({error:"dataset is not equipped with queries"});if(o=s.queries[e.query.querykey],!o)return t.send({error:"invalid querykey"})}if(e.query.getexpression4gene)return async function(e,t,n,s,o){try{const n=e.query.getexpression4gene;if(!n.chr)throw"chr missing";if(!Number.isFinite(n.start))throw"invalid start pos";if(!Number.isFinite(n.stop))throw"invalid stop pos";if(!n.name)throw"unknown gene name";if(o.checkrnabam){const s=Pr[e.query.genome],r=s.tracks.find((e=>e.__isgene)),i=(await go(s,r,n.chr,n.start,n.stop)).get(n.name);if(!i)throw"no gene matching with "+n.name;const a={};await ro(new Map([[n.name,i]]),n.chr,n.start,n.stop,o,a);const l={};for(const e of a.checkrnabam)if(e.genes){const t=e.genes.find((e=>e.gene==n.name));t&&(l[e.sample]=t)}return void t.send({sample2rnabam:l})}let i;if(o.iscustom?i=o.checkexpressionrank:o.expressionrank_querykey&&(i=s.queries[o.expressionrank_querykey]),!i)throw"missing expression data source";const a=i.file?null:await F.d1(i.url,i.indexURL),l=[];await F.UE({args:[i.file?y().join(r().tpmasterdir,i.file):i.url,n.chr+":"+n.start+"-"+n.stop],dir:a,callback:e=>{const t=e.split("\t");let s;try{s=JSON.parse(t[3])}catch(e){reject("invalid json from expression data")}s.sample&&s.gene&&Number.isFinite(s.value)&&(delete s.outlier,s.gene.toLowerCase()==n.name.toLowerCase()&&l.push(s))}});const c=function(e,t,n){const s={};if(e&&e.cohort&&e.cohort.annotation&&t.groupsamplebyattr&&t.groupsamplebyattr.attrlst){const r=new Map;for(const s of n){const n=e.cohort.annotation[s.sample];if(!n)continue;const o=[];for(const e of t.groupsamplebyattr.attrlst)o.push(n[e.k]);const i=o.join(",");r.has(i)||r.set(i,[]),r.get(i).push(s)}for(const e of r.values()){e.sort(((e,t)=>e.value-t.value));for(const t of e)t.rank=vo(t.value,e),s[t.sample]=t}}else{n.sort(((e,t)=>e.value-t.value));for(const e of n)e.rank=vo(e.value,n),s[e.sample]=e}return s}(s,o,l);t.send({sample2rank:c})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}}(e,t,0,s,o);if(e.query.ifsamplehasvcf)return function(e,t,n,s,r){if(e.query.iscustom)return t.send({no:1});if(!r.vcf_querykey)return t.send({yes:1});const o=s.queries[r.vcf_querykey];if(!o)return t.send({error:"vcf query missing"});t.send(o.singlesamples?{yes:1}:{no:1})}(e,t,0,s,o);if(!e.query.rglst)return t.send({error:"rglst missing"});if(o.viewrangeupperlimit){if(e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=o.viewrangeupperlimit)return t.send({error:"zoom in under "+$.bplen(o.viewrangeupperlimit)+" to view details"})}e.query.hiddendt&&(i=new Set(e.query.hiddendt));if(e.query.hiddenmattr){a={};for(const t in e.query.hiddenmattr)a[t]=new Set(e.query.hiddenmattr[t])}if(e.query.filteralleleattr){l={};for(const t in e.query.filteralleleattr){const n=e.query.filteralleleattr[t];n.cutoffvalue,l[t]=n}}if(e.query.filterlocusattr){c={};for(const t in e.query.filterlocusattr){const n=e.query.filterlocusattr[t];n.cutoffvalue,c[t]=n}}if(e.query.sampleset){const t=new Set,n=new Map;for(const s of e.query.sampleset)for(const e of s.samples)t.add(e),n.set(e,s.name);t.size&&(u={set:t,sample2group:n})}if(e.query.hiddensampleattr){f={};for(const t in e.query.hiddensampleattr)f[t]=new Set(e.query.hiddensampleattr[t])}if(o.url)try{o.dir=await F.d1(o.url,o.indexURL)}catch(e){return t.send({error:"svcnv file index url error"})}const d=await function(e,t,n,s,o,i,a){if(!t.file&&!t.url)return[];const l=[];for(const c of n.query.rglst){const u=new Promise(((l,u)=>{const f=[],d=(0,x.spawn)(Gr,[t.file?y().join(r().tpmasterdir,t.file):t.url,c.chr+":"+c.start+"-"+c.stop],{cwd:t.dir});I().createInterface({input:d.stdout}).on("line",(t=>{const r=t.split("\t"),l=Number.parseInt(r[1]),c=Number.parseInt(r[2]);let u;try{u=JSON.parse(r[3])}catch(e){return}if(!(null==u.dt||s&&s.has(u.dt))){if(u.dt==$.dtloh){if(u.segmean&&n.query.segmeanValueCutoff&&u.segmean<n.query.segmeanValueCutoff)return;if(n.query.lohLengthUpperLimit&&c-l>n.query.lohLengthUpperLimit)return;u.chr=r[0],u.start=l,u.stop=c}else if(u.dt==$.dtfusionrna||u.dt==$.dtsv)u._chr=r[0],u._pos=l,u.chrA?(u.chrB=r[0],u.posB=l):(u.chrA=r[0],u.posA=l);else if(u.dt==$.dtcnv){if(n.query.hide_cnvloss&&u.value<0)return;if(n.query.hide_cnvgain&&u.value>0)return;if(n.query.valueCutoff&&Math.abs(u.value)<n.query.valueCutoff)return;if(n.query.bplengthUpperLimit&&c-l>n.query.bplengthUpperLimit)return;u.chr=r[0],u.start=l,u.stop=c}else{if(u.dt!=$.dtitd)return void console.error("unknown dt from svcnv file: "+u.dt);u.chr=r[0],u.start=l,u.stop=c}if(n.query.singlesample){if(u.sample!=n.query.singlesample)return}else if(a){if(!a.set.has(u.sample))return}else if(u.sample&&e.cohort&&e.cohort.annotation){const t=e.cohort.annotation[u.sample];if(!t)return;if(o)for(const e in o){const n=t[e];if(o[e].has(n))return}}if(i)for(const e in i){let t=u.mattr?u.mattr[e]:void 0;if(null==t&&(t=$.not_annotated),i[e].has(t))return}f.push(u)}}));const p=[];d.stderr.on("data",(e=>p.push(e))),d.on("close",(e=>{const t=p.join("");!t||Dr(t)?l(f):u(t)}))}));l.push(u)}return Promise.all(l)}(s,o,e,i,f,a,u),[p,m]=await function(e,t,n,s){if(n.query.singlesample)return[];let o;if(t.iscustom?o=t.checkexpressionrank:t.expressionrank_querykey&&e.queries[t.expressionrank_querykey]&&(o=e.queries[t.expressionrank_querykey]),!o)return[];let i=o.viewrangeupperlimit;if(!i&&t.iscustom&&(i=5e6),i&&n.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=i)return[i];return Promise.resolve().then((()=>o.file?"":(0,F.d1)(o.url,o.indexURL))).then((e=>{const t=new Map,s=[];for(const i of n.query.rglst){const n=new Promise(((n,s)=>{const a=(0,x.spawn)(r().tabix,[o.file?y().join(r().tpmasterdir,o.file):o.url,i.chr+":"+i.start+"-"+i.stop],{cwd:e});I().createInterface({input:a.stdout}).on("line",(e=>{const n=e.split("\t");let s;try{s=JSON.parse(n[3])}catch(e){return}s.gene&&s.sample&&Number.isFinite(s.value)&&(t.has(s.gene)||t.set(s.gene,{chr:n[0],start:Number.parseInt(n[1]),stop:Number.parseInt(n[2]),samples:new Map}),t.get(s.gene).samples.set(s.sample,{value:s.value,ase:s.ase}))}));const l=[];a.stderr.on("data",(e=>l.push(e))),a.on("close",(e=>{const t=l.join("");!t||(0,F.sI)(t)?n():s(t)}))}));s.push(n)}return Promise.all(s).then((()=>[!1,t]))}))}(s,o,e),[g,b]=await async function(e,t,n,s,o,i,a,l,c,u){let f;n.iscustom?f=n.checkvcf:n.vcf_querykey&&t.queries[n.vcf_querykey]&&(f=t.queries[n.vcf_querykey]);if(!f)return[null,null];if(s.query.singlesample&&f.singlesamples){const n=f.singlesamples.samples[s.query.singlesample];if(n){const i={file:y().join(r().tpmasterdir,n)};try{await h().promises.stat(i.file)}catch(e){return[null,null]}const a=await bo(i.file),[u,f,d,p]=D.e(a);if(p)throw p;return i.info=u,i.format=f,i.samples=d,i.nochr=await F.Jy(i.file,null,e),function(e,t,n,s,r,o,i){const a=[],l=[];for(const r of e.query.rglst){const c=new Promise(((l,c)=>{const u=(0,x.spawn)(Gr,[n.file,(n.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop]);I().createInterface({input:u.stdout}).on("line",(r=>{const[l,c,u]=D.S(r,n);for(const n of c){if(!n.sampledata)continue;const r=n.sampledata.find((t=>t.sampleobj.name==e.query.singlesample));if(r){if(delete r.allele2readcount,n.sampledata=[r],s){let e=!1;for(const t in s){const r=n.altinfo[t];if(null==r){e=!0;break}const o=s[t];if(null!=o.cutoffvalue){if(!Number.isFinite(r)){e=!0;break}if(o.keeplowerthan){if(r>o.cutoffvalue){e=!0;break}}else if(r<o.cutoffvalue){e=!0;break}}}if(e)continue}if(!r.gtallref){if(r.__gtalleles){if(-1==r.__gtalleles.indexOf(n.alt))continue;delete r.__gtalleles}if(o){const e=[];for(const t of n.sampledata){let n=!0;for(const e in o){let s=t[e];if(null==s&&(s=$.not_annotated),o[e].has(s)){n=!1;break}}n&&e.push(t)}if(0==e.length)continue;n.sampledata=e}if(i&&t.cohort&&t.cohort.annotation){const e=[];for(const s of n.sampledata){const n=t.cohort.annotation[s.sampleobj.name];if(!n)continue;let r=!0;for(const e in i){const t=n[e];if(i[e].has(t)){r=!1;break}}r&&e.push(s)}if(0==e.length)continue;n.sampledata=e}delete n._m,delete n.vcf_ID,delete n.name,n.dt=$.dtsnvindel,a.push(n)}}}}));const f=[];u.stderr.on("data",(e=>f.push(e))),u.on("close",(e=>{const t=f.join("");!t||Dr(t)?l():c(t)}))}));l.push(c)}return Promise.all(l).then((()=>[null,a]))}(s,t,i,o,0,l,c)}}let d=f.viewrangeupperlimit;!d&&n.iscustom&&(d=Lr.customMdsSingleSampleVcfNoRangeLimit?0:2e6);s.query.singlesample&&(d*=5);if(d){if(s.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=d)return[d,null]}const p=[];for(const e of f.tracks){const n=Promise.resolve().then((()=>e.file?"":F.d1(e.url,e.indexURL))).then((n=>{e.dir=n;const a=[],d=[];for(const p of s.query.rglst){const m=new Promise(((d,m)=>{const h=(0,x.spawn)(Gr,[e.file?y().join(r().tpmasterdir,e.file):e.url,(e.nochr?p.chr.replace("chr",""):p.chr)+":"+p.start+"-"+p.stop],{cwd:n});I().createInterface({input:h.stdout}).on("line",(n=>{if(e.type==$.mdsvcftype.vcf){const[r,d,p]=D.S(n,{nochr:e.nochr,samples:e.samples,info:f.info,format:e.format});for(const e of d)if(e.sampledata){if(o){let t=!1;for(const n in o){const s=e.altinfo[n];if(null==s){t=!0;break}const r=o[n];if(null!=r.cutoffvalue){if(!Number.isFinite(s)){t=!0;break}if(r.keeplowerthan){if(s>r.cutoffvalue){t=!0;break}}else if(s<r.cutoffvalue){t=!0;break}}else if(r.includes(s)){t=!0;break}}if(t)continue}if(i){let t=!1;for(const n in i){const s=e.info[n];if(null==s){t=!0;break}let r=s;if(Array.isArray(s)&&(r=s[0],"."==r)){t=!0;break}const o=i[n];if(null!=o.cutoffvalue){if(!Number.isFinite(r)){t=!0;break}if(o.keeplowerthan){if(r>o.cutoffvalue){t=!0;break}}else if(r<o.cutoffvalue){t=!0;break}}else if(o.includes(r)){t=!0;break}}if(t)continue}{const t=[];for(const n of e.sampledata)if(!n.gtallref){if(n.__gtalleles){if(-1==n.__gtalleles.indexOf(e.alt))continue;delete n.__gtalleles}t.push(n)}if(0==t.length)continue;e.sampledata=t}if(s.query.singlesample){let t=null;for(const n of e.sampledata)if(n.sampleobj.name==s.query.singlesample){t=n;break}if(!t)continue;e.sampledata=[t]}else if(u){const t=e.sampledata.filter((e=>u.set.has(e.sampleobj.name)));if(!t.length)continue;e.sampledata=t}if(l){const t=[];for(const n of e.sampledata){let e=!0;for(const t in l){let s=n[t];if(null==s&&(s=$.not_annotated),l[t].has(s)){e=!1;break}}e&&t.push(n)}if(0==t.length)continue;e.sampledata=t}if(c&&t.cohort&&t.cohort.annotation){const n=[];for(const s of e.sampledata){const e=t.cohort.annotation[s.sampleobj.name];if(!e)continue;let r=!0;for(const t in c){const n=e[t];if(c[t].has(n)){r=!1;break}}r&&n.push(s)}if(0==n.length)continue;e.sampledata=n}for(const t of e.sampledata)delete t.allele2readcount;delete e._m,delete e.vcf_ID,delete e.name,e.dt=$.dtsnvindel,a.push(e)}}else console.error('unknown "type" from a vcf file')}));const g=[];h.stderr.on("data",(e=>g.push(e))),h.on("close",(e=>{const t=g.join("");!t||Dr(t)?d():m(t)}))}));d.push(m)}return Promise.all(d).then((()=>a))}));p.push(n)}return Promise.all(p).then((e=>{const t=[];for(const n of e)for(const e of n)if(e.dt!=$.dtsnvindel)console.error("unknown dt: "+e.dt);else{if(!e.sampledata)continue;let n=!0;for(const s of t)if(e.chr==s.chr&&e.pos==s.pos&&e.ref==s.ref&&e.alt==s.alt){for(const t of e.sampledata)s.sampledata.push(t);n=!1;break}n&&t.push(e)}return t.sort(((e,t)=>e.pos-t.pos)),[null,t]}))}(n,s,o,e,l,c,0,a,f,u),v=function(e){const t=new Map;for(const n of e)for(const e of n){if(!e.sample)continue;const n=e.sample;t.has(n)||t.set(n,[]),e._chr?t.get(n).push(e):(delete e.sample,delete e.sampletype,t.get(n).push(e))}return t}(d);if(e.query.singlesample){const n={lst:v.get(e.query.singlesample)};return g?n.vcfrangelimit=g:n.data_vcf=b,void t.send(n)}const w={samplegroups:lo(s,o,d,b,v,u),vcfrangelimit:g,data_vcf:b};e.query.getallsamples&&o.allow_getallsamples&&(w.getallsamples=!0);o.checkrnabam?await async function(e,t,n,s){if(!n.checkvcf)return;if(e.stop-e.start>=5e5)return void(s.expressionrangelimit=5e5);const r=t.tracks.find((e=>e.__isgene)),o=await go(t,r,e.chr,e.start,e.stop);let i,a=null;for(const e of o.values())null==a?(a=e.start,i=e.stop):(a=Math.min(a,e.start),i=Math.max(i,e.stop));await ro(o,e.chr,a,i,n,s)}(e.query.rglst[0],n,o,w):function(e,t,n,s){if(n)return void(e.expressionrangelimit=n);if(s){e.gene2coord={};for(const[t,n]of s)e.gene2coord[t]={chr:n.chr,start:n.start,stop:n.stop};if(0==e.samplegroups.length)return;if(e.getallsamples){const t=new Set(e.samplegroups[0].samples.map((e=>e.samplename))),n=new Set;for(const[e,r]of s)for(const e of r.samples.keys())t.has(e)||n.add(e);for(const t of n)e.samplegroups[0].samples.push({samplename:t,items:[]})}for(const n of e.samplegroups){const e=new Map;for(const[r,o]of s){e.set(r,[]);for(const[s,i]of o.samples)if(n.attributes&&t.cohort&&t.cohort.annotation){const o=t.cohort.annotation[s];if(!o)continue;let a=!0;for(const e of n.attributes)if(o[e.k]!=e.kvalue){a=!1;break}a&&e.get(r).push(i)}else e.get(r).push(i)}for(const[t,n]of e)n.sort(((e,t)=>e.value-t.value));for(const t of n.samples){t.expressionrank={};for(const[n,r]of e){const e=s.get(n).samples.get(t.samplename);if(null==e)continue;const o=vo(e.value,r);t.expressionrank[n]={rank:o};for(const s in e)t.expressionrank[n][s]=e[s]}}}}}(w,s,p,m);(function(e,t){if(e.cohort&&e.cohort.sampleAttribute&&e.cohort.sampleAttribute.attributes&&e.cohort.annotation){t.sampleannotation={};const n=[];for(const t in e.cohort.sampleAttribute.attributes){e.cohort.sampleAttribute.attributes[t].clientnoshow||n.push(t)}for(const s of t.samplegroups)for(const r of s.samples){const s=e.cohort.annotation[r.samplename];if(s){const e={};let o=!1;for(const t of n){const n=s[t];null!=n&&(o=!0,e[t]=n)}o&&(t.sampleannotation[r.samplename]=e)}}}})(s,w),t.send(w)})),Jr.post(Hr+"/mdsgenecount",(async function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"invalid genome";if(!n.datasets)throw"no datasets from genome";const s=n.datasets[e.query.dslabel];if(!s)throw"invalid dataset";if(!s.gene2mutcount)throw"not supported on this dataset";if(!e.query.samples)throw".samples missing";let r,o;r=e.query.selectedMutTypes?e.query.selectedMutTypes.join("+"):"total",o=e.query.nGenes?e.query.nGenes:15;const i=`WITH\n\tfiltered AS (\n\t\tSELECT gene, ${r} AS total FROM genecount\n\t\tWHERE sample IN (${JSON.stringify(e.query.samples).replace(/[[\]\"]/g,"").split(",").map((e=>"'"+e+"'")).join(",")})\n\t)\n\tSELECT gene, SUM(total) AS count\n\tFROM filtered\n\tGROUP BY gene\n\tORDER BY count DESC\n\tLIMIT ${o}`,a=s.gene2mutcount.db.prepare(i).all(),l=[];for(const e of a){const t=n.genedb.getCoordByGene.get(e.gene);t&&(t.gene=e.gene,t.count=e.count,delete t.name,l.push(t))}t.send({genes:l})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.post(Hr+"/mds2",function(e){return async(t,n)=>{const s=t.query;try{const t=e[s.genome],r=await async function(e,t){if(!t)throw"invalid genome";if(e.dslabel){const n=t.datasets[e.dslabel];if(!n)throw"invalid dslabel";if(!n.track)throw"no mds2 track found for dataset";return n}const n={iscustom:1,track:{}};e.vcf&&(n.track.vcf=e.vcf,await F._H(n.track.vcf,t));e.ld;return n}(s,t);if(s.trigger_overlayld)return await async function(e,t,n){if(!e.ldtkname)throw".ldtkname missing";const s=t.track.ld.tracks.find((t=>t.name==e.ldtkname));if(!s)throw"ld tk not found by name: "+e.ldtkname;const r=e.m.ref+"."+e.m.alt,o=(s.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+e.m.pos+"-"+(e.m.pos+1),i=[];await F.UE({args:[s.file,o],dir:s.dir,callback:t=>{const n=t.split("\t"),s=Number.parseInt(n[1]),o=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);s==e.m.pos&&a==r?i.push({pos:o,alleles:l,r2:c}):o==e.m.pos&&l==r&&i.push({pos:s,alleles:a,r2:c})}}),n.send({lst:i})}(s,r,n);s.hidden_mclass&&(s.hidden_mclass=new Set(s.hidden_mclass));const o={mclass2count:{}};if(s.info_fields){o.info_fields={};for(const e of s.info_fields)if(e.iscategorical)o.info_fields[e.key]={value2count:{}};else if(e.isnumerical)o.info_fields[e.key]={filteredcount:0};else{if(!e.isflag)throw"unknown info type";o.info_fields[e.key]={count_yes:0,count_no:0}}}if(s.trigger_mafcovplot&&await async function(e,t,n,s){try{if(!n.track)throw"ds.track missing";const t=n.track.vcf;if(!t)throw"ds.track.vcf missing";if(n.iscustom)t.plot_mafcov={show_samplename:1};else if(!t.plot_mafcov)throw"maf-cov plot is not supported on this track";if(!e.m)throw".m{} missing";if(!t.AD)throw"vcf.AD{} missing";const r=(t.AD.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+(e.m.pos+1)+"-"+(e.m.pos+1),o=t.AD.chr2bcffile[e.m.chr];if(!o)throw"chr not in tk.AD.chr2bcffile";let i;if(await F.UE({isbcf:!0,args:["query","-r",r,"-f",fr,o],dir:t.AD.dir,callback:n=>{const[s,r,o]=D.S(n,t.AD);for(const t of r)if(t.pos==e.m.pos&&t.ref==e.m.ref&&t.alt==e.m.alt)return void(i=t)}}),!i)throw"variant not found";if(s.plotgroups=function(e,t,n){const s=[],r={name:"?",lst:[]};for(const s of e.sampledata){const o=s.AD[e.ref]||0,i=s.AD[e.alt]||0,a=o+i,l={mut:i,total:o+i,maf:0==a?0:i/a};t.plot_mafcov.show_samplename&&(l.sampleobj={name:n.cohort.termdb.q.id2sampleName(s.sampleobj.name)}),r.lst.push(l)}return s.push(r),s}(i,t,n),e.overlay_term){const t=await bs.g5({ds:n,term1_id:e.overlay_term,term1_q:e.overlay_term_q}),r=new Map;for(const e of t.lst)r.set(e.sample,e.key1);const o=(0,lr.Z)(cr),i=new Map;let a=0;for(const e of s.plotgroups)for(const t of e.lst){const e=r.get(t.sampleobj.name);if(e){const n=o(e);t.sampleobj.color=n,i.has(e)||i.set(e,{count:0,color:n,label:e}),i.get(e).count++}else a++,t.sampleobj.color=ur}if(s.categories=[],t.CTE1&&t.CTE1.name2bin)for(const e of t.CTE1.name2bin.keys()){const t=i.get(e);t&&s.categories.push(t)}else for(const[e,t]of i)s.categories.push(t);a&&s.categories.push({count:a,color:ur,label:"Unannotated"})}}catch(e){s.error=e.message||e,e.stack&&console.log(e.stack)}}(s,0,r,o),s.trigger_vcfbyrange&&(await sr(s,0,r,o),s.trigger_ld)){o.__mposset=new Set;for(const e of o.vcf.rglst)if(e.variants)for(const t of e.variants)o.__mposset.add(t.pos)}if(s.trigger_ld){o.ld={};for(const e of s.trigger_ld.tracks)await dr(e,s,0,r,o);delete o.__mposset}s.trigger_ssid_onevcfm&&await async function(e,t,n,s){if(n.iscustom)throw"custom ds not allowed";const r=n.track.vcf;if(!r)throw"ds.track.vcf missing";if(!e.m)throw"q.m missing";const o=(r.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+(e.m.pos+1)+"-"+(e.m.pos+1),i=r.chr2bcffile[e.m.chr];if(!i)throw"chr not in chr2bcffile";let a;if(await F.UE({isbcf:!0,args:["query",i,"-r",o,"-f",nr+"\t%FORMAT\n"],dir:r.dir,callback:t=>{const[n,s,o]=D.S(t,r);for(const t of s)if(t.pos==e.m.pos&&t.ref==e.m.ref&&t.alt==e.m.alt)return void(a=t)}}),!a)throw"variant not found";const l=[],c=[],u=[];for(const t of a.sampledata){if(!t.genotype)continue;const n=-1!=t.genotype.indexOf(e.m.ref),s=-1!=t.genotype.indexOf(e.m.alt);n?s?c.push(t.sampleobj.name):l.push(t.sampleobj.name):s&&u.push(t.sampleobj.name)}const f=Math.random().toString();s.ssid=f,s.groups={};const d=[];if(l.length){const e="Homozygous reference";s.groups[e]={size:l.length},d.push(e+"\t"+l.join(","))}if(c.length){const e="Heterozygous";s.groups[e]={size:c.length},d.push(e+"\t"+c.join(","))}if(u.length){const e="Homozygous alternative";s.groups[e]={size:u.length},d.push(e+"\t"+u.join(","))}await F.Sf(y().join(tr.cachedir_ssid,f),d.join("\n"))}(s,0,r,o),s.trigger_getvcfcsq&&await async function(e,t,n,s){const r=n.track.vcf;if(!r)throw"ds.track.vcf missing";if(!e.m)throw"q.m missing";const o=(r.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+(e.m.pos+1)+"-"+(e.m.pos+1),i=r.chr2bcffile[e.m.chr];if(!i)throw"chr not in chr2bcffile";await F.UE({isbcf:!0,args:["query",i,"-r",o,"-f",nr+"\\n"],dir:r.dir,callback:t=>{const[n,o,i]=D.S(t,r);for(const t of o)if(t.pos==e.m.pos&&t.ref==e.m.ref&&t.alt==e.m.alt)return void(s.csq=t.csq)}})}(s,0,r,o),n.send(o)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Pr)),Jr.post(Hr+"/mdsexpressionrank",(function(e,t){let n,s,o,i=new Set;Promise.resolve().then((()=>{if(!e.query.rglst)throw"rglst missing";if(e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>1e7)throw"Zoom in below 10 Mb to show expression rank";if(!e.query.sample)throw"sample missing";if(e.query.iscustom){if(n=Pr[e.query.genome],!n)throw"invalid genome";if(!e.query.file&&!e.query.url)throw"no file or url for expression data";s={},o={file:e.query.file,url:e.query.url,indexURL:e.query.indexURL}}else{const[t,r,i,a]=so(e.query);if(t)throw t;if(n=r,s=i,o=a,!o.samples)throw"total samples missing from server config";if(-1==o.samples.indexOf(e.query.sample))throw{nodata:1}}if(o.viewrangeupperlimit&&e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>o.viewrangeupperlimit)throw"zoom in under "+$.bplen(o.viewrangeupperlimit)+" to view data";if(e.query.levelkey){if(!e.query.levelvalue)throw"levelvalue is required when levelkey is used";if(!s.cohort||!s.cohort.annotation)throw".cohort.annotation missing from dataset"}if(!o.file){if(!o.url)throw"file or url missing";return F.d1(o.url,o.indexURL)}})).then((t=>{const n=[];for(const a of e.query.rglst)n.push(new Promise(((n,l)=>{const c=(0,x.spawn)(Gr,[o.file?y().join(r().tpmasterdir,o.file):o.url,a.chr+":"+a.start+"-"+a.stop],{cwd:t}),u=I().createInterface({input:c.stdout}),f=new Map;u.on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);if(!r.gene)return;if(!r.sample)return;if(!Number.isFinite(r.value))return;const o=n[0],a=Number.parseInt(n[1]),l=Number.parseInt(n[2]);if(r.sample==e.query.sample)return f.has(r.gene)||f.set(r.gene,{chr:o,start:a,stop:l,allvalues:[]}),f.get(r.gene).thisvalue=r.value,void(r.ase&&(f.get(r.gene).ase=r.ase));if(e.query.attributes){const t=s.cohort.annotation[r.sample];if(!t)return;for(const n of e.query.attributes)if(n.k&&n.kvalue&&n.kvalue!=t[n.k])return}i.add(r.sample),f.has(r.gene)||f.set(r.gene,{chr:o,start:a,stop:l,allvalues:[]}),f.get(r.gene).allvalues.push({value:r.value})}));const d=[];c.stderr.on("data",(e=>d.push(e))),c.on("close",(e=>{const t=d.join("");t&&!Dr(t)&&l({message:t}),n(f)}))})));return Promise.all(n)})).then((e=>{const n=[];for(const t of e)for(const[e,s]of t)null!=s.thisvalue&&(s.allvalues.sort(((e,t)=>e.value-t.value)),s.rank=vo(s.thisvalue,s.allvalues),delete s.allvalues,s.gene=e,n.push(s));t.send({result:n,samplecount:i.size})})).catch((e=>{e.stack&&console.log(e),e.nodata?t.send({nodata:1}):t.send({error:e.message?e.message:e})}))})),Jr.post(Hr+"/mdsgeneboxplot",(e=>async(t,n)=>{try{const[s,o,i,a]=function(e,t){if(!t.query.gene)throw"gene name missing";if(!t.query.chr)throw"chr missing";if(!Number.isInteger(t.query.start))throw"start missing";if(!Number.isInteger(t.query.stop))throw"stop missing";const n=e[t.query.genome];if(!n)throw"invalid genome";let s,r,o;if(t.query.iscustom){if(!t.query.file&&!t.query.url)throw"no file or url for expression data";s={},r={file:t.query.file,url:t.query.url,indexURL:t.query.indexURL}}else{if(!n.datasets)throw"genome is not equipped with datasets";if(!t.query.dslabel)throw"dslabel missing";if(s=n.datasets[t.query.dslabel],!s)throw"invalid dslabel";if(!s.queries)throw"dataset is not equipped with queries";if(!t.query.querykey)throw"querykey missing";if(r=s.queries[t.query.querykey],!r)throw"invalid querykey"}if(t.query.svcnv)if(o={},t.query.iscustom)o.dsquery={file:t.query.svcnv.file,url:t.query.svcnv.url,indexURL:t.query.svcnv.indexURL};else{t.query.svcnv.genome=t.query.genome;const e=n.datasets[t.query.svcnv.dslabel];if(!e)throw"invalid dslabel";if(!e.queries)throw"dataset is not equipped with queries";if(!t.query.svcnv.querykey)throw"querykey missing";const s=e.queries[t.query.svcnv.querykey];if(!s)throw"invalid querykey";o.ds=e,o.dsquery=s}if(t.query.getgroup)if(t.query.sampleset);else{if(!s.cohort||!s.cohort.annotation)throw"no sample annotation for getting group";if(t.query.getgroup_unannotated){if(!r.boxplotbysamplegroup)throw"dsquery.boxplotbysamplegroup{} missing when getgroup_unannotated"}else{if(!Array.isArray(t.query.getgroup))throw"getgroup should be array";for(const e of t.query.getgroup){if(!e.k)throw"k missing from one of getgroup";if(!e.kvalue)throw"kvalue missing from one of getgroup"}}}return[n,s,r,o]}(e,t);t.query.getalllst,n.send(await async function(e,t,n,s,o){n.url&&(n.dir=await F.d1(n.url,n.indexURL));s&&s.dsquery.url&&(s.dsquery.dir=await F.d1(s.dsquery.url,s.dsquery.indexURL));const i=function(e){if(!e.query.sampleset)return;const t=new Map;for(const n of e.query.sampleset)for(const e of n.samples)t.set(e,n.name);return t}(o),a=new Map,l=[],c=[];if(await F.UE({args:[n.file?y().join(r().tpmasterdir,n.file):n.url,o.query.chr+":"+o.query.start+"-"+o.query.stop],dir:n.dir,callback:e=>{const s=e.split("\t"),r=JSON.parse(s[3]);if(r.gene&&r.gene==o.query.gene&&Number.isFinite(r.value))if(o.query.getalllst)l.push({sample:r.sample,value:r.value});else if(o.query.getgroup){if(!r.sample)return;if(i)return void(o.query.getgroup_unannotated?i.has(r.sample)||c.push(r):i.get(r.sample)==o.query.getgroup[0].full&&c.push(r));const e=t.cohort.annotation[r.sample];if(o.query.getgroup_unannotated){if(!e)return void c.push(r);for(const t of n.boxplotbysamplegroup.attributes)if(null==e[t.k])return void c.push(r);return}if(!e)return;for(const t of o.query.getgroup)if(t.kvalue!=e[t.k])return;c.push(r)}else if(n.boxplotbysamplegroup&&t.cohort&&t.cohort.annotation){if(!r.sample)return;let e;e=null==o.query.index_boxplotgroupers||0==o.query.index_boxplotgroupers?n.boxplotbysamplegroup.attributes:n.boxplotbysamplegroup.additionals[o.query.index_boxplotgroupers-1].attributes;const s=t.cohort.annotation[r.sample];if(!s)return void l.push({sample:r.sample,value:r.value});const i=s[e[0].k];if(null==i)return void l.push({sample:r.sample,value:r.value});const c=[];for(let t=1;t<e.length;t++){const n=s[e[t].k];if(null==n)break;c.push(n)}c.unshift(i);const u=c.join(", ");if(!a.has(u)){const t={samples:[],attributes:[]};for(const n of e){const e=s[n.k];if(null==e)break;const r={k:n.k,kvalue:e};n.full&&(r.full=n.full,r.fullvalue=s[n.full]),t.attributes.push(r)}a.set(u,t)}a.get(u).samples.push({sample:r.sample,value:r.value})}else if(i){if(!r.sample)return;const e=i.get(r.sample);if(!e)return void l.push({sample:r.sample,value:r.value});a.has(e)||a.set(e,{samples:[],attributes:[{full:e}]}),a.get(e).samples.push({sample:r.sample,value:r.value})}else l.push({sample:r.sample,value:r.value})}}),o.query.getgroup2boxplot){c.sort(((e,t)=>e.value-t.value));const{w1:e,w2:t,p25:n,p50:s,p75:r,out:o}=F.JC(c);return{n:c.length,min:c[0].value,max:c[c.length-1].value,w1:e,w2:t,p25:n,p50:s,p75:r,out:o}}const u=[];for(const[e,t]of a)u.push({name:e,values:t.samples,attributes:t.attributes});l.length&&u.push({name:"Unannotated",values:l});c.length&&u.push({values:c});if(o.query.getalllst)return{lst:u[0].values};if(o.query.iscustom&&!i||1==u.length){if(u[0]){const e=u[0].values;return e.sort(((e,t)=>t.value-e.value)),{lst:e,max:e[0].value,min:e[e.length-1].value}}return{nodata:1}}const f=await async function(e,t){if(!t||!e.query.svcnv.useloss&&!e.query.svcnv.usegain&&!e.query.svcnv.usesv)return;let n=e.query.start,s=e.query.stop;e.query.svcnv.usesv&&Number.isInteger(e.query.svcnv.svflank)&&(n=Math.max(0,n-e.query.svcnv.svflank),s+=e.query.svcnv.svflank);const o=new Map;return await F.UE({args:[t.dsquery.file?y().join(r().tpmasterdir,t.dsquery.file):t.dsquery.url,e.query.chr+":"+n+"-"+s],dir:t.dsquery.dir,callback:t=>{const n=t.split("\t"),s=JSON.parse(n[3]);if(s.sample)if(s.chrA||s.chrB){if(!e.query.svcnv.usesv)return;o.has(s.sample)||o.set(s.sample,{}),o.get(s.sample).sv=1}else{if(!e.query.svcnv.usegain&&!e.query.svcnv.useloss)return;if(e.query.svcnv.usesv&&e.query.svcnv.svflank){const t=Number.parseInt(n[1]),s=Number.parseInt(n[2]);if(Math.max(e.query.start,t)>Math.min(e.query.stop,s))return}if(!Number.isFinite(s.value))return;if(!e.query.svcnv.usegain&&s.value>0)return;if(!e.query.svcnv.useloss&&s.value<0)return;if(e.query.svcnv.valueCutoff&&Math.abs(s.value)<e.query.svcnv.valueCutoff)return;if(e.query.svcnv.bplengthUpperLimit&&Number.parseInt(n[2])-Number.parseInt(n[1])>e.query.svcnv.bplengthUpperLimit)return;o.has(s.sample)||o.set(s.sample,{}),s.value>0?o.get(s.sample).gain=1:s.value<0&&(o.get(s.sample).loss=1)}}}),o}(o,s);if(o.query.getgroup){if(u[0]){const e=u[0].values;if(e.sort(((e,t)=>t.value-e.value)),f)for(const t of e){const e=f.get(t.sample);if(e)for(const n in e)t[n]=e[n]}return{lst:e,max:e[0].value,min:e[e.length-1].value}}return{nodata:1}}const d=[];let p=null,m=null;for(const e of u){e.values.sort(((e,t)=>e.value-t.value));const t=e.values.length;null==p?(p=e.values[0].value,m=e.values[t-1].value):(p=Math.min(p,e.values[0].value),m=Math.max(m,e.values[t-1].value));const{w1:n,w2:s,p25:r,p50:i,p75:a,out:l}=F.JC(e.values),c=[{isall:1,w1:n,w2:s,p25:r,p50:i,p75:a,out:l}];if(f){if(o.query.svcnv.usegain){const t=e.values.filter((e=>f.has(e.sample)&&f.get(e.sample).gain));if(t.length){const{w1:e,w2:n,p25:s,p50:r,p75:o,out:i}=F.JC(t);c.push({iscnvgain:1,samplecount:t.length,w1:e,w2:n,p25:s,p50:r,p75:o,out:i})}}if(o.query.svcnv.useloss){const t=e.values.filter((e=>f.has(e.sample)&&f.get(e.sample).loss));if(t.length){const{w1:e,w2:n,p25:s,p50:r,p75:o,out:i}=F.JC(t);c.push({iscnvloss:1,samplecount:t.length,w1:e,w2:n,p25:s,p50:r,p75:o,out:i})}}if(o.query.svcnv.usesv){const t=e.values.filter((e=>f.has(e.sample)&&f.get(e.sample).sv));if(t.length){const{w1:e,w2:n,p25:s,p50:r,p75:o,out:i}=F.JC(t);c.push({issv:1,samplecount:t.length,w1:e,w2:n,p25:s,p50:r,p75:o,out:i})}}}d.push({name:e.name+" ("+e.values.length+")",boxplots:c,attributes:e.attributes})}return d.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)),{groups:d,min:p,max:m}}(0,o,i,a,t))}catch(e){e.stack&&console.log(e),n.send({error:e.message||e})}})(Pr)),Jr.post(Hr+"/mdsgenevalueonesample",(async function(e,t){const n=e.query;try{if(!n.sample)throw".sample missing";if(!n.genes)throw".genes[] missing";let s,o,i;if(e.query.iscustom){if(s=Pr[n.genome],!s)throw"invalid genome";if(!n.file&&!n.url)throw"no file or url for expression data";o={},i={file:n.file,url:n.url,indexURL:n.indexURL}}else{const[e,t,r,a]=so(n);if(e)throw e;s=t,o=r,i=a}const a=i.file?null:await F.d1(i.url,i.indexURL),l={};let c=!0;for(const e of n.genes){let t;await F.UE({args:[i.file?y().join(r().tpmasterdir,i.file):i.url,e.chr+":"+e.start+"-"+e.stop],dir:a,callback:s=>{const r=s.split("\t");if(!r[3])return;const o=JSON.parse(r[3]);o.gene==e.gene&&o.sample==n.sample&&(t=o.value)}}),Number.isFinite(t)&&(l[e.gene]=t,c=!1)}c?t.send({nodata:1}):t.send({result:l})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/vcf",(async function(e,t){try{const[n,s,r]=F.ZX(e);if(n)throw n;const o=r?await F.d1(s,e.query.indexURL):null;if(!e.query.rglst)throw"rglst missing";const i=[];for(const t of e.query.rglst)await F.UE({args:[s,t.chr+":"+t.start+"-"+t.stop],dir:o,callback:e=>i.push(e)});t.send({linestr:i.join("\n")})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.get(Hr+"/vcfheader",(async function(e,t){try{if(!e.query.genome)throw"genome missing";const n=Pr[e.query.genome];if(!n)throw"invalid genome";const[s,r,o]=F.ZX(e);if(s)throw s;const i=o?await F.d1(r,e.query.indexURL):null;t.send({metastr:(await F.ZD(r,i)).join("\n"),nochr:await F.Jy(r,i,n)})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/translategm",(async function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"invalid genome";const s=e.query.gm;if(!s)throw"missing gm{}";if(!s.chr)throw"gm.chr missing";if(!s.start)throw"gm.start missing";if(!Number.isInteger(s.start))throw"gm.start not integer";if(!s.stop)throw"gm.stop missing";if(!Number.isInteger(s.stop))throw"gm.stop not integer";const r=await F.Kf(n,s.chr+":"+(s.start+1)+"-"+s.stop),o=$.fasta2gmframecheck(s,r);t.send({frame:o})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.post(Hr+"/samplematrix",(function(e,t){Promise.resolve().then((()=>{const t=Pr[e.query.genome];if(!t)throw"invalid genome";let n,s;if(e.query.iscustom){if(!e.query.querykey2tracks)throw"querykey2tracks{} missing for custom dataset";n={queries:{}};for(const t in e.query.querykey2tracks){const s=e.query.querykey2tracks[t];if(!s.type)throw'missing "type" for a data track';if(s.type==$.tkt.mdsvcf){const s=e.query.querykey2tracks[t];s.type=$.mdsvcftype.vcf,n.queries[t]={type:$.tkt.mdsvcf,info:s.info,tracks:[s]}}else if(s.type==$.tkt.mdssvcnv)n.queries[t]=s;else{if(s.type!=$.tkt.mdsexpressionrank)throw"unknown type of data track: "+s.type;n.queries[t]=s}}}else{if(!t.datasets)throw"genome is not equipped with datasets";if(!e.query.dslabel)throw"dslabel missing";if(n=t.datasets[e.query.dslabel],!n)throw"invalid dslabel";if(!n.queries)throw"dataset is not equipped with queries"}if(e.query.sampleset)s=new Set(e.query.sampleset);else if(e.query.limitsamplebyeitherannotation){if(!n.cohort)throw"limitsamplebyeitherannotation but no cohort in ds";if(!n.cohort.annotation)throw"limitsamplebyeitherannotation but no cohort.annotation in ds";s=new Set;for(const t in n.cohort.annotation){const r=n.cohort.annotation[t];for(const n of e.query.limitsamplebyeitherannotation)if(r[n.key]==n.value){s.add(t);break}}}const r=[];for(const t of e.query.features){let e,o=[];if(t.querykey){if(!n.queries)throw"using querykey for a feature but no ds.queries";if(e=n.queries[t.querykey],!e)throw"unknown dsquery by key "+t.querykey}else if(t.querykeylst){if(!n.queries)throw"using querykeylst for a feature but no ds.queries";for(const e of t.querykeylst){const t=n.queries[e];if(!t)throw'unknown key "'+e+'" from querykeylst';o.push(t)}if(0==o.length)throw"no valid keys in querykeylst"}else if(!t.issampleattribute)throw"unknown way to query a feature";if(t.isgenevalue){const[o,i]=_o(t,n,e,s);if(o)throw"error with isgenevalue: "+o;r.push(i)}else if(t.iscnv){const[o,i]=ko(t,n,e,s);if(o)throw"error with iscnv: "+o;r.push(i)}else if(t.isloh){const[o,i]=qo(t,n,e,s);if(o)throw"error with isloh: "+o;r.push(i)}else if(t.isvcf){const[o,i]=Co(t,n,e,s);if(o)throw"error with isvcf: "+o;r.push(i)}else if(t.isitd){const[o,i]=xo(t,n,e,s);if(o)throw"error with isitd: "+o;r.push(i)}else if(t.issvfusion){const[o,i]=No(t,n,e,s);if(o)throw"error with issvfusion: "+o;r.push(i)}else if(t.issvcnv){const[o,i]=So(t,n,e,s);if(o)throw"error with issvcnv: "+o;r.push(i)}else if(t.ismutation){const[e,i]=Ao(t,n,o,s);if(e)throw"error with ismutation: "+e;r.push(i)}else{if(!t.issampleattribute)throw"unknown type of feature";{const[e,o]=wo(t,n,s);if(e)throw"error with issampleattribute: "+e;r.push(o)}}}return Promise.all(r)})).then((e=>{t.send({results:e})})).catch((e=>{t.send({error:"string"==typeof e?e:e.message}),e.stack&&console.error(e.stack)}))})),Jr.get(Hr+"/mdssamplescatterplot",(async function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"invalid genome";const s=n.datasets[e.query.dslabel];if(!s)throw"invalid dataset";if(!s.cohort)throw"no cohort for dataset";if(!s.cohort.annotation)throw"cohort.annotation missing for dataset";const r=s.cohort.scatterplot;if(!r)throw"scatterplot not supported for this dataset";const o=[];for(const t in s.cohort.annotation){const n=s.cohort.annotation[t];if(e.query.subsetkey&&n[e.query.subsetkey]!=e.query.subsetvalue)continue;const i=n[r.x.attribute];if(!Number.isFinite(i))continue;const a=n[r.y.attribute];Number.isFinite(a)&&o.push({sample:t,x:i,y:a,s:n})}t.send({colorbyattributes:r.colorbyattributes,colorbygeneexpression:r.colorbygeneexpression,querykey:r.querykey,dots:o,tracks:r.tracks})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/mdssamplesignature",(function(e,t){try{const n=e.query;if(!n.sample)throw".sample missing";const s=Pr[n.genome];if(!s)throw"invalid genome";const r=s.datasets[n.dslabel];if(!r)throw"invalid dataset";if(!r.cohort)throw"no cohort for dataset";if(!r.cohort.mutation_signature)throw"no mutation_signature for cohort";const o=[];for(const e in r.cohort.mutation_signature.sets){const t=r.cohort.mutation_signature.sets[e];if(!t.samples)continue;const s=t.samples.map.get(n.sample);if(!s)continue;const i=[];for(const e in t.signatures)s[e]&&i.push({k:e,v:s[e]});i.length&&o.push({key:e,valuename:t.samples.valuename,annotation:i.sort(((e,t)=>t.v-e.v))})}t.send({lst:o})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/mdssurvivalplot",function(e){return async(t,n)=>{try{const s=t.query,r=e[s.genome];if(!r)throw"invalid genome";const o=r.datasets[s.dslabel];if(!o)throw"invalid dataset";if(!o.cohort)throw"no cohort for dataset";if(!o.cohort.annotation)throw"cohort.annotation missing for dataset";const i=o.cohort.survivalplot;if(!i)throw"survivalplot not supported for this dataset";if(!i.plots)throw".plots{} missing";if(t.query.init)return void n.send(i.init);if(!s.type)throw".type missing";const a=i.plots[s.type];if(!a)throw"unknown plot type: "+s.type;const l=function(e,t,n){if(!e.samplerule)throw".samplerule missing";if(!e.samplerule.full)throw".samplerule.full missing";const s=[];if(e.samplerule.full.byattr){const n=e.samplerule.full.key;if(!n)throw"key missing from samplerule.full{}";const r=e.samplerule.full.value;if(null==r)throw"value missing from samplerule.full{}";for(const e in t.cohort.annotation){const o=t.cohort.annotation[e];o[n]==r&&s.push({name:e,o})}}else if(e.samplerule.full.useall)for(const e in t.cohort.annotation){const n=t.cohort.annotation[e];s.push({name:e,o:n})}else{if(!e.samplerule.full.usesampleset)throw"unknown rule for samplerule.full";{const n=e.samplerule.full.sampleset;for(const e in n){const r=n[e],o=t.cohort.annotation[r];null!=o&&s.push({name:r,o})}}}const r=[];for(const e of s)Number.isFinite(e.o[n.serialtimekey])&&(e.serialtime=e.o[n.serialtimekey],e.censored=e.o[n.iscensoredkey],r.push(e));if(0==r.length)throw"no samples found for full set";return r}(s,o,a),c=await async function(e,t,n,s){if(t.samplerule.mutated_sets){const n=new Set(e.map((e=>e.name))),s=t.samplerule.mutated_sets.reduce(((t,s)=>{const r=new Set(s.samplenames);s.lst=e.filter((e=>r.has(e.name)));for(const e of s.samplenames)n.delete(e);return delete s.samplenames,t.push(s),t}),[]);return s.push({name:"No mutation (n="+n.size+")",lst:e.filter((e=>n.has(e.name))),is_notmutated:!0}),s}const r=t.samplerule.set;if(!r)return[{name:"All",lst:e}];if(r.geneexpression){if(!r.gene)throw".gene missing from samplerule.set";if(!r.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(r.start))throw".start not integer from samplerule.set";if(!Number.isInteger(r.stop))throw".start not integer from samplerule.set";if(r.bymedian)return await async function(e,t,n,s){const r=t.samplerule.set,[o,i]=await Cr(e,t,n),a=Math.ceil(i.length/2),l=i[a-1].genevalue;return[{name:r.gene+" "+o.datatype+" below median (n="+a+", value<"+l+")",lst:i.slice(0,a)},{name:r.gene+" "+o.datatype+" above median (n="+(i.length-a)+", value>="+l+")",lst:i.slice(a,i.length)}]}(e,t,n);if(r.byquartile)return await async function(e,t,n,s){const r=t.samplerule.set,[o,i]=await Cr(e,t,n),a=Math.ceil(.25*i.length),l=Math.ceil(.5*i.length),c=Math.ceil(.75*i.length),u=i[a-1].genevalue,f=i[l-1].genevalue,d=i[c-1].genevalue;return[{name:r.gene+" "+o.datatype+" from 1st quartile (n="+a+", value<"+u+")",lst:i.slice(0,a),isfirstquartile:!0},{name:r.gene+" "+o.datatype+" from 2nd quartile (n="+(l-a)+", "+u+"<=value<"+f+")",lst:i.slice(a,l)},{name:r.gene+" "+o.datatype+" from 3rd quartile (n="+(c-l)+", "+f+"<=value<"+d+")",lst:i.slice(l,c)},{name:r.gene+" "+o.datatype+" from 4th quartile (n="+(i.length-c)+", value>="+d+")",lst:i.slice(c,i.length),isfourthquartile:!0}]}(e,t,n)}if(r.mutation){if(!r.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(r.start))throw".start not integer from samplerule.set";if(!Number.isInteger(r.stop))throw".start not integer from samplerule.set";return await async function(e,t,n){const s=t.samplerule.set;if(s.samples_snvindel=new Set,s.samples_cnv=new Set,s.samples_loh=new Set,s.samples_sv=new Set,s.samples_fusion=new Set,s.samples_itd=new Set,s.cnv&&!s.snvindel&&!s.loh&&!s.sv&&!s.fusion&&!s.itd){const[s,r]=await Nr(e,t,n,!0),o=[],i=[],a=[];for(const t of e)s.has(t.name)?o.push(t):r.has(t.name)?i.push(t):a.push(t);const l=[];return i.length&&l.push({name:"Copy number loss (n="+i.length+")",lst:i}),o.length&&l.push({name:"Copy number gain (n="+o.length+")",lst:o}),a.length&&l.push({name:"No copy number variation (n="+a.length+")",lst:a}),l}const r=await Nr(e,t,n),o=[];for(const t of e)r.find((e=>e.name==t.name))||o.push(t);const i=[];r.length&&i.push({name:"With mutation (n="+r.length+")",lst:r});o.length&&i.push({name:"No mutation (n="+o.length+")",lst:o});return i}(e,t,n)}throw"unknown rule for samplerule.set{}"}(l,s,o);let u;c.length>1&&(u=await xr(c)),await async function(e,t){if(!e.samplerule.mutated_sets)return;const n=t.find((e=>e.is_notmutated));if(!n)return;for(const e of t){if(e.is_notmutated)continue;const t=await xr([e,n]);e.pvalue=t}}(s,c),await async function(e,t){if(!e.samplerule.set)return;if(!e.samplerule.set.geneexpression)return;if(!e.samplerule.set.byquartile)return;if(4!=t.length)return;if(e.samplerule.set.against1st){for(let e=1;e<4;e++)t[e].pvalue=await xr([t[0],t[e]]);return}if(e.samplerule.set.against4th){for(let e=0;e<3;e++)t[e].pvalue=await xr([t[e],t[3]]);return}}(s,c);for(const e of c)jr(e),delete e.lst;const f={samplesets:c,pvalue:u};s.samplerule.set&&s.samplerule.set.mutation&&(f.count_snvindel=s.samplerule.set.samples_snvindel.size,f.count_cnv=s.samplerule.set.samples_cnv.size,f.count_loh=s.samplerule.set.samples_loh.size,f.count_sv=s.samplerule.set.samples_sv.size,f.count_fusion=s.samplerule.set.samples_fusion.size,f.count_itd=s.samplerule.set.samples_itd.size),n.send(f)}catch(e){e.stack&&console.error(e.stack),n.send({error:e.message||e})}}}(Pr)),Jr.post(Hr+"/fimo",function(e){return async(t,n)=>{try{const s=t.query;if(!s.m)throw"no mutation";if(!s.m.chr)throw"mutation chr missing";if(!Number.isInteger(s.m.pos))throw"mutation position is not integer";if(!s.m.ref)throw"mutation ref allele missing";if(!s.m.alt)throw"mutation alt allele missing";const r=e[s.genome];if(!r)throw"invalid genome";if(!r.fimo_motif)throw"motif finding not supported on this genome";const o=await async function(e,t){const n=e.m.pos-e.flankspan,s=e.m.pos+e.flankspan,r=await F.Kf(t,e.m.chr+":"+n+"-"+s);!function(e,t,n){if(!e.m.ref)return;if("-"==e.m.ref)return;const s=n.split("\n").slice(1).join("").toUpperCase(),r=s.substring(e.m.pos-t,e.m.pos-t+e.m.ref.length);if(r==e.m.ref.toUpperCase())return;if(common.reversecompliment(r)==e.m.ref.toUpperCase())e.m.ref=r,"-"!=e.m.alt&&(e.m.alt=common.reversecompliment(e.m.alt))}(e,n,r);const o=await _r(e,t,r),i=new Map;for(const e of o)e.pvalue_ref=e.pvalue,delete e.pvalue,e.logpvalue_ref=e.logpvalue,delete e.logpvalue,i.has(e.name)||i.set(e.name,[]),i.get(e.name).push(e);const a=function(e,t,n,s){const r=s.split("\n"),o=r.slice(1).join("");return r[0]+"\n"+o.substr(0,e.pos-t)+("-"==e.alt?"":e.alt)+o.substr(e.pos-t+("-"==e.ref?0:e.ref.length))}(e.m,n,0,r),l=await _r(e,t,a);for(const e of l){e.pvalue_alt=e.pvalue,delete e.pvalue,e.logpvalue_alt=e.logpvalue,delete e.logpvalue,i.has(e.name)||i.set(e.name,[]);let t=!0;for(const n of i.get(e.name))if(null!=n.logpvalue_ref&&n.strand==e.strand&&Math.abs(e.start-n.start)<=2&&Math.abs(e.stop-n.stop)<=2){n.pvalue_alt=e.pvalue_alt,n.logpvalue_alt=e.logpvalue_alt,n.logpvaluediff=e.logpvalue_alt-n.logpvalue_ref,n.logpvaluediff>0?n.gain=!0:n.loss=!0,t=!1;break}t&&i.get(e.name).push(e)}let c=0,u=0;const f=[];for(const t of i.values())for(const n of t)null==n.logpvaluediff&&(null==n.pvalue_ref?(n.gain=!0,n.logpvaluediff=n.logpvalue_alt):null==n.pvalue_alt&&(n.loss=!0,n.logpvaluediff=-n.logpvalue_ref)),null!=e.minabslogp&&Math.abs(n.logpvaluediff)<e.minabslogp||(n.logpvaluediff>0?c=Math.max(c,n.logpvaluediff):u=Math.min(u,n.logpvaluediff),f.push(n));return{items:f,valuemin:u,valuemax:c,refstart:n,refstop:s,refseq:r.split("\n").slice(1).join("")}}(s,r);n.send(o)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Pr)),Jr.all(Hr+"/termdb",we.TO(Pr)),Jr.all(Hr+"/termdb-barsql",Ae.TO(Pr)),Jr.post(Hr+"/singlecell",function(e){return async(t,n)=>{try{const s=t.query,r=e[s.genome];if(!r)throw"invalid genome";if(s.getpcd)return void await async function(e,t){const n={},s=await async function(e,t){if(!e.textfile)throw".textfile missing";{const[t,n,s]=F.ZX({query:{file:e.textfile}});if(t)throw".textfile error: "+t;if(!s){if(await F.yE(n))throw"file not exist: "+e.textfile;if(await F.t7(n))throw"file not readable: "+e.textfile}e.textfile=n}let n,s,r,o,i;if(e.getpcd.category_autocolor){const t=e.getpcd.values_count&&e.getpcd.values_count<=10?cr:gr;n=lr.Z(t),r={},o={}}else if(e.getpcd.category_customcolor){const t=lr.Z(gr);a=e.getpcd.cat_values,l=t,n=e=>{let t=!1;for(const n of a)if(n.value==e)return t=!0,n.color;if(!t)return l(e)},r={},o={},i={}}else if(e.getpcd.gene_expression){const n=e.getpcd.gene_expression;if(!n.file)throw"gene_expression.file missing";{const[e,t,s]=F.ZX({query:{file:n.file}});if(e)throw e;n.file=t}if(!Number.isInteger(n.barcodecolumnidx))throw"gene_expression.barcodecolumnidx missing";if(!n.chr)throw"gene_expression.chr missing";if(!n.start)throw"gene_expression.start missing";if(!n.stop)throw"gene_expression.stop missing";if(!n.genename)throw"gene_expression.genename missing";if(!n.autoscale)throw"gene_expression: unknown scaling method";if(!n.color_min)throw"gene_expression.color_min missing at autoscale";if(!n.color_max)throw"gene_expression.color_max missing at autoscale";const r=(n.nochr?n.chr.replace("chr",""):n.chr)+":"+n.start+"-"+n.stop,o=new Map;s=new Map;let i=0,a=0;if(t.numbercellwithgeneexp=0,t.numbercelltotal=0,await F.UE({args:[n.file,r],callback:e=>{const s=JSON.parse(e.split("\t")[3]);s.gene==n.genename&&Number.isFinite(s.value)&&(t.numbercellwithgeneexp++,n.autoscale&&(i=Math.min(i,s.value),a=Math.max(a,s.value)),o.set(s.sample,s.value))}}),n.autoscale){t.minexpvalue=i,t.maxexpvalue=a;const e=Pe.ZP(n.color_min,n.color_max);for(const[t,n]of o){const r=ke.ZP(e((n-i)/(a-i)));s.set(t,Number.parseInt(br(r.r,r.g,r.b),16))}}}var a,l;return new Promise(((i,a)=>{const l=[],c=I().createInterface({input:h().createReadStream(e.textfile)});let u=!0,f=0,d=0;c.on("line",(i=>{if(u)return void(u=!1);const a=i.split(e.delimiter),c=[];for(const t of e.getpcd.coord)c.push(a[t]),f=Math.max(f,a[t]),d=Math.min(d,a[t]);if(2==e.getpcd.coord.length&&c.push("0"),n){const t=a[e.getpcd.category_index],s=n(t);if(e.hidden_types.includes(t))if(e.background_color){const t=ke.ZP(e.background_color),n=Number.parseInt(br(t.r,t.g,t.b),16);c.push(n)}else c.push(16777215);else c.push(Number.parseInt(s.slice(1),16));r&&(r[t]=s),o&&(o[t]=t in o?o[t]+1:1)}else if(s){t.numbercelltotal++;const n=a[e.getpcd.gene_expression.barcodecolumnidx];let r=s.get(n);if(void 0===r)if(e.getpcd.gene_expression.color_no_exp){const t=ke.ZP(e.getpcd.gene_expression.color_no_exp);r=Number.parseInt(br(t.r,t.g,t.b),16)}else r="2894892";c.push(r)}l.push(c.join(" "))})),c.on("close",(()=>{r&&(e.getpcd.category_customorder&&(r=function(e,t){let n={};const s=Object.keys(e).length;for(var r=1;r<=s;r++){const s=t.find((e=>{if(e.order==r)return e.value}));s&&(n[s.value]=e[s.value])}for(const s of t)s.order||(n[s.value]=e[s.value]);for(const s in e){t.find((e=>{if(e.value==JSON.stringify(s))return!0}))||(n[s]=e[s])}return n}(r,e.getpcd.cat_values)),t.category2color=r,t.categorycount=o),t.data_sphere_r=Math.max(Math.abs(f),Math.abs(d)),i(l)}))}))}(e,n),r="# .PCD v.7 - Point Cloud Data file format\nVERSION .7\nFIELDS x y z rgb\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH 1200\nHEIGHT 800\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS 960000\nDATA ascii\n";n.pcddata=r+s.join("\n"),t.send(n)}(s,n);if(s.getgeneboxplot)return void await async function(e,t,n){const s=e.getgeneboxplot,r=e.getgeneboxplot.values_count&&e.getgeneboxplot.values_count<=10?lr.Z(cr):lr.Z(gr);if(!s.expfile)throw"getgeneboxplot.expfile missing";{const[e,t,n]=F.ZX({query:{file:s.expfile}});if(e)throw"getgeneboxplot.expfile error: "+e;s.expfile=t}if(!s.chr)throw"getgeneboxplot.chr missing";if(!s.start)throw"getgeneboxplot.start missing";if(!s.stop)throw"getgeneboxplot.stop missing";if(!s.genename)throw"getgeneboxplot.genename missing";const o=await vr(s),i=(s.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop;let a=0,l=0;await F.UE({args:[s.expfile,i],callback:e=>{const t=JSON.parse(e.split("\t")[3]);if(t.gene!=s.genename)return;if(!t.sample)return;if(!Number.isFinite(t.value))return;const n=o.get(t.sample);n&&(n.expvalue=t.value,a=Math.min(a,t.value),l=Math.max(l,t.value))}});const c=new Map;for(const[e,t]of o)c.has(t.category)||c.set(t.category,[]),s.exclude_cells&&0==parseInt(t.expvalue)||c.get(t.category).push({value:t.expvalue});const u=[],f=(d=rs.Z().domain([a,l]).ticks(20),e=>{const t=[];for(let e=1;e<d.length;e++)t.push(0);for(const n of e)for(let e=1;e<d.length;e++)if(n.value<=d[e]){t[e-1]++;break}return t});var d;for(const[e,t]of c){t.sort(((e,t)=>e.value-t.value));const n=F.JC(t);delete n.out;const s=r(e);n.category=e,n.color=s,n.numberofcells=t.length,n.density=f(t),u.push(n)}let p=[];if(e.getgeneboxplot.cat_values){const t=Object.keys(e.getgeneboxplot.cat_values).length;for(var m=1;m<=t;m++){const t=e.getgeneboxplot.cat_values.find((e=>{if(e.order==m)return e.value}));t&&p.push(u.filter((e=>e.category==t.value))[0])}for(const t of e.getgeneboxplot.cat_values)t.order||p.push(u.filter((e=>e.category==t.value))[0]);for(const t of u){e.getgeneboxplot.cat_values.find((e=>{if(e.value==t.category)return!0}))||p.push(t)}for(const t of p){const n=e.getgeneboxplot.cat_values.find((e=>{if(e.value==t.category)return e}));n&&n.color&&(t.color=n.color)}}else p=u;n.send({boxplots:p,minexpvalue:a,maxexpvalue:l})}(s,0,n);if(s.getheatmap)return void await async function(e,t,n){const s=e.getheatmap,r=[];if(!s.expfile)throw"getgeneboxplot.expfile missing";{const[e,t,n]=F.ZX({query:{file:s.expfile}});if(e)throw"getgeneboxplot.expfile error: "+e;s.expfile=t}s.gene_list.forEach((e=>{if(!e.chr)throw"getgeneboxplot.chr missing";if(!e.start)throw"getgeneboxplot.start missing";if(!e.stop)throw"getgeneboxplot.stop missing";if(!e.gene)throw"getgeneboxplot.genename missing"}));const o=await vr(s);for(const e of s.gene_list){const t=(e.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;let n=0,i=0;const a=e.gene;await F.UE({args:[s.expfile,t],callback:t=>{const s=JSON.parse(t.split("\t")[3]);if(s.gene.toUpperCase()!==e.gene.toUpperCase())return;if(!s.sample)return;if(!Number.isFinite(s.value))return;const r=o.get(s.sample);r&&(r.expvalue=s.value,n=Math.min(n,s.value),i=Math.max(i,s.value))}});const l=new Map;for(const[e,t]of o)l.has(t.category)||l.set(t.category,[]),l.get(t.category).push({value:t.expvalue});const c=[];for(const[e,t]of l){let n=0;for(const e of t)n+=e.value;const s=t.length,r=(n/s).toFixed(3);c.push({category:e,mean:r,numberofcells:s})}r.push({genename:a,heatmap:c})}n.send({gene_heatmap:r})}(s,0,n)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Pr)),Jr.post(Hr+"/massSession",(async function(e,t){try{const n=e.body.__sessionFor__,{filename:s,route:o,dslabel:i,embedder:a}=n||{};let l;if(s){const t={headers:e.headers,query:n};if(l=mr.i.getPayloadFromHeaderAuth(t,o),!l.email)throw"invalid credentials: no jwt.email";if(l.dslabel!=i||l.route!=o||l.embedder!=a)throw"invalid credentials: mismatched payload";delete e.body.__sessionFor__}const c=s||function(){const e=[];for(;e.length<15;){const t=46+Math.floor(80*Math.random());(t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122)&&e.push(String.fromCharCode(t))}return e.join("")}(),u=JSON.stringify(e.body),f=s?hr(n,l):r().cachedir_massSession;await h().promises.access(f).then((()=>!0)).catch((()=>!1))||h().mkdirSync(f,{recursive:!0}),await F.Sf(y().join(f,c),u),t.send({id:c})}catch(e){t.send({error:e.message||e})}})),Jr.get(Hr+"/massSession",(async function(e,t){try{const n=e.query.id;if(!n)throw"session id missing";const{route:s,dslabel:o,embedder:i}=e.query,a=e.query.route?mr.i.getPayloadFromHeaderAuth(e,e.query.route):null,l=e.query.route?hr(e.query,a):r().cachedir_massSession,c=y().join(l,n);let u;try{u=(await h().promises.stat(c)).birthtime}catch(e){throw"invalid session"}const f=await F.b5(c),d=JSON.parse(f);if(e.query.route)return void t.send({state:d});const p=new Date,m=new Date(u),g=r().features.massSessionDuration||30,b=g-Math.round((p.getTime()-m.getTime())/864e5);t.send({state:d,sessionDaysLeft:b,massSessionDuration:g})}catch(e){t.send({error:e.message||e})}})),Jr.delete(Hr+"/massSession",(async function(e,t){try{const n=e.query.ids;if(!n)throw"session ids[] missing";const{route:s,dslabel:o,embedder:i}=e.query,a=e.query.route?mr.i.getPayloadFromHeaderAuth(e,e.query.route):null;if(!a)throw"missing credentials";const l=e.query.route?hr(e.query,a):r().cachedir_massSession,c=[];for(const e of n){const t=y().join(l,e);h().unlink(t,(e=>{if(e)throw c.push(e),e}))}c.length||t.send({status:"ok"})}catch(e){t.send({error:e.message||e})}})),Jr.get(Hr+"/sessionIds",(async function(e,t){try{const{filename:n,route:s,dslabel:r,embedder:o}=e.query,i=mr.i.getPayloadFromHeaderAuth(e,s);if(!i.email)throw"invalid credentials: no jwt.email";if(i.dslabel!=r||i.route!=s||i.embedder!=o)throw"invalid credentials: mismatched payload";const a=hr(e.query,i);if(!await h().promises.access(a).then((()=>!0)).catch((()=>!1)))return void t.send({status:"ok",sessionIds:[]});const l=await h().promises.readdir(a);t.send({status:"ok",sessionIds:l})}catch(e){t.status(401),t.send({error:e.message||e})}})),Jr.get(Hr+"/isoformbycoord",(async function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"invalid genome";if(!e.query.chr)throw"chr missing";const s=Number(e.query.pos);if(!Number.isInteger(s))throw"pos must be positive integer";const o=n.tracks.find((e=>e.__isgene));o||reject("no gene track");const i=[];await F.UE({args:[y().join(r().tpmasterdir,o.file),e.query.chr+":"+s+"-"+s],callback:e=>{const t=e.split("\t")[3];if(!t)return;const s=JSON.parse(t);if(!s.isoform)return;const r={isoform:s.isoform},o=n.genedb.getjsonbyisoform.get(s.isoform);o&&(r.name=JSON.parse(o.genemodel).name,r.isdefault=o.isdefault),i.push(r)}}),t.send({lst:i})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/ase",(async function(e,t){const n=e.query,s=3e6,o=5e5;try{const e=Pr[n.genome];if(!e)throw"invalid genome";if(!n.samplename)throw"samplename missing";if(!n.chr)throw"no chr";if(!n.start||!n.stop)throw"no start/stop";if(!n.rnabarheight)throw"no rnabarheight";if(!n.dnabarheight)throw"no dnabarheight";if(!Number.isInteger(n.barypad))throw"invalid barypad";if(n.rnamax&&!Number.isFinite(n.rnamax))throw"invalid value for rnamax";if(!n.checkrnabam)throw".checkrnabam{} missing";const i=fo(n.checkrnabam);if(i)throw i;if(n.refcolor||(n.refcolor="blue"),n.altcolor||(n.altcolor="red"),!e.tracks)throw"genome.tracks[] missing";const a=e.tracks.find((e=>e.__isgene));if(!a)throw"no gene track from this genome";await async function(e,t){if(e.rnabamfile)e.rnabamfile=y().join(r().tpmasterdir,e.rnabamfile);else{if(!e.rnabamurl)throw"no file or url for rna bam";e.rnabamurl_dir=await F.d1(e.rnabamurl,e.rnabamindexURL||e.rnabamurl+".bai")}if(e.rnabam_nochr=await F.Dp(e.rnabamfile||e.rnabamurl,t,e.rnabamurl_dir),e.vcffile)e.vcffile=y().join(r().tpmasterdir,e.vcffile);else{if(!e.vcfurl)throw"no file or url for vcf";e.vcfurl_dir=await F.d1(e.vcfurl,e.vcfindexURL)}e.vcf_nochr=await F.Jy(e.vcffile||e.vcfurl,e.vcfurl_dir,t)}(n,e);const l=await go(e,a,n.chr,n.start,n.stop),c={};if(n.stop-n.start<s)for(const[e,t]of l){const e={file:n.rnabamfile,url:n.rnabamurl,dir:n.rnabamurl_dir,nochr:n.rnabam_nochr};let s;s=n.rnabamispairedend?await io(e,n.chr,t):await oo(e,n.chr,t),t.fpkm=1e9*s/(n.rnabamtotalreads*t.exonlength)}else c.fpkmrangelimit=s;const[u,f,d,p]=function(e,t){let n=e.start,s=e.stop;for(const[e,r]of t)n=Math.min(n,r.start),s=Math.max(s,r.stop);const r=e.start,o=e.stop;return[n,s,r,o]}(n,l),m=await async function(e,t,n,s,r){const o=await bo(e.vcffile||e.vcfurl,e.vcfurl_dir),[i,a,l,c]=D.e(o);if(c)throw c;const u={info:i,format:a,samples:l},f=await yo(e.vcffile||e.vcfurl,(e.vcf_nochr?e.chr.replace("chr",""):e.chr)+":"+s+"-"+r,e.vcfurl_dir),d=[];for(const t of f||[]){const[n,s,r]=D.S(t,u);for(const t of s){if(!$.basecolor[t.ref]||!$.basecolor[t.alt])continue;if(!t.sampledata)continue;const n=ho(t,e.samplename,e.checkrnabam);n&&d.push(n)}}const p=[];for(const e of d)for(const[t,s]of n)if(e.pos>=s.start&&e.pos<=s.stop){p.push(e);break}return p}(n,0,l,u,f);for(const e of m)e.rnacount={nocoverage:1};let g,b;p-d>=o?c.covplotrangelimit=o:(n.rnamax?g=n.rnamax:(g=await async function(e,t,n){let s=0;return await F.UE({isbam:!0,args:["depth","-r",(e.rnabam_nochr?e.chr.replace("chr",""):e.chr)+":"+(t+1)+"-"+(n+1),"-g","DUP",e.rnabamurl||e.rnabamfile],dir:e.rnabamurl_dir,callback:e=>{const t=e.split("\t");if(3!=t.length)return;const n=Number.parseInt(t[2]);Number.isInteger(n)&&(s=Math.max(s,n))}}),s}(n,d,p),c.rnamax=g),b=await async function(e,t,n,s,r){const o=new Map;for(const e of s)e.dnacount.ishet&&e.pos>=t&&e.pos<=n&&o.set(e.pos,e);const i=(0,S.createCanvas)(e.width*e.devicePixelRatio,(e.rnabarheight+e.barypad+e.dnabarheight)*e.devicePixelRatio),a=i.getContext("2d");e.devicePixelRatio>1&&a.scale(e.devicePixelRatio,e.devicePixelRatio);let l,c,u=!1;n-t<=e.width?(u=!0,l=1,c=e.width/(n-t),a.lineWidth=c):(c=1,l=(n-t)/e.width);return await F.UE({isbam:!0,args:["depth","-r",(e.rnabam_nochr?e.chr.replace("chr",""):e.chr)+":"+(t+1)+"-"+(n+1),"-g","DUP",e.rnabamurl||e.rnabamfile],dir:e.rnabamurl_dir,callback:n=>{const s=n.split("\t");if(3!=s.length)return;const i=Number.parseInt(s[1])-1;if(!Number.isInteger(i))return;const f=Number.parseInt(s[2]);if(!Number.isInteger(f))return;const d=e.rnabarheight*Math.min(f,r)/r,p=u?(i-t)*c:(i-t)/l;a.strokeStyle="#ccc",a.beginPath(),a.moveTo(p+c/2,e.rnabarheight),a.lineTo(p+c/2,e.rnabarheight-d),a.stroke(),a.closePath(),f>r&&(a.strokeStyle="blue",a.beginPath(),a.moveTo(p+c/2,0),a.lineTo(p+c/2,2),a.stroke(),a.closePath());const m=o.get(i);m&&(m.rnacount.h=d)}}),{canvas:i,ctx:a,isbp:u,binpxw:c,binbpsize:l}}(n,d,p,m,g)),c.coveragesrc=await function(e,t,n,s,r,o,i,a){const l=[];for(const n of t)n.dnacount.ishet&&l.push((e.rnabam_nochr?e.chr.replace("chr",""):e.chr)+":"+(n.pos+1)+"-"+(n.pos+1));return new Promise(((n,s)=>{const c=(0,x.spawn)(Br,["mpileup","-q",e.checkrnabam.rnapileup_q,"-Q",e.checkrnabam.rnapileup_Q,"--no-reference","-a","INFO/AD","-d",999999,"-r",l.join(","),e.rnabamurl||e.rnabamfile],{cwd:e.rnabamurl_dir});I().createInterface({input:c.stdout}).on("line",(e=>{if("#"==e[0])return;const n=mo(e);if(!n)return;let s;n.pos>=r&&n.pos<=o&&n.DP;const i=t.find((e=>e.pos==n.pos));if(i){i.__x=s;const e=n.allele2count[i.ref]||0,t=n.allele2count[i.alt]||0;e+t>0&&(delete i.rnacount.nocoverage,i.rnacount.ref=e,i.rnacount.alt=t,i.rnacount.f=t/(e+t))}})),c.on("close",(()=>{if(!i)return void n();const{canvas:s,ctx:l,binpxw:c}=i;l.lineWidth=Math.max(3,c);let u=0;for(const n of t)n.dnacount&&(n.pos<r||n.pos>o||(n.__x=e.width*(n.pos-r)/(o-r),u=Math.max(u,n.dnacount.ref+n.dnacount.alt)));for(const n of t){if(null==n.__x)continue;n.rnacount.nocoverage||(null==n.rnacount.h&&(n.rnacount.h=e.rnabarheight*(n.rnacount.ref+n.rnacount.alt)/a),l.strokeStyle=e.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight),l.lineTo(n.__x+c/2,e.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.stroke(),l.closePath(),l.strokeStyle=e.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.lineTo(n.__x+c/2,e.rnabarheight-n.rnacount.h),l.stroke(),l.closePath());const t=e.dnabarheight*(n.dnacount.ref+n.dnacount.alt)/u;n.dnacount.ishet&&(l.strokeStyle=e.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight+e.barypad),l.lineTo(n.__x+c/2,e.rnabarheight+e.barypad+(1-n.dnacount.f)*t),l.stroke(),l.closePath(),l.strokeStyle=e.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight+e.barypad+(1-n.dnacount.f)*t),l.lineTo(n.__x+c/2,e.rnabarheight+e.barypad+t),l.stroke(),l.closePath()),delete n.__x}n(s.toDataURL())}))}))}(n,m,0,0,d,p,b,g),await async function(e,t){if(0==e.length)return;const n=[];for(const s of e)s.rnacount.nocoverage||s.rnacount.ref+s.rnacount.alt<t.checkrnabam.rna_mintotalreads||n.push(s);if(0==n.length)return;const s=await function(e){const t=y().join(r().cachedir,Math.random().toString())+".snp",n=[];for(const t of e)t.rnacount.nocoverage||null!=t.rnacount.ref&&null!=t.rnacount.alt&&n.push(t.pos+"."+t.ref+"."+t.alt+"\t\t\t\t\t\t\t\t"+t.rnacount.ref+"\t"+t.rnacount.alt);return new Promise(((e,s)=>{h().writeFile(t,n.join("\n")+"\n",(n=>{n&&s("cannot write"),e(t)}))}))}(n),o=await po(s);await function(e,t){return new Promise(((n,s)=>{h().readFile(t,"utf8",((t,r)=>{t&&s("cannot read binom pvalue"),r||n();for(const t of r.trim().split("\n")){const n=t.split("\t"),s=e.find((e=>n[0]==e.pos+"."+e.ref+"."+e.alt));s&&(s.rnacount.pvalue=Number.parseFloat(n[10]))}n()}))}))}(e,o),h().unlink(s,(()=>{})),h().unlink(o,(()=>{}))}(m,n),c.genes=function(e,t,n){const s=[];for(const[r,o]of t){s.push(o);const t=e.filter((e=>e.pos>=o.start&&e.pos<=o.stop));if(0==t.length){o.nosnp=1;continue}o.snps=t;const r=t.filter((e=>null!=e.rnacount.pvalue));if(0==r.length){o.nornasnp=1;continue}const i=r.reduce(((e,t)=>e+Math.abs(t.rnacount.f-.5)),0);let a=null,l=0;for(const e of r)null==a?a=e.rnacount.pvalue:a*=e.rnacount.pvalue,e.rnacount.pvalue<=n.checkrnabam.binompvaluecutoff&&l++;o.ase={markers:t.filter((e=>e.dnacount.ishet)).length,ase_markers:l,mean_delta:i/r.length,geometricmean:Math.pow(a,1/r.length)}}return s}(m,l,n);let v=0;for(const e of m)e.dnacount&&e.pos>=d&&e.pos<=p&&(v=Math.max(v,e.dnacount.ref+e.dnacount.alt));c.dnamax=v,t.send(c)}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.post(Hr+"/bamnochr",(async function(e,t){const n=e.query;try{const e=Pr[n.genome];if(!e)throw"invalid genome";if(n.file)n.file=y().join(r().tpmasterdir,n.file);else{if(!n.url)throw"no bam file or url";n.url_dir=await F.d1(n.url,n.indexURL||n.url+".bai")}const s=await F.Dp(n.file||n.url,e,n.url_dir);t.send({nochr:s})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Jr.get(Hr+"/gene2canonicalisoform",(function(e,t){try{if(!e.query.gene)throw".gene missing";const n=Pr[e.query.genome];if(!n)throw"unknown genome";if(!n.genedb.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const s=n.genedb.get_gene2canonicalisoform.get(e.query.gene);t.send(s)}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Jr.get(Hr+"/ideogram",(function(e,t){try{const n=Pr[e.query.genome];if(!n)throw"invalid genome";if(!n.genedb.hasIdeogram)throw"ideogram not supported on this genome";if(!e.query.chr)throw".chr missing";const s=n.genedb.getIdeogramByChr.all(e.query.chr);if(!s.length)throw"no ideogram data for this chr";t.send(s)}catch(e){t.send({error:e.message||e})}}));F.lY,F.ZX;function To(e){const t=e.split(/\r?\n/);if(t.length<=1||!t[0])return[null,[]];const n=t[0].split("\t"),s=[];for(let e=1;e<t.length;e++){if("#"==t[e][0])continue;const r=t[e].split("\t"),o={};for(let e=0;e<n.length;e++){const t=r[e];t&&(o[n[e]]=t)}s.push(o)}return[null,s]}async function Mo(e){try{await h().promises.stat(e.tpmasterdir)}catch(t){const n="Error with "+e.tpmasterdir+": "+t.code;if("validate"==process.argv[2])throw n;return void console.log("\n!!! "+n+"\n")}if(function(){if(r().features.skip_checkDependenciesAndVersions)return void console.log("SKIPPED checkDependenciesAndVersions()");const e=["jsonlite","cmprsk","hwde","lmtest"];for(const t of e){const e=N().spawnSync(r().Rscript,["-e",`suppressPackageStartupMessages(library("${t}"))`],{encoding:"utf8"});if(e.stderr.trim())throw e.stderr}const t=10;{const e=N().execSync(r().samtools+" --version",{encoding:"utf8"}).trim().split("\n"),[n,s]=e[0].split(" ");if("samtools"!=n||!s)throw'cannot run "samtools version"';const[o,i]=s.split(".");if("1"!=o)throw"samtools not 1.*";if(Number(i)<t)throw`samtools not >= 1.${t}`}{const e=N().execSync(r().bcftools+" -v",{encoding:"utf8"}).trim().split("\n"),[n,s]=e[0].split(" ");if("bcftools"!=n||!s)throw'cannot run "bcftools version"';const[o,i]=s.split(".");if("1"!=o)throw"bcftools not 1.*";if(Number(i)<t)throw`bcftools not >= 1.${t}`}}(),null!=e.base_zindex){const t=Number.parseInt(e.base_zindex);if(Number.isNaN(t)||t<=0)throw"base_zindex must be positive integer";e.base_zindex=t}if(e.jwt){if(!e.jwt.secret)throw"jwt.secret missing";if(!e.jwt.permissioncheck)throw"jwt.permissioncheck missing"}if(!e.tpmasterdir)throw".tpmasterdir missing";if(!e.cachedir)throw".cachedir missing";if(e.cachedir_massSession=await Eo("massSession"),e.cachedir_massSessionTrash=await Eo("massSessionTrash"),e.cache_snpgt={dir:await Eo("snpgt"),fileNameRegexp:/[^\w]/,sampleColumn:6},e.cachedir_bam=await Eo("bam"),e.cachedir_genome=await Eo("genome"),e.cachedir_ssid=await Eo("ssid"),e.commonOverrides&&$.applyOverrides(e.commonOverrides),!e.genomes)throw".genomes[] missing";if(!Array.isArray(e.genomes))throw".genomes[] not array";for(const t of e.genomes){if(!t.name)throw".name missing from a genome: "+JSON.stringify(t);if(!t.file)throw".file missing from genome "+t.name;const n=y().join(process.cwd(),t.file),s=require(h().existsSync(n)?n:t.file),r=s.default||s;if(Pr[t.name]=r,!r.genomefile)throw".genomefile missing from .js file of genome "+t.name;if("NA"==r.genomefile||(r.genomefile=y().join(e.tpmasterdir,r.genomefile)),r.genomicNameRegexp||(r.genomicNameRegexp=/[^a-zA-Z0-9.:_-]/),r.tracks||(r.tracks=[]),t.tracks)for(const e of t.tracks)r.tracks.push(e);if(t.datasets&&(r.rawdslst=t.datasets),t.snp&&(r.snp=t.snp),t.blat){if(!t.blat.host)throw".blat.host missing for "+t.name;if(!t.blat.port)throw".blat.port missing for "+t.name;r.blat=t.blat}if(t.nosnp&&delete r.snp,t.nohicenzyme&&delete r.hicenzymefragment,t.nohicdomain&&delete r.hicdomain,r.genedb&&t.no_gene2canonicalisoform&&delete r.genedb.gene2canonicalisoform,t.updateAttr)for(const e of t.updateAttr){let t=r;for(const[n,s]of e.entries())if(t)if("object"==typeof s)for(const e in s)t[e]=s[e];else{if("string"==typeof t[s]){e[n+1]&&(t[s]=e[n+1]);break}t=t[s]}}}e.defaultgenome&&Pr[e.defaultgenome]&&(Pr[e.defaultgenome].isdefault=!0);for(const t in Pr){const n=Pr[t];if(!n.majorchr)throw t+": majorchr missing";if(!n.defaultcoord)throw t+": defaultcoord missing";if(await F.Kf(n,n.defaultcoord.chr+":"+n.defaultcoord.start+"-"+(n.defaultcoord.start+1)),n.tracks||(n.tracks=[]),"string"==typeof n.majorchr){const e=n.majorchr.trim().split(/[\s\t\n]+/),s={},r=[];for(let n=0;n<e.length;n+=2){const o=e[n],i=Number.parseInt(e[n+1]);if(Number.isNaN(i))throw t+" majorchr invalid chr size for "+o+" ("+e[n+1]+")";s[o]=i,r.push(o)}n.majorchr=s,n.majorchrorder=r}n.chrlookup={};for(const e in n.majorchr)n.chrlookup[e.toUpperCase()]={name:e,len:n.majorchr[e],major:!0};if(n.minorchr){if("string"==typeof n.minorchr){const e=n.minorchr.trim().split(/[\s\t\n]+/),s={};for(let n=0;n<e.length;n+=2){const r=Number.parseInt(e[n+1]);if(Number.isNaN(r))throw t+" minorchr invalid chr size for "+e[n]+" ("+e[n+1]+")";s[e[n]]=r}n.minorchr=s}for(const e in n.minorchr)n.chrlookup[e.toUpperCase()]={name:e,len:n.minorchr[e]}}if(n.genedb){if(!n.genedb.dbfile)throw t+": .genedb.dbfile missing";try{console.log("Connecting",n.genedb.dbfile),n.genedb.db=F.sE(n.genedb.dbfile)}catch(e){throw`Cannot connect genedb: ${n.genedb.dbfile}: ${e}`}n.genedb.getnamebynameorisoform=n.genedb.db.prepare("select name from genes where name=? or isoform=?"),n.genedb.getnamebyisoform=n.genedb.db.prepare("select distinct name from genes where isoform=?"),n.genedb.getjsonbyname=n.genedb.db.prepare("select isdefault,genemodel from genes where name=?"),n.genedb.getjsonbyisoform=n.genedb.db.prepare("select isdefault,genemodel from genes where isoform=?"),n.genedb.getnameslike=n.genedb.db.prepare("select distinct name from genes where name like ? limit 20");const e=(0,vs.jj)(n.genedb.db);e.has("genealias")&&(n.genedb.getNameByAlias=n.genedb.db.prepare("select name from genealias where alias=?"),n.genedb.getAliasByName=n.genedb.db.prepare("select alias from genealias where name=?")),e.has("gene2coord")&&(n.genedb.getCoordByGene=n.genedb.db.prepare("select * from gene2coord where name=?")),e.has("ideogram")?(n.genedb.hasIdeogram=!0,n.genedb.getIdeogramByChr=n.genedb.db.prepare("select * from ideogram where chromosome=?")):n.genedb.hasIdeogram=!1,e.has("gene2canonicalisoform")&&(n.genedb.get_gene2canonicalisoform=n.genedb.db.prepare("select isoform from gene2canonicalisoform where gene=?")),e.has("buildDate")&&(n.genedb.get_buildDate=n.genedb.db.prepare("select date from buildDate")),n.genedb.hasTable_refseq2ensembl=e.has("refseq2ensembl"),n.genedb.sqlTables=[...e],n.genedb.tableSize={};for(const t of e)"buildDate"!=t&&(n.genedb.tableSize[t]=n.genedb.db.prepare(`select count(*) as size from ${t}`).get().size)}if(n.termdbs)for(const e in n.termdbs)(0,vs.JV)(n.termdbs[e],Lr),console.log(`${e} initiated as ${t}-level termdb`);for(const t of n.tracks)if(t.__isgene){if(!t.file)throw"Tabix file missing for gene track: "+JSON.stringify(t);try{await F.LC(y().join(e.tpmasterdir,t.file))}catch(e){throw"Error with "+t.file+": "+e}}if(n.proteindomain){if(!n.proteindomain.dbfile)throw t+".proteindomain: missing dbfile for sqlite db";if(!n.proteindomain.statement)throw t+".proteindomain: missing statement for sqlite db";let e;try{console.log("Connecting",n.proteindomain.dbfile),e=F.sE(n.proteindomain.dbfile)}catch(e){throw"Error with "+n.proteindomain.dbfile+": "+e}n.proteindomain.getbyisoform=e.prepare(n.proteindomain.statement)}if(n.snp){if(!n.snp.bigbedfile)throw t+".snp: missing bigBed file";n.snp.bigbedfile=y().join(e.tpmasterdir,n.snp.bigbedfile),await F.Ic(n.snp.bigbedfile)}if(n.fimo_motif){if(!n.fimo_motif.db)throw t+".fimo_motif: db file missing";if(n.fimo_motif.db=y().join(e.tpmasterdir,n.fimo_motif.db),n.fimo_motif.annotationfile){const[t,s]=To(h().readFileSync(y().join(e.tpmasterdir,n.fimo_motif.annotationfile),{encoding:"utf8"}).trim());n.fimo_motif.tf2attr={};for(const e of s)n.fimo_motif.tf2attr[e.Model.split("_")[0]]=e}}if(n.hicenzymefragment){if(!Array.isArray(n.hicenzymefragment))throw"hicenzymefragment should be an array";for(const t of n.hicenzymefragment){if(!t.enzyme)throw".enzyme missing for one element of hicenzymefragment[]";if(!t.file)throw".file missing for one element of hicenzymefragment[]";try{await F.LC(y().join(e.tpmasterdir,t.file))}catch(e){throw"Error with "+t.file+": "+e}}}if(n.hicdomain){if(!n.hicdomain.groups)throw".groups{} missing from hicdomain";for(const t in n.hicdomain.groups){const s=n.hicdomain.groups[t];if(!s.name)throw".name missing from hicdomain "+t;if(!s.sets)throw".set{} missing from hicdomain "+t;for(const n in s.sets){const r=s.sets[n];if(!r.name)throw".name missing from hicdomain "+t+" > "+n;if(!r.file)throw".file missing from hicdomain "+t+" > "+n;r.file=y().join(e.tpmasterdir,r.file);try{await F.LC(r.file)}catch(e){throw"Error with "+r.file+": "+e}}}}if(n.rawdslst){n.datasets={};for(const e of n.rawdslst){if(e.skip)continue;if(!e.name)throw"a nameless dataset from "+t;if(n.datasets[e.name])throw t+" has duplicating dataset name: "+e.name;if(!e.jsfile)throw"jsfile not available for dataset "+e.name+" of "+t;const s=y().join(process.cwd(),e.jsfile),r=require(h().existsSync(s)?s:e.jsfile),o="function"==typeof r?r($):"function"==typeof r?.default?r.default($):r.default||r;if(ws(o,e),o.noHandleOnClient=e.noHandleOnClient,o.label=e.name,o.genomename=t,n.datasets[o.label]=o,o.isMds3)try{await Ms(o,n,0,Jr,Hr)}catch(e){throw e.stack&&console.log(e.stack),"Error with mds3 dataset "+o.label+": "+e}else if(o.isMds)try{await Fo(o,n,e)}catch(e){throw"Error with mds dataset "+o.label+": "+e}else Io(o,n)}Oo(),delete n.rawdslst}}}async function Oo(){const e=await h().promises.readdir(r().cachedir_massSession);try{e.forEach((async e=>{const t=(await h().promises.stat(y().join(r().cachedir_massSession,e))).birthtime,n=new Date,s=new Date(t),o=r().features.massSessionDuration||30;Math.round((n.getTime()-s.getTime())/864e5)>o&&(await h().promises.copyFile(y().join(r().cachedir_massSession,e),y().join(r().cachedir_massSessionTrash,e)),await h().promises.unlink(y().join(r().cachedir_massSession,e)),console.log("File deleted: ",e,t))}))}catch(e){throw`Error: ${e}`}}function Io(e,t){if(e.dbfile)try{console.log("Connecting",e.dbfile),e.newconn=F.sE(e.dbfile)}catch(t){throw"Error with "+e.dbfile+": "+t}if(e.snvindel_attributes)for(const t of e.snvindel_attributes)if(t.lst)for(const e of t.lst)e.get=e.get.toString();else t.get=t.get.toString();if(e.cohort){if(e.cohort.levels){if(!Array.isArray(e.cohort.levels))throw"cohort.levels must be array for "+e.genomename+"."+e.label;if(0==e.cohort.levels.length)throw"levels is blank array for cohort of "+e.genomename+"."+e.label;for(const t of e.cohort.levels)if(!t.k)throw".k key missing in one of the levels, .cohort, in "+e.genomename+"."+e.label}if(e.cohort.fromdb){if(!e.cohort.fromdb.sql)throw".sql missing from ds.cohort.fromdb in "+e.genomename+"."+e.label;const t=e.newconn.prepare(e.cohort.fromdb.sql).all();delete e.cohort.fromdb,e.cohort.raw=t,console.log(t.length+" rows retrieved for "+e.label+" sample annotation")}if(e.cohort.files){let t=[];for(const n of e.cohort.files){if(!n.file)throw".file missing from one of cohort.files[] for "+e.genomename+"."+e.label;const s=h().readFileSync(y().join(r().tpmasterdir,n.file),"utf8").trim();if(!s)throw n.file+" is empty for "+e.genomename+"."+e.label;t=[...t,...ee(s)]}delete e.cohort.files,e.cohort.raw?e.cohort.raw=[...e.cohort.raw,...t]:e.cohort.raw=t,console.log(t.length+" rows retrieved for "+e.label+" sample annotation")}if(e.cohort.tosampleannotation){if(!e.cohort.tosampleannotation.samplekey)throw".samplekey missing from .cohort.tosampleannotation for "+e.genomename+"."+e.label;if(!e.cohort.key4annotation)throw".cohort.key4annotation missing when .cohort.tosampleannotation is on for "+e.genomename+"."+e.label}}if(!e.queries)throw".queries missing from dataset "+e.label+", "+e.genomename;if(!Array.isArray(e.queries))throw e.label+".queries is not array";for(const n of e.queries){const s=Ro(n,e,t);if(s)throw'Error parsing a query in "'+e.label+'": '+s}if(e.vcfinfofilter){const t=$.validate_vcfinfofilter(e.vcfinfofilter);if(t)throw e.label+": vcfinfofilter error: "+t}if(e.url4variant)for(const t of e.url4variant){if(!t.makelabel)throw"makelabel() missing for one item of url4variant from "+e.label;if(!t.makeurl)throw"makeurl() missing for one item of url4variant from "+e.label;t.makelabel=t.makelabel.toString(),t.makeurl=t.makeurl.toString()}}async function Eo(e){const t=y().join(r().cachedir,e);try{await h().promises.stat(t)}catch(e){if("ENOENT"!=e.code)throw"error stating dir";try{await h().promises.mkdir(t)}catch(e){throw"cannot make dir"}}return t}function Ro(e,t,n){if(!e.name)return".name missing";if(e.dsblocktracklst){if(!Array.isArray(e.dsblocktracklst))return"dsblocktracklst not an array in "+t.label;for(const n of e.dsblocktracklst){if(!n.type)return"missing type for a blocktrack of "+t.label;if(!n.file&&!n.url)return"neither file or url given for a blocktrack of "+t.label}}else if(e.vcffile){const t=N().execSync(Gr+" -H "+y().join(r().tpmasterdir,e.vcffile),{encoding:"utf8"}).trim();if(""==t)return"no meta lines in VCF file "+e.vcffile+" of query "+e.name;const[s,o,i,a]=D.e(t.split("\n"));if(a)return"error parsing VCF meta lines of "+e.vcffile+": "+a.join("; ");e.vcf={vcfid:Math.random().toString(),info:s,format:o,samples:i},e.hlinfo&&(e.vcf.hlinfo=e.hlinfo,delete e.hlinfo),e.infopipejoin&&(e.vcf.infopipejoin=e.infopipejoin,delete e.infopipejoin);const l=N().execSync(Gr+" -l "+y().join(r().tpmasterdir,e.vcffile),{encoding:"utf8"}).trim();if(""==l)return"tabix -l found no chromosomes/contigs in "+e.vcffile+" of query "+e.name;e.vcf.nochr=$.contigNameNoChr(n,l.split("\n"));let c=0;if(s)for(const e in s)c++;console.log("Parsed vcf meta from "+e.vcffile+": "+c+" INFO, "+i.length+" sample, "+(e.vcf.nochr?'no "chr"':'has "chr"'))}else{if(!e.makequery)return"do not know how to parse query: "+e.name;if(e.isgeneexpression){if(!e.config)return"config object missing for gene expression query of "+e.name;e.config.maf&&(e.config.maf.get=e.config.maf.get.toString())}}}async function Fo(e,t,n){if((e.isMds2||e.isMds3||e.isMds)&&ws(e,n),e.assayAvailability){if(!e.assayAvailability.file)throw".assayAvailability.file missing";if(!e.assayAvailability.assays)throw".assayAvailability.assays[] missing";Object.freeze(e.assayAvailability.assays),e.assayAvailability.samples=new Map;for(const t of h().readFileSync(y().join(r().tpmasterdir,e.assayAvailability.file),{encoding:"utf8"}).trim().split("\n")){const[n,s]=t.split("\t");e.assayAvailability.samples.set(n,JSON.parse(s))}console.log(e.assayAvailability.samples.size+" samples with assay availability ("+e.label+")")}if(e.gene2mutcount){if(!e.gene2mutcount.dbfile)throw".gene2mutcount.dbfile missing";try{console.log("Connecting",e.gene2mutcount.dbfile),e.gene2mutcount.db=F.sE(e.gene2mutcount.dbfile),console.log("DB connected for "+e.label+": "+e.gene2mutcount.dbfile)}catch(t){throw`Error connecting db at ${e.gene2mutcount.dbfile}`}}if(e.sampleAssayTrack){if(!e.sampleAssayTrack.file)throw".file missing from sampleAssayTrack";e.sampleAssayTrack.samples=new Map;let t=0,n=new Set;for(const s of h().readFileSync(y().join(r().tpmasterdir,e.sampleAssayTrack.file),{encoding:"utf8"}).trim().split("\n")){if(!s)continue;if("#"==s[0])continue;const[r,o,i]=s.split("\t");if(!o||!i)continue;if(!e.sampleAssayTrack.samples.has(r)){if(e.cohort&&e.cohort.annotation&&!e.cohort.annotation[r]){n.add(r);continue}e.sampleAssayTrack.samples.set(r,[])}const a=JSON.parse(i);if(!$.tkt[a.type])throw"invalid type from a sample track: "+i;a.name||(a.name=r+" "+o),a.assayName=o,e.sampleAssayTrack.samples.get(r).push(a),t++}console.log(t+" assay-tracks from "+e.sampleAssayTrack.samples.size+" samples ("+e.label+")"),n.size&&console.log("Error: "+n.size+" samples with assay tracks are unannotated: "+[...n].join(" "))}if(e.singlesamplemutationjson){const t=e.singlesamplemutationjson;if(!t.file)throw".file missing from singlesamplemutationjson";t.samples={};let n=0;for(const e of h().readFileSync(y().join(r().tpmasterdir,t.file),{encoding:"utf8"}).trim().split("\n")){if(!e)continue;if("#"==e[0])continue;const[s,r]=e.split("\t");s&&r&&(n++,t.samples[s]=r)}console.log(n+" samples for disco plot")}if(e.cohort&&e.cohort.db&&e.cohort.termdb&&await Xs(e,Jr,Hr),e.cohort&&e.cohort.files){if(!Array.isArray(e.cohort.files))throw".cohort.files is not array";if(!e.cohort.tohash)throw".tohash() missing from cohort";if("function"!=typeof e.cohort.tohash)throw".cohort.tohash is not function";if(!e.cohort.samplenamekey)throw".samplenamekey missing";if(e.cohort.annotation={},e.cohort.mutation_signature){const t=e.cohort.mutation_signature;if(!t.sets)throw".mutation_signature.sets missing";for(const n in t.sets){const s=t.sets[n];if(s.name||(s.name=n),!s.signatures)throw".signatures{} missing from a signature set";if(s.samples){if(!s.samples.file)throw".samples.file missing from a signature set";const[t,n]=To(h().readFileSync(y().join(r().tpmasterdir,s.samples.file),{encoding:"utf8"}).trim());s.samples.map=new Map;for(const t of n){const n=t[e.cohort.samplenamekey];if(!n)throw e.cohort.samplenamekey+" missing in file "+s.samples.file;s.samples.map.set(n,t);for(const e in s.signatures)if(t[e]){const r=Number.parseFloat(t[e]);if(Number.isNaN(r))throw"mutation signature value is not float: "+t[e]+" from sample "+n;s.samples.skipzero&&0==r?delete t[e]:t[e]=r}}}}}if(e.cohort.attributes){if(!e.cohort.attributes.lst)throw".lst[] missing for cohort.attributes";if(!Array.isArray(e.cohort.attributes.lst))return".cohort.attributes.lst is not array";for(const t of e.cohort.attributes.lst){if(!t.key)throw".key missing from one of the .cohort.attributes.lst[]";if(!t.label)throw".label missing from one of the .cohort.attributes.lst[]";if(!t.values)throw".values{} missing from "+t.label+" of .cohort.attributes.lst";for(const e in t.values)if(!t.values[e].label)throw".label missing from one value of "+t.label+" in .cohort.attributes.lst"}if(e.cohort.attributes.defaulthidden)for(const t in e.cohort.attributes.defaulthidden){const n=e.cohort.attributes.lst.find((e=>e.key==t));if(!n)throw"invalid defaulthidden key: "+t;for(const s in e.cohort.attributes.defaulthidden[t])if(!n.values[s])throw"invalid defaulthidden value "+s+" for "+t}}if(e.cohort.hierarchies){if(!e.cohort.hierarchies.lst)throw".lst[] missing from .cohort.hierarchies";if(!Array.isArray(e.cohort.hierarchies.lst))throw".cohort.hierarchies.lst is not array";for(const t of e.cohort.hierarchies.lst){if(!t.name)throw".name missing from one hierarchy";if(!t.levels)throw".levels[] missing from one hierarchy";if(!Array.isArray(t.levels))throw".levels is not array from one hierarchy";for(const e of t.levels)if(!e.k)throw".k missing from one level in hierarchy "+t.name}}if(e.cohort.sampleAttribute){if(!e.cohort.sampleAttribute.attributes)throw"attributes{} missing from cohort.sampleAttribute";for(const t in e.cohort.sampleAttribute.attributes){const n=e.cohort.sampleAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from cohort.sampleAttribute.attributes";if(n.values)for(const e in n.values){const t=n.values[e];if("object"!=typeof t)throw'value "'+e+'" not pointing to {} from sampleAttribute';t.name||(t.name=e)}if(n.showintrack&&!n.isinteger&&!n.isfloat)throw n.label+": .showintrack requires .isinteger or .isfloat"}}if(e.cohort.scatterplot){if(!e.cohort.sampleAttribute)throw".sampleAttribute missing but required for .cohort.scatterplot";const t=e.cohort.scatterplot;if(!t.querykey)throw".querykey missing from .cohort.scatterplot";{if(!e.queries)throw".cohort.scatterplot.querykey in use but ds.queries{} missing";const n=e.queries[t.querykey];if(!n)throw"unknown query by .cohort.scatterplot.querykey: "+t.querykey;if(n.type!=$.tkt.mdssvcnv)throw"type is not "+$.tkt.mdssvcnv+" of the track pointed to by .cohort.scatterplot.querykey"}if(t.colorbygeneexpression){if(!t.colorbygeneexpression.querykey)throw"querykey missing from .cohort.scatterplot.colorbygeneexpression";if(!e.queries)throw".cohort.scatterplot.colorbygeneexpression in use but ds.queries{} missing";const n=e.queries[t.colorbygeneexpression.querykey];if(!n)throw"unknown query by .cohort.scatterplot.colorbygeneexpression.querykey: "+t.colorbygeneexpression.querykey;if(!n.isgenenumeric)throw"isgenenumeric missing from the track pointed to by .cohort.scatterplot.colorbygeneexpression.querykey"}if(t.tracks,!t.x)throw".x missing from .cohort.scatterplot";if(!t.x.attribute)throw".attribute missing from .cohort.scatterplot.x";const n=e.cohort.sampleAttribute.attributes[t.x.attribute];if(!n)throw"scatterplot.x.attribute is not defined in sampleAttribute";if(!n.isfloat)throw'scatterplot.x is not "isfloat"';if(!t.y)throw".y missing from .cohort.scatterplot";if(!t.y.attribute)throw".attribute missing from .cohort.scatterplot.y";const s=e.cohort.sampleAttribute.attributes[t.y.attribute];if(!s)throw"scatterplot.y.attribute is not defined in sampleAttribute";if(!s.isfloat)throw'scatterplot.y is not "isfloat"';if(t.colorbyattributes)for(const n of t.colorbyattributes){if(!n.key)throw".key missing from one of scatterplot.colorbyattributes";const t=e.cohort.sampleAttribute.attributes[n.key];if(!t)throw"unknown attribute by key "+n.key+" from scatterplot.colorbyattributes";n.label=t.label,n.values=t.values}}for(const t of e.cohort.files){if(!t.file)throw".file missing from one of .cohort.files";const[n,s]=To(h().readFileSync(y().join(r().tpmasterdir,t.file),{encoding:"utf8"}).trim());if(n)throw'cohort annotation file "'+t.file+'": '+n;console.log(e.label+": "+s.length+" samples loaded from annotation file "+t.file),s.forEach((t=>{for(const n in t){let s;e.cohort.sampleAttribute&&(s=e.cohort.sampleAttribute.attributes[n]),s||e.cohort.termdb&&e.cohort.termdb.termjson&&e.cohort.termdb.termjson.map&&(s=e.cohort.termdb.termjson.map.get(n)),s&&(s.isfloat?t[n]=Number.parseFloat(t[n]):s.isinteger&&(t[n]=Number.parseInt(t[n])))}e.cohort.tohash(t,e)}))}if(e.cohort.annorows=Object.values(e.cohort.annotation),console.log(e.label+": total samples from sample table: "+e.cohort.annorows.length),e.cohort.survivalplot){const t=e.cohort.survivalplot;if(!t.plots)throw".plots{} missing from survivalplot";t.init={plottypes:[]};for(const e in t.plots){const n=t.plots[e];if(!n.name)throw".name missing from survivalplot "+e;if(!n.serialtimekey)throw".serialtimekey missing from survivalplot "+e;if(!n.iscensoredkey)throw".iscensoredkey missing from survivalplot "+e;if(!n.timelabel)throw".timelabel missing from survivalplot "+e;n.key=e,t.init.plottypes.push({key:e,name:n.name,timelabel:n.timelabel})}if(t.samplegroupattrlst){t.init.samplegroupings=[];for(const n of t.samplegroupattrlst){if(!n.key)throw".key missing from an attr of samplegroupattrlst for survival";const s=e.cohort.sampleAttribute.attributes[n.key];if(!s)throw'unknown attribute key "'+n.key+'" from survival samplegroupattrlst';const r=new Map;for(const s in e.cohort.annotation){const o=e.cohort.annotation[s],i=o[n.key];if(null==i)continue;let a=!1;for(const e in t.plots)if(null!=o[t.plots[e].serialtimekey]){a=!0;break}a&&(r.has(i)?r.set(i,r.get(i)+1):r.set(i,1))}if(0==r.size)throw'no value found for "'+n.key+'" from survival samplegroupattrlst';const o=[];for(const[e,t]of r)o.push({value:e,count:t});t.init.samplegroupings.push({key:n.key,label:s.label,values:o})}}}}if(e.mutationAttribute){if(!e.mutationAttribute.attributes)throw"attributes{} missing from mutationAttribute";for(const t in e.mutationAttribute.attributes){const n=e.mutationAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from mutationAttribute.attributes";if(!n.appendto_link&&n.values)for(const e in n.values){if(!n.values[e].name)throw".name missing for value "+e+" of key "+t+" from mutationAttribute.attributes"}}}if(e.alleleAttribute){if(!e.alleleAttribute.attributes)throw"attributes{} missing from alleleAttribute";for(const t in e.alleleAttribute.attributes){const n=e.alleleAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from alleleAttribute.attributes";if(!n.isnumeric){if(!n.values)throw".values{} missing for non-numeric key "+t+" from alleleAttribute.attributes";for(const e in n.values){if(!n.values[e].name)throw".name missing for value "+e+" of key "+t+" from alleleAttribute.attributes"}}}}if(e.locusAttribute){if(!e.locusAttribute.attributes)throw"attributes{} missing from locusAttribute";for(const t in e.locusAttribute.attributes){const n=e.locusAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from locusAttribute.attributes";if(!n.isnumeric&&!n.appendto_link){if(!n.values)throw".values{} missing for non-numeric key "+t+" from locusAttribute.attributes";for(const e in n.values){if(!n.values[e].name)throw".name missing for value "+e+" of key "+t+" from locusAttribute.attributes"}}}}if(e.queries)for(const s in e.queries){if(n.remove_queries&&-1!=n.remove_queries.indexOf(s)){delete e.queries[s];continue}const r=e.queries[s];if(n.hide_queries&&-1!=n.hide_queries.indexOf(s)&&(r.hideforthemoment=1),r.istrack){if(!r.type)throw".type missing for track query "+s;if(r.viewrangeupperlimit&&!Number.isInteger(r.viewrangeupperlimit))throw".viewrangeupperlimit should be integer for track query "+s;if(r.type==$.tkt.mdsjunction){const n=Do(r,e,t);if(n)throw s+" (mdsjunction) error: "+n}else if(r.type==$.tkt.mdscnv){const n=Go(r,e,t);if(n)throw s+" (mdscnv) error: "+n}else if(r.type==$.tkt.mdssvcnv){const n=Uo(r,e,t);if(n)throw s+" (svcnv) error: "+n}else{if(r.type!=$.tkt.mdsvcf)throw"unknown track type for a query: "+r.type+" "+s;{const n=await zo(r,e,t);if(n)throw s+" (vcf) error: "+n}}$o(r,e)}else{if(!r.isgenenumeric)throw"unknown type of query from "+s;{const n=Bo(r,e,t);if(n)throw s+" (genenumeric) error: "+n}}}if(e.track&&await Ys(e,t),e.annotationsampleset2matrix){if(!e.cohort)throw"ds.cohort misssing when annotationsampleset2matrix is in use";if(!e.cohort.annotation)throw"ds.cohort.annotation misssing when annotationsampleset2matrix is in use";if(!e.queries)throw"ds.queries misssing when annotationsampleset2matrix is in use";if(!e.annotationsampleset2matrix.key)throw".key STR missing in annotationsampleset2matrix";if(!e.annotationsampleset2matrix.groups)throw".groups{} missing in annotationsampleset2matrix";if("object"!=typeof e.annotationsampleset2matrix.groups)throw"ds.annotationsampleset2matrix.groups{} not an object";for(const t in e.annotationsampleset2matrix.groups){const n=e.annotationsampleset2matrix.groups[t];if(!n.groups||!Array.isArray(n.groups)||0==n.groups.length)throw".groups[] must be nonempty array in "+t;for(const s of n.groups){if(!s.name)throw".name missing from one of .groups[] in "+t;const n=s.matrixconfig;if(!n)throw".matrixconfig missing from one of .groups[] of "+t;if(!n.features)throw".features[] missing from group "+t;if(!Array.isArray(n.features))throw".features[] should be array from group "+t;if(0==n.features.length)throw".features[] zero length from group "+t;for(const s of n.features){if(e.annotationsampleset2matrix.commonfeatureattributes)for(const t in e.annotationsampleset2matrix.commonfeatureattributes)null==s[t]&&(s[t]=e.annotationsampleset2matrix.commonfeatureattributes[t]);if(!s.ismutation)return"unknown feature type from group "+t;if(!s.position)throw"position missing from feature "+JSON.stringify(s)+" from group "+t;if(!s.querykeylst)throw".querykeylst[] missing from ismutation feature from group "+t;if(!Array.isArray(s.querykeylst))throw".querykeylst[] not an array from ismutation feature from group "+t;if(0==s.querykeylst.length)throw".querykeylst[] zero length from ismutation feature from group "+t;for(const n of s.querykeylst)if(!e.queries[n])throw'unknown query key "'+n+'" from ismutation feature of group '+t}if(!n.limitsamplebyeitherannotation)throw".limitsamplebyeitherannotation[] missing from group "+t;if(!Array.isArray(n.limitsamplebyeitherannotation))throw".limitsamplebyeitherannotation[] should be array from group "+t;if(0==n.limitsamplebyeitherannotation.length)throw".limitsamplebyeitherannotation[] zero length from group "+t;for(const e of n.limitsamplebyeitherannotation){if(!e.key)throw"key missing from one of limitsamplebyeitherannotation from group "+t;if(!e.value)throw"value missing from one of limitsamplebyeitherannotation from group "+t}}}delete e.annotationsampleset2matrix.commonfeatureattributes}}function $o(e,t){if(e.groupsamplebyattr){e.groupsamplebyattr.key2group=new Map;for(const n in t.cohort.annotation)uo(n,[],e.groupsamplebyattr.key2group,[],t,e)}}function Do(e,t,n){if(e.readcountCutoff&&(!Number.isInteger(e.readcountCutoff)||e.readcountCutoff<1))return"readcountCutoff must be positive integer";let s;if(e.file){const[t,n]=jo(e.file);if(t)return"tabix file error: "+t;e.file=n,s=n}else{if(!e.url)return"no file or url given for mdsjunction "+e.name;s=e.url}const r={encoding:"utf8"};const o=N().execSync(Gr+" -H "+s,r).trim();if(o){const n=o.split("\n");if(1!=n.length)return"mdsjunction file has multiple header lines (begin with #), but should have just 1";const s=n[0].split("\t");if(s[5]){e.samples=s.slice(5),e.attributeSummary=Lo(e.samples,t),e.hierarchySummary=Po(e.samples,t);for(const t in e.hierarchySummary){let n=0;for(const s in e.hierarchySummary[t])n++;console.log(n+" "+t+" hierarchy levels for "+e.name)}}}{const t=N().execSync(Gr+" -l "+s,r).trim();if(!t)return"no chromosomes found";e.nochr=$.contigNameNoChr(n,t.split("\n"))}if(console.log("(mdsjunction) "+e.name+": "+(e.samples?e.samples.length:0)+" samples, "+(e.nochr?'no "chr"':'has "chr"')),!e.infoFilter)return".infoFilter{} missing";if(!e.infoFilter.lst)return".lst[] missing from .infoFilter";for(const t of e.infoFilter.lst){if(!t.key)return".key missing from one of infoFilter";if(!t.label)return".label missing from one of infoFilter";if(!t.categories)return".categories missing from one of infoFilter";for(const e in t.categories){if(!t.categories[e].label)return".label missing from one category of "+t.label;if(!t.categories[e].color)return".color missing from on category of "+t.label}if(t.hiddenCategories){for(const e in t.hiddenCategories)if(!t.categories[e])return"invalid hidden key "+e+" of "+t.label}else t.hiddenCategories={}}if(!e.singlejunctionsummary)return".singlejunctionsummary missing but is currently required from "+e.name;if(e.singlejunctionsummary.readcountboxplotpercohort){if(!e.singlejunctionsummary.readcountboxplotpercohort.groups)return".groups[] missing from query.singlejunctionsummary.readcountboxplotpercohort for "+e.name;for(const t of e.singlejunctionsummary.readcountboxplotpercohort.groups){if(!t.key)return".key missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups";if(!t.label)return".label missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups"}}}function Lo(e,t){if(!(t.cohort&&t.cohort.annotation&&t.cohort.attributes&&e))return;const n={};for(const s of t.cohort.attributes.lst){const r={};for(const e in s.values)r[e]=0;for(const n of e){const e=t.cohort.annotation[n];if(!e)continue;const o=e[s.key];null!=o&&(o in r&&r[o]++)}n[s.key]=r}return n}function Po(e,t){if(!t.cohort||!t.cohort.annotation||!t.cohort.hierarchies||0==e.length)return;const n=[];for(const s of e){const e=t.cohort.annotation[s];e&&n.push(e)}const s={};for(const e of t.cohort.hierarchies.lst){const t=(0,A.N)(n,e.levels),r=he()(t);r.sum((e=>e.value));const o={};r.eachBefore((e=>{o[e.id]=e.value})),s[e.name]=o}return s}function Go(e,t,n){let s;if(e.file){const[t,n]=jo(e.file);if(t)return"tabix file error: "+t;s=n}else{if(!e.url)return"no file or url given for (mdscnv) "+e.name;s=e.url}const r={encoding:"utf8"};const o=N().execSync(Gr+" -H "+s,r).trim();if(o){const n=o.split("\n");if(1!=n.length)return"mdscnv file has multiple header lines (begin with #), but should have just 1";const s=n[0].split("\t");e.samples=s.slice(5),e.attributeSummary=Lo(e.samples,t),e.hierarchySummary=Po(e.samples,t);for(const t in e.hierarchySummary){let n=0;for(const s in e.hierarchySummary[t])n++;console.log(n+" "+t+" hierarchy levels for "+e.name)}}{const t=N().execSync(Gr+" -l "+s,r).trim();if(!t)return"no chromosomes found";e.nochr=$.contigNameNoChr(n,t.split("\n"))}console.log("("+e.type+") "+e.name+": "+(e.samples?e.samples.length:"no")+" samples, "+(e.nochr?'no "chr"':'has "chr"'))}function Uo(e,t,n){let s;if(e.file){const[t,n]=jo(e.file);if(t)return"tabix file error: "+t;s=n}else{if(!e.url)return"no file or url given for (svcnv) "+e.name;s=e.url}const r={encoding:"utf8"};const o=N().execSync(Gr+" -H "+s,r).trim();if(o){const n=new Set;for(const e of o.split("\n"))for(const t of e.split(" ").slice(1))n.add(t);if(0==n.size)return"no samples from the header line";if(e.samples=[...n],t.cohort&&t.cohort.annotation){const n=new Set;for(const s of e.samples)t.cohort.annotation[s]||n.add(s);n.size&&console.log("mdssvcnv unannotated samples: "+(e.noprintunannotatedsamples?n.size:[...n].join(" ")))}}{const t=N().execSync(Gr+" -l "+s,r).trim();if(!t)return"no chromosomes found";e.nochr=$.contigNameNoChr(n,t.split("\n"))}if(e.expressionrank_querykey){const n=t.queries[e.expressionrank_querykey];if(!n)return"invalid key by expressionrank_querykey";if(!n.isgenenumeric)return"query "+e.expressionrank_querykey+" not tagged as isgenenumeric"}if(e.vcf_querykey){const n=t.queries[e.vcf_querykey];if(!n)return"invalid key by vcf_querykey";if(n.type!=$.tkt.mdsvcf)return"query "+e.vcf_querykey+" not of mdsvcf type"}if(e.groupsamplebyattr){if(!e.groupsamplebyattr.attrlst)return".attrlst[] missing from groupsamplebyattr";if(0==e.groupsamplebyattr.attrlst.length)return"groupsamplebyattr.attrlst[] empty array";if(!t.cohort)return"groupsamplebyattr in use but ds.cohort missing";if(!t.cohort.annotation)return"groupsamplebyattr in use but ds.cohort.annotation missing";t.cohort.sampleAttribute||(t.cohort.sampleAttribute={}),t.cohort.sampleAttribute.attributes||(t.cohort.sampleAttribute.attributes={},console.log("cohort.sampleAttribute added when groupsamplebyattr is in use"));for(const n of e.groupsamplebyattr.attrlst){if(!n.k)return"k missing from one of groupsamplebyattr.attrlst[]";t.cohort.sampleAttribute.attributes[n.k]||(t.cohort.sampleAttribute.attributes[n.k]={label:n.label||n.k})}if(e.groupsamplebyattr.sortgroupby){if(!e.groupsamplebyattr.sortgroupby.key)return".key missing from .sortgroupby";if(!e.groupsamplebyattr.sortgroupby.order)return".order[] missing from .sortgroupby";if(!Array.isArray(e.groupsamplebyattr.sortgroupby.order))return".order must be an array"}e.groupsamplebyattr.attrnamespacer||(e.groupsamplebyattr.attrnamespacer=", ")}console.log("("+e.type+") "+e.name+": "+(e.samples?e.samples.length:"no")+" samples, "+(e.nochr?'no "chr"':'has "chr"'))}function Bo(e,t,n){if(!e.datatype)return"datatype missing";if(e.viewrangeupperlimit&&Number.isNaN(e.viewrangeupperlimit))return"invalid value for viewrangeupperlimit";let s;if(!e.file)return"file missing";{const[t,n]=jo(e.file);if(t)return"tabix file error: "+t;s=n}const r={cwd:null,encoding:"utf8"};{const t=N().execSync(Gr+" -H "+s,r).trim();if(!t)return"no header line (#sample <sample1> ...)";const n=new Set;for(const e of t.split("\n")){const t=e.split(" ");for(let e=1;e<t.length;e++)n.add(t[e])}if(0==n.size)return"no sample names from header line";e.samples=[...n],console.log("(genenumeric) "+e.name+": "+e.samples.length+" samples")}if(e.boxplotbysamplegroup){if(!e.boxplotbysamplegroup.attributes)return"boxplotbysamplegroup.attributes missing";if(!Array.isArray(e.boxplotbysamplegroup.attributes))return"boxplotbysamplegroup.attributes should be array";for(const t of e.boxplotbysamplegroup.attributes)if(!t.k)return"k missing from one of boxplotbysamplegroup.attributes[]"}}async function zo(e,t,n){if(!e.tracks)return"tracks[] missing";if(!Array.isArray(e.tracks))return"tracks should be array";e.info={};for(const s of e.tracks){if(!s.file)return"file missing from a track (url not supported yet)";const[r,o]=jo(s.file);if(r)return"tabix file error: "+r;if(s.type!=$.mdsvcftype.vcf)return"invalid track type: "+s.type;{s.cwd;const t=await F.ZD(o,s.cwd);if(0==t.length)return"no meta/header lines for "+o;const[n,r,i,a]=D.e(t);if(a)return"error parsing vcf meta for "+o+": "+a.join("\n");if(0==i.length)return"vcf file has no sample: "+o;for(const t in n)e.info[t]=n[t];if(s.format=r,s.samplenameconvert){if("function"!=typeof s.samplenameconvert)return".samplenameconvert must be function";for(const e of i)e.name=s.samplenameconvert(e.name)}s.samples=i}if(t.cohort&&t.cohort.annotation){const e=[];for(const n of s.samples)t.cohort.annotation[n.name]||e.push(n.name);e.length&&console.log(t.label+": VCF "+s.file+" has unannotated samples: "+e.join(","))}{const e=[];if(await F.UE({args:["-l",o],dir:s.cwd,callback:t=>{e.push(t)}}),0==e.length)return"no chr from "+o;s.nochr=$.contigNameNoChr(n,e)}console.log("("+e.type+") "+o+": "+s.samples.length+" samples, "+(s.nochr?"no chr":"has chr"))}if(e.singlesamples){if(!e.singlesamples.tablefile)return".singlesamples.tablefile missing for the VCF query";e.singlesamples.samples={};let t=0;for(const n of h().readFileSync(y().join(r().tpmasterdir,e.singlesamples.tablefile),{encoding:"utf8"}).trim().split("\n")){if(!n)continue;if("#"==n[0])continue;const s=n.split("\t");s[0]&&s[1]&&(e.singlesamples.samples[s[0]]=s[1],t++)}console.log(t+" single-sample VCF files")}}},6191:(e,t,n)=>{"use strict";n.d(t,{i:()=>y});var s=n(7147),r=n(1017),o=n.n(r),i=n(9344),a=n.n(i),l=n(8088);async function c(e,t){!function(e){for(const t in e){const n=e[t];if("login"==n.type){if(n.embedders)throw"unexpected 'embedders' property";n["*"]={"*":{type:"basic",password:n.password,secret:n.secret}},delete n.type,delete n.password}else if("jwt"==n.type){for(const e in n.embedders)n.termdb={[e]:Object.assign({type:n.type},n.embedders[e])},n.headerKey&&(n.termdb[e].headerKey=n.headerKey);delete n.type,delete n.embedders,delete n.headerKey}else if(n.type)throw`unknown legacy credentials type='${n.type}'`}}(e);const n="secrets";if("string"==typeof e[n]){const t=await s.promises.readFile(e[n],"utf8");e[n]=JSON.parse(t)}for(const t in e){const n=e[t];n["*"]&&(n["/**"]=n["*"],delete n["*"]);const s=n.headerKey||"x-ds-access-token";delete n.headerKey;for(const r in n){const o=n[r];for(const n in o){o[n]=JSON.parse(JSON.stringify(o[n]));const i=o[n],a="string"==typeof i?e.secrets[i]:i;if("basic"==a.type)a.secret||(a.secret=a.password),a.authRoute="/dslogin";else if("jwt"==a.type)a.authRoute="/jwt-status",a.headerKey||(a.headerKey=s);else if("forbidden"!=a.type&&"open"!=a.type)throw`unknown cred.type='${a.type}' for dsCredentials[${t}][${n}][${r}]`;a.dslabel=t,a.route=r,a.cookieId="termdb"==r&&a.headerKey||`${t}-${r}-${n}-Id`}}}}const u={termdb:["matrix"],samples:["singleSampleData","getAllSamples","scatter","convertSampleId","getAllSamplesByName"]};function f(e,t){return e.cookies?.[`${t?.cookieId}`]||e.cookies?.[`${e.query.dslabel}SessionId`]||e.headers?.["x-sjppds-sessionid"]||e.query?.["x-sjppds-sessionid"]}async function d(e,t,n,r,o,i,l=""){if(r.secret)try{const c=Date.now(),u=Math.floor(c/1e3),f={dslabel:t.dslabel,id:n,iat:u,time:c,ip:e.ip,embedder:t.embedder,route:r.route,exp:u+Math.floor(o/1e3),email:l};r.dsnames&&(f.datasets=r.dsnames.map((e=>e.id)));const d=a().sign(f,r.secret);return await s.promises.appendFile(i,`${t.dslabel}\t${n}\t${c}\t${l}\t${e.ip}\t${t.embedder}\t${r.route}\n`),d}catch(e){throw e}}function p(e,t,n,s,r){if(!s.headers.authorization||n&&e[t]?.[n])return;if(!r.secret)throw{status:"error",error:`no credentials set up for this embedder='${s.query.embedder}'`,code:403};const[o,i]=s.headers.authorization.split(" ");if("bearer"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Bearer'`;const c=Buffer.from(i,"base64").toString();try{const o=a().verify(c,r.secret);if(n&&o.id!=n&&s.headers?.["x-sjppds-sessionid"]!=o.id)return;e[t]||(e[t]={});const i="/"!=s.path[0]||r.route.startsWith("/")?s.path:s.path.slice(1);if((0,l.isMatch)(i,r.route)||"authorizedActions"==i)return e[t][o.id]=o,o.id}catch(e){return}}async function m(e,t,n,r,o,i,a){const l=Date.now(),c=Math.random().toString()+"."+l.toString().slice(4),u=i.ip;return n[e.dslabel]||(n[e.dslabel]={}),n[e.dslabel][c]={id:c,time:l,email:o,ip:u},await s.promises.appendFile(r,`${e.dslabel}\t${c}\t${l}\t${o}\t${u}\t${e.embedder}\t${a.route}\n`),a.cookieMode&&"set-cookie"!=a.cookieMode||t.header("Set-Cookie",`${a.cookieId}=${c}; HttpOnly; SameSite=None; Secure`),c}function h(e,t,n,s,r=null){if(!n)return;if(!e.embedder)throw"missing q.embedder";const o=n.secret;if(!o)throw{status:"error",error:"no credentials set up for this embedder",code:403};const i=Math.floor((s||Date.now())/1e3),l=t[n.headerKey];if(!l)throw`missing header['${n.headerKey}']`;const c=n.processor?require(n.processor):{},u=c.handleToken?.(l)||l,f=a().verify(u,o);if(r)return{iat:f.iat,email:f.email,ip:f.ip};if(c.handlePayload)try{c.handlePayload(n,f,i)}catch(e){if("bad decrypt"==e.reason)throw`Please login again to access this feature. (${e.reason})`;throw e}if(i>f.exp)throw"Please login again to access this feature. (expired token)";const d=(n.dsnames||[e.dslabel]).filter((e=>!f.datasets?.includes(e.id))).map((e=>e.id));if(d.length)throw{error:"Missing access",linkKey:d.join(",")};return{iat:f.iat,email:f.email,ip:f.ip}}function g(e,t,n){if(!n.looseIpCheck||!e.ip?.includes(":")&&t){if(!t)throw"Server error: missing ip address in saved session";if(e.ip!=t&&e.ips?.[0]!=t&&e.connection?.remoteAddress!=t)throw"Your connection has changed, please refresh your page or sign in again."}}const y={maySetAuthRoutes:async function(e,t="",r=null){const i=r||n(334),b=i.features?.sessionTracking||"",v=o().join(i.cachedir,"dsSessions"),w=o().join(i.cachedir,"authorizedActions"),_=i.dsCredentials||{};delete i.dsCredentials;const k=i.maxSessionAge||576e5;let q;if(!_||!Object.keys(_).length)return y.getDsAuth=()=>[],y.getForbiddenRoutesForDsEmbedder=()=>[],y.userCanAccess=()=>!0,y.getRequiredCredForDsEmbedder=()=>{},void(y.getPayloadFromHeaderAuth=()=>({}));try{c(_)}catch(e){throw e}function x(e,t,n){if(!e.dslabel)return;const s=_[e.dslabel]||_["*"];if(s){if("/jwt-status"==t){const t=s[e.route]||s.termdb||s["/**"];return t&&(t[e.embedder]||t["*"])}if("/dslogin"==t){const t=s[e.route]||s["/**"];return t&&(t[e.embedder]||t["*"])}if(t.startsWith("/termdb")&&s.termdb){const t=s.termdb;return(n||u.termdb).includes(e.for)&&(t[e.embedder]||t["*"])}if(t.startsWith("/burden")&&s.burden)return s.burden[e.embedder]||s.burden["*"]}for(const n in _){if(n!=e.dslabel&&"*"!=n)continue;const s=_[n];for(const n in s){const r=s[n].routePattern||n;if(!(0,l.isMatch)(t,r))continue;const o=s[n];for(const t in o)if(t==e.embedder||"*"==t)return o[t]}}}e.use(((e,t,n)=>{if("/dslogin"==e.path||"/jwt-status"==e.path||"/dslogout"==e.path)return void n();const s=e.query,r=x(s,e.path);if(!r)return void n();let o;"jwt-only"==b&&(q={});try{const i=f(e,r);let a;if(!i){if("OPTIONS"==e.method.toUpperCase())return t.status(204),void t.send();if(a=p(q,s.dslabel,i,e,r),!a)throw o=401,"missing session cookie"}a||(a=p(q,s.dslabel,i,e,r));const l=q[s.dslabel]?.[i]||q[s.dslabel]?.[a];if(!l)throw o=401,"unestablished or expired browser session";g(e,l.ip,r);const c=Date.now();if(c-l.time>k){const{iat:t}=h(s,e.headers,r,l),n=c-t;if(n>k)throw delete q[s.dslabel][i],"Please login again to access this feature. (expired session)";if(n<3e5)return void(l.time=c)}l.time-c<900&&(l.time=c),n()}catch(e){console.log(e);const n=e.code||o;n&&t.status(n),t.send("object"==typeof e?e:{error:e})}}));try{q=await async function(e,t,n){const r={};for(const t in e)r[t]||(r[t]={});try{const e=await s.promises.readFile(t,"utf8"),o=+new Date;for(const t of e.split("\n")){if(!t)continue;const[e,s,i,a,l]=t.split("\t"),c=Number(i);r[e]||(r[e]={}),o-c<n&&(r[e][s]={id:s,time:c,email:a,ip:l})}return r}catch(e){return(0,s.existsSync)(t)&&console.log(e),r}}(_,v,k);const e=[];for(const t in q)for(const n in q[t]){const s=q[t][n];e.push(`${s.dslabel}\t${s.id}\t${s.time}\t${s.email}\t${s.ip}\t${s.embedder}\t${s.route}`)}await s.promises.writeFile(v,e.join("\n"))}catch(e){throw e}var N;await(N=0,new Promise((e=>setTimeout(e,N)))),e.post(t+"/dslogin",(async(e,t)=>{let n=401;try{const s=e.query,r=x(s,e.path);if(!r)throw n=400,`No login required for dataset='${s.dslabel}'`;if("/dslogin"!=r.authRoute)throw n=400,`Incorrect authorization route, use '${r.authRoute}'`;if(!e.headers.authorization)throw"missing authorization header";const[o,i]=e.headers.authorization.split(" ");if("basic"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Basic'`;if(Buffer.from(i,"base64").toString()!=r.password)throw"invalid password";const a=await m(s,t,q,v,"",e,r);n=401;const l=await d(e,s,a,r,k,v);t.send({status:"ok",jwt:l,route:r.route})}catch(e){t.status(n),t.send({error:e})}})),e.post(t+"/dslogout",(async(e,t)=>{try{const n=e.query,r=f(e,x(n,e.path));if(!r)throw"missing session cookie";const o=q[n.dslabel]?.[r];if(!o)return void t.send({status:"ok"});delete q[n.dslabel][r];e.ip;await s.promises.appendFile(v,`${n.dslabel}\t${r}\t0\t\t${o.ip}\t${o.embedder}\t${o.route}\n`),t.send({status:"ok"})}catch(e){t.status(401),t.send({error:e})}})),e.post(t+"/jwt-status",(async(e,t)=>{let n=401;try{const s=e.query,r=x(s,e.path);if(!r)return void t.send({status:"ok"});if("/jwt-status"!=r.authRoute)throw n=400,`Incorrect authorization route, use ${r.authRoute}'`;const{email:o,ip:i}=await h(s,e.headers,r);g(e,i,r);const a=await m(s,t,q,v,o,e,r);n=401;const l=await d(e,s,a,r,k,v,o);t.send({status:"ok",jwt:l,route:r.route,[r.cookieId]:a})}catch(e){console.log(e),t.status(n),t.send(e instanceof Error||"object"!=typeof e?{error:e}:e)}})),e.post(t+"/authorizedActions",(async(e,t)=>{const n=e.query;try{const r=x(n,"termdb");if(!r)return void t.send({status:"ok"});const o=f(e),i=p(q,n.dslabel,o,e,r),a=q[n.dslabel]?.[o]||q[n.dslabel]?.[i],{email:l}=a.email,c=new Date;await s.promises.appendFile(w,`${n.dslabel}\t${l}\t${c}\t${n.action}\t${JSON.stringify(n.details)}\n`),t.send({status:"ok"})}catch(e){t.status(401),t.send("object"==typeof e?e:{error:e})}})),y.getDsAuth=function(e){const t=[],n=e.query.embedder||e.get("host").split(":")[0];for(const s in _){if(s.startsWith("__"))continue;const r=_[s];for(const o in r){const i=r[o];for(const r in i){if(!(0,l.isMatch)(n,r))continue;const a=i[r],c=f({query:Object.assign({},e.query,{dslabel:s}),headers:e.headers,cookies:e.cookies},a),u=q[s]?.[c],d=u?.time||0;t.push({dslabel:s,route:o,type:a.type||"basic",insession:("basic"!=a.type||!e.path.startsWith("/genomes"))&&(("jwt"!=a.type||c)&&Date.now()-d<k)})}}}return t},y.getForbiddenRoutesForDsEmbedder=function(e,t){const n=[],s=_[e]||_["*"];if(!s)return n;for(const e in s){const r=s[e][t]||s[e]["*"];"forbidden"==r?.type&&n.push(e)}return n},y.getRequiredCredForDsEmbedder=function(e,t){const n=[];for(const s in _)if((0,l.isMatch)(e,s))for(const e in _[s])for(const r in _[s][e]){if(!(0,l.isMatch)(t,r))continue;const o=_[s][e][r];n.push({route:e,type:o.type,headerKey:o.headerKey})}return n},y.userCanAccess=function(e,t){const n=x(e.query,e.path,u.samples);if(!n)return!0;if("basic"==n.type&&e.path.startsWith("/genomes"))return!1;const s=f(e,n),r=p(q,t.label,s,e,n),o=q[t.label]?.[s]||q[t.label]?.[r],i=o?.time||0;return Date.now()-i<k},y.getPayloadFromHeaderAuth=function(e,t){if(!e.headers?.authorization)return{};const n=x(e.query,t);if(!n)return{};const[s,r]=e.headers.authorization.split(" ");if("bearer"!=s.toLowerCase())throw`unsupported authorization type='${s}', allowed: 'Bearer'`;const o=Buffer.from(r,"base64").toString();return a().verify(o,n.secret)||{}}},getJwtPayload:h,canDisplaySampleIds:(e,t)=>!!t.cohort.termdb.displaySampleIds&&y.userCanAccess(e,t),getDsAuth:()=>[],getForbiddenRoutesForDsEmbedder:()=>[],userCanAccess:()=>!0,getRequiredCredForDsEmbedder:()=>{},getPayloadFromHeaderAuth:()=>({})}},7833:(e,t,n)=>{"use strict";n.r(t);var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=(n(3345),n(334)),l=n.n(a),c=n(8907),u=n(8064),f=n(5494),d=n(6733),p=n(5558),m=n(3602),h=n(6279);const g={snvindel:f,sv:h,fusion:h,svjson:n(8423),cnv:d,itd:m,deletion:p,truncation:n(8235)};function y(e,t,n,s,r,o){for(const i of t.yesSamples){if(o&&!o.includes(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:parseInt(e),class:"WT",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:parseInt(e),class:"WT",_SAMPLEID_:i})}for(const i of t.noSamples){if(o&&!o.includes(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:parseInt(e),class:"Blank",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:parseInt(e),class:"Blank",_SAMPLEID_:i})}}async function b(e,t){const n=e.cohort;try{if(n.mutationFlagSet)return n.mutationFlagSet;if(!n.mutationset)return;const s={},r=e.sampleName2Id;for(const[e,o]of n.mutationset.entries()){const n=await v(e,o,t);s[Math.random()]=n;for(const e in n.data)for(const t of n.data[e])t._SAMPLENAME_=t.sample.split(";")[0].trim(),t._SAMPLEID_=r.get(t._SAMPLENAME_)||t._SAMPLENAME_}return n.mutationFlagSet=s,s}catch(e){throw e}}async function v(e,t,n){const s=u.Dz(n);if(!s)throw"init_bulk_flag() failed";s.tpsetname=t.name?t.name:"set"+e;for(const e in t){if(!(e in g))throw`unknown mutationset: ${e}`;const n=t[e].startsWith("/")?t[e]:i().join(l().tpmasterdir,t[e]);try{const t=(await r().promises.readFile(n,"utf8")).trim().split(/\r?\n/);if(g[e].parseheader(t[0],s))throw`${e} header line error: herr`;for(let n=1;n<t.length;n++)g[e].parseline(n,t[n],s)}catch(e){throw e}}return s}exports.mayGetGeneVariantData=async function(e,t){const n=this,s=e.term.name,r=await b(n,t.genome),o=new Map;if(!r)return o;let i;t?.filter?.lst.length>0&&(i=[...new Set((await(0,c.cf)(t.filter,n)).map((e=>e.id)))]);for(const e in r){const t=r[e];if(s in t.data){for(const e of t.data[s]){const t=e._SAMPLEID_;if(i&&!i.includes(t))continue;o.has(t)||o.set(t,{sample:t});const n=o.get(t);s in n||(n[s]={key:s,values:[],label:s}),n[s].values.push(e)}if(n.assayAvailability?.byDt)for(const e in n.assayAvailability.byDt){const t=n.assayAvailability.byDt[e];if(t.byOrigin)for(const n in t.byOrigin){y(e,t.byOrigin[n],o,s,n,i)}else y(e,t,o,s,!1,i)}}}return o},exports.getTermTypes=async function(e){const t=this;try{const n="string"==typeof e.ids?JSON.parse(e.ids):e.ids,s=n.map((()=>"?")).join(","),r=`SELECT id, name, type, jsondata, parent_id FROM terms WHERE id IN (${s}) OR name IN (${s})`,o=t.cohort.db.connection.prepare(r).all([...n,...n]),i={};for(const e of o)e.jsondata&&Object.assign(e,JSON.parse(e.jsondata)),i[e.id]=e;const a=n.filter((e=>!i[e])),l=await b(t,e.genome);if(l)for(const e in l){const t=l[e];if(t.data)for(const e of a)e in t.data&&!(e in i)&&(i[e]={name:e,type:"geneVariant"})}return i}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}},exports.mayGetMatchingGeneNames=async function(e,t,n,s=25){const r=await b(this,n.genome);if(r)for(const n in r){const o=r[n];for(const n in o.data){if(n.length>s)continue;if(!o.data[n]?.length)continue;const r={name:n,type:"geneVariant",isleaf:!0};n===t?e.equals.push(r):n.startsWith(t)?e.startsWith.push(r):n.includes(" "+t)?e.startsWord.push(r):n.includes(t)?e.includes.push(r):"TP53"==n&&0}}},exports.get_flagset=b},4065:(e,t,n)=>{"use strict";function s(e,t){if(e.genomicNameRegexp.test(t.input))throw"invalid character in gene name";if(t.deep){const n={};let s;{const n=e.genedb.getnamebynameorisoform.get(t.input,t.input);n&&(s=n.name)}if(!s&&e.genedb.getNameByAlias){const n=e.genedb.getNameByAlias.get(t.input);n&&(s=n.name)}if(!s&&e.genedb.get_gene2canonicalisoform&&t.input.toUpperCase().startsWith("ENSG")){const r=e.genedb.get_gene2canonicalisoform.get(t.input);if(r&&r.isoform){const t=r.isoform;n.found_isoform=t;const o=e.genedb.getnamebynameorisoform.get(t,t);if(!o)throw"cannot map enst isoform to symbol";s=o.name}}s||(s=t.input);const r=e.genedb.getjsonbyname.all(s);return n.gmlst=r.map((e=>{const t=JSON.parse(e.genemodel);return e.isdefault&&(t.isdefault=!0),t})),n}const n=t.input.toUpperCase(),s=(n.substr(0,2),e.genedb.getnameslike.all(n+"%"));if(s.length)return s.sort(),{hits:s.map((e=>e.name))};if(e.genedb.getNameByAlias){const t=e.genedb.getNameByAlias.all(n);if(t.length)return{hits:t.map((e=>e.name))}}{const n=e.genedb.getnamebynameorisoform.get(t.input,t.input);if(n)return{hits:[n.name]}}return{hits:[]}}n.d(t,{S:()=>s})},2062:(e,t,n)=>{"use strict";n.d(t,{W:()=>a,A:()=>l});var s=n(334),r=n.n(s),o=n(7147),i=n.n(o);async function a(e){l.deps||async function(){const e=`${process.cwd()}/package.json`;try{if(!i().existsSync(e))return;{const t=i().readFileSync(e,{encoding:"utf8"}),n=JSON.parse(t),s=n?.dependencies["@sjcrh/proteinpaint-server"];s&&(l.deps["@sjcrh/proteinpaint-server"].entry=s);const r=n?.dependencies["@sjcrh/proteinpaint-client"];r&&(l.deps.entry["@sjcrh/proteinpaint-client"]||(l.deps["@sjcrh/proteinpaint-client"]={}),l.deps["@sjcrh/proteinpaint-client"]=r)}}catch(e){console.log(e)}}();const t={status:"ok",genomes:{},versionInfo:l};for(const n in e){const s=e[n],r={};if(s.genedb&&(r.genedb={buildDate:s.genedb.get_buildDate?.get().date||"unknown",tables:s.genedb.tableSize}),s.termdbs){r.termdbs={};for(const e in s.termdbs){const t=s.termdbs[e];r.termdbs[e]={buildDate:t.cohort.termdb.q.get_buildDate?.get().date||"unknown"}}}Object.keys(r).length&&t.genomes&&(t.genomes[n]=r)}return t}const l={pkgver:"2.43.1",codedate:function(){const e=i().existsSync(r().binpath+"/server.js")&&i().statSync(r().binpath+"/server.js").mtime||new Date(0),t=i().existsSync("public/bin/proteinpaint.js")&&i().statSync("public/bin/proteinpaint.js").mtime||new Date(0);return(e>t?e:t).toDateString()}(),launchdate:new Date(Date.now()).toString().split(" ").slice(0,5).join(" "),deps:{}},c=`${r().binpath}/package.json`;if(i().existsSync(c)){const e=JSON.parse(i().readFileSync(c,{encoding:"utf8"}));l.deps["@sjcrh/proteinpaint-server"]={installed:e.version}}const u=c.replace("server","client");if(i().existsSync(u)){const e=JSON.parse(i().readFileSync(u,{encoding:"utf8"}));l.deps["@sjcrh/proteinpaint-client"]={installed:e.version}}},9157:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>c});var s=n(7147),r=n.n(s),o=(n(1017),n(334)),i=n.n(o),a=n(2081),l=n(2781);async function c(e,t,n=[]){try{await r().promises.stat(e)}catch(t){throw`${e} does not exist`}const s=[],o=[];return new Promise(((r,c)=>{const u=(0,a.spawn)(i().Rscript,[e,...n]);if(t&&t.length>0)try{const e=t.join("\n")+"\n";l.Readable.from(e).pipe(u.stdin)}catch(e){u.kill();let t=e;o.length>0&&(t+=`\nR stderr: ${o.join("").trim()}`),c(t)}u.stdout.on("data",(e=>s.push(e))),u.stderr.on("data",(e=>o.push(e))),u.on("error",(e=>c(e))),u.on("close",(e=>{if(0!==e){let t=`R process exited with non-zero status code=${e}`;s.length>0&&(t+=`\nR stdout: ${s.join("").trim()}`),o.length>0&&(t+=`\nR stderr: ${o.join("").trim()}`),c(t)}if(o.length>0){const e=o.join("").trim();c(`R process emitted standard error\nR stderr: ${e}`)}const t=s.join("").trim().split("\n");r(t)}))}))}},901:(e,t,n)=>{"use strict";n.d(t,{T:()=>r,w:()=>o});var s=n(8907);async function r(e,t,n){if(!t)return;const r=function(e,t){{const t=e.filter||e.filterObj;if(t){if(!Array.isArray(t.lst))throw"filterObj.lst is not array";return 0==t.lst.length?null:t}}if(e.tid2value){if("object"!=typeof e.tid2value)throw"q.tid2value{} not object";return o(e.tid2value,t)}}(e,n);if(!r)return;const i=[...new Set((await(0,s.cf)(r,n)).map((e=>e.id)))];let a;a=Number.isInteger(t[0])?new Set(t):new Set(t.map((e=>e.name)));const l=new Set;for(const e of i)a.has(e)&&l.add(e);return l}function o(e,t){const n={type:"tvslst",in:!0,join:"and",lst:[]};for(const s in e){const r=t.cohort.termdb.q.termjsonByOneid(s);if(!r)continue;const o=e[s];n.lst.push({type:"tvs",tvs:{term:r,values:[{key:o}]}})}return n}},4555:(e,t,n)=>{"use strict";n.d(t,{Ak:()=>$,Z5:()=>G,sV:()=>ne,eG:()=>P,r8:()=>oe,z7:()=>re,ws:()=>ee,nD:()=>X,wm:()=>te,IK:()=>J,CN:()=>U,xq:()=>L,vK:()=>D});var s=n(2273),r=n(4048);class o extends Error{constructor(e,t,n){const s=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=n}}class i extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const a=e=>null!==e&&"object"==typeof e,l=(...e)=>{for(const t of e)if((!a(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return u({},...e)},c=(e={},t={})=>{const n=new globalThis.Headers(e),s=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[e,t]of r.entries())s&&"undefined"===t||void 0===t?n.delete(e):n.set(e,t);return n},u=(...e)=>{let t={},n={};for(const s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(a(s)){for(let[e,n]of Object.entries(s))a(n)&&e in t&&(n=u(t[e],n)),t={...t,[e]:n};a(s.headers)&&(n=c(n,s.headers),t.headers=n)}return t},f=(()=>{let e=!1,t=!1;const n="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return n&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),d="function"==typeof globalThis.AbortController,p="function"==typeof globalThis.ReadableStream,m="function"==typeof globalThis.FormData,h=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},y=2147483647,b=Symbol("stop"),v={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},w={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},_=e=>h.includes(e)?e.toUpperCase():e,k=[413,429,503],x={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:k,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},N=(e={})=>{if("number"==typeof e)return{...x,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...x,...e,afterStatusCodes:k}};class S{static create(e,t){const n=new S(e,t),s=async()=>{if("number"==typeof n._options.timeout&&n._options.timeout>y)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await n._fetch();for(const t of n._options.hooks.afterResponse){const s=await t(n.request,n._options,n._decorateResponse(e.clone()));s instanceof globalThis.Response&&(e=s)}if(n._decorateResponse(e),!e.ok&&n._options.throwHttpErrors){let t=new o(e,n.request,n._options);for(const e of n._options.hooks.beforeError)t=await e(t);throw t}if(n._options.onDownloadProgress){if("function"!=typeof n._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!p)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(e.clone(),n._options.onDownloadProgress)}return e},r=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(s):s();for(const[e,s]of Object.entries(g))r[e]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||s);const o=(await r).clone();if("json"===e){if(204===o.status)return"";if(0===(await o.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await o.text())}return o[e]()};return r}constructor(e,t={}){Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e;const n="credentials"in Request.prototype;if(this._options={credentials:n?this._input.credentials:void 0,...t,headers:c(this._input.headers,t.headers),hooks:u({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:_(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:N(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(d){if(this.abortController=new globalThis.AbortController,this._options.signal){const e=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(e.reason)}))}this._options.signal=this.abortController.signal}if(f&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(m&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(t,{...this.request}),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<=this._options.retry.limit&&!(e instanceof i)){if(e instanceof o){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const t=e.response.headers.get("Retry-After");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t);return Number.isNaN(e)?e=Date.parse(t)-Date.now():e*=1e3,void 0!==this._options.retry.maxRetryAfter&&e>this._options.retry.maxRetryAfter?0:e}if(413===e.response.status)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const n=Math.min(this._calculateRetryDelay(t),y);if(0!==n&&this._retryCount>0){await async function(e,{signal:t}){return new Promise(((n,s)=>{function r(){clearTimeout(o),s(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",r,{once:!0}));const o=setTimeout((()=>{t?.removeEventListener("abort",r),n()}),e)}))}(n,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===b)return}return this._retry(e)}throw t}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const n={};for(const s in t)s in w||s in v||s in e||(n[s]=t[s]);return n})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),e):async function(e,t,n,s){return new Promise(((r,o)=>{const a=setTimeout((()=>{n&&n.abort(),o(new i(e))}),s.timeout);s.fetch(e,t).then(r).catch(o).then((()=>{clearTimeout(a)}))}))}(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const n=Number(e.headers.get("content-length"))||0;let s=0;return 204===e.status?(t&&t({percent:1,totalBytes:n,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(r){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array),await async function e(){const{done:i,value:a}=await o.read();if(i)r.close();else{if(t){s+=a.byteLength;t({percent:0===n?0:s/n,transferredBytes:s,totalBytes:n},a)}r.enqueue(a),await e()}}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}const A=e=>{const t=(t,n)=>S.create(t,l(e,n));for(const n of h)t[n]=(t,s)=>S.create(t,l(e,s,{method:n}));return t.create=e=>A(l(e)),t.extend=t=>A(l(e,t)),t.stop=b,t},C=A();var j=n(1017),T=n.n(j),M=n(4973);function O(e){const t={op:e.in?"and":"not",content:[]};if(!Array.isArray(e.lst))throw"filter.lst[] not array";for(const n of e.lst){if("tvs"!=n.type)throw'filter.lst[] item.type!="tvs"';if(!n.tvs)throw"item.tvs missing";if(!n.tvs.term)throw"item.tvs.term missing";if(n.tvs.values){const e={op:n.tvs.isnot?"!=":"in",content:{field:I(n.tvs.term.id),value:n.tvs.values.map((e=>e.key))}};t.content.push(e)}else{if(!n.tvs.ranges)throw"unknown tvs structure when converting to gdc filter";for(const e of n.tvs.ranges)e.startunbounded?t.content.push({op:e.stopinclusive?n.tvs.isnot?">":"<=":n.tvs.isnot?">=":"<",content:{field:I(n.tvs.term.id),value:e.stop}}):e.stopunbounded?t.content.push({op:e.startinclusive?n.tvs.isnot?"<":">=":n.tvs.isnot?"<=":">",content:{field:I(n.tvs.term.id),value:e.start}}):n.tvs.isnot?t.content.push({op:"or",content:[{op:"and",content:[{op:e.startinclusive?"<":"<=",content:{field:I(n.tvs.term.id),value:e.start}}]},{op:"and",content:[{op:e.stopinclusive?">":">=",content:{field:I(n.tvs.term.id),value:e.stop}}]}]}):t.content.push({op:"and",content:[{op:e.startinclusive?">=":">",content:{field:I(n.tvs.term.id),value:e.start}},{op:e.stopinclusive?"<=":"<",content:{field:I(n.tvs.term.id),value:e.stop}}]})}}return t}function I(e){const t=e.split(".");return"case"==t[0]&&(t[0]="cases"),t.join(".")}n(3345);var E=n(334),R=n.n(E);function F(...e){R().debugmode&&console.log(e.join(" "))}function $(e,t){e.convertSampleId.get=e=>{const n={};for(const s of e)n[s]=t.__gdc.map2caseid.get(s)||s;return n}}async function D(e,t){e.get=async e=>{if(!e.ssm_id)throw".ssm_id missing";const{host:n,headers:s}=t(e),r=await C(T().join(n.rest,"ssms",e.ssm_id+"?fields=consequence.transcript.is_canonical,consequence.transcript.transcript_id"),{headers:s}).json();if(!Array.isArray(r?.data?.consequence))throw".data.consequence not array";const o=r.data.consequence.find((e=>e.transcript.is_canonical));return o?o.transcript.transcript_id:r.data.consequence[0].transcript.transcript_id}}function L(e){e.queries.snvindel.byrange.get=async t=>await e.queries.snvindel.byisoform.get(t)}function P(e,t){e.queries.geneExpression.get=async n=>{if(!Array.isArray(n.genes))throw"q.genes[] not array";const s=new Map,r=new Date,o=await G(n,e);if(0==o.length)return{gene2sample2value:s,byTermId:{}};const i=new Date;F(o.length,"cases with exp data:",i-r,"ms");const[a,l]=await async function(e,t,n,s,r){const o=[],i=new Map;for(const n of e){const e=n.gene||n.name;if("string"!=typeof e)continue;if(e.startsWith("ENSG")&&15==e.length){o.push(e),i.set(e,e);continue}const s=t.genedb.getAliasByName.all(e);if(Array.isArray(s))for(const t of s)if(t.alias.startsWith("ENSG")){o.push(t.alias),i.set(t.alias,e);break}if(o.length>100)break}try{const{host:e,headers:t}=s.getHostHeaders(r),a=await C.post(`${e.geneExp}/gene_expression/gene_selection`,{headers:t,json:{case_ids:n,gene_ids:o,selection_size:o.length}}).json();if(!Array.isArray(a.gene_selection))throw"re.gene_selection[] not array";const l=[];for(const e of a.gene_selection){if("string"!=typeof e.gene_id)throw".gene_id missing from one of re.gene_selection[]";l.push(e.gene_id)}return[l,i]}catch(e){throw e}}(n.genes,t,o,e,n);if(0==a.length)return{gene2sample2value:s,byTermId:{}};const c=new Date;F(a.length,"out of",n.genes.length,"genes selected for exp:",c-i,"ms");const u={};for(const e of a){const t=l.get(e);u[t]={gencodeId:e},s.set(t,new Map)}const f=await async function(e,t,n,s,r,o){const{host:i,headers:a}=o.getHostHeaders(e),l=(await C.post(`${i.geneExp}/gene_expression/values`,{headers:a,json:{case_ids:n,gene_ids:t,format:"tsv",tsv_units:"uqfpkm"}}).text()).trim().split("\n");if(l.length<=1)throw"less than 1 line from tsv response.body";const c=l[0].split("\t").slice(1);if(c.length!=n.length)throw"sample column length != case_ids.length";const u={};for(const e of c){const t=o.__gdc.caseid2submitter.get(e);if(!t)throw"case submitter id unknown for a uuid";u[e]={label:t}}for(let e=1;e<l.length;e++){const t=l[e].split("\t");if(t.length!=c.length+1)throw"number of fields in gene line does not equal header";const n=t[0];if(!n)throw"ensg l[0] missing from a line";const o=s.get(n);if(!o)throw"symbol missing for "+n;for(const[e,n]of c.entries()){const s=Number(t[e+1]);if(!Number.isFinite(s))throw"non-numeric exp value from gdc";r.get(o)[n]=s}}return u}(n,a,o,l,s,e);return F("gene-case matrix built:",new Date-c,"ms"),{gene2sample2value:s,byTermId:u,bySampleId:f}}}async function G(e,t){const n={op:"and",content:[]};e.filter0&&n.content.push(e.filter0),e.filterObj&&n.content.push(O(e.filterObj)),e.filter&&n.content.push(O(e.filter));const s={size:1e4,fields:"case_id"};n.content.length&&(s.case_filters=n);try{const{host:n,headers:r}=t.getHostHeaders(e),o=await C.post(T().join(n.rest,"cases"),{headers:r,json:s}).json();if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";const i=[];for(const e of o.data.hits)if(e.id&&t.__gdc.casesWithExpData.has(e.id)&&(i.push(e.id),1e3==i.length))break;return i}catch(e){throw e.stack&&console.log(e.stack),e}}function U(e){e.queries.snvindel.byisoform.get=async t=>{const n=B(t,e),r=await async function(e,t){const n=ie,s=le,{host:r,headers:o}=t.getHostHeaders(e),i=C.post(T().join(r.rest,n.endpoint),{headers:o,json:Object.assign({size:n.size,fields:n.fields.join(",")},n.filters(e))}).json(),a=C.post(T().join(r.rest,s.endpoint),{headers:o,json:Object.assign({size:s.size,fields:s.fields.join(",")},s.filters(e,t))}).json(),[l,c]=await Promise.all([i,a]);if(!Array.isArray(l?.data?.hits)||!Array.isArray(c?.data?.hits))throw"ssm tandem query not returning data.hits[]";const u=new Map;for(const t of l.data.hits){if(!t.ssm_id)throw"ssm_id missing from a ssms hit";if(!t.consequence)throw".consequence[] missing from a ssm";if(!Number.isInteger(t.start_position))throw"hit.start_position is not integer";let n;t.csqcount=t.consequence.length,n=e.isoform?t.consequence.find((t=>t.transcript.transcript_id==e.isoform)):t.consequence.find((e=>e.transcript.is_canonical)),t.consequence=n||t.consequence[0],t.cases=[],u.set(t.ssm_id,t)}for(const e of c.data.hits){if(!e.ssm)throw".ssm{} missing from a case";if(!e.ssm.ssm_id)throw".ssm.ssm_id missing from a case";const t=u.get(e.ssm.ssm_id);if(!t)throw"ssm_id not found in ssms query";if(!e.case)throw".case{} missing from a case";t.cases.push(e.case)}return[...u.values()]}(t,e),o=[];for(const e of r){const n={ssm_id:e.ssm_id,dt:s.dtsnvindel,chr:e.chromosome,pos:e.start_position-1,ref:e.reference_allele,alt:e.tumor_allele,isoform:t.isoform,csqcount:e.csqcount};if(z(n,e.consequence),!t.hiddenmclass||!t.hiddenmclass.has(n.class)){n.samples=[];for(const s of e.cases){const e={};if(t.gdcUseCaseuuid){if(e.sample_id=s.case_id,!e.sample_id)throw"gdcUseCaseuuid=true but c.case_id undefined"}else if(e.sample_id=s.observation?.[0]?.sample?.tumor_sample_uuid,!e.sample_id)throw"gdcUseCaseuuid=false but c.observation?.[0]?.sample?.tumor_sample_uuid undefined";n.samples.push(e)}o.push(n)}}if(n){t.isoform=n;for(const e of o)e.isoform=n}return o}}function B(e,t){if(!e.isoform)return;let n;if("N"==e.isoform[0]&&t.refseq2ensembl_query){const s=t.refseq2ensembl_query.get(e.isoform);s&&(n=e.isoform,e.isoform=s.ensembl)}return n}function z(e,t){if(t&&t.transcript.consequence_type){const[n,r,o]=s.vepinfo(t.transcript.consequence_type);e.class=r,e.mname=t.transcript.aa_change}e.mname||(e.mname=e.ref+">"+e.alt),e.class||(s.basecolor[e.ref]&&s.basecolor[e.alt]?e.class=s.mclasssnv:"-"==e.ref?e.class=s.mclassinsertion:"-"==e.alt?e.class=s.mclassdeletion:e.class=s.mclassmnv)}function J(e){const t=["cnv.cnv_change","cnv.gene_level_cn","cnv.consequence.gene.symbol","case.submitter_id","case.case_id"];function n(e){const n=t.slice();if(e.twLst)for(const t of e.twLst){let e=t.term.id;e.startsWith("case.")&&(e="occurrence."+e),n.push(e)}return n.join(",")}function r(e){if(!e.gene&&"string"!=typeof e.gene)throw"p.gene does not provide non-empty string";const t={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};return e.gene&&t.filters.content.push({op:"=",content:{field:"cnv.consequence.gene.symbol",value:e.gene.split(",")}}),e.filter0&&t.case_filters.content.push(e.filter0),e.filterObj&&t.case_filters.content.push(O("string"==typeof e.filterObj?JSON.parse(e.filterObj):e.filterObj)),t}e.queries.geneCnv.bygene.get=async t=>{const{host:o,headers:i}=e.getHostHeaders(t),a=await C.post(T().join(o.rest,"cnv_occurrences"),{headers:i,json:Object.assign({size:1e5,fields:n(t)},r(t))}).json();if(!Array.isArray(a?.data?.hits))throw"geneCnv response body is not {data:hits[]}";const l={ssm_id:"geneCnvGain",dt:s.dtcnv,class:s.mclasscnvgain,samples:[]},c={ssm_id:"geneCnvLoss",dt:s.dtcnv,class:s.mclasscnvloss,samples:[]};for(const e of a.data.hits){if("object"!=typeof e.cnv)throw"hit.cnv{} not obj";if("object"!=typeof e.case)throw"hit.case{} not obj";if(!e.cnv.gene_level_cn)throw"hit.cnv.gene_level_cn is not true";let n;if("Gain"==e.cnv.cnv_change)n=l;else{if("Loss"!=e.cnv.cnv_change)throw"hit.cnv.cnv_change is not Gain/Loss";n=c}const s={sample_id:e.case.case_id};if(t.twLst)for(const n of t.twLst)W(s,e.case,n);n.samples.push(s)}const u=[];return l.samples.length&&u.push(l),c.samples.length&&u.push(c),u}}function H(e,t){if(!t)return;const n=t.split(",");for(const t of n){const n=t.split("--");if(2==n.length)return e.geneA=n[0].split("(")[0],void(e.geneB=n[1].split("(")[0])}}function W(e,t,n){const s=n.term.id.split(".");if(function t(r,o){const i=s[o];if(o==s.length-1)return void(e[n.term.id]?e[n.term.id].add(r[i]):e[n.term.id]=r[i]);const a=r[i];if(null==a)return;if(Array.isArray(a)){e[n.term.id]=new Set;for(const e of a)t(e,o+1);return}t(a,o+1)}(t,1),e[n.term.id]instanceof Set&&(e[n.term.id]=[...e[n.term.id]][0]),n.term.id in e&&"categorical"==n.term.type){const t=function(e,t){if("custom-groupset"==t.q?.type&&Array.isArray(t.q?.groupsetting?.customset?.groups))for(const n of t.q.groupsetting.customset.groups){if(!Array.isArray(n.values))throw"group.values[] not array from tw.q.groupsetting.customset.groups";if(-1!=n.values.findIndex((t=>t.key==e)))return n.name}if("predefined-groupset"==t.q?.type&&Number.isInteger(t.q.groupsetting?.predefined_groupset_idx)&&t.term.groupsetting?.lst[t.q.groupsetting.predefined_groupset_idx])for(const n of t.term.groupsetting.lst[t.q.groupsetting.predefined_groupset_idx]){if(!Array.isArray(n.values))throw"group.values[] not array from tw.term.groupsetting.lst[]";if(-1!=n.values.findIndex((t=>t.key==e)))return n.name}}(e[n.term.id],n);t&&(e[n.term.id]=t)}}function V(e,t){const n={};for(const s of t)if(("integer"==s.term.type||"float"==s.term.type)&&s.q?.mode)if("discrete"==s.q.mode||"binary"==s.q.mode){const t={};for(const n of e){const e=n[s.term.id];Number.isFinite(e)&&("min"in t?(t.min=Math.min(e,t.min),t.max=Math.max(e,t.max)):(t.min=e,t.max=e))}const o=(0,r.gp)(s.q,(e=>t),s.term.valueConversion);for(const e of o)e.name=e.label;n[s.term.id]={bins:o};for(const t of e){const e=t[s.term.id];Number.isFinite(e)&&(t[s.term.id]=Z(o,e))}}else if("continuous"!=s.q.mode)throw"mayApplyBinning: unknown numeric q.mode";return n}function Z(e,t){for(const n of e)if(n.startunbounded){if(t<n.stop)return n.label;if(n.stopinclusive&&t==n.stop)return n.label}else if(n.stopunbounded){if(t>n.start)return n.label;if(n.startinclusive&&t==n.start)return n.label}else if((t>n.start||t===n.start&&n.startinclusive)&&(t<n.stop||t===n.stop&&n.stopinclusive))return n.label}function K(e){for(const t of e)if(null==t.id||""==t.id){if(!t?.term?.id)throw"tw.id and tw.term are both missing";t.id=t.term.id}else t.term||(t.term={id:t.id})}async function X(e,t,n,s){if(e.isHierCluster)return await async function(e,t,n){const s={op:"and",content:[]};e.filter0&&s.content.push(e.filter0);e.filterObj&&s.content.push(O(e.filterObj));const r=[];for(const e of t){const t=n.cohort.termdb.q.termjsonByOneid(e.term.id);t&&r.push({term:t,q:e.q})}const o=["case_id"],i=new Map;for(const e of r){const t=e.term.id.replace(/^case\./,"");o.push(t),i.set(t,e.term.id)}const{host:a,headers:l}=n.getHostHeaders(e),c=await C.post(T().join(a.rest,"cases"),{headers:l,json:{size:n.__gdc.casesWithExpData.size,fields:o.join(","),case_filters:s.content.length?s:void 0}}).json();if(!Array.isArray(c?.data?.hits))throw"re.data.hits[] not array";const u=[];for(const e of c.data.hits){if("string"!=typeof e.case_id)throw"h.case_id missing";if(!n.__gdc.casesWithExpData.has(e.case_id))continue;const t={sample_id:e.case_id};for(const n of r)W(t,e,n);u.push(t)}const f=V(u,r);return{byTermId:f,samples:u}}(e,t,n);if(K(t),s){if(!Array.isArray(s))throw"geneTwLst not array";e.isoforms=[];for(const t of s){if(!t?.term?.name)throw"gene tw missing .term.name";if(t.term.isoform)e.isoforms.push(t.term.isoform);else{if("object"!=typeof e.genome)throw"serverside genome obj missing, needed to map gene name to canonical isoform";if(!e.genome?.genedb?.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const n=e.genome.genedb.get_gene2canonicalisoform.get(t.term.name);if(!n?.isoform)continue;e.isoforms.push(n.isoform)}}}t.some((e=>"case.observation.sample.tumor_sample_uuid"==e.id))||t.push({term:{id:"case.observation.sample.tumor_sample_uuid"}}),t.some((e=>"case.case_id"==e.id))||t.push({term:{id:"case.case_id"}}),"samples"==e.get&&(e.ssm_id_lst||e.isoform)&&(t.some((e=>"ssm.ssm_id"==e.id))||t.push({term:{id:"ssm.ssm_id"}}),t.some((e=>"case.observation.read_depth.t_alt_count"==e.id))||t.push({term:{id:"case.observation.read_depth.t_alt_count"}}),t.some((e=>"case.observation.read_depth.t_depth"==e.id))||t.push({term:{id:"case.observation.read_depth.t_depth"}}),t.some((e=>"case.observation.read_depth.n_depth"==e.id))||t.push({term:{id:"case.observation.read_depth.n_depth"}}));const r=[];for(const e of t){const t=n.cohort.termdb.q.termjsonByOneid(e.term.id);t&&r.push({term:t,q:e.q})}const o=t.map((e=>e.term.id));e.hiddenmclass&&(o.push("ssm.consequence.transcript.consequence_type"),o.push("ssm.consequence.transcript.transcript_id"),o.push("ssm.consequence.transcript.is_canonical")),e.rglst&&(o.push("ssm.chromosome"),o.push("ssm.start_position"));const i={size:1e4,fields:o.join(",")};B(e,n),Object.assign(i,le.filters(e,n));const{host:a,headers:l}=n.getHostHeaders(e),c=await C.post(T().join(a.rest,le.endpoint),{headers:l,json:i}).json();if(delete e.isoforms,!Array.isArray(c?.data?.hits))throw"variant2samples re.data.hits is not array for query";const u=[];for(const t of c.data.hits){if(!t.case)throw"variant2samples .case{} missing from a hit";const s={};if(t.ssm&&(s.ssm_id=t.ssm.ssm_id),e.hiddenmclass){if(!Array.isArray(t.ssm?.consequence))continue;let n;n=e.isoform?t.ssm.consequence.find((t=>t.transcript.transcript_id==e.isoform)):t.ssm.consequence.find((e=>e.transcript.is_canonical));const s={};if(z(s,n||t.ssm.consequence[0]),e.hiddenmclass.has(s.class))continue}if(e.gdcUseCaseuuid){if(s.sample_id=t.case.case_id,!s.sample_id)throw"querySamples_gdcapi: case.case_id missing"}else{const e=t.case?.observation?.[0]?.sample?.tumor_sample_uuid;if(!e)throw"querySamples_gdcapi: aliquot_id missing";s.sample_id=await n.__gdc.aliquot2submitter.get(e),s.sample_URLid=t.case.case_id+"?bioId="+e}for(const e of r)W(s,t.case,e);Y(t.case,s),Q(s,n),u.push(s)}const f=V(u,r);if(s){const e={gene:s.map((e=>e.term.name)).join(","),twLst:r},t=await n.queries.geneCnv.bygene.get(e);for(const e of t)for(const t of e.samples)u.push(t)}const d=new Map;for(const e of u)(0,M.z9)([e],d,e.ssm_id);return{byTermId:f,samples:[...d.values()]}}function Y(e,t){if(!e.observation)return;const n=e.observation[0];n&&n.read_depth&&(t.formatK2v={TumorAC:n.read_depth.t_depth-n.read_depth.t_alt_count+","+n.read_depth.t_alt_count,NormalDepth:n.read_depth.n_depth})}function Q(e,t){const n=e["case.project.project_id"];n&&(e.caseIsOpenAccess=t.__gdc.gdcOpenProjects?.has(n))}async function ee(e,t,n,s){K(e);const r=[];for(const t of e)t.term&&"categorical"==t.term.type&&r.push({id:t.id,path:t.id.replace("case.","").replace(/\./g,"__"),type:t.term.type});const o=function(e){const t=[];for(const n of e)if(n.id)if(n.type="categorical")t.push(n.path+" {buckets { doc_count, key }}");else{if("integer"!=n.type&&"float"!=n.type)throw"unknown term type";t.push(n.path+" {stats { count }}")}const n=`query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (case_filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\t${t.join("\n")}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`;return n}(r),i=function(e,t){const n={filters:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}}]}};ce(e?.tid2value,n.filters.content,t),e&&e.ssm_id_lst&&n.filters.content.push({op:"=",content:{field:"cases.gene.ssm.ssm_id",value:e.ssm_id_lst.split(",")}});e.filter0&&n.filters.content.push(e.filter0);e.filterObj&&n.filters.content.push(O(e.filterObj));return n}(t,s),{host:a,headers:l}=s.getHostHeaders(t),c=["data","explore","cases","aggregations"];let u=(await C.post(a.graphql,{headers:l,json:{query:o,variables:i}}).json())[c[0]];for(let e=1;e<c.length;e++)if(u=u[c[e]],!u)throw`.${c[e]} missing from data structure of termid2totalsize2 for query :${o} and filter: ${filter}`;for(const e of r){if("categorical"==e.type&&!Array.isArray(u[e.path].buckets))throw c.join(".")+" not array for query :"+o+" and filter: "+filter;if(("integer"==e.type||"float"==e.type)&&"object"!=typeof u[e.path].stats)throw c.join(".")+" not object for query :"+o+" and filter: "+filter}const f=new Map;for(const e of r)if("categorical"==e.type){const t=u[e.path].buckets,n=[];for(const e of t)n.push([e.key.replace(".","__"),e.doc_count]);f.set(e.id,n)}else if("integer"==e.type||"float"==e.type){const t=u[e.path].stats.count;f.set(e.id,{total:t})}return n?[f,n]:f}function te(e){const t=["consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change"];e.queries.snvindel.m2csq.get=async n=>{const{host:s,headers:r}=e.getHostHeaders(n),o=await C(s.rest+"/ssms/"+n.ssm_id+"?fields="+t.join(","),{headers:r}).json();if(!o.data||!o.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(o.data.consequence))throw".data.consequence not array";return o.data.consequence.map((e=>e.transcript))}}function ne(e,t){e.queries.singleSampleMutation.get=async t=>{if(t.sample.startsWith("___")){const e=t.sample.substring(3);if(!e)throw"expecting uuid after prefix but got blank";t.case_id=e}else e.__gdc.caseid2submitter.has(t.sample)?t.case_id=t.sample:(t.case_id=e.__gdc.map2caseid.get(t.sample),t.case_id||(t.case_id=await se(t.sample,e)));return await async function(e,t,n){const r={mlst:[],dt2total:[]};{const{host:n,headers:o}=t.getHostHeaders(e),i=await C.post(T().join(n.rest,ie.endpoint),{headers:o,json:{size:1e4,fields:ie.fields.join(","),filters:ie.filters(e).filters}}).json();if(!Number.isInteger(i.data?.pagination?.total))throw"re.data.pagination.total not integer";if(!Array.isArray(i.data?.hits))throw"re.data.hits[] not array";i.data.hits.length<i.data.pagination.total&&r.dt2total.push({dt:1,total:i.data.pagination.total});for(const e of i.data.hits){let t=e.consequence.find((e=>1==e.transcript.is_canonical));t||(t=e.consequence[0]);const n=t.transcript.aa_change||t.transcript.consequence_type,[o,i,a]=s.vepinfo(t.transcript.consequence_type);r.mlst.push({dt:s.dtsnvindel,mname:n,class:i,gene:t.transcript.gene.symbol,chr:e.chromosome,pos:e.start_position,ref:e.reference_allele,alt:e.tumor_allele})}}{const n=await async function(e,t){const{host:n,headers:r}=t.getHostHeaders(e),o=await C.post(T().join(n.rest,"files"),{headers:r,json:{size:1e4,fields:["cases.samples.sample_type","data_type","file_id","data_format","experimental_strategy","analysis.workflow_type"].join(","),filters:function(e){if(!e.case_id)throw".case_id missing";return{op:"and",content:[{op:"in",content:{field:"cases.case_id",value:[e.case_id]}},{op:"in",content:{field:"data_type",value:["Masked Copy Number Segment","Copy Number Segment","Transcript Fusion"]}}]}}(e)}}).json();if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";let i,a,l;for(const e of o.data.hits)if("BEDPE"!=e.data_format){if("TXT"==e.data_format){if("Genotyping Array"==e.experimental_strategy){const t=e.cases?.[0].samples?.[0]?.sample_type;if(!t)continue;if(t.includes("Normal"))continue;if("Masked Copy Number Segment"!=e.data_type)continue;i=e.file_id;continue}if("WGS"==e.experimental_strategy){if(!e.file_id)continue;if("Copy Number Segment"!=e.data_type)continue;a=e.file_id;continue}}}else{if("RNA-Seq"!=e.experimental_strategy)continue;if("Arriba"!=e.analysis?.workflow_type)continue;if("Transcript Fusion"!=e.data_type)continue;l=e.file_id}const c=[];if(a){const e=(await C(T().join(n.rest,"data",a),{headers:r}).text()).split("\n");for(let t=1;t<e.length;t++){const n=e[t].split("\t");if(7!=n.length)continue;const r=Number(n[4]),o=Number(n[5]),i=Number(n[6]);if(Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(i))continue;const a={dt:s.dtcnv,chr:n[1],start:Number(n[2]),stop:Number(n[3]),value:r};!a.chr||Number.isNaN(a.start)||Number.isNaN(a.stop)||(c.push(a),r>0&&0==i&&o>0&&c.push({dt:s.dtloh,chr:a.chr,start:a.start,stop:a.stop,segmean:.5}))}}else if(i){const e=(await C(T().join(n.rest,"data",i),{headers:r}).text()).split("\n");for(let t=1;t<e.length;t++){const n=e[t].split("\t");if(6!=n.length)continue;if(!n[1])continue;const r={dt:s.dtcnv,chr:"chr"+n[1],start:Number(n[2]),stop:Number(n[3]),value:Number(n[5])};Number.isNaN(r.start)||Number.isNaN(r.stop)||Number.isNaN(r.value)||c.push(r)}}if(l)try{const e=(await C(T().join(n.rest,"data",l),{headers:r}).text()).split("\n");for(let t=1;t<e.length;t++){const n=e[t].split("\t"),r={dt:s.dtfusionrna,chrA:n[0],posA:Number(n[1]),chrB:n[3],posB:Number(n[4])};r.chrA&&r.chrB&&!Number.isNaN(r.posA)&&!Number.isNaN(r.posB)&&(H(r,n[6]),c.push(r))}}catch(e){}return c}(e,t);r.mlst.push(...n)}return r}(t,e)}}async function se(e,t){const{host:n,headers:s}=t.getHostHeaders(q),r=await C.post(T().join(n.rest,"cases"),{headers:s,json:{size:1,fields:"case_id,submitter_id",filters:{op:"or",content:[{op:"=",content:{field:"samples.portions.analytes.aliquots.aliquot_id",value:[e]}},{op:"=",content:{field:"submitter_id",value:[e]}},{op:"=",content:{field:"samples.submitter_id",value:[e]}}]}}}).json();console.log(r);for(const e of r.data.hits)if(e.case_id)return e.case_id;throw"cannot convert to case_id (uuid)"}function re(e,t){e.queries.singleCell.samples.get=async t=>{const n={op:"and",content:[]};t.filter0&&n.content.push(t.filter0);const s={filters:{op:"and",content:[{op:"=",content:{field:"data_format",value:"tsv"}},{op:"=",content:{field:"data_type",value:"Single Cell Analysis"}},{op:"=",content:{field:"experimental_strategy",value:"scRNA-Seq"}}]},case_filters:n,size:100,fields:["cases.submitter_id","cases.project.project_id","cases.samples.sample_type","cases.samples.submitter_id","cases.primary_site","cases.disease_type"].join(",")},{host:r,headers:o}=e.getHostHeaders(t),i=await C.post(T().join(r.rest,"files"),{headers:o,json:s}).json();if(!Number.isInteger(i.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(i.data?.hits))throw"re.data.hits[] not array";const a=new Map;for(const e of i.data.hits){if(!e.id)throw"h.id (fileId) missing";const t=e.id,n=e.cases?.[0];if(!n)throw"h.cases[0] missing";const s=n.submitter_id;if(a.has(s)||a.set(s,{sample:s,"case.primary_site":n.primary_site,"case.disease_type":n.disease_type,"case.project.project_id":n.project?.project_id,experiments:[]}),!n.samples?.[0])throw"h.cases[0].samples[0] missing";a.get(s).experiments.push({experimentID:t,sampleName:n.samples[0].submitter_id,sampleType:n.samples[0].sample_type})}return{samples:[...a.values()]}}}function oe(e,t){e.queries.singleCell.data.get=async t=>{const{host:n,headers:s}=e.getHostHeaders(t),r=(await C(T().join(n.rest,"data",t.sample),{headers:s}).text()).trim().split("\n"),o={name:"UMAP",cells:[],colorBy:"Cluster"},i={name:"TSNE",cells:[],colorBy:"Cluster"},a={name:"PCA",cells:[],colorBy:"Cluster"},l={id:"cluster",name:"Seurat cluster",type:"categorical",values:{}},c={[l.id]:{}};for(let e=1;e<r.length;e++){const t=r[e],n=t.split("\t"),s=n[0];if(!s)throw"cellId missing from a line: "+t;const u=n[3];if(!u)throw"seuratCluster missing from a line";l.values[u]={label:"Cluster "+u},c[l.id][s]=`Cluster ${u}`;const f=Number(n[4]),d=Number(n[5]),p=Number(n[9]),m=Number(n[10]),h=Number(n[14]),g=Number(n[15]);if(Number.isNaN(f))throw"umap1 is nan";if(Number.isNaN(d))throw"umap2 is nan";if(Number.isNaN(p))throw"tsne1 is nan";if(Number.isNaN(m))throw"tsne2 is nan";if(Number.isNaN(h))throw"pc1 is nan";if(Number.isNaN(g))throw"pc2 is nan";const y=`Cluster ${u}`;o.cells.push({cellId:s,x:f,y:d,category:y}),i.cells.push({cellId:s,x:p,y:m,category:y}),a.cells.push({cellId:s,x:h,y:g,category:y})}return{plots:[i,o,a],terms:[l],tid2cellvalue:c}}}const ie={endpoint:"/ssms",size:1e5,fields:["ssm_id","chromosome","start_position","reference_allele","tumor_allele","consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change","consequence.transcript.gene.symbol","consequence.transcript.is_canonical"],filters:e=>{const t={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};let n;if(e.rglst&&(n=e.rglst[0],ae(n)),e.isoform){if("string"!=typeof e.isoform)throw".isoform value not string";t.filters.content.push({op:"=",content:{field:"consequence.transcript.transcript_id",value:[e.isoform]}}),n&&(t.filters.content.push({op:">=",content:{field:"start_position",value:n.start}}),t.filters.content.push({op:"<=",content:{field:"start_position",value:n.stop}}))}else if(n)t.filters.content.push({op:"=",content:{field:"chromosome",value:n.chr}}),t.filters.content.push({op:">=",content:{field:"start_position",value:n.start}}),t.filters.content.push({op:"<=",content:{field:"start_position",value:n.stop}});else{if(!e.case_id)throw".isoform, .rglst, and .case_id are all missing";if("string"!=typeof e.case_id)throw".case_id value not string";t.filters.content.push({op:"=",content:{field:"cases.case_id",value:[e.case_id]}})}if(e.set_id){if("string"!=typeof e.set_id)throw".set_id value not string";t.case_filters.content.push({op:"in",content:{field:"cases.case_id",value:[e.set_id]}})}return e.filter0&&t.case_filters.content.push(e.filter0),e.filterObj&&t.case_filters.content.push(O(e.filterObj)),t}};function ae(e){if("object"!=typeof e)throw"p.rglst[0] not object";if("string"!=typeof e.chr||!e.chr||!Number.isInteger(e.start)||!Number.isInteger(e.stop))throw"p.rglst[0] not valid {chr,start,stop}"}const le={endpoint:"/ssm_occurrences",size:1e5,fields:["ssm.ssm_id","case.case_id","case.submitter_id","case.observation.sample.tumor_sample_uuid"],filters:(e,t)=>{const n={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};let s=!1;if(e.ssm_id_lst){if("string"!=typeof e.ssm_id_lst)throw"ssm_id_lst not string";n.filters.content.push({op:"=",content:{field:"ssm.ssm_id",value:e.ssm_id_lst.split(",")}}),s=!0}else if(e.isoform)n.filters.content.push({op:"=",content:{field:"ssms.consequence.transcript.transcript_id",value:[e.isoform]}}),s=!0;else if(e.isoforms){if(!Array.isArray(e.isoforms))throw".isoforms[] not array";n.filters.content.push({op:"in",content:{field:"ssms.consequence.transcript.transcript_id",value:e.isoforms}}),s=!0}{let t;if(e.rglst&&(t=e.rglst[0],ae(t)),s)t&&(n.filters.content.push({op:">=",content:{field:"ssms.start_position",value:t.start}}),n.filters.content.push({op:"<=",content:{field:"ssms.start_position",value:t.stop}}));else{if(!t)throw".ssm_id_lst, .isoform, .isoforms, .rglst[] are all missing";n.filters.content.push({op:"=",content:{field:"ssms.chromosome",value:t.chr}}),n.filters.content.push({op:">=",content:{field:"ssms.start_position",value:t.start}}),n.filters.content.push({op:"<=",content:{field:"ssms.start_position",value:t.stop}})}}if(e.set_id){if("string"!=typeof e.set_id)throw".set_id value not string";n.case_filters.content.push({op:"in",content:{field:"cases.case_id",value:[e.set_id]}})}return e.filter0&&n.case_filters.content.push(e.filter0),e.filterObj&&n.case_filters.content.push(O(e.filterObj)),ce(e.tid2value,n.case_filters.content,t),n}};function ce(e,t,n){if(e)for(const s in e){const r=n.cohort.termdb.q.termjsonByOneid(s);if(!r)continue;const o=s.replace(/^case\./,"cases.");if("categorical"==r.type)t.push({op:"in",content:{field:o,value:[e[s]]}});else if("integer"==r.type)for(const n of e[s])t.push({op:n.op,content:{field:o,value:n.range}})}}},4973:(e,t,n)=>{"use strict";n.d(t,{z9:()=>p,dq:()=>f,uK:()=>d});var s=n(1881),r=n(4555),o=n(8877),i=n(7011);async function a(e,t){const n=[];let s=null,r=null;for(const o of t.map((t=>t[e.id]))){if(e.values?.[o]?.uncomputable)continue;const t=Number(o);Number.isFinite(t)&&(n.push(t),null===s?s=r=t:(s=Math.min(s,t),r=Math.max(r,t)))}const a=(0,o.Z)().domain([s,r]).range([10,510]),l=(0,i.q)(a,{values:n},!0,20);if(!Array.isArray(l.bins))throw"getBinsDensity does not return []";if(0==l.bins.length)throw"getBinsDensity returns an empty array";return{minvalue:s,maxvalue:r,densityMax:l.densityMax,density:l.bins,samplecount:n.length,unit:e.unit,ticks:20}}n(3345);var l=n(2273),c=n(4065),u=n(2974);const f=".";function d(e){const t=e.variant2samples;if(t){if(t.type_samples="samples",t.type_sunburst="sunburst",t.type_summary="summary",!t.variantkey)throw".variantkey missing from variant2samples";if(-1==["ssm_id"].indexOf(t.variantkey))throw"invalid value of variantkey";if(t.twLst){if(!Array.isArray(t.twLst))throw"variant2samples.twLst[] is not array";if(0==t.twLst.length)throw"variant2samples.twLst[] empty array";if(!e.cohort||!e.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.twLst is in use";for(const n of t.twLst){if(!n.id)throw"tw.id missing from one of variant2samples.twLst[]";const t=e.cohort.termdb.q.termjsonByOneid(n.id);if(!t)throw"term not found for one of variant2samples.twLst: "+n.id;if(n.term=t,!n.q)throw"tw.q{} missing for one of variant2samples.twLst: "+n.id}}if(t.sunburst_twLst){if(!Array.isArray(t.sunburst_twLst))throw".sunburst_twLst[] not array from variant2samples";if(0==t.sunburst_twLst.length)throw".sunburst_twLst[] empty array from variant2samples";if(!e.cohort||!e.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.sunburst_twLst is in use";for(const n of t.sunburst_twLst){if(!n.id)throw"tw.id missing from one of variant2samples.sunburst_twLst[]";const t=e.cohort.termdb.q.termjsonByOneid(n.id);if(!t)throw"term not found for one of variant2samples.sunburst_twLst: "+n.id;if(n.term=t,!n.q)throw"tw.q{} missing for one of variant2samples.sunburst_twLst: "+n.id}}if(t.gdcapi);else{let t=!1;if(e.queries?.snvindel?.byrange?._tk?.samples&&(t=!0),e.queries?.svfusion?.byrange?.samples&&(t=!0),!t)throw"cannot find a sample source from ds.queries{}"}t.get=async t=>await async function(e,t){!function(e,t){if("samples"==e.get){const n=t.queries?.snvindel?.byrange;n&&(n.bcffile||n.chr2bcffile)&&n._tk.format&&(e.addFormatValues=!0)}}(e,t);const n=await async function(e,t){const n=e.twLst?e.twLst.slice():[];if(t.variant2samples.gdcapi)return await(0,r.nD)(e,n,t,e.geneTwLst);if(e.ssm_id_lst)return await async function(e,t,n){const s=new Map;for(const t of e.ssm_id_lst.split(",")){const r=t.split(f);if(4!=r.length){if(6!=r.length)throw"unknown format of ssm id";{if(!n.queries.svfusion||!n.queries.svfusion.byrange)throw"queries.svfusion.byrange missing when id has 6 fields";const[t,o,i,a,c,u]=r,f=decodeURIComponent(u),d=Number(t);if(d!=l.dtsv&&d!=l.dtfusionrna)throw"dt not sv/fusion";const m=Number(i);if(Number.isNaN(m))throw"position not integer";const h=Number(c);if(Number.isNaN(h))throw"pairlstIdx not integer";const g=Object.assign({},e,{rglst:[{chr:o,start:m,stop:m+1}]}),y=await n.queries.svfusion.byrange.get(g);for(const e of y)e.dt==d&&e.pos==m&&e.strand==a&&e.pairlstIdx==h&&e.mname==f&&p(e.samples,s,e.ssm_id)}}else{if(!n.queries.snvindel||!n.queries.snvindel.byrange)throw"queries.snvindel.byrange missing when id has 4 fields";const[t,o,i,a]=r,l=Number(o);if(Number.isNaN(l))throw"no integer position for snvindel from ssm id";const c=Object.assign({},e,{rglst:[{chr:t,start:l,stop:l}]}),u=await n.queries.snvindel.byrange.get(c);for(const e of u)e.pos==l&&e.ref==i&&e.alt==a&&p(e.samples,s,e.ssm_id)}}return m(s,t,n),{samples:[...s.values()]}}(e,n,t);if(e.rglst)return await h(e,n,t);if(e.geneTwLst){if("object"!=typeof e.genome)throw"serverside genome obj needed";e.rglst=[];for(const t of e.geneTwLst)if(t.term.chr&&t.term.start&&t.term.stop)e.rglst.push({chr:t.term.chr,start:t.term.start,stop:t.term.stop});else{const n=c.S(e.genome,{deep:1,input:t.term.name});if(n.gmlst){const t=n.gmlst[0];e.rglst.push({chr:t.chr,start:t.start,stop:t.stop})}}const s=await h(e,n,t);return delete e.rglst,{samples:s}}if(!t?.cohort?.termdb)throw"unable to do sql query: .cohort.termdb missing for ds";const s={ds:t,filter:e.filter||e.filterObj},o=await(0,u.gh)(s,e.twLst),i=[];for(const t in o.samples){const n=o.samples[t];n.sample_id=n.sample,delete n.sample;for(const t of e.twLst)n[t.term.id]&&(n[t.term.id]=n[t.term.id].key);i.push(n)}return{samples:i}}(e,t);if(e.get==t.variant2samples.type_samples)return!e.useIntegerSampleId&&t?.cohort?.termdb?.q?.id2sampleName&&n.samples.forEach((e=>e.sample_id=t.cohort.termdb.q.id2sampleName(e.sample_id))),n;if(e.get==t.variant2samples.type_sunburst)return n.nodes=await async function(e,t,n){const r=(0,s.N)(e,n.twLst.map((e=>({k:e.id}))));for(const e of r)delete e.lst;if(t?.cohort?.termdb?.termid2totalsize2){const e=await async function(e,t,n,s){if(0==e.length)throw"zero terms for crosstab";if(e.length>3)throw"crosstab will not work with more than 3 levels";const r=[],o=new Map;for(const t of e)o.set(t.id,new Set);const i=!s;if(s)for(const n of s){if(n.id0){if(!n.v0)continue;o.get(n.id0).add(t.cohort.termdb.useLower?n.v0.toLowerCase():n.v0)}if(n.id1&&e[1]){if(!n.v1)continue;o.get(n.id1).add(t.cohort.termdb.useLower?n.v1.toLowerCase():n.v1)}if(n.id2&&e[2]){if(!n.v2)continue;o.get(n.id2).add(t.cohort.termdb.useLower?n.v2.toLowerCase():n.v2)}}const a=e[0].id;{const s={};n.filterObj&&(s.filterObj=n.filterObj),n.filter0&&(s.filter0=n.filter0);const l=await t.cohort.termdb.termid2totalsize2.get([e[0]],s);for(const[e,n]of l.get(a)){const s=t.cohort.termdb.useLower?e.toLowerCase():e;i?(o.get(a).add(s),r.push({count:n,id0:a,v0:s})):o.get(a).has(s)&&r.push({count:n,id0:a,v0:s})}}const l=e?.[1]?.id;if(l){const s=[];for(const r of o.get(a)){const o={tid2value:{[a]:r}};n.filterObj&&(o.filterObj=n.filterObj),n.filter0&&(o.filter0=n.filter0),s.push(t.cohort.termdb.termid2totalsize2.get([e[1]],o,r))}const c=await Promise.all(s);for(const[e,n]of c)for(const[s,c]of e.get(l)){const e=t.cohort.termdb.useLower?s.toLowerCase():s;i?(o.get(l).add(e),r.push({count:c,id0:a,v0:n,id1:l,v1:e})):o.get(l).has(e)&&r.push({count:c,id0:a,v0:n,id1:l,v1:e})}}const c=e?.[2]?.id;if(c){const s=[];for(const r of o.get(a))for(const i of o.get(l)){const o={tid2value:{[a]:r,[l]:i}};n.filterObj&&(o.filterObj=n.filterObj),n.filter0&&(o.filter0=n.filter0),s.push(t.cohort.termdb.termid2totalsize2.get([e[2]],o,{v0:r,v1:i}))}const u=await Promise.all(s);for(const[e,n]of u)for(const[e,s]of v2counts.get(c)){const u=t.cohort.termdb.useLower?e.toLowerCase():e;i?(o.get(c).add(u),r.push({count:s,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:u})):o.get(c).has(u)&&r.push({count:s,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:u})}}return r}(n.twLst,t,n,r);await async function(e,t,n){for(const s of e){if(!s.id0)continue;if(!s.v0)continue;const e=n.cohort.termdb.useLower?s.v0.toLowerCase():s.v0;if(!s.id1){const n=t.find((t=>null==t.id1&&t.v0==e));n&&(s.cohortsize=n.count);continue}if(!s.v1)continue;const r=n.cohort.termdb.useLower?s.v1.toLowerCase():s.v1;if(!s.id2){const n=t.find((t=>null==t.id2&&t.v0==e&&t.v1==r));n&&(s.cohortsize=n.count);continue}if(!s.v2)continue;const o=n.cohort.termdb.useLower?s.v2.toLowerCase():s.v2;if(!s.id3){const t=crosstabL2.find((t=>t.v0==e&&t.v1==r&&t.v2==o));t&&(s.cohortsize=t.count)}}}(r,e,t)}return r}(n.samples,t,e),delete n.samples,n;if(e.get==t.variant2samples.type_summary)return n.summary=await async function(e,t,n){if(!n.twLst)throw"q.twLst[] missing for make_summary()";const s=[];for(const t of n.twLst)if(t.term)if("categorical"==t.term.type){const n=g(e,t.id);s.push({termid:t.id,numbycategory:[...n].sort(((e,t)=>t[1]-e[1]))})}else{if("integer"!=t.term.type&&"float"!=t.term.type)throw"unknown term type";{const n=await a(t.term,e);s.push({termid:t.id,density_data:n})}}if(t.cohort.termdb.termid2totalsize2){const e=await t.cohort.termdb.termid2totalsize2.get(n.twLst,n);for(const{termid:t,numbycategory:n}of s){if(!n)continue;const s=e.get(t);if(s)for(const e of n){const t=s.find((t=>t[0].toLowerCase()==e[0].toLowerCase()));t&&e.push(t[1])}}}return s}(n.samples,t,e),delete n.samples,n;throw"unknown get type"}(t,e)}}function p(e,t,n){for(const s of e){t.has(s.sample_id)||(s.ssm_id_lst=[],s.formatK2v&&(s.ssmid2format={}),t.set(s.sample_id,s));const e=t.get(s.sample_id);e.ssm_id_lst.push(n),e.ssmid2format&&(e.ssmid2format[n]=s.formatK2v)}}function m(e,t,n){if(t)for(const s of e.values())for(const e of t){const t=n.cohort.termdb.q.getSample2value(e.id,s.sample_id);t[0]&&(s[e.id]=t[0].value)}}async function h(e,t,n){const s=new Map;if(n.queries.snvindel){const t=await n.queries.snvindel.byrange.get(e);for(const e of t)p(e.samples,s,e.ssm_id)}if(n.queries.svfusion){const t=await n.queries.svfusion.byrange.get(e);for(const e of t)p(e.samples,s,e.ssm_id)}if(n.queries.cnv){const t=await n.queries.cnv.byrange.get(e);for(const e of t)p(e.samples,s,e.ssm_id)}return m(s,t,n),{samples:[...s.values()]}}function g(e,t){const n=new Map;if("sample_id"in e[0]){for(const s of e){const e=s[t];e&&(n.has(e)||n.set(e,new Set),n.get(e).add(s.sample_id))}const s=new Map;for(const[e,t]of n)s.set(e,t.size);return s}if("case_uuid"in e[0]){for(const s of e){const e=s[t];e&&(n.has(e)||n.set(e,new Set),n.get(e).add(s.case_uuid))}const s=new Map;for(const[e,t]of n)s.set(e,t.size);return s}for(const t of e){const e=t[term.id];e&&n.set(e,1+(n.get(e)||0))}return n}},334:(e,t,n)=>{const s=n(7147),r=n(1017),o=process.cwd()?process.cwd()+"/serverconfig.json":"",i=r.join(__dirname,"../serverconfig.json"),a=r.join(__dirname,"../../serverconfig.json"),l=o&&s.existsSync(o)?o:s.existsSync(i)?i:s.existsSync(a)?a:"";let c;if(!l)throw"missing serverconfig.json";try{const e=s.readFileSync(l,{encoding:"utf8"});c=JSON.parse(e)}catch(e){throw`Error reading or parsing ${l}:`+e}if(c.port||(c.port=process.env.PP_PORT||3e3),c.tabix||(c.tabix="tabix"),c.samtools||(c.samtools="samtools"),c.bcftools||(c.bcftools="bcftools"),c.hicstraw||(c.hicstraw="straw"),c.bigwigsummary||(c.bigwigsummary="bigWigSummary"),c.bigBedToBed||(c.bigBedToBed="bigBedToBed"),c.bigBedInfo||(c.bigBedInfo="bigBedInfo"),c.bigBedNamedItems||(c.bigBedNamedItems="bigBedNamedItems"),c.clustalo||(c.clustalo="clustalo"),c.Rscript||(c.Rscript="Rscript"),c.gfServer||(c.gfServer="gfServer"),c.gfClient||(c.gfClient="gfClient"),!("allow_env_overrides"in c)&&c.debugmode&&(c.allow_env_overrides=!0),!c.binpath){const e=process.argv.find((e=>e.includes("/build")));if(e)c.binpath=e.split("/build")[0]+"/server";else{if(process.argv.find((e=>e.includes(".spec.js"))))c.binpath=r.dirname(__dirname);else{const e=process.argv.find((e=>e.endsWith("/bin.js")||e.endsWith("/server.js")||e.endsWith("/proteinpaint")||e.endsWith("/proteinpaint-server")));if(e)try{const t=s.realpathSync(e);c.binpath=r.dirname(t)}catch(e){throw e}else if(s.existsSync("./server"))c.binpath=s.realpathSync("./server");else if(s.existsSync("./src"))c.binpath=s.realpathSync("./src/..");else if(__dirname.includes("/server/"))c.binpath=__dirname.split("/server/")[0]+"/server";else{if(!__dirname.includes("/proteinpaint"))throw"unable to determine the serverconfig.binpath";c.binpath=__dirname}}}}if(c.debugmode){const e=[],t=r.join(c.binpath,"src/test/routes"),n=["gdc.js","specs.js","readme.js"];if(c.routeSetters)for(const o of c.routeSetters)if(!n.includes(o))if(s.existsSync(o))e.push(o);else if(s.existsSync(`${t}/${o}`))e.push(`${t}/${o}`);else{const t=r.join(c.binpath,o);s.existsSync(t)&&e.push(t)}for(const r of n){const n=`${t}/${r}`;!e.includes(n)&&s.existsSync(n)&&e.push(n)}c.routeSetters=e}if(c.allow_env_overrides){if(process.env.PP_URL&&(c.URL=process.env.URL),"PP_BASEPATH"in process.env&&(c.basepath=process.env.PP_BASEPATH),s.existsSync("./.ssl")&&!c.ssl){c.ssl={};const e=s.readdirSync("./.ssl");for(const t of e)t.endsWith(".key")&&(c.ssl.key=process.cwd()+"/.ssl/"+t),t.endsWith(".crt")&&(c.ssl.cert=process.cwd()+"/.ssl/"+t)}"PP_BACKEND_ONLY"in process.env&&(c.backend_only=1==+process.env.PP_BACKEND_ONLY||"true"===process.env.PP_BACKEND_ONLY)}if(process.env.PP_MODE?.startsWith("container")&&Object.assign(c,{port:3e3,tpmasterdir:"/home/root/pp/tp",cachedir:"/home/root/pp/cache",hicstraw:"/home/root/pp/tools/straw",bigwigsummary:"/home/root/pp/tools/bigWigSummary",bigBedToBed:"/home/root/pp/tools/bigBedToBed",bigBedNamedItems:"/home/root/pp/tools/bigBedNamedItems",bigBedInfo:"/home/root/pp/tools/bigBedInfo"}),c.features||(c.features={}),process.argv.find((e=>"validate"==e))&&(c.features.stopGdcCacheAliquot=!0),!c.backend_only&&s.existsSync(r.join(process.cwd(),"./public"))){const e=r.join(c.binpath,"cards");c.cards||(c.cards={target:e,path:"cards"})}if(s.existsSync("./public/rev.txt")){const e=s.readFileSync("./public/rev.txt",{encoding:"utf8"}).trim().split(" ")[1];e&&(c.commitHash=e)}if(s.existsSync("./package.json")){const e=s.readFileSync("./package.json",{encoding:"utf8"});c.version=JSON.parse(e).version}e.exports=c},938:(e,t,n)=>{"use strict";n.d(t,{e8:()=>f,Tt:()=>m,TO:()=>u});n(1017);var s=n(3345);const r=require("partjson");var o=n.n(r),i=n(670),a=n(1271),l=n(2974),c=n(2273);(0,i.WU)(".3r");function u(e){return async(t,n)=>{const s=t.query;for(const e of[0,1,2]){const t="term"+e,n=t+"_id";"string"==typeof s[n]?s[n]=decodeURIComponent(s[n]):"string"==typeof s[t]&&(s[t]=JSON.parse(decodeURIComponent(s[t])));const r=t+"_q";"string"==typeof s[r]&&(s[r]=JSON.parse(decodeURIComponent(s[r])))}try{const t=e[s.genome];if(!t)throw"invalid genome";const r=t.datasets[s.dslabel];if(!r)throw"invalid dslabel";if(!r.cohort)throw"ds.cohort missing";const o=r.cohort.termdb;if(!o)throw"no termdb for this dataset";const i=await f(s,r,o);s.term2_q&&await async function(e,t,n){const s=[];for(const t of e.charts){const e={};e.chartId=t.chartId,e.serieses=[];const r=t.serieses.filter((e=>!n.term1.includes(e.seriesId)));for(const t of r){const s={};s.seriesId=t.seriesId,s.data=t.data.filter((e=>!n.term2.includes(e.dataId))),s.total=s.data.reduce(((e,t)=>e+t.total),0),e.serieses.push(s)}e.total=e.serieses.reduce(((e,t)=>e+t.total),0),e.maxSeriesTotal=e.serieses.reduce(((e,t)=>e<t.total?t.total:e),0),s.push(e)}e.tests={};for(const n of s){const s={};for(const e of n.serieses)for(const t of e.data)s[t.dataId]=void 0===s[t.dataId]?t.total:s[t.dataId]+t.total;const r=[];let o=0;const i=new Map;for(const e of n.serieses)for(const t of e.data){const a=t.total,l=s[t.dataId]-t.total,c=e.total-t.total,u=n.total-s[t.dataId]-(e.total-t.total),f=e.seriesId,d=t.dataId;r.push({index:o,n1:a,n2:l,n3:c,n4:u}),i.set(o,{seriesId:f,dataId:d}),o++}const l={input:r},c=t.cohort.termdb.multipleTestingCorrection;c&&(l.mtc=c.method,c.skipLowSampleSize&&(l.skipLowSampleSize=c.skipLowSampleSize));const u=await(0,a.run_rust)("fisher",JSON.stringify(l)),f=[];for(const e of JSON.parse(u)){const t=i.get(e.index).seriesId,n=i.get(e.index).dataId,s=e.n1,r=e.n2,o=e.n3,a=e.n4,l=e.p_value,c="chisq"===e.fisher_chisq,u=null===l,d=e.adjusted_p_value,p=f.find((e=>e.term1comparison===t));p?p.term2tests.push({term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:s,R2C1:r,R1C2:o,R2C2:a},isChi:c,skipped:u}):f.push({term1comparison:t,term2tests:[{term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:s,R2C1:r,R1C2:o,R2C2:a},isChi:c,skipped:u}]})}e.tests[n.chartId]=f}}(i.data,r,s.hiddenValues),n.send(i)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}async function f(e,t,n){if(e.ds=t,e.ssid){const[t,n]=await s.L0(e.ssid);e.sample2gt=t,e.genotype2sample=n}const r=+new Date;e.results={};const i=new Map;for(let t=0;t<=2;t++){let n=null;if(e[`term${t}_id`]){const s=e[`term${t}_id`];n={id:s,q:e[`term${t}_q`],term:{id:s}}}else e[`term${t}`]&&(n={term:e[`term${t}`],q:e[`term${t}_q`]});n&&i.set(t,n)}const a=[...i.values()],u=await(0,l.Yu)({filter:e.filter,terms:a},e.ds,e.genome),f=new Map,d=[];if(u.samples)if("geneVariant"==i.get(1)?.term?.type||"geneVariant"==i.get(2)?.term?.type)!function(e,t,n,s,r){t.push([]);let o=1;const i=e.get(1)?e.get(1).term:null,a=i?.id?i.id:i?.name;a&&n.refs.byTermId[a]?.bins?t.push(n.refs.byTermId[a]?.bins):t.push([]);const l=e.get(2)?e.get(2).term:null,u=l?.id?l.id:l?.name;u&&n.refs.byTermId[u]?.bins?t.push(n.refs.byTermId[u]?.bins):t.push([]);for(const[t,i]of Object.entries(n.samples)){const n=parseInt(t);if("geneVariant"==e.get(1)?.term?.type){const e=[],t=i[a];for(const s of t.values)if(e.some((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))){const t=e.filter((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))[0];if("object"!=typeof t.item.key1){const e=t.item.key1;t.item.key1={},t.item.key1[e]=1}t.item.key1[c.mclass[s.class].label]=t.item.key1[c.mclass[s.class].label]?t.item.key1[c.mclass[s.class].label]+1:1}else{const t={sample:o,name:r.sampleId2Name.get(n)};t.key1=c.mclass[s.class].label,t.val1=c.mclass[s.class].label;const a=r.assayAvailability?.byDt?.[s.dt]?.byOrigin;t.key0=t.val0=a?(a[s.origin]?.label||s.origin)+" "+c.dt2label[s.dt]:c.dt2label[s.dt],t.key2=i[u]?i[u].key:"",t.val2=i[u]?i[u].value:"",e.push({value:s,item:t})}for(const t of e){if("object"==typeof t.item.key1){let e="";for(const[n,s]of Object.entries(t.item.key1))e+=`${n}(${s})+`;t.item.key1=e.slice(0,-1),t.item.val1=e.slice(0,-1)}s.set(o.toString(),t.item),o++}}else if("geneVariant"==e.get(2)?.term?.type){const e=[],t=i[u],l=i[a];for(const s of t.values)if(e.some((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))){const t=e.filter((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))[0];if("object"!=typeof t.item.key2){const e=t.item.key2;t.item.key2={},t.item.key2[e]=1}t.item.key2[c.mclass[s.class].label]=t.item.key2[c.mclass[s.class].label]?t.item.key2[c.mclass[s.class].label]+1:1}else{const t={sample:o,name:r.sampleId2Name.get(n)};t.key1=l.key,t.val1=l.value;const i=r.assayAvailability?.byDt?.[s.dt]?.byOrigin;t.key0=t.val0=i?(i[s.origin]?.label||s.origin)+" "+c.dt2label[s.dt]:c.dt2label[s.dt],t.key2=c.mclass[s.class].label,t.val2=c.mclass[s.class].label,e.push({value:s,item:t})}for(const t of e){if("object"==typeof t.item.key2){let e="";for(const[n,s]of Object.entries(t.item.key2))e+=`${n}(${s})+`;t.item.key2=e.slice(0,-1),t.item.val2=e.slice(0,-1)}s.set(o.toString(),t.item),o++}}}}(i,d,u,f,t);else for(let e=0;e<=2;e++){const t=i.get(e)?.q,n=i.get(e)?i.get(e).term:null,s=n?.id?n.id:n?.name;if(s&&u.refs.byTermId[s]?.bins?d.push(u.refs.byTermId[s]?.bins):d.push([]),t?.binColored)for(const n of d[e]){const e=t.binColored;n.start==e.start&&n.stop==e.stop&&(n.color=e.color)}for(const[t,n]of Object.entries(u.samples)){let r;if(f.get(t))r=f.get(t);else if(!f.has(t)){r={sample:parseInt(t)},f.set(t,r)}if(r)if(s){const o=n[s];o?(r[`key${e}`]=1!=e?o.key:o.values?.map((e=>e.key))||[o.key],r[`val${e}`]=o.value,1===e&&(r.dedupkey1=o.values?[`${o.values.length}-value samples`]:[o.key])):f.set(t,null)}else r[`key${e}`]="",r[`val${e}`]=""}}e.results.lst=[...f.values()].filter((e=>null!==e)),e.results.bins=d;const h=+new Date,g=function(e,t,n,r){const i=[0,1,2].map((t=>{const s=function(e,t,n){const s=e["term"+n+"_id"];let r={};e[s]||s?r=t.q.termjsonByOneid(s):e[`term${n}`]&&(r=e[`term${n}`]);const o="integer"==r.type||"float"==r.type,i=r.values?Object.keys(r.values).filter((e=>r.values[e].uncomputable)).map((e=>+e)):[],a=e=>o&&!i.includes(e),l=e["term"+n+"_q"]?e["term"+n+"_q"]:{};return{term:r,isComputableVal:a,q:l}}(e,n,t);s.q.index=t;const r=e.results.bins[t];return Object.assign(s,{key:"key"+t,val:"val"+t,nval:"nval"+t,bins:r,q:s.q,orderedLabels:m(s.term,r,void 0,s.q)})}));return new(o())({data:t,seed:'{"results": {"charts": [], "refs":{}}}',template:p,"=":{prep(e){for(const t of i)if("key1"!=t.key||Array.isArray(e[t.key])||(e[t.key]=[e[t.key]]),"condition"==t.term.type){if(t.q.bar_by_grade)if(Array.isArray(e[t.key])){for(const[n,s]of e[t.key].entries())s in t.term.values&&(e[t.key][n]=t.term.values[s].label);if("key1"==t.key&&e.dedupkey1)for(const[n,s]of e.dedupkey1.entries())s in t.term.values&&(e.dedupkey1[n]=t.term.values[s].label)}else e[t.key]in t.term.values&&(e[t.key]=t.term.values[e[t.key]].label)}else"float"!=t.term.type&&"integer"!=t.term.type||t.isComputableVal(e[t.val])&&(e[t.nval]=e[t.val]);return!0},sampleCount:(e,t)=>t.self.samples?t.self.samples.size:void 0,maxSeriesTotal(e,t){let n=0;for(const e of t.self.serieses)e&&e.total>n&&(n=e.total);return n},maxAcrossCharts(e,t){let n=0;for(const e of t.self.charts)e.maxSeriesTotal>n&&(n=e.maxSeriesTotal);return n},boxplot(e,t){const n=t.self.values;if(!n||!n.length)return;n.sort(((e,t)=>e-t));const r=s.JC(n.map((e=>({value:+e}))));r.mean=t.self.sum/n.length;let o=0;for(const e of n)o+=Math.pow(e-r.mean,2);return r.sd=Math.sqrt(o/(n.length-1)),r.min=t.self.min,r.max=t.self.max,r},getAF(t,n){if(r.track&&r.track.vcf&&r.track.vcf.termdb_bygenotype&&r.track.vcf.termdb_bygenotype.getAF&&e.term2_is_genotype){if(!e.chr)throw"chr missing for getting AF";if(!e.pos)throw"pos missing for getting AF";return function(e,t,n,r,o){const i=o.track.vcf.termdb_bygenotype,a=r.has(s.EO.href)?r.get(s.EO.href):new Set,l=r.has(s.EO.halt)?r.get(s.EO.halt):new Set,c=r.has(s.EO.het)?r.get(s.EO.het):new Set;let u=0,f=0;for(const s of e){let e=!1;if(i.sex_chrs.has(t))if(i.male_samples.has(s)){if(i.chr2par&&i.chr2par[t])for(const s of i.chr2par[t])if(n>=s.start&&n<=s.stop){e=!0;break}}else e=!0;else e=!0;e?(f+=2,l.has(s)?u+=2:c.has(s)&&u++):(f++,a.has(s)||u++)}return 0==f||0==u?0:(u/f).toFixed(3)}(n.self.samples?[...n.self.samples]:[],e.chr,Number(e.pos),e.genotype2sample,r)}},filterEmptySeries(e){const t=e.serieses.filter((e=>e.total));e.serieses.splice(0,e.serieses.length,...t)},bins:()=>i.map((e=>e.bins)),q:()=>i.map(((e,t)=>{const n={};for(const t in e.q)"index"!=t&&(n[t]=e.q[t]);return n})),useColOrder:()=>i[1].orderedLabels.length>0,useRowOrder:()=>i[2].orderedLabels.length>0,sortColsRows(e){if(i[1].orderedLabels.length){const t=i[1].orderedLabels;e.cols.sort(((e,n)=>t.indexOf(e)-t.indexOf(n))),e.dedupCols&&e.dedupCols.sort(((e,n)=>t.indexOf(e)-t.indexOf(n)))}if(i[2].orderedLabels.length){const t=i[2].orderedLabels;e.rows.sort(((e,n)=>t.indexOf(e)-t.indexOf(n)))}if(e.dedupCols){const t=i[1].orderedLabels;e.dedupCols.sort(((e,n)=>{const s=`${e}`.includes("-value samples"),r=`${n}`.includes("-value samples");return s||r?s&&r?e<n?-1:1:s?1:r?-1:0:t.indexOf(e)-t.indexOf(n)}))}},sortCharts(e){if(i[0].orderedLabels.length){const t=i[0].orderedLabels;e.charts.sort(((e,n)=>t.indexOf(e.chartId)-t.indexOf(n.chartId)))}}}})}(e,e.results.lst,n,t);g.tree.results&&(g.tree.results.times={sql:h-r,pj:g.times});return{data:g.tree.results,bins:d}}const d={seriesId:"@key",data:[{dataId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()"},"$key2"],"_:_max":"<$nval2","~values":["$nval2",0],"~sum":"+$nval2","~samples":["$sample","set"],"__:total":"=sampleCount()","__:boxplot":"=boxplot()","__:AF":"=getAF()"},p=JSON.stringify({"@errmode":["","","",""],"@before()":"=prep()",results:{"_2:maxAcrossCharts":"=maxAcrossCharts()","_:_min":">$nval1","_:_max":"<$nval1",charts:[{chartId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()","_1:maxSeriesTotal":"=maxSeriesTotal()","@done()":"=filterEmptySeries()",serieses:[d,"$key1[]"],dedupedSerieses:[d,"$dedupkey1[]"]},"$key0"],"~sum":"+$nval1","~values":["$nval1",0],"__:boxplot":"=boxplot()","_:_refs":{cols:["$key1[]"],dedupCols:["$dedupkey1[]"],colgrps:["-"],rows:["$key2"],rowgrps:["-"],col2name:{"$key1[]":{name:"@branch",grp:"-"}},row2name:{$key2:{name:"@branch",grp:"-"}},"__:useColOrder":"=useColOrder()","__:useRowOrder":"=useRowOrder()","__:bins":"=bins()","__:q":"=q()","@done()":"=sortColsRows()"},"@done()":"=sortCharts()"}});function m(e,t,n,s){if(n)return n.map((e=>e.label));if("condition"==e.type){if(s?.groups?.length)return s.groups.map((e=>e.name));if(e.values)return Object.keys(e.values).map(Number).sort(((e,t)=>e-t)).map((t=>e.values[t].label))}const r=Object.values(e.values||{})[0];return r&&"order"in r?Object.keys(e.values).sort(((t,n)=>"order"in e.values[t]&&"order"in e.values[n]?e.values[t].order-e.values[n].order:"order"in e.values[t]?e.values[t].order:"order"in e.values[n]?e.values[n].order:0)).map((t=>e.values[t].key)):t?.map((e=>e.name?e.name:e.label))}},4453:(e,t,n)=>{"use strict";n.d(t,{g:()=>d,y:()=>p});var s=n(1017),r=n.n(s),o=n(8907),i=n(3345),a=n(7147),l=n.n(a),c=n(9157),u=n(334),f=n.n(u);async function d(e,t){try{if(!t.cohort)throw"cohort missing from ds";const n=t.cohort.termdb.minTimeSinceDx,s=Number(e.minSampleSize);if(!Number.isFinite(n))throw"invalid minTimeSinceDx";if(!Number.isFinite(s))throw"invalid minSampleSize";e.ds=t;const r={data:{}},i=await(0,o.g5)(e);if(!i.lst.length)return r;const a={};for(const e of i.lst){const t=e.key0,n=e.val1,s=e.key1,r=e.key2;t in a||(a[t]=[]),a[t].push({time:n,event:s,series:r})}const l=e.term2_id&&i.CTE2.bins?i.CTE2.bins:[];r.refs={bins:l};const c={data:{},startTime:n};r.noEvents={},r.lowSampleSize={};for(const e in a){const t=a[e],n=new Set(t.map((e=>e.series)));for(const o of n){const n=t.filter((e=>e.series==o));n.find((e=>1===e.event))?n.length<s?r.lowSampleSize[e]=(r.lowSampleSize[e]||[]).concat([o]):c.data[e]=(c.data[e]||[]).concat(n):r.noEvents[e]=(r.noEvents[e]||[]).concat([o])}e in c.data||(r.data[e]={})}if(!Object.keys(c.data).length)return{data:{}};const u=await p(c);return Object.assign(r.data,u),r}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}async function p(e){for(let t in e.data)""===t&&(t="*",e.data[t]=e.data[""],delete e.data[""]),e.data[t]=e.data[t].map((e=>({time:e.time,event:e.event,series:""===e.series?"*":e.series})));const t=r().join(f().cachedir,Math.random().toString()+".json");await(0,i.Sf)(t,JSON.stringify(e));const n=await(0,c.default)(r().join(f().binpath,"utils/cuminc.R"),[],[t]),s=JSON.parse(n[0]);for(const e in s)"*"===e&&(s[""]=s[e],delete s[e]);for(const e in s)for(const t in s[e].estimates)"*"===t&&(s[e].estimates[""]=s[e].estimates[t],delete s[e].estimates[t]);return l().unlink(t,(()=>{})),s}},5257:(e,t,n)=>{"use strict";async function s(e,t,n="f"){if(!e)return;if("tvslst"!=e.type)throw'filter.type is not "tvslst" but: '+e.type;if(!Array.isArray(e.lst))throw"filter.lst must be an array";if(0==e.lst.length)return console.error("filter.lst[] is zero length, see if is an error");if(1==e.lst.length){if("tvslst"==e.lst[0].type)throw'only one element at a level: type should not be "tvslst"'}else if("or"!=e.join&&"and"!=e.join)throw'multiple elements at a level: filter.join must equal either "or" or "and"';"in"in e||(e.in=!0);const u=[],f=[],d=[];for(const[p,m]of e.lst.entries()){const e=n+"_"+p;let h;if("tvslst"==m.type)h=await s(m,t,e);else{if(!m.tvs)throw"filter item should have a 'tvs' or 'lst' property";if(m.tvs.term.id&&!t.cohort.termdb.q.termjsonByOneid(m.tvs.term.id))throw"invalid term id in tvs";if("categorical"==m.tvs.term.type)h=r(m.tvs,e);else if("survival"==m.tvs.term.type)h=o(m.tvs,e);else if("samplelst"==m.tvs.term.type)h=i(m.tvs,e);else if("integer"==m.tvs.term.type||"float"==m.tvs.term.type)h=l(m.tvs,e,t);else if("condition"==m.tvs.term.type)h=c(m.tvs,e);else{if("geneVariant"!=m.tvs.term.type)throw"unknown term type";h=await a(m.tvs,e,t)}}u.push(h.CTEname),f.push(...h.CTEs),d.push(...h.values)}const p="and"==e.join?"INTERSECT":"UNION",m=u.map((e=>"SELECT * FROM "+e)).join("\n"+p+"\n");return e.in?f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\t${m}\n\t\t\t\t)\n\t\t\t`):f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\tSELECT id as sample\n\t\t\t\t\tFROM sampleidmap\n\t\t\t\t\tWHERE sample NOT IN (\n\t\t\t\t\t\t${m}\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t`),{filters:f.join(",\n"),CTEs:f,values:d,CTEname:n}}function r(e,t){return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = ?\n\t\t\t\tAND value ${e.isnot?"NOT":""} IN (${e.values.map((e=>"?")).join(", ")})\n\t\t\t)`],values:[e.term.id,...e.values.map((e=>e.key))],CTEname:t}}function o(e,t){return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM survival\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${e.q?.cutoff?"AND tte >= "+e.q?.cutoff:""}\n\t\t\t\tAND exit_code ${e.isnot?"NOT":""} IN (${e.values.map((e=>"?")).join(", ")})\n\t\t\t)`],values:[e.term.id,...e.values.map((e=>e.key))],CTEname:t}}function i(e,t){const n=[];for(const t in e.term.values){const s=e.term.values[t].list;n.push(...s)}return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id ${e.isnot?"NOT IN":"IN"} (${Array(n.length).fill("?").join(", ")})\n\t\t\t)`],values:[...n.map((e=>e.sampleId))],CTEname:t}}async function a(e,t,n){const s={term:e.term,q:{}},r=await n.mayGetGeneVariantData(s,{genome:n.genomename}),o=[];for(const[t,n]of r){const s=n[e.term.name].values;let r=!0;for(const t of e.values){const e=s.filter((e=>e.dt==t.dt&&(!t.origin||t.origin==e.origin)));for(const n of e)if(t.mclassExcludeLst.includes(n?.class)){r=!1;break}}r&&o.push(t)}return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${o.map((e=>"?")).join(", ")})\n\t\t\t)`],values:[...o],CTEname:t}}function l(e,t,n){if(!e.ranges)throw".ranges{} missing";const s=[e.term.id],r=n.cohort.termdb.q.termjsonByOneid(e.term.id),o=[];let i,a=!1;for(const t of e.ranges)if("value"in t){const n=e.isnot?"!":"";o.push(`value ${n}= ?`),s.push(""+t.value)}else{a=!0;const n=[];t.startunbounded||(t.startinclusive?n.push("value >= ?"):n.push("value > ? "),s.push(t.start)),t.stopunbounded||(t.stopinclusive?n.push("value <= ?"):n.push("value < ? "),s.push(t.stop));const r=e.isnot?"NOT ":"";n.length&&o.push(r+"("+n.join(" AND ")+")")}a&&r.values&&(i=Object.keys(r.values).filter((e=>r.values[e].uncomputable)).map(Number).filter((t=>e.isnot||!e.ranges.find((e=>"value"in e&&Number(e.value)==t)))),i.length&&s.push(...i));const l=o.join(" OR ");return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_${r.type}\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${l?"AND ("+l+")":""}\n\t\t\t\t${i&&i.length?`AND value NOT IN (${i.map((e=>"?")).join(",")})`:""}\n\t\t\t)`],values:s,CTEname:t}}function c(e,t){let n,s;if(e.bar_by_children)n="child";else{if(!e.bar_by_grade)throw"must set the bar_by_grade or bar_by_children query parameter";n="grade"}if(e.value_by_max_grade)s="max_grade";else if(e.value_by_most_recent)s="most_recent";else{if(!e.value_by_computable_grade)throw"unknown setting of value_by_?";s="computable_grade"}const r=[],o=[];if(!e.values)throw e.grade_and_child?"-- Todo: tvs.grade_and_child":'unknown condition term filter type: expecting term-value "values" or "grade_and_child" key';return o.push(e.term.id,...e.values.map((e=>""+e.key))),r.push(`\n\t\t\t${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM ${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\tWHERE term_id = ? \n\t\t\t\tAND ${s} = 1\n\t\t\t\tAND value ${e.isnot?"NOT":""} IN (${e.values.map((e=>"?")).join(", ")})\n\t\t\t)`),{CTEs:r,values:o,CTEname:t}}n.d(t,{w:()=>s})},2826:(e,t,n)=>{"use strict";n.d(t,{iK:()=>G,pq:()=>P,TO:()=>L});var s=n(334),r=n.n(s),o=n(394),i=(n(8088),n(6191));function a(e,t,n,s){const o=n.cohort.termdb,a={selectCohort:o.selectCohort,supportedChartTypes:o.q.getSupportedChartTypes(e.embedder),hiddenChartTypes:n.cohort.hiddenChartTypes,renamedChartTypes:n.cohort.renamedChartTypes,allowedTermTypes:l(n),termMatch2geneSet:o.termMatch2geneSet,massSessionDuration:r().features.massSessionDuration||30,dataDownloadCatch:o.dataDownloadCatch,matrix:o.matrix,hierCluster:o.hierCluster,mclass:o.mclass,alwaysRefillCategoricalTermValues:o.alwaysRefillCategoricalTermValues,isGeneSetTermdb:o.isGeneSetTermdb,lollipop:o.lollipop,urlTemplates:o.urlTemplates};o.chartConfigByType&&(a.chartConfigByType=o.chartConfigByType),o.multipleTestingCorrection&&(a.multipleTestingCorrection=o.multipleTestingCorrection),o.helpPages&&(a.helpPages=o.helpPages),o.minTimeSinceDx&&(a.minTimeSinceDx=o.minTimeSinceDx),o.timeUnit&&(a.timeUnit=o.timeUnit),o.cohortStartTimeMsg&&(a.cohortStartTimeMsg=o.cohortStartTimeMsg),o.displaySampleIds&&(a.displaySampleIds=o.displaySampleIds),o.logscaleBase2&&(a.logscaleBase2=o.logscaleBase2),n.assayAvailability&&(a.assayAvailability=n.assayAvailability),n.customTwQByType&&(a.customTwQByType=n.customTwQByType),a.requiredAuth=i.i.getRequiredCredForDsEmbedder(e.dslabel,e.embedder),function(e,t){if(!t.restrictAncestries)return;e.restrictAncestries=t.restrictAncestries.map((e=>({name:e.name,tvs:e.tvs,PCcount:e.PCcount})))}(a,o),function(e,t){if(!t.cohort.scatterplots)return;e.scatterplots=t.cohort.scatterplots.plots.map((e=>({name:e.name,dimensions:e.dimensions,colorTW:e.colorTW,shapeTW:e.shapeTW})))}(a,n),function(e,t){if(!t.cohort.matrixplots)return;e.matrixplots=t.cohort.matrixplots.plots.map((e=>({name:e.name})))}(a,n),function(e,t,n){const s=t.queries;if(!s)return;e.queries={defaultCoord:s.defaultCoord||n.defaultcoord};const r=e.queries;s.defaultBlock2GeneMode&&(r.defaultBlock2GeneMode=s.defaultBlock2GeneMode);s.snvindel&&(r.snvindel={allowSNPs:s.snvindel.allowSNPs});if(s.cnv){r.cnv={};for(const e of["cnvMaxLength","cnvGainCutoff","cnvLossCutoff","absoluteValueRenderMax","gainColor","lossColor"])e in s.cnv&&(r.cnv[e]=s.cnv[e])}s.topMutatedGenes&&(r.topMutatedGenes=s.topMutatedGenes);s.topVariablyExpressedGenes&&(r.topVariablyExpressedGenes=s.topVariablyExpressedGenes);s.singleSampleMutation&&(r.singleSampleMutation={sample_id_key:s.singleSampleMutation.sample_id_key,discoSkipChrM:s.singleSampleMutation.discoSkipChrM});if(s.singleSampleGenomeQuantification){r.singleSampleGenomeQuantification={};for(const e in s.singleSampleGenomeQuantification)r.singleSampleGenomeQuantification[e]=JSON.parse(JSON.stringify(s.singleSampleGenomeQuantification[e])),delete r.singleSampleGenomeQuantification[e].folder}if(s.singleSampleGbtk){r.singleSampleGbtk={};for(const e in s.singleSampleGbtk)r.singleSampleGbtk[e]=JSON.parse(JSON.stringify(s.singleSampleGbtk[e])),delete r.singleSampleGbtk[e].folder}s.rnaseqGeneCount&&(r.rnaseqGeneCount=!0);s.singleCell&&(r.singleCell={samples:{firstColumnName:s.singleCell.samples.firstColumnName,sampleColumns:s.singleCell.samples.sampleColumns,experimentColumns:s.singleCell.samples.experimentColumns},data:{sameLegend:s.singleCell.data.sameLegend,refName:s.singleCell.data.refName}})}(a,n,s),t.send({termdbConfig:a})}function l(e){(0,o.qN)(e);const t=new Set;for(const n of e.cohort.termdb.termtypeByCohort)n.type&&t.add(n.type);if(e.cohort.termdb.allowedTermTypes)for(const n of e.cohort.termdb.allowedTermTypes)t.add(n);return e?.queries?.defaultBlock2GeneMode&&t.add("geneVariant"),[...t]}var c=n(8907),u=n(5708),f=n(4453),d=n(1017),p=n.n(d),m=n(2974),h=n(3345),g=n(7147),y=n.n(g),b=n(9157);async function v(e,t){try{if(!t.cohort)throw"cohort missing from ds";e.ds=t;const n=[];for(const t of[0,1,2]){const s="term"+t,r=s+"_id";"string"==typeof e[r]?(e[r]=decodeURIComponent(e[r]),e[s]=e.ds.cohort.termdb.q.termjsonByOneid(e[r])):"string"==typeof e[s]&&(e[s]=JSON.parse(decodeURIComponent(e[s])));const o=s+"_q";e[s]&&n.push({term:e[s],q:e[o]})}if(e.term2){if("survival"==e.term2.type&&"survival"==e.term1.type)throw"term and overlay are both survival terms - only one could be a survival term";if("survival"!=e.term2.type&&"survival"!=e.term1.type)throw"no survival terms, either the main term OR the overlay term must be a survival term"}else if("survival"!=e.term1.type)throw"non-survival term";if(e.term0&&"survival"==e.term0.type)throw"term0 must not be a survival term";const s=function(e){if(e.term1&&"survival"==e.term1.type)return 1;if(!e.term2)throw"term1.type is not survival and term2 is missing";if("survival"!=e.term2.type)throw"both term1 and term2 are not survival type";return 2}(e),o=e[`term${s}`],i=e["term"+(1==s?2:1)],a=await(0,m.Yu)({terms:n,filter:e.filter},t,e.genome);if(a.error)throw a.error;const l=function(e,t){const n=Object.values(e.samples).filter((e=>e[t.id]));return n.sort(((e,n)=>e[t.id].value<n[t.id].value?-1:1))}(a,o),c={},u={chart:new Set,series:new Set};for(const t of l){const n=t[o.id],s=n.value;if(s<0)continue;const r=n.key;let a;if(i)if("id"in i){if(!(i.id in t))continue;a=t[i.id].key}else if("samplelst"==i.type){if(!(i.name in t))continue;a=t[i.name].key}else a=w(i,t);else a="*";u.series.add(a);const l=e.term0&&t[e.term0.id||e.term0.name]||{key:""};l.key in c||(c[l.key]=[],u.chart.add(l.key)),c[l.key].push({time:s,status:r,series:a})}const f=e.term2_id&&a.refs[e.term2.id]?.bins||[],d={keys:["chartId","seriesId","time","survival","lower","upper","nevent","ncensor","nrisk"],case:[],refs:{bins:f}};for(const e in c){const t=c[e],n=p().join(r().cachedir,Math.random().toString()+".json");await(0,h.Sf)(n,JSON.stringify(t));const s=await(0,b.default)(p().join(r().binpath,"utils/survival.R"),[],[n]),o=JSON.parse(s);for(const t of o.estimates){for(const e in t)t[e]="series"==e?"*"==t[e]?"":t[e]:Number(t[e]);d.case.push([e,t.series,t.time,t.surv,t.lower,t.upper,t.nevent,t.ncensor,t.nrisk])}o.tests&&(d.tests||(d.tests={}),d.tests[e]=o.tests),y().unlink(n,(()=>{}))}d.case.sort(((e,t)=>e[2]-t[2]));const g=function(e,t=[]){if(e){if("condition"==e.type&&e.values)return Object.keys(e.values).map(Number).sort(((e,t)=>e-t)).map((t=>e.values[t].label));if(e.values)return Object.keys(e.values).sort(((t,n)=>"order"in e.values[t]&&"order"in e.values[n]?e.values[t].order-e.values[n].order:0)).map((t=>e.values[t].label))}return t.map((e=>e.name?e.name:e.label))}(e.term2,f?f.map((e=>e.name?e.name:e.label)):[]);return d.refs.orderedKeys={chart:[...u.chart].sort(),series:[...u.series].sort(g?(e,t)=>g.indexOf(e)-g.indexOf(t):void 0)},d}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}function w(e,t){const n=e.name;if("geneVariant"==e.type){if(!t[n]||!t[n].values)return"Wildtype";const e=t[n].values.filter((e=>"Blank"!=e.class));return e.find((e=>"WT"!=e.class))?`${n} Variant`:e.find((e=>"WT"==e.class))?`${n} Wildtype`:t[n].values.length>e.length?"Not tested":"Not sure"}throw`cannot get series key for term='${n}'`}var _=n(8599),k=n(3795),q=n(1575),x=n(2188);var N=n(478),S=n(1271);async function A(e,t,n,s){!function(e,t){if(!e.chr)throw"q.chr missing";if(e.start=Number(e.start),e.stop=Number(e.stop),!Number.isInteger(e.start)||!Number.isInteger(e.stop))throw"q.start/stop is not integer";if("object"!=typeof e.details)throw"q.details{} not object";if(!Array.isArray(e.details.groups))throw"q.details.groups[] not array";if(!e.details.groups[0])throw"q.details.groups[0] missing";if(e.details.groups.length>2)throw"q.details.groups[] has more than 2";for(const n of e.details.groups)if("filter"==n.type){if("object"!=typeof n.filter)throw".filter not an object for group type=filter"}else if("population"==n.type){if(!n.key)throw".key missing from group type=population";if(!t.queries.snvindel?.populations)throw"group type=population but this ds does not have populations";if(!t.queries.snvindel.populations.find((e=>e.key==n.key)))throw"invalid key of group type=population"}else{if("info"!=n.type)throw"unknown group type from details.groups[]";if(!n.infoKey)throw".infoKey missing from group type=info"}if(e.details.groupTestMethods){if(!Array.isArray(e.details.groupTestMethods))throw"details.groupTestMethods[] not array";if(!Number.isInteger(e.details.groupTestMethodsIdx))throw"details.groupTestMethodsIdx not integer";if(!e.details.groupTestMethods[e.details.groupTestMethodsIdx])throw"invalid array index of details.groupTestMethodsIdx"}}(e,n);const r=await async function(e,t){const n={rglst:[{chr:e.chr,start:e.start,stop:e.stop}],addFormatValues:!0,variantFilter:e.variantFilter},[s,r]=e.details.groups;if("filter"==s.type&&"filter"==r?.type){n.filterObj=T(e,s.filter);const o=j(await t.queries.snvindel.byrange.get(n));n.filterObj=T(e,r.filter);const i=j(await t.queries.snvindel.byrange.get(n)),a=function(e,t,n){const[s,r]=n.details.groups,o=[];for(const n of e){n.groupData=[{refCount:n._refCount,altCount:n._altCount}];const e=t.find((e=>e.chr==n.chr&&e.pos==n.pos&&e.ref==n.ref&&e.alt==n.alt));e?n.groupData.push({refCount:e._refCount,altCount:e._altCount}):n.groupData.push({refCount:0,altCount:0}),o.push(n)}for(const n of t){e.find((e=>e.chr==n.chr&&e.pos==n.pos&&e.ref==n.ref&&e.alt==n.alt))||(n.groupData=[{refCount:0,altCount:0},{refCount:n._refCount,altCount:n._altCount}],o.push(n))}return o}(o.mlst,i.mlst,e);return{mlst:a,totalSampleCount_group1:C(o.mlst),totalSampleCount_group2:C(i.mlst)}}n.filterObj=T(e);const o=await t.queries.snvindel.byrange.get(n),i=j(o);"filter"==s.type?i.totalSampleCount_group1=C(o):"filter"==r?.type&&(i.totalSampleCount_group2=C(o));return i}(e,n);if(1==e.details.groups.length)M(n,r.mlst,e.details.groups[0]);else{if(2!=e.details.groups.length)throw"q.details.groups.length not 1 or 2";await async function(e,t,n){const[s,r]=t.groups;if("filter"==s.type&&"filter"==r.type)return void await async function(e,t,n){const s=t.groupTestMethods[t.groupTestMethodsIdx];if(!s)throw"details.groupTestMethodsIdx out of bound";switch(s.name){case"Allele frequency difference":return void I(e,t,n);case"Fisher's exact test":return void await F(n);default:throw"unknown value from groupTestMethods[]"}}(e,t,n.mlst);if("population"==s.type&&"filter"==r.type||"population"==r.type&&"filter"==s.type)return void await async function(e,t,n){const s=await async function(e,t,n){const s=t.groups.find((e=>"population"==e.type));if(!s)return;if(!s.adjust_race)return;const r=e.queries.snvindel.populations.find((e=>e.key==s.key));if(!r)throw"invalid group.key for population";const o=new Set;for(const e of n.mlst)for(const t of e.samples)o.add(t.sample_id);const i=new Map;let a=0;for(const t of r.sets){const n={infokey_AC:t.infokey_AC,infokey_AN:t.infokey_AN,average:0},s=await(0,c.J4)({ds:e,key:t.key});for(const e of s){if(!o.has(e.sample))continue;const t=Number(e.value);Number.isFinite(t)&&(n.average+=t,a+=t)}i.set(t.key,n)}for(const[e,t]of i)t.average/=a;n.pop2average={};for(const[e,t]of i)n.pop2average[e]=t.average;return i}(e,t,n);for(const r of n.mlst)r.groupData=E(e,t,r,s);const r=t.groupTestMethods[t.groupTestMethodsIdx];if(!r)throw"details.groupTestMethodsIdx out of bound";switch(r.name){case"Allele frequency difference":return void I(e,t,n.mlst);case"Fisher's exact test":return void await F(n.mlst);default:throw"unknown value from groupTestMethods[]"}}(e,t,n);I(e,t,n.mlst)}(n,e.details,r)}for(const e of r.mlst)delete e.samples,delete e._altCount,delete e._refCount;t.send(r)}function C(e){const t=new Set;for(const n of e)if(n.samples)for(const e of n.samples)t.add(e.sample_id);return t.size}function j(e){const t={mlst:[],skipMcountWithoutAlt:0};for(const n of e){const[e,s]=O(n);0!=e?(n._altCount=e,n._refCount=s-e,t.mlst.push(n)):t.skipMcountWithoutAlt++}return t}function T(e,t){const n=[e.filter];if(t)n.push(t);else for(const t of e.details.groups)"filter"==t.type&&n.push(t.filter);return(0,N.xH)(n)}function M(e,t,n){if("filter"!=n.type)if("info"!=n.type){if("population"!=n.type)throw"unknown type of single group";{const s=e.queries.snvindel.populations.find((e=>e.key==n.key));if(!s)throw"unknown population";for(const e of t){let t=0,n=0;for(const r of s.sets)t+=Number(e.info[r.infokey_AC]||0),n+=Number(e.info[r.infokey_AN]||0);e.nm_axis_value=t/n}}}else{if(!n.infoKey)throw"infoKey missing on single group.type=info";for(const e of t){const t=e.info[n.infoKey];if(null==t);else{const n=Number(t);Number.isNaN(n)||(e.nm_axis_value=n)}}}else for(const e of t)e.nm_axis_value=Number((e._altCount/(e._altCount+e._refCount)).toPrecision(2))}function O(e){let t=0,n=0;for(const s of e.samples){if(!s?.formatK2v?.GT)continue;const r=s.formatK2v.GT.split("/").map(Number);n+=r.length;for(const n of r)n==e.altAlleleIdx&&t++}return[t,n]}function I(e,t,n){const[s,r]=t.groups;M(e,n,s);const o=n.map((e=>e.nm_axis_value));M(e,n,r);for(const[e,t]of n.entries())t.nm_axis_value=o[e]-t.nm_axis_value}function E(e,t,n,s){const r=[];for(const o of t.groups)if("info"!=o.type)if("filter"!=o.type){if("population"!=o.type)throw"unknown group.type";{if(!o.key)throw"group.key missing for type=population";const t=e.queries.snvindel.populations.find((e=>e.key==o.key));if(!t)throw"invalid group.key for population";const i=new Map;for(const e of t.sets)i.set(e.key,{ACraw:Number(n.info[e.infokey_AC]||0),ANraw:Number(n.info[e.infokey_AN]||0)});let a=0,l=0;if(o.adjust_race)[a,l]=R(i,s);else for(const e of i.values())l+=e.ACraw,a+=e.ANraw-e.ACraw;r.push({altCount:l,refCount:a})}}else r.push({altCount:n._altCount,refCount:n._refCount});else{if(!o.key)throw"group.key missing for type=info";r.push({value:n.info[o.key]})}return r}function R(e,t){let n=0;for(const t of e.values())n+=t.ANraw;let s=0,r=0;for(const[o,i]of e)i.ANadj=n*t.get(o).average,i.ACadj=0==i.ANadj?0:i.ACraw*i.ANadj/i.ANraw,s+=i.ACadj,r+=i.ANadj;return[r-s,s]}async function F(e){for(let t=0;t<Math.ceil(e.length/200);t++){const n=[];for(let s=200*t;s<200*(t+1);s++){const t=e[s];if(!t)break;const r=t.groupData;r&&r[0]&&r[1]&&Number.isFinite(r[0].altCount)&&Number.isFinite(r[0].refCount)&&Number.isFinite(r[1].altCount)&&Number.isFinite(r[1].refCount)?(n.push({index:s,n1:Math.floor(r[0].altCount),n2:Math.floor(r[0].refCount),n3:Math.floor(r[1].altCount),n4:Math.floor(r[1].refCount)}),t.htmlSections=[{key:"Contigency table",html:`<table style="font-size:.9em">\n\t\t\t\t<tr style="opacity:.5">\n\t\t\t\t <td></td>\n\t\t\t\t <td>Group1</td>\n\t\t\t\t <td>Group 2</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">ALT allele count</td>\n\t\t\t\t <td>${r[0].altCount}</td>\n\t\t\t\t <td>${Math.floor(r[1].altCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">REF allele count</td>\n\t\t\t\t <td>${r[0].refCount}</td>\n\t\t\t\t <td>${Math.floor(r[1].refCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">Allele frequency</td>\n\t\t\t\t <td>${(r[0].altCount/(r[0].altCount+r[0].refCount)).toFixed(3)}</td>\n\t\t\t\t <td>${(r[1].altCount/(r[1].altCount+r[1].refCount)).toFixed(3)}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>`}]):console.log(`${t.chr}.${t.pos}.${t.ref}.${t.alt}\t${JSON.stringify(r)}`)}const s=await(0,S.run_rust)("fisher",JSON.stringify({input:n}));for(const t of JSON.parse(s)){const n=e[t.index];n&&(n.p_value=t.p_value.toPrecision(2),t.p_value>0&&(n.nm_axis_value=Number((-Math.log10(t.p_value)).toPrecision(2))))}}let t=0;for(const n of e)n.p_value>0&&(t=Math.max(t,n.nm_axis_value));for(const n of e)0==n.p_value&&(n.nm_axis_value=Math.max(50,t))}var $=n(4065),D=n(3936);function L(e){return async(t,n)=>{const s=t.query;(0,h.Y5)(s,t.cookies);try{const r=e[s.genome];if(!r)throw"invalid genome";const[o,l]=P(r,s);if(s.findterm)return await async function(e,t,n,s,r){const o={equals:[],startsWith:[],startsWord:[],includes:[]},i=decodeURIComponent(e.findterm).toUpperCase(),a=[];try{if("snp"==e.targetType){if(!s.queries?.snvindel?.allowSNPs)throw"this dataset does not support snp search";const e=await(0,D.SC)({byName:!0,lst:[i.toLowerCase()]},r);for(const t of e)a.push({type:"geneVariant",name:t.name,subtype:"snp",chr:t.chrom,start:t.chromStart,stop:t.chromEnd,alleles:t.alleles})}else{const t=(0,q.CG)({type:"geneVariant"},e.usecase).has("plot");if(s.mayGetMatchingGeneNames&&t&&await s.mayGetMatchingGeneNames(o,i,e),s.queries?.defaultBlock2GeneMode&&t)try{const e=(0,$.S)(r,{input:i});if(Array.isArray(e.hits))for(let t=0;t<7&&e.hits[t];t++)a.push({name:e.hits[t],type:"geneVariant"})}catch(e){}}const l=await n.q.findTermByName(i,e.cohortStr,e.treeFilter,e.usecase);a.push(...l.map(G));a.forEach((e=>{"geneVariant"!=e.type&&(e.__ancestors=n.q.getAncestorIDs(e.id),e.__ancestorNames=n.q.getAncestorNames(e.id))})),t.send({lst:a})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}}(s,n,l,o,r);if(s.getterminfo)return function(e,t,n){if(!e.tid)throw"no term id";t.send({terminfo:n.q.getTermInfo(e.tid)})}(s,n,l);if(s.phewas)return s.update?await u.update_image(s,n):s.getgroup?await u.getgroup(s,n):await u.trigger(s,n,o);if(s.gettermdbconfig)return a(s,n,o,r);if(s.getcohortsamplecount)return n.send({count:o.cohort.termdb.q.getcohortsamplecount(s.cohort)});if(s.getsamplecount)return n.send(await async function(e,t,n){const s=i.i.canDisplaySampleIds(e,n);if("list"==t.getsamplecount){return await c.cf(t.filter,n,s)}return await c.B9(t,n)}(t,s,o));if(s.getsamples)return await async function(e,t,n){const s=await c.cf(e.filter,n),r=s.map((e=>n.cohort.termdb.q.id2sampleName(e)));t.send({samples:r})}(s,n,o);if(s.getcuminc)return await async function(e,t,n){const s=await(0,f.g)(e,n);t.send(s)}(s,n,o);if(s.getsurvival)return await async function(e,t,n){const s=await v(e,n);t.send(s)}(s,n,o);if(s.getregression)return await async function(e,t,n){const s=await(0,_.j)(e,n);t.send(s)}(s,n,o);if(s.validateSnps)return n.send(await(0,k.G)(s,l,o,r));if(s.getvariantfilter)return function(e,t){if(t.track)return void e.send(t.track.variant_filter);e.send(t?.queries?.snvindel?.variant_filter||{})}(n,o);if(s.getLDdata)return await async function(e,t,n){if(!e.ldtkname)throw".ldtkname missing";if(!t.queries?.ld?.tracks)throw"no ld tk";const s=t.queries.ld.tracks.find((t=>t.name==e.ldtkname));if(!s)throw"unknown ld tk";if("object"!=typeof e.m)throw"q.m{} not object";if(!e.m.chr)throw"q.m.chr missing";if(!Number.isInteger(e.m.pos))throw"q.m.pos not integer";if(!e.m.ref||!e.m.alt)throw"q.m{} invalid alleles";const r=e.m.ref+"."+e.m.alt,o=(s.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+e.m.pos+"-"+(e.m.pos+1),i=[];await(0,h.UE)({args:[s.file,o],dir:s.dir,callback:t=>{const n=t.split("\t"),s=Number.parseInt(n[1]),o=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);s==e.m.pos&&a==r?i.push({pos:o,alleles:l,r2:c}):o==e.m.pos&&l==r&&i.push({pos:s,alleles:a,r2:c})}}),n.send({lst:i})}(s,o,n);if(s.genesetByTermId)return function(e,t,n){if(!n.termMatch2geneSet)throw"this feature is not enabled";if("string"!=typeof e.genesetByTermId||0==e.genesetByTermId.length)throw"invalid query term id";const s=n.q.getGenesetByTermId(e.genesetByTermId);t.send(s)}(s,n,l);if(s.getSampleScatter&&(s.for="scatter"),"scatter"==s.for)return await(0,x.uR)(t,s,n,o,r);if(s.getLowessCurve)return await(0,x.v8)(t,s,n);if(s.getCohortsData)return await async function(e,t,n){const s=function(e){const t=e.cohort.db.connection.prepare("select * from features").all();return{cohorts:e.cohort.db.connection.prepare("select * from cohorts where cohort in (select distinct(cohort) from cohort_features)\n\t\t order by sample_count desc").all(),features:t,cfeatures:e.cohort.db.connection.prepare("select * from cohort_features").all()}}(n);t.send(s)}(0,n,o);if("mds3queryDetails"==s.for)return function(e,t){const n={},s=t.queries||{};s.snvindel&&(n.snvindel={},s.snvindel.details&&(n.snvindel.details=s.snvindel.details),s.snvindel.populations&&(n.snvindel.populations=s.snvindel.populations));s.trackLst&&(n.trackLst=s.trackLst);if(s.ld){n.ld=JSON.parse(JSON.stringify(s.ld));for(const e of n.ld.tracks)delete e.file}e.send(n)}(n,o);if("termTypes"==s.for)return n.send(await o.getTermTypes(s));if("matrix"==s.for)return await async function(e,t,n,s,r){if(e.getPlotDataByName){if(!s.cohort?.matrixplots?.plots)throw"ds.cohort.matrixplots.plots missing for the dataset";const t=s.cohort.matrixplots.plots.find((t=>t.name===e.getPlotDataByName));if(!t)throw"invalid name of premade matrix plot";return void n.send(t.matrixConfig)}const o=await(0,m.Yu)(e,s,r);if(i.i.canDisplaySampleIds(t,s))for(const e of Object.values(o.samples))e.sampleName=s.sampleId2Name.get(e.sample);n.send(o)}(s,t,n,o,r);if("getSamplesPerFilter"==s.for)return await(0,m.fZ)(s,o,n);if("mds3variantData"==s.for)return await A(s,n,o);if(s.for,"convertSampleId"==s.for)return function(e,t,n){if(!n.convertSampleId)throw"not supported on this ds";if(!Array.isArray(e.inputs))throw"q.inputs[] not array";t.send({mapping:n.convertSampleId.get(e.inputs)})}(s,n,l);if("singleSampleData"==s.for)return async function(e,t,n,s,r){const o=i.i.canDisplaySampleIds(t,s);let a=[];if(o)try{a=r.q.getSingleSampleData(e.sampleId,e.term_ids),n.send(a)}catch(e){n.send({error:e.message||e})}else n.send({error:"Requires sign in to access the sample data"})}(s,t,n,o,l);if("getProfileFacilities"==s.for)return async function(e,t,n,s,r){const o=i.i.canDisplaySampleIds(t,s);let a=[];if(o)try{a=r.q.getProfileFacilities(),n.send(a)}catch(e){n.send({error:e.message||e})}else n.send({error:"Requires sign in to access the sample data"})}(0,t,n,o,l);if("getAllSamples"==s.for)return async function(e,t,n,s){const r=i.i.canDisplaySampleIds(t,s);let o=[];r&&(o=Object.fromEntries(s.sampleId2Name));n.send(o)}(0,t,n,o);if("getAllSamplesByName"==s.for)return async function(e,t,n,s){if(!i.i.canDisplaySampleIds(t,s))return n.send({});if(s.queries?.singleCell?.samples?.get){const e=await s.queries.singleCell.samples.get(),t={};for(const n of e.samples)t[n.sample]=s.cohort.termdb.q.sampleName2id(n.sample);return void n.send(t)}{let t=s.sampleName2Id;if(e.filter){e.ds=s;const n=await(0,c.cf)(e.filter,e.ds,!0);t=new Map;for(const e of n)t.set(e.name,e.id)}n.send(Object.fromEntries(t))}}(s,t,n,o);if("DEanalysis"==s.for)return await async function(e,t,n){if(!n.queries?.rnaseqGeneCount)throw"not enabled by this dataset";const s=await n.queries.rnaseqGeneCount.get(e);t.send(s)}(s,n,o);throw"termdb: doesn't know what to do"}catch(e){n.send({error:e.message||e}),e.stack?console.log(e.stack):console.log(e)}}}function P(e,t){{const n=e.datasets[t.dslabel];if(n){if(n?.cohort?.termdb)return[n,n.cohort.termdb];throw".cohort.termdb not found on this dataset"}}if(!e.termdbs)throw"invalid dslabel";const n=e.termdbs[t.dslabel];if(!n)throw"invalid dslabel";if(!n.cohort)throw"ds.cohort missing for genome-level termdb";if(!n.cohort.termdb)throw"ds.cohort.termdb{} missing for a genome-level termdb";return[n,n.cohort.termdb]}function G(e){return JSON.parse(JSON.stringify(e))}},2974:(e,t,n)=>{"use strict";n.d(t,{Yu:()=>f,fZ:()=>d,gh:()=>p,te:()=>m});var s=n(1017),r=n.n(s),o=n(8907),i=n(5257),a=(n(9157),n(7147),n(7219),n(334)),l=n.n(a),c=n(3345),u=n(8599);async function f(e,t,n){try{return function(e,t,n){if(!t.cohort)throw"cohort missing from ds";if(!e.terms)throw"missing 'terms' parameter";e.ds=t,e.genome=n;for(const t of e.terms)t.term.name||(t.term=e.ds.cohort.termdb.q.termjsonByOneid(t.term.id)),t.q||console.log("do something??");if(e.currentGeneNames&&!Array.isArray(e.currentGeneNames))throw"currentGeneNames[] is not array";e.filter0&&"string"==typeof e.filter0&&(e.filter0=JSON.parse(e.filter0))}(e,t,n),await async function(e){const[t,n]=function(e){const t=[],n=[];for(const s of e){const e=s.term.type;"snplst"==e||"snplocus"==e||"geneVariant"==e?n.push(s):t.push(s)}return[t,n]}(e.terms),[s,r]=await async function(e,t){if(!t.length)return[{},{}];if(e.ds?.cohort?.db)return await p(e,t);if(e.ds?.variant2samples?.get)return await async function(e,t){const n={filter0:e.filter0,filterObj:e.filter,genome:e.genome,get:"samples",twLst:t,gdcUseCaseuuid:!0,isHierCluster:e.isHierCluster};e.rglst&&(n.rglst=e.rglst);if(e.currentGeneNames){n.geneTwLst=[];for(const t of e.currentGeneNames)n.geneTwLst.push({term:{name:t,type:"geneVariant"}})}const s=await e.ds.variant2samples.get(n),r={};for(const e of s.samples){const n={sample:e.sample_id};for(const s of t){const t=e[s.term.id];Array.isArray(t)&&null!=t[0]&&null!=t[0]?n[s.term.id]={key:t[0],value:t[0]}:null!=t&&null!=t&&(n[s.term.id]={key:t,value:t})}r[e.sample_id]=n}return[r,s.byTermId||{}]}(e,t);throw"unknown method for dictionary terms"}(e,t);if(t.length&&!Object.keys(s).length)return{samples:s,refs:{byTermId:r,bySampleId:{}}};const i=await async function(e,t){if(!t.find((e=>"snplst"==e.term.type||"snplocus"==e.term.type)))return;if(!e.filter)return;return new Set((await(0,o.cf)(e.filter,e.ds)).map((e=>e.id)))}(e,n);for(const o of n)if("geneVariant"==o.term.type){e.ds.cohort?.termdb?.getGeneAlias&&(r[o.term.name]=e.ds.cohort?.termdb?.getGeneAlias(e,o));const n=await e.ds.mayGetGeneVariantData(o,e);for(const[e,r]of n.entries())o.term.name in r&&(t.length||e in s||(s[e]={sample:e}),s[e]&&(s[e][o.term.name]=r[o.term.name]))}else{if("snplst"!=o.term.type&&"snplocus"!=o.term.type)throw"unknown type of non-dictionary term";{o.type=o.term.type;const e=new Map;await(0,u._)(o,e,!0);for(const[t,n]of e){if(i&&!i.has(t))continue;t in s||(s[t]={sample:t});const e={};for(const[t,s]of n.id2value)e[t]=s.value;s[t][o.term.id]=e}}}const a={};for(const t in s)e.ds.cohort?.termdb?.q?.id2sampleName?a[t]={label:e.ds.cohort.termdb.q.id2sampleName(Number(t))}:e.ds.__gdc?.caseid2submitter&&(a[t]={label:e.ds.__gdc.caseid2submitter.get(t)});return{samples:s,refs:{byTermId:r,bySampleId:a}}}(e)}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}async function d(e,t,n){e.ds=t;const s={};for(const t in e.filters){const n=e.filters[t],r=(await(0,o.cf)(n,e.ds)).map((e=>e.id));s[t]=Array.from(new Set(r))}n.send(s)}async function p(e,t){const n={},s={},r={},a=await(0,i.w)(e.filter,e.ds),l=a?a.values.slice():[],c=await Promise.all(t.map((async(t,n)=>{const i=await(0,o.Bi)(e,l,n,a,t);if(i.bins&&(s[t.term.id]={bins:i.bins}),i.events&&(s[t.term.id]={events:i.events}),t.term.values){const e=Object.values(t.term.values);e.find((e=>"order"in e))&&(s[t.term.id]={keyOrder:e.sort(((e,t)=>e.order-t.order)).map((e=>e.key))})}return"id"in t.term&&(r[t.term.id]=t),i}))).catch(console.error);l.push(...t.map((e=>e.term.id||e.term.name)));const u=`WITH\n\t\t${a?a.filters+",":""}\n\t\t${c.map((e=>e.sql)).join(",\n")}\n\t\t${c.map((e=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${e.tablename}\n\t\t\t${a?`WHERE sample IN ${a.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,f=e.ds.cohort.db.connection.prepare(u).all(l),d=await async function(e){if(!e.currentGeneNames)return;const t=new Set;for(const n of e.currentGeneNames){const s={term:{name:n,type:"geneVariant"}},r=await e.ds.mayGetGeneVariantData(s,e);for(const e of r.keys())t.add(e)}return t}(e);for(const{sample:e,term_id:t,key:s,value:o}of f){if(d&&!d.has(e))continue;n[e]||(n[e]={sample:e});r[t];if(n[e][t]){if(!n[e][t].values){const s=n[e][t];n[e][t]={values:[s]}}n[e][t].values.push({key:s,value:o})}else n[e][t]={key:s,value:o}}return[n,s]}async function m(e){if(e.cohort.matrixplots){if(!Array.isArray(e.cohort.matrixplots.plots))throw"cohort.matrixplots.plots is not array";for(const t of e.cohort.matrixplots.plots){if(!t.name)throw".name missing from one of matrixplots.plots[]";if(!t.file)throw"unknown data source of one of matrixplots.plots[]";{const e=await c.b5(r().join(l().tpmasterdir,t.file));t.matrixConfig=JSON.parse(e),t.getConfig&&(t.matrixConfig=t.getConfig(t.matrixConfig))}}}}},5708:(e,t,n)=>{"use strict";n.r(t),n.d(t,{do_precompute:()=>y,getgroup:()=>N,trigger:()=>g,update_image:()=>k});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(8907),c=n(6718),u=n(2826),f=n(4521),d=n.n(f),p=n(334),m=n.n(p),h=n(9157);async function g(e,t,n){if(!n.cohort)throw"ds.cohort missing";if(!n.cohort.termdb)throw"cohort.termdb missing";if(!n.cohort.termdb.phewas)throw"not allowed on this dataset";if(!e.ssid)throw"ssid missing";const s={};let r;e.filter&&(r=new Set(await l.cf(e.filter,n)));const[o,c]=await a.L0(e.ssid,r);s.numberofsamples=o.size;const f=c.has(a.EO.het)?c.get(a.EO.het).size:0,d=c.has(a.EO.href)?c.get(a.EO.href).size:0,p=c.has(a.EO.halt)?c.get(a.EO.halt).size:0,g=function(e,t,n,s,r,o){const i=[];let a;if(t.cohort.termdb.selectCohort&&e){const t=e.lst.find((e=>"cohortFilter"==e.tag));t&&(a=t.tvs.values.map((e=>e.key)).sort().join(","))}for(const e of t.cohort.termdb.q.getcategory2vcfsample()){if(a&&e.subcohort!=a)continue;const l=u.iK(t.cohort.termdb.q.termjsonByOneid(e.term_id));for(const t of e.categories){const[a,c,u]=x(n,t.group1lst);let f,d,p;t.group2lst?[f,d,p]=x(n,t.group2lst):(f=s-a,d=o-c,p=r-u),a+f+c+d+u+p!=0&&i.push({term:l,group_name:e.group_name,parent_name:e.parent_name,group1label:t.group1label,group2label:t.group2label,table:[u,p,a,f,c,d]})}}return i}(e.filter,n,o,f,d,p);s.testcount=g.length;{const e=[];for(let t=0;t<g.length;t++)e.push(t+"\t"+g[t].table.join("\t"));const t=await(0,h.default)(i().join(m().binpath,"utils/fisher.2x3.R"),e);let n=0;for(const e of t)g[n++].pvalue=Number(e.split("\t")[7])}s.maxlogp=function(e){let t=0;for(const n of e)0==n.pvalue?n.logp=100:n.logp=-Math.log10(n.pvalue),t=Math.max(t,n.logp);return t}(g);const y=function(e){const t=new Map;for(const n of e)t.has(n.group_name)||t.set(n.group_name,[]),t.get(n.group_name).push(n);const n=[];for(const[e,s]of t)n.push({group_name:e,categories:s});return n}(g);s.tmpfile=await function(e){const t=[];for(const n of e)for(const e of n.categories)t.push(n.group_name+"\t"+e.logp+"\t"+e.pvalue+"\t"+JSON.stringify(e));return a.tG(t.join("\n"))}(y),q(y,s,e);{const e=.05;s.hoverdots=g.filter((t=>t.pvalue<=e))}t.send(s)}async function y(e){if(!e.cohort)throw"ds.cohort missing";if(!e.cohort.termdb)throw"cohort.termdb missing";if(!e.cohort.termdb.phewas)throw"not allowed on this dataset";e.cohort.termdb.selectCohort?await async function(e){const t=await async function(e){if(!e.cohort.termdb.phewas.precompute_subcohort2totalsamples)return;for(const t in e.cohort.termdb.phewas.precompute_subcohort2totalsamples){const n=e.cohort.termdb.phewas.precompute_subcohort2totalsamples[t];if(n.termtype)for(const t in n.termtype)n.termtype[t].samples=await l.cf(n.termtype[t].filter,e)}return e.cohort.termdb.phewas.precompute_subcohort2totalsamples}(e),n=function(e){const t=new Map,n=e.cohort.db.connection.prepare("SELECT * FROM subcohort_terms");for(const{term_id:e,cohort:s}of n.all())t.has(e)||t.set(e,new Set),t.get(e).add(s);return t}(e),s=r().createWriteStream("category2vcfsample"),o=[];for(const{group_name:r,term:i}of e.cohort.termdb.q.getAlltermsbyorder()){if(!i.type)continue;if(!n.has(i.id)){o.push(i.id);continue}let a="";{const t=e.cohort.termdb.q.getTermParent(i.id);t&&(a=t.name)}const c=v(i,e,n);for(const n of c){const o=await l.g5(n);let c;if("categorical"==i.type||"integer"==i.type||"float"==i.type)c=w(o.lst,i,e);else{if("condition"!=i.type)throw"unknown term type";c=e.cohort.termdb.phewas.comparison_groups?_(o.lst,e):w(o.lst,i,e)}c=b({categories:c,q:n,subcohortTermtype2samples:t,term:i});for(const e of c)console.log(e.group1lst.length+(e.group2lst?"/"+e.group2lst.length:"")+"\t"+e.group1label+"\t"+i.name+"\t"+n.cohortname);s.write(n.cohortname+"\t"+r+"\t"+i.id+"\t"+a+"\t"+(n.term1_q?JSON.stringify(n.term1_q):"{}")+"\t"+JSON.stringify(c)+"\n")}}s.end((()=>{console.log('Phewas precompute result written to file "category2vcfsample".'),o.length&&(console.log(o.length+" empty terms:"),console.log(o.join("\n")))}))}(e):await async function(e){const[t]=await async function(e){let t=null;if(e.cohort.termdb.phewas.samplefilter4termtype&&e.cohort.termdb.phewas.samplefilter4termtype.condition){const n=await l.cf(e.cohort.termdb.phewas.samplefilter4termtype.condition.filter,e);if(e.track&&e.track.vcf&&e.track.vcf.sample2arrayidx){t=[];for(const s of n)e.track.vcf.sample2arrayidx.has(s)&&t.push(s)}else t=n}return[t]}(e),n=[];for(const{group_name:s,term:r}of e.cohort.termdb.q.getAlltermsbyorder()){if(!r.type)continue;let o="";{const t=e.cohort.termdb.q.getTermParent(r.id);t&&(o=t.name)}const i=v(r,e);for(const a of i){const i=await l.g5(a);let c;if("categorical"==r.type||"integer"==r.type||"float"==r.type)c=w(i.lst,r,e);else{if("condition"!=r.type)throw"unknown term type";c=e.cohort.termdb.phewas.comparison_groups?_(i.lst,e):w(i.lst,r,e)}c=b({categories:c,q:a,term:r,condition_samplelst:t});for(const e of c)console.log(e.group1lst.length+(e.group2lst?"/"+e.group2lst.length:"")+"\t"+e.group1label+"\t"+r.name);n.push(s+"\t"+r.id+"\t"+o+"\t"+(a.term1_q?JSON.stringify(a.term1_q):"{}")+"\t"+JSON.stringify(c))}}r().writeFileSync("category2vcfsample",n.join("\n")),console.log('Phewas precompute result written to file "category2vcfsample".')}(e)}function b(e){const{categories:t,q:n,term:s,subcohortTermtype2samples:r,condition_samplelst:o}=e;if(r&&r[n.cohortname]&&r[n.cohortname].termtype&&r[n.cohortname].termtype[s.type]){const e=r[n.cohortname].termtype[s.type].samples;for(const n of t)if(n.group2lst)n.group2lst=n.group2lst.filter((t=>-1!=e.indexOf(t)));else if(n.copycontrolfrom1stgroup){n.group2lst=[];for(const e of t[0].group2lst)n.group2lst.push(e)}else{const t=new Set(n.group1lst);n.group2lst=e.filter((e=>!t.has(e)))}return t}if(o&&"condition"==s.type){for(const e of t)if(e.group2lst)e.group2lst=e.group2lst.filter((e=>-1!=o.indexOf(e)));else if(e.copycontrolfrom1stgroup){e.group2lst=[];for(const n of t[0].group2lst)e.group2lst.push(n)}else{const t=new Set(e.group1lst);e.group2lst=o.filter((e=>!t.has(e)))}return t}if(!s.values)return t;const i=new Set;for(const e in s.values)s.values[e].uncomputable&&i.add(s.values[e].label);if(0==i.size)return t;const a=[];for(const e of t)i.has(e.group1label)?console.log("skip "+e.group1label+", "+s.id):a.push(e);for(let e=0;e<a.length;e++){const t=a[e];t.group2lst=[];for(let n=0;n<a.length;n++)n!=e&&t.group2lst.push(...a[n].group1lst)}return a}function v(e,t,n){const s=[];if(t.cohort.termdb.selectCohort){if(!n)throw"term2cohort is required when cohort selection is enabled";for(const r of t.cohort.termdb.selectCohort.values){const o=r.keys.sort().join(",");if(!n.get(e.id).has(o))continue;const i={type:"tvslst",in:!0,join:"",lst:[{type:"tvs",tvs:{term:t.cohort.termdb.selectCohort.term,values:r.keys.map((e=>({key:e})))}}]};if("categorical"==e.type)s.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:t,term1_id:e.id});else if("float"==e.type||"integer"==e.type)s.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:t,term1_id:e.id,term1_q:e.bins.default});else{if("condition"!=e.type)throw"unknown term type";s.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:t,term1_id:e.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}}}else if("categorical"==e.type)s.push({ds:t,term1_id:e.id});else if("float"==e.type||"integer"==e.type)s.push({ds:t,term1_id:e.id,term1_q:e.bins.default});else{if("condition"!=e.type)throw"unknown term type";s.push({ds:t,term1_id:e.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}return s}function w(e,t,n){const s=new Map;for(const r of e){if(n.track&&n.track.vcf&&n.track.vcf.sample2arrayidx&&!n.track.vcf.sample2arrayidx.has(r.sample))continue;const e=r.key1;if(!s.has(e)){let n=e;t.values&&(n=t.values[e]?t.values[e].label:e),s.set(e,{group1label:n,group2label:"All others",group1lst:[]})}s.get(e).group1lst.push(r.sample)}return[...s.values()]}function _(e,t){const n=[];for(const s of t.cohort.termdb.phewas.comparison_groups){const r=[],o=[];for(const n of e){if(t.track&&t.track.vcf&&t.track.vcf.sample2arrayidx&&!t.track.vcf.sample2arrayidx.has(n.sample))continue;const e=Number(n.key1);s.group1grades.has(e)?r.push(n.sample):s.group2grades&&s.group2grades.has(e)&&o.push(n.sample)}0!=r.length?n.push({group1label:s.group1label,group2label:s.group2label,group1lst:r,group2lst:o.length?o:void 0,copycontrolfrom1stgroup:s.copycontrolfrom1stgroup}):console.log("Empty group1: "+s.group1label)}return n}async function k(e,t){const n=await a.b5(i().join(m().cachedir,e.file)),s=[];for(const e of n.trim().split("\n")){const[t,n]=e.split("\t",2),r=Number(n);0!=s.length&&s[s.length-1].group_name==t||s.push({group_name:t,categories:[]}),s[s.length-1].categories.push({logp:r})}const r={maxlogp:Number(e.max)};q(s,r,e),t.send(r)}function q(e,t,n){const s=Number(n.intendwidth),r=Number(n.axisheight),o=Number(n.groupnamefontsize),i=Number(n.dotradius),a=Number(n.groupxspace),l=Number(n.leftpad),u=Number(n.rightpad),f=Number(n.toppad),d=Number(n.bottompad),p=Number(n.devicePixelRatio),m=s/e.reduce(((e,t)=>e+t.categories.length),0),h=(0,c.createCanvas)(10,10),g=h.getContext("2d");let y=0;for(const t of e){const e=t.categories.length*m;t.width=Math.max(e,o)+2*a,t.dotshiftx=e>o?m:o/t.categories.length,y+=t.width}const b=l+y+u;h.width=b*p;const v=f+r+d;h.height=v*p,p>1&&g.scale(p,p),y=0,g.fillStyle="#FDFEE2";for(const[t,n]of e.entries())t%2==0&&g.fillRect(y,f,n.width,r),y+=n.width;y=0,g.fillStyle="black",t.grouplabels=[];for(const n of e){t.grouplabels.push({name:n.group_name,x:y+n.width/2,y:f+r+2*i});let e=0;for(const s of n.categories){const o=0==t.maxlogp?0:s.logp>=t.maxlogp?r:r*s.logp/t.maxlogp;g.beginPath(),g.arc(y+a+e,f+r-o,i,0,2*Math.PI),g.fill(),s.x=y+a+e,e+=n.dotshiftx}y+=n.width}t.canvaswidth=b,t.canvasheight=v,t.toppad=f,t.bottompad=d,t.axisheight=r,t.dotradius=i,t.groupnamefontsize=o,t.src=h.toDataURL()}function x(e,t){const n=new Map;for(const s of t){const t=e.get(s);t&&n.set(t,1+(n.get(t)||0))}return[n.get(a.EO.het)||0,n.get(a.EO.halt)||0,n.get(a.EO.href)||0]}async function N(e,t){if(!e.file)throw"file missing";return new Promise(((n,s)=>{const o=[],a=d().createInterface({input:r().createReadStream(i().join(m().cachedir,e.file))});a.on("line",(t=>{if(!t.startsWith(e.getgroup+"\t"))return;const n=t.split("\t"),s=JSON.parse(n[3]);s.pvalue=Number(n[2]),o.push(s)})),a.on("close",(()=>{t.send({categories:o}),n()}))}))}},8599:(e,t,n)=>{"use strict";n.d(t,{_:()=>M,j:()=>k});var s=n(1017),r=n.n(s),o=n(8907),i=n(5257),a=n(9157),l=n(7147),c=n.n(l),u=n(7219),f=n.n(u),d=n(334),p=n.n(d),m=n(3345),h=n(1271),g=n(4453);const y=["linear","logistic","cox"],b=1;let v,w;const _={NodeJS:{},"regression.R":{}};async function k(e,t){try{!function(e,t){if(!t.cohort)throw"cohort missing from ds";if(e.ds=t,!e.regressionType)throw"regressionType missing";if(!y.includes(e.regressionType))throw"unknown regressionType";if(!e.outcome)throw"missing 'outcome' parameter";if(!("id"in e.outcome))throw"outcome.id missing";if(!e.outcome.q)throw"outcome.q missing";if(e.outcome.q.computableValuesOnly=!0,e.outcome.term=t.cohort.termdb.q.termjsonByOneid(e.outcome.id),!e.outcome.term)throw"invalid outcome term: "+e.outcome.id;if(!e.independent)throw"independent[] missing";if(!Array.isArray(e.independent)||0==e.independent.length)throw"q.independent is not non-empty array";for(const n of e.independent){if(!n.q)throw`missing q for independent term '${n.id}'`;if(q(n,e,t),"snplst"!=n.type&&"snplocus"!=n.type){if(n.q.computableValuesOnly=!0,!n.id)throw".id missing for an independent term";if(n.term=t.cohort.termdb.q.termjsonByOneid(n.id),!n.term)throw`invalid independent term='${n.id}'`}else{if(!n.q.cacheid)throw"q.cacheid missing";if(p().cache_snpgt.fileNameRegexp.test(n.q.cacheid))throw"invalid cacheid";if("object"!=typeof n.q.snp2effAle)throw"q.snp2effAle{} is not object";if(!Number.isInteger(n.q.alleleType))throw"q.alleleType is not integer";if(!Number.isInteger(n.q.geneticModel))throw"q.geneticModel is not integer";if(3==n.q.geneticModel&&"object"!=typeof n.q.snp2refGrp)throw"q.snp2refGrp{} is not object when geneticMode=3";if("snplst"==n.type&&!Number.isInteger(n.q.missingGenotype))throw"q.missingGenotype is not integer for snplst"}}for(const t of e.independent){t.interactions||(t.interactions=[]);for(const n of t.interactions)if(!e.independent.find((e=>e.id==n)))throw"interacting term id missing from independent[]: "+n}}(e,t),v=(new Date).getTime();const n=await async function(e,t,n){const[s,r]=function(e){const t=[],n=[];for(const s of e)"snplst"==s.type||"snplocus"==s.type?n.push(s):t.push(s);return[t,n]}(t),a=await async function(e,t){const n=new Map,s=await(0,i.w)(e.filter,e.ds),r=s?s.values.slice():[],a=await Promise.all(t.map((async(t,n)=>await(0,o.Bi)(e,r,n,s,t)))).catch(console.error);r.push(...t.map((e=>e.id)));const l=`WITH\n\t\t${s?s.filters+",":""}\n\t\t${a.map((e=>e.sql)).join(",\n")}\n\t\t${a.map((e=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${e.tablename}\n\t\t\t${s?`WHERE sample IN ${s.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,c=e.ds.cohort.db.connection.prepare(l).all(r),u=[],f=e.ds.cohort.termdb.ageEndOffset;if(!f)throw"missing age end offset";for(const t of c)if("cox"==e.regressionType&&t.term_id==e.outcome.id){const n=t.key,{age_start:s,age_end:r}=JSON.parse(t.value);if(-1==n)continue;const o={age_start:s,age_end:"age"==e.outcome.q.timeScale?r+f:r};u.push({sample:t.sample,key:n,value:o,term_id:t.term_id})}else u.push(t);for(const{sample:e,term_id:s,key:r,value:o}of u){const i=t.find((e=>e.id==s));if(n.has(e)||n.set(e,{sample:e,id2value:new Map}),n.get(e).id2value.has(s))throw`duplicate '${s}' entry for sample='${e}'`;n.get(e).id2value.set(s,{key:i.q.scale?r/i.q.scale:r,value:i.q.scale?o/i.q.scale:o})}const d=new Set;for(const e of n.values())for(const n of t)if(!e.id2value.has(n.id)){d.add(e.sample);break}for(const e of d)n.delete(e);return n}(e,s);for(const e of r){if(T(e,a,n),"snplst"!=e.type&&"snplocus"!=e.type)throw"unknown type of independent non-dictionary term";await M(e,a)}return[...a.values()]}(e,[e.outcome,...e.independent],t);w=(new Date).getTime(),_.NodeJS.getSampleData=(w-v)/1e3+" sec",v=(new Date).getTime();const s=function(e,t){const n={id:e.outcome.id,name:e.outcome.term.name,rtype:"numeric"};"logistic"==e.regressionType&&(n.categories={ref:e.outcome.refGrp,nonref:S(e.outcome)});"cox"==e.regressionType&&(n.timeToEvent={timeId:e.outcome.id+"_time",eventId:e.outcome.id+"_event",timeScale:e.outcome.q.timeScale},"age"==n.timeToEvent.timeScale&&(n.timeToEvent.agestartId=e.outcome.id+"_agestart",n.timeToEvent.ageendId=e.outcome.id+"_ageend"));const s=[];for(const t of e.independent)"snplst"==t.type||"snplocus"==t.type?N(t,s,e):x(t,s,e);const r=[];for(const o of t){const{sample:t,id2value:i}=o;if(!i.has(e.outcome.id)){o.noOutcome=!0;continue}const a=i.get(e.outcome.id);let l=!1;for(const t of e.independent)if("snplocus"!=t.type)if("snplst"==t.type){for(const e of t.highAFsnps.keys())if(!i.get(e)){l=!0;break}}else{if(!i.get(t.id)){l=!0;break}}if(l)continue;const c={};if("linear"==e.regressionType&&(c[n.id]=a.value),"logistic"==e.regressionType&&(c[n.id]=a.key===e.outcome.refGrp?0:1),"cox"==e.regressionType){c[n.timeToEvent.eventId]=a.key;const{age_start:t,age_end:s}=a.value;c[n.timeToEvent.timeId]=s-t,"age"==e.outcome.q.timeScale&&(c[n.timeToEvent.agestartId]=t,c[n.timeToEvent.ageendId]=s)}for(const e of s){const t=i.get(e.id);c[e.id]=t?"numeric"===e.rtype?t.value:t.key:null}r.push(c)}const o={regressionType:e.regressionType,binpath:p().binpath,data:r,outcome:n,independent:s};return o}(e,n);w=(new Date).getTime(),_.NodeJS.makeRinput=(w-v)/1e3+" sec",function(e){const t=e.regressionType,n=e.outcome;if(e.data.length<b)throw"too few samples to fit model";let s=e.independent.length;if("cox"==t)if("time"==n.timeToEvent.timeScale)s+=2;else{if("age"!=n.timeToEvent.timeScale)throw"unknown cox regression time scale";s+=4}else s+=1;if(e.data.find((e=>Object.keys(e).length!=s)))throw"unequal number of variables in data entries";if("logistic"==t){if([...new Set(e.data.map((e=>e[n.id])))].find((e=>![0,1].includes(e))))throw"non-0/1 outcome values found"}if("cox"==t){if([...new Set(e.data.map((e=>e[n.timeToEvent.eventId])))].find((e=>![0,1].includes(e))))throw"non-0/1 outcome event values found"}for(const t of e.independent)if("numeric"==t.rtype){if(t.refGrp)throw`reference group given for '${t.id}'`}else{if("factor"!=t.rtype)throw`variable rtype='${t.rtype}' not recognized`;{if(!t.refGrp)throw`reference group not given for '${t.id}'`;if("snplst"==t.type||"snplocus"==t.type)continue;const n=new Set(e.data.map((e=>e[t.id])));if(n.size<2)throw`fewer than 2 categories in data of variable='${t.id}'`;if(!n.has(t.refGrp))throw`reference group missing in data of variable='${t.id}'`}}}(s);const[r,a]=function(e){const t={},n={};if(t.outcome=e.outcome.id,n[e.outcome.id]="outcome",e.outcome.timeToEvent){const s=e.outcome.timeToEvent;t.outcome_time=s.timeId,n[s.timeId]="outcome_time",t.outcome_event=s.eventId,n[s.eventId]="outcome_event","age"==s.timeScale&&(t.outcome_agestart=s.agestartId,t.outcome_ageend=s.ageendId,n[s.agestartId]="outcome_agestart",n[s.ageendId]="outcome_ageend")}for(const[s,r]of e.independent.entries())t["id"+s+"_"]=r.id,n[r.id]="id"+s+"_";if(e.outcome.id=n[e.outcome.id],e.outcome.timeToEvent){const t=e.outcome.timeToEvent;t.timeId=n[t.timeId],t.eventId=n[t.eventId],"age"==t.timeScale&&(t.agestartId=n[t.agestartId],t.ageendId=n[t.ageendId])}for(const t of e.independent)if(t.id=n[t.id],t.interactions&&t.interactions.length>0)for(const[e,s]of t.interactions.entries())t.interactions[e]=n[s];for(const t of e.data)for(const e in t)t[n[e]]=t[e],delete t[e];return[t,n]}(s),l={resultLst:[]};return await Promise.all([A(s,r,e,l),C(e,n,s,l)]),console.log("benchmark:",_),l}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}function q(e,t,n){if(!e.q.restrictAncestry)return;if(!("name"in e.q.restrictAncestry))throw".name missing from tw.q.restrictAncestry";if(!n.cohort.termdb.restrictAncestries)throw"ds.cohort.termdb.restrictAncestries missing";const s=n.cohort.termdb.restrictAncestries.find((t=>t.name==e.q.restrictAncestry.name));if(!s)throw"unknown ancestry for restriction: "+e.q.restrictAncestry.name;if(s.pcs)e.q.restrictAncestry.pcs=s.pcs;else{if(!s.PCBySubcohort)throw"unknown way of accessing pcs from ds.cohort.termdb.restrictAncestries: "+e.q.restrictAncestry.name;{if(!t.filter)throw"q.filter missing while trying to access subcohort for PCBySubcohort";const n=I(t.filter,"cohortFilter");if(!n)throw"tvs by tag=cohortFilter missing from q.filter.lst[] while trying to access subcohort for PCBySubcohort";const r=n.tvs.values.map((e=>e.key)).sort().join(","),o=s.PCBySubcohort[r];if(!o)throw"unknown key for PCBySubcohort: "+r;if(!o.pcs)throw"pcs Map() missing from PCBySubcohort[]: "+r;e.q.restrictAncestry.pcs=o.pcs}}}function x(e,t,n){const s={id:e.id,name:e.term.name,type:"spline"==e.q.mode?"spline":"other",rtype:"continuous"==e.q.mode||"spline"==e.q.mode?"numeric":"factor"};if(e.interactions.length>0){s.interactions=[];for(const t of e.interactions){const e=n.independent.find((e=>e.id==t));if("snplst"==e.type)for(const t of e.highAFsnps.keys())s.interactions.push(t);else{if("snplocus"==e.type)continue;s.interactions.push(t)}}}"factor"===s.rtype&&(s.refGrp=e.refGrp),"spline"==e.q.mode&&(s.spline={knots:e.q.knots.map((e=>Number(e.value)))},n.independent.find((e=>"snplocus"==e.type))||(s.spline.plotfile=r().join(p().cachedir,Math.random().toString()+".png"))),t.push(s)}function N(e,t,n){for(const s of e.highAFsnps.keys()){const r={id:s,name:s,type:e.type};3==e.q.geneticModel?(r.rtype="factor",r.refGrp=e.q.snp2refGrp[s]):r.rtype="numeric";for(const t of n.independent)t.interactions.includes(e.id)&&(r.interactions||(r.interactions=[]),r.interactions.push(t.id));t.push(r)}if(e.q.restrictAncestry)for(const n of e.q.restrictAncestry.pcs.keys())t.push({id:n,name:n,type:"float",rtype:"numeric"})}function S(e){if("condition"==e.term.type){for(const t of e.q.groups)if(t.name!=e.refGrp)return t;throw"nonref group not found for logistic outcome"}if("predefined-groupset"==e.q.type){if(!e.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!Number.isInteger(e.q.groupsetting.predefined_groupset_idx))throw'outcome.q.predefined_groupset_idx not integer when q.type is "predefined-groupset"';if(!e.term.groupsetting)throw"outcome.term.groupsetting missing";const t=e.term.groupsetting.lst[e.q.groupsetting.predefined_groupset_idx];if(!t)throw"groupset not found by outcome.q.predefined_groupset_idx";const n=t.groups.find((t=>t.name!=e.refGrp));if(!n)throw"non-ref group not found for predefined-groupset";return n.name}if("custom-groupset"==e.q.type){if(!e.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!e.q.groupsetting.customset)throw"outcome.q.customset missing";const t=e.q.groupsetting.customset.groups.find((t=>t.name!=e.refGrp));if(!t)throw"non-ref group not found for custom-groupset";return t.name}if("values"==e.q.type){if(!e.term.values)throw"outcome.term.values{} missing";for(const t in e.term.values){const n=e.term.values[t];if(n.label!=e.refGrp)return n.label}throw"unknown nonref group from outcome.term.values"}if("custom-bin"==e.q.type){const t=e.q.lst.find((t=>t.label!=e.refGrp));if(!t)throw"non-ref bin is not found for custom-bin";return t.label}if("regular-bin"==e.q.type)throw"do not know a way to find computed bin list for type=regular-bin";throw"unknown outcome.q.type"}async function A(e,t,n,s){v=(new Date).getTime();const o=r().join(p().cachedir,Math.random().toString()+".json");await m.Sf(o,JSON.stringify(e));const i=await(0,a.default)(r().join(p().binpath,"utils","regression.R"),[],[o]);c().unlink(o,(()=>{})),await async function(e,t,n,s,r){if(1!=t.length)throw"expected 1 json line in R output";const o=JSON.parse(t[0]),i=o.data;_["regression.R"]=o.benchmark;for(const t of i){const o={data:{sampleSize:t.data.sampleSize,eventCnt:t.data.eventCnt?t.data.eventCnt:null}};if(t.id){const e=n[t.id];o.id=e;const r=s.independent.find((e=>"snplocus"==e.type));if(!r)throw"snplocus term missing";o.AFstr=r.snpid2AFstr.get(e),o.data.headerRow=j(e,r)}const i=t.data;if(i.residuals&&(o.data.residuals=i.residuals,o.data.residuals.label="linear"==e.regressionType?"Residuals":"Deviance residuals"),"cox"==e.regressionType){if(i.coefficients.rows.length<1)throw"fewer than 1 row in coefficients table"}else if(i.coefficients.rows.length<2)throw"fewer than 2 rows in coefficients table";o.data.coefficients={header:i.coefficients.header,intercept:"cox"==e.regressionType?null:i.coefficients.rows.shift(),terms:{},interactions:[]};for(const e of i.coefficients.rows)if(-1!=e[0].indexOf(":")){const t={},[s,r]=e.shift().split(":"),[i,a]=e.shift().split(":");t.term1=n[s],t.category1=i,t.term2=n[r],t.category2=a,t.lst=e,o.data.coefficients.interactions.push(t)}else{const t=e.shift(),s=e.shift(),r=n[t];o.data.coefficients.terms[r]||(o.data.coefficients.terms[r]={}),s?(o.data.coefficients.terms[r].categories||(o.data.coefficients.terms[r].categories={}),o.data.coefficients.terms[r].categories[s]=e):o.data.coefficients.terms[r].fields=e}o.data.coefficients.label="Coefficients",o.data.type3={header:i.type3.header,terms:{},interactions:[]},"cox"!=e.regressionType&&(o.data.type3.intercept=i.type3.rows.shift());for(const e of i.type3.rows)if(-1!=e[0].indexOf(":")){const t={},[s,r]=e.shift().split(":");t.term1=n[s],t.term2=n[r],t.lst=e,o.data.type3.interactions.push(t)}else{const t=n[e.shift()];o.data.type3.terms[t]||(o.data.type3.terms[t]=e)}if(o.data.type3.label="Type III statistics",i.totalSnpEffect){if(1!=i.totalSnpEffect.rows.length)throw"total SNP effect table should have 1 row";o.data.totalSnpEffect={header:i.totalSnpEffect.header.slice(0,4)};const e=i.totalSnpEffect.rows[0].slice(0,4),t=i.totalSnpEffect.rows[0][4].split(";"),s=t.findIndex((e=>!e.includes(":"))),r=t.splice(s,1)[0];o.data.totalSnpEffect.snp=n[r];const a=[];for(const e of t){if(!e.includes(":"))throw"expected interaction";const[t,s]=e.split(":");a.push({term1:n[t],term2:n[s]})}o.data.totalSnpEffect.interactions=a,o.data.totalSnpEffect.lst=e,o.data.totalSnpEffect.label="Total SNP effect"}i.tests&&(o.data.tests=i.tests,o.data.tests.label="Statistical tests"),o.data.other=i.other,o.data.other.label="Other summary statistics";for(const t of e.independent)if(t.spline&&t.spline.plotfile){o.data.splinePlots||(o.data.splinePlots=[]);const e=t.spline.plotfile,n=await c().promises.readFile(e);o.data.splinePlots.push({src:"data:image/png;base64,"+new Buffer.from(n).toString("base64"),size:f()(e)}),c().unlink(e,(e=>{if(e)throw e}))}i.warnings&&(o.data.warnings=i.warnings);const a=s.independent.find((e=>"snplst"==e.type));if(a){if(a.lowAFsnps&&a.lowAFsnps.size){o.data.warnings||(o.data.warnings=[]);for(const e of a.lowAFsnps.keys())o.data.warnings.push(`${e}: effect allele frequency below cutoff, excluded from analysis`)}if(a.monomorphicLst&&a.monomorphicLst.length){o.data.warnings||(o.data.warnings=[]);for(const e of a.monomorphicLst)o.data.warnings.push(`${e}: monomorphic, excluded from analysis`)}}r.resultLst.push(o)}}(e,i,t,n,s),w=(new Date).getTime(),_.NodeJS.runRegression=(w-v)/1e3+" sec"}async function C(e,t,n,s){const o=e.independent.find((e=>"snplocus"==e.type));if(o){if(v=(new Date).getTime(),function(e,t){for(const n of e.monomorphicLst){const s=e.snpgt2count.get(n),r=[];for(const[e,t]of s)r.push(e+"="+t);const o={id:n,data:{headerRow:j(n,e)}};t.resultLst.push(o)}}(o,s),o.lowAFsnps.size)if("linear"==e.regressionType)await async function(e,t,n,s){const o=[],i=new Map;for(const[s,r]of e.lowAFsnps){let e=0,a=null,l=null;const c=[],u=[];for(const{sample:s,noOutcome:o}of t){if(o)continue;const t=n.data[e++].outcome;if(!Number.isFinite(t))continue;const i=r.samples.get(s);if(!i)continue;null==a?a=l=t:(a=Math.min(a,t),l=Math.max(l,t));const[f,d]=i.split("/");f==r.effAle||d==r.effAle?c.push(t):u.push(t)}o.push({group1_id:s+"_hasEffAllele",group1_values:c,group2_id:s+"_noEffAllele",group2_values:u}),i.set(s,{minv:a,maxv:l})}const l=r().join(p().cachedir,Math.random().toString()+".json");await m.Sf(l,JSON.stringify(o));const u=await(0,a.default)(r().join(p().binpath,"utils/wilcoxon.R"),[],[l]);c().unlink(l,(()=>{}));const f=JSON.parse(u);for(const t of f){const n=t.group1_id.replace("_hasEffAllele",""),r=t.group1_values,o=t.group2_values;let a;a=null==t.pvalue||"null"==t.pvalue?"NA":t.pvalue.toPrecision(4);const{minv:l,maxv:c}=i.get(n),u=m.JC(r.sort(((e,t)=>e-t)).map((e=>({value:e}))));u.label=`Carry ${0==e.q.alleleType?"minor":"alternative"} allele, n=${r.length}`;const f=m.JC(o.sort(((e,t)=>e-t)).map((e=>({value:e}))));f.label=`No ${0==e.q.alleleType?"minor":"alternative"} allele, n=${o.length}`;const d={id:n,AFstr:e.snpid2AFstr.get(n),data:{headerRow:j(n,e),wilcoxon:{pvalue:a,boxplots:{minv:l,maxv:c,hasEff:u,noEff:f}}}};s.resultLst.push(d)}}(o,t,n,s);else if("logistic"==e.regressionType)await async function(e,t,n,s){const r=[];let o=0;const i=new Map;for(const[s,a]of e.lowAFsnps){let e=0,l=0,c=0,u=0,f=0;for(const{sample:s,noOutcome:r}of t){if(r)continue;const t=n.data[f++],o="outcome"in t?t.outcome:t.outcome_event;if(0!=o&&1!=o)throw"outcome is not 0 or 1";const i=a.samples.get(s);if(!i)continue;const[d,p]=i.split("/"),m=a.effAle==d||a.effAle==p;0==o?m?l++:e++:m?u++:c++}i.set(o,s);const d={index:o,n1:u,n2:l,n3:c,n4:e};r.push(d),o++}const a=await(0,h.run_rust)("fisher",JSON.stringify({input:r}));for(const t of JSON.parse(a)){const n=i.get(t.index),{effAle:r}=e.lowAFsnps.get(n),o=t.p_value,a="chisq"===t.fisher_chisq,l={id:n,AFstr:e.snpid2AFstr.get(n),data:{headerRow:j(n,e),fisher:{isChi:a,pvalue:Number(o.toFixed(4)),rows:[["","Carry "+r+" allele","No "+r+" allele"],["Have event",t.n1,t.n3],["No event",t.n2,t.n4]]}}};s.resultLst.push(l)}}(o,t,n,s);else{if("cox"!=e.regressionType)throw"unknown regression type";await async function(e,t,n,s){const r={data:{}},o=new Set;for(const[s,i]of e.lowAFsnps){const e=[];let a=0;for(const{sample:s,noOutcome:r}of t){if(r)continue;const t=n.data[a++];if(0!==t.outcome_event&&1!==t.outcome_event)throw"d.outcome_event is not 0/1";if(!Number.isFinite(t.outcome_time))throw"d.outcome_time is not numeric";const o={time:t.outcome_time,event:t.outcome_event},l=i.samples.get(s);if(!l)continue;const[c,u]=l.split("/");o.series=i.effAle==c||i.effAle==u?"1":"2",e.push(o)}new Set(e.map((e=>e.series))).size<2?o.add(s):r.data[s]=e}const i=await(0,g.y)(r);let a;for(const[t,n]of e.lowAFsnps){if(o.has(t)){a={pvalue:"NA",msg:"Cannot perform cumulative incidence test on this snp - at least one allele is not found in any sample"}}else{if(1==!i[t].tests?.length)throw"must have a single test";const e=Number(i[t].tests[0].pvalue);if(!Number.isFinite(e))throw"invalid pvalue";a={pvalue:Number(e.toFixed(4)),ci_data:{[t]:i[t]}}}const n={id:t,AFstr:e.snpid2AFstr.get(t),data:{headerRow:j(t,e),cuminc:a}};s.resultLst.push(n)}}(o,t,n,s)}w=(new Date).getTime(),_.NodeJS.snplocusPostprocess=(w-v)/1e3+" sec"}}function j(e,t){const n=t.snpgt2count.get(e);if(!n)return{k:"Error",v:"Variant not found"};const s=[];for(const[e,t]of n)s.push(e+"="+t);const r={snpid:e,gtcounts:s};return t.monomorphicLst.includes(e)?r.monomorphic=!0:(r.effAle=t.highAFsnps.has(e)?t.highAFsnps.get(e).effAle:t.lowAFsnps.get(e).effAle,r.af=t.snpid2AFstr.get(e)),{k:"Variant:",v:r}}function T(e,t,n){if(e.q.restrictAncestry)for(const[n,s]of e.q.restrictAncestry.pcs)for(const[e,r]of s)t.has(e)&&t.get(e).id2value.set(n,{key:r,value:r})}async function M(e,t,n){const s=(await m.b5(r().join(p().cache_snpgt.dir,e.q.cacheid))).split("\n"),o=s[0].split("\t").slice(p().cache_snpgt.sampleColumn).map(Number);if(n)for(const e of o)t.set(e,{id2value:new Map});const i=o.map((e=>t.has(e))),a=new Map;for(let t=1;t<s.length;t++){const n=s[t].split("\t"),r=n[0],l={refAle:n[3],altAles:n[4].split(","),samples:new Map};e.q.snp2effAle?l.effAle=e.q.snp2effAle[r]:l.effAle=l.altAles[0],a.set(r,l);for(const[e,t]of o.entries()){if(!i[e])continue;const s=n[e+p().cache_snpgt.sampleColumn];s&&a.get(r).samples.set(t,s)}}"snplst"!=e.type||n||function(e,t,n,s){if(0==t.q.missingGenotype){for(const t of e.values()){let e;if(t.refAle!=t.effAle)e=t.refAle;else for(const n of t.altAles)if(n!=t.effAle){e=n;break}if(!e)throw"not finding a non-effect allele";for(const[r,o]of n.entries())s[r]&&(t.samples.has(o)||t.samples.set(o,e+"/"+e))}return}if(1==t.q.missingGenotype){const t=new Set;for(const{samples:r}of e.values())for(const[e,o]of n.entries())s[e]&&(r.has(o)||t.add(o));for(const{samples:n}of e.values())for(const e of t)n.delete(e);return}throw"invalid missingGenotype value"}(a,e,o,i),e.snpgt2count=new Map;for(const[t,n]of a){const s=new Map;for(const[e,t]of n.samples)s.set(t,1+(s.get(t)||0));e.snpgt2count.set(t,s)}!function(e,t){e.lowAFsnps=new Map,e.highAFsnps=new Map,e.monomorphicLst=[],e.snpid2AFstr=new Map;for(const[n,s]of t){if(1==e.snpgt2count.get(n).size){e.monomorphicLst.push(n);continue}const t=s.samples.size;let r=0;for(const[e,t]of s.samples){const[e,n]=t.split("/");r+=(e==s.effAle?1:0)+(n==s.effAle?1:0)}const o=r/(2*t);e.snpid2AFstr.set(n,(100*o).toFixed(1)+"%"),o<e.q.AFcutoff/100?e.lowAFsnps.set(n,s):e.highAFsnps.set(n,s)}}(e,a);for(const[n,s]of e.highAFsnps)for(const[r,o]of s.samples){const[i,a]=o.split("/"),l=O(e,s.effAle,i,a);t.get(r).id2value.set(n,{key:l,value:l})}}function O(e,t,n,s){switch(e.q.geneticModel){case 0:return(n==t?1:0)+(s==t?1:0);case 1:return n==t||s==t?1:0;case 2:return n==t&&s==t?1:0;case 3:return n+"/"+s;default:throw"unknown geneticModel option"}}function I(e,t){if(e.tag===t)return e;if("tvslst"===e.type)for(const n of e.lst){const e=I(n,t);if(e)return e}}},2188:(e,t,n)=>{"use strict";n.d(t,{uR:()=>g,v8:()=>q,wz:()=>h});var s=n(2974),r=n(1017),o=n.n(r),i=n(3345),a=n(334),l=n.n(a),c=n(2273),u=n(8907),f=n(5257),d=n(6191),p=n(9157);const m="#F5F5DC";async function h(e){if(e.cohort.scatterplots){if(!Array.isArray(e.cohort.scatterplots.plots))throw"cohort.scatterplots.plots is not array";for(const t of e.cohort.scatterplots.plots){if(!t.name)throw".name missing from one of scatterplots.plots[]";if(!t.file)throw"unknown data source of one of scatterplots.plots[]";{const n=(await(0,i.b5)(o().join(l().tpmasterdir,t.file))).trim().split("\n"),s=n[0].split("\t");t.filterableSamples=[];const r=[];let a=0,c=0;for(let o=1;o<n.length;o++){const i=n[o].split("\t"),l=Number(i[1]),u=Number(i[2]);if(Number.isNaN(l)||Number.isNaN(u)){a++;continue}const f={sample:i[0],x:l,y:u},d=e.cohort.termdb.q.sampleName2id(i[0]);if(null==d){if(s[3]){f.info={};for(let e=3;e<s.length;e++)f.info[s[e]]=i[e]}r.push(f)}else c++,f.sampleId=d,t.filterableSamples.push(f)}r.length&&(t.referenceSamples=r),console.log(t.filterableSamples.length,`scatterplot lines from ${t.name} of ${e.label},`,t.referenceSamples?t.referenceSamples.length+" reference cases":"",a?a+" lines with invalid X/Y values":"")}}}}async function g(e,t,n,r,o){try{let i,a;if(2==t.coordTWs.length)i=[],a=await async function(e,t,n){t.ds=n;const s=[];if(2!=t.coordTWs.length)return s;const r=await(0,f.w)(t.filter,t.ds);let o="";r&&(o+=(0,u.ig)(`WITH ${r.filters}`,r.values.slice()));const i=t.coordTWs[0].term,a=t.coordTWs[1].term;let l;t.divideByTW&&"continuous"==t.divideByTW.q.mode&&(l=t.divideByTW.term);o+=`SELECT ax.sample AS sampleId, ax.value as x, ay.value AS y , ${l?"az.value AS z":"0 as z"}\n\t\t\tFROM anno_${i.type} ax \n\t\t\tJOIN anno_${a.type} ay on ax.sample = ay.sample \n\t\t\t${l?`JOIN anno_${l.type} az on ax.sample = az.sample and az.term_id = '${l.id}' `:""}\n\t\t\tWHERE ax.term_id = '${i.id}' and ay.term_id = '${a.id}'`,r&&(o+=` AND ax.sample IN ${r.CTEname}`);const c=t.ds.cohort.db.connection.prepare(o).all(),p=d.i.canDisplaySampleIds(e,n);for(const{sampleId:e,x:r,y:o,z:i}of c){const a={sampleId:e,x:r,y:o,z:i};p&&(a.sample=n.sampleId2Name.get(e));const l=k(t.coordTWs[0].term,r)&&k(t.coordTWs[1].term,o)&&k(t.divideByTW?.term,i);a&&l&&s.push(a)}return s}(e,t,r);else{if(!t.plotName)throw"Neither plot name or coordinates where provided";if(!r.cohort.scatterplots||!r.cohort.scatterplots.plots)throw"not supported";const e=r.cohort.scatterplots.plots.find((e=>e.name==t.plotName));if(!e)throw`plot not found with plotName ${t.plotName}`;const n=await async function(e,t,n){if(n.filterableSamples){let e=[],t=[];return n.referenceSamples&&(t=s(n.referenceSamples)),n.filterableSamples&&(e=s(n.filterableSamples)),[t,e]}if(n.gdcapi)throw"gdcapi not implemented yet";throw"do not know how to load data from this plot";function s(e){const t=[];for(const n of JSON.parse(JSON.stringify(e)))t.push(n);return t}}(0,0,e);i=n[0],a=n[1]}const l=[];t.coordTWs&&l.push(...t.coordTWs),t.colorTW&&l.push(t.colorTW),t.shapeTW&&l.push(t.shapeTW),t.divideByTW&&l.push(t.divideByTW),t.scaleDotTW&&l.push(t.scaleDotTW);const p=await(0,s.Yu)({filter:t.filter,terms:l},r,o);if(p.error)throw p.error;const h=await async function(e,t,n,s){const r={};for(const o of t){const t=n.samples[o.sampleId.toString()];if(!t)continue;let i=!1;if(s.colorTW&&!y(t,s.colorTW)||s.shapeTW&&!y(t,s.shapeTW))continue;let a="Default";if(s.divideByTW&&"continuous"!=s.divideByTW.q.mode)if(o.z=0,"geneVariant"==s.divideByTW.term.type)a=v(!0,t,s.divideByTW),null==a&&(a=v(!1,t,s.divideByTW),i=!0);else{const e=s.divideByTW.term.id||s.divideByTW.term.name,n=t[e]?.key;if(null==n)continue;a=s.divideByTW.term.values?.[n]?.label||n}if(!r[a]){const t=e.map((e=>({...e,category:"Ref",shape:"Ref",z:0})));r[a]={samples:t,colorMap:{},shapeMap:{},isLast:i}}if(s.divideByTW||(o.z=0),s.scaleDotTW){const e=t?.[s.scaleDotTW.id]?.key;if(!e||!k(s.scaleDotTW.term,e))continue;o.scale=e}else o.scale=1;o.cat_info={},o.hidden={},s.colorTW?"continuous"===s.colorTW?.q?.mode?t&&(o.category=t[s.colorTW.term.id||s.colorTW.term.name].value):b(t,o,s.colorTW,r[a].colorMap,"category"):o.category="Default",s.shapeTW?b(t,o,s.shapeTW,r[a].shapeMap,"shape"):o.shape="Ref",r[a].samples.push(o)}let o=0;for(const[e,t]of Object.entries(r))o=Math.max(o,Object.keys(t.colorMap).length);const i=(0,c.getColors)(o);for(const[o,a]of Object.entries(r)){if(s.colorTW&&"continuous"!==s.colorTW.q.mode){let e=20;const t=c.schemeCategory20,r=Object.entries(a.colorMap);for(const[o,a]of r){let r;if(s.colorTW.term.values?.[o])r=s.colorTW.term.values?.[o];else for(const e in s.colorTW.term.values)s.colorTW.term.values?.[e].label==o&&(r=s.colorTW.term.values?.[e]);if(r&&"color"in r)a.color=r.color;else if(n.refs?.byTermId[s.colorTW.term.id]?.bins){const r=n.refs.byTermId[s.colorTW.term.id].bins.find((e=>e.name===o));r?a.color=r.color:(a.color=t[e],e--)}else"geneVariant"!=s.colorTW.term.type&&(a.color=i(o))}}let r=1;for(const[e,t]of Object.entries(a.shapeMap))"shape"in t||(t.shape=r),r++;a.colorLegend=s.colorTW?_(a.colorMap,s.colorTW,n.refs):[["Default",{sampleCount:t.length,color:"blue"}]],a.colorLegend.push(["Ref",{sampleCount:e.length,color:s.colorTW?.term.values?.Ref?s.colorTW.term.values?.Ref.color:m}]),a.shapeLegend=_(a.shapeMap,s.shapeTW,n.refs),a.shapeLegend.push(["Ref",{sampleCount:e.length,shape:0}])}return r}(i,a,p,t);n.send(h)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}function y(e,t){const n=e?.[t?.term?.id||t?.term?.name]?.key,s=void 0!==n;return s||console.log(JSON.stringify(e)+" missing value for the term "+JSON.stringify(t)),s}function b(e,t,n,s,r){let o=null;"geneVariant"==n.term.type?function(e,t,n,s,r){if("geneVariant"==n.term.type){const o=e?.[n.term.name]?.values;t.cat_info[r]=[];for(const e of o){const n=c.mclass[e.class],o=w(e);let i;t.cat_info[r].push(e),null==s[o]?(i={color:n.color,sampleCount:1,hasOrigin:"origin"in e},s[o]=i):(i=s[o],i.sampleCount=i.sampleCount+1,i.hasOrigin=i.hasOrigin||"origin"in e)}t[r]=v(!0,e,n)||v(!1,e,n),t[r]||(t[r]=w(o[0])),t.hidden[r]=!!n.q.hiddenValues&&t[r]in n.q.hiddenValues}}(e,t,n,s,r):(o=e?.[n.id||n.term.name]?.key,n.term.values?.[o]?.label?(o=n.term.values?.[o]?.label,t.hidden[r]=!!n.q.hiddenValues&&o in n.q.hiddenValues):t.hidden[r]=!!n.q.hiddenValues&&e?.[n.id]?.key in n.q.hiddenValues,o&&(t[r]=o.toString(),null==s[o]?s[o]={sampleCount:1}:s[o].sampleCount++))}function v(e,t,n){const s=t?.[n.term.name]?.values;for(const[t,r]of Object.entries(c.dt2label)){const r=s.find((e=>{const s=w(e),r=!(n.q.hiddenValues&&s in n.q.hiddenValues);return e.dt==t&&r}));if(!r)continue;const o="WT"==r.class||"Blank"==r.class;if(e&&o)continue;return w(r)}}function w(e){const t=e.dt,n=c.mclass[e.class],s=c.morigin[e.origin]?.label,r=s?`${s[0]} ${c.dt2label[t]}`:c.dt2label[t];return`${n.label}, ${r}`}function _(e,t,n){let s=[];if(!t||0==e.size)return s;if("geneVariant"==t.term.type)s=Object.entries(e),s.sort(((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0));else if(n?.byTermId[t.term.id]?.bins){const r=n.byTermId[t.term.id].bins;for(const t of r)e[t.name]&&s.push([t.name,e[t.name]]);for(const[t,n]of Object.entries(e))s.some((e=>e[0]===t))||s.push([t,n])}else s=Object.entries(e),s.sort(((e,n)=>{let s,r;for(const o in t.term.values){const i=t.term.values[o];(i.label&&e[0]==i.label||o==e[0])&&(s=i),(i.label&&n[0]==i.label||o==n[0])&&(r=i)}return s&&"order"in s?s?.order<r?.order?-1:1:e[1].sampleCount>n[1].sampleCount?-1:1}));return s}function k(e,t){if(!e)return!0;return!e.values?.[t]?.uncomputable}async function q(e,t,n){const s=t.coords,r=o().join(l().cachedir,Math.random().toString()+".json");await(0,i.Sf)(r,JSON.stringify(s));let a=await(0,p.default)(o().join(l().binpath,"utils/lowess.R"),[],[r]);a=JSON.parse(a);const c=[];for(const[e,t]of Object.entries(a.x))c.push([t,a.y[e]]);return n.send(c)}},394:(e,t,n)=>{"use strict";n.d(t,{JV:()=>l,jj:()=>c,qN:()=>u});var s=n(334),r=n.n(s),o=n(3345),i=n(1575),a=n(6191);function l(e){if(!e.cohort)throw"ds.cohort missing";if(!e.cohort.db)throw"ds.cohort.db missing";if(!e.cohort.termdb)throw"ds.cohort.termdb missing";const t=e.cohort.db.file_fullpath||e.cohort.db.file;if(!t)throw"both file and file_fullpath missing";let n;try{console.log("Connecting",t),n=(0,o.sE)(t),console.log(`DB connected for ${e.label}: ${t}`)}catch(e){throw`Cannot connect db ${t}: ${e.message||e}`}e.cohort.db.connection=n;const s=c(n),l=["cohorts","sampleidmap","terms","ancestry","alltermsbyorder","termhtmldef","category2vcfsample","chronicevents","precomputed_chc_grade","precomputed_chc_child","precomputed_cuminc","precomputed_cox","subcohort_terms","subcohort_samples","survival","features","cohort_features","anno_integer","anno_float","anno_categorical","buildDate"];for(const e of l)s.has(e)||console.log(`${e} table missing!!!!!!!!!!!!!!!!!!!!`);if(!s.has("terms"))throw"terms table missing";if(!s.has("ancestry"))throw"ancestry table missing";if(e.cohort.termdb.selectCohort&&!s.has("subcohort_terms"))throw"subcohort_terms table is missing while termdb.selectCohort is enabled";e.cohort.termdb.q={};const f=e.cohort.termdb.q;if(s.has("buildDate")&&(f.get_buildDate=n.prepare("select date from buildDate")),s.has("term2genes")){e.cohort.termdb.termMatch2geneSet=!0;const t=n.prepare("SELECT genes FROM term2genes WHERE id=?"),s=new Map;f.getGenesetByTermId=e=>{if(s.has(e))return s.get(e);const n=t.get(e);if(n&&n.genes){const t=JSON.parse(n.genes);return s.set(e,t),t}}}if(s.has("sampleidmap")){const t=new Map,s=new Map,r=n.prepare("SELECT * FROM sampleidmap");let o=0;for(const{id:e,name:n}of r.all())t.set(e,n),s.set(n,e),o++;if(f.id2sampleName=e=>t.get(e),f.sampleName2id=e=>s.get(e),e.cohort.termdb.selectCohort){const e=n.prepare("SELECT cohort,sample_count from cohorts").all(),t={};for(const n of e)t[n.cohort]=n.sample_count;f.getcohortsamplecount=e=>e?t[e]||0:o}else f.getcohortsamplecount=()=>o}if(s.has("category2vcfsample")){const e=n.prepare("SELECT * FROM category2vcfsample");let t;f.getcategory2vcfsample=()=>{if(t)return t;t=e.all();for(const e of t)e.q=JSON.parse(e.q),e.categories=JSON.parse(e.categories);return t}}if(s.has("alltermsbyorder")){const e=n.prepare("SELECT * FROM alltermsbyorder");let t;f.getAlltermsbyorder=()=>{if(t)return t;const n=e.all();t=[];for(const e of n){const n=f.termjsonByOneid(e.id);n&&t.push({group_name:e.group_name,term:n})}return t}}{const e=n.prepare("SELECT name, jsondata FROM terms WHERE id=?"),t=new Map;f.termjsonByOneid=n=>{if(t.has(n))return t.get(n);const s=e.get(n);if(s){const e=JSON.parse(s.jsondata);return e.id=n,e.name=s.name||e.name,t.set(n,e),e}}}{const e=n.prepare("select id from terms where parent_id=?"),t=new Map;f.termIsLeaf=n=>{if(t.has(n))return t.get(n);let s=!0;const r=e.get(n);return r&&r.id&&(s=!1),t.set(n,s),s}}{const e=n.prepare("SELECT id, name, jsondata, s.included_types, s.child_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE parent_id is null\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),t=new Map;f.getRootTerms=(n="")=>{const s=n;if(t.has(s))return t.get(s);const r=e.all(n).map((e=>{const t=JSON.parse(e.jsondata);return t.id=e.id,t.name=e.name||t.name,t.included_types=e.included_types?e.included_types.split(","):["TO-DO-PLACEHOLDER"],t.child_types=e.child_types?e.child_types.split(","):[],t}));return t.set(s,r),r}}{const e=n.prepare("SELECT parent_id FROM terms WHERE id=?");{const t=new Map;f.termHasParent=n=>{if(t.has(n))return t.get(n);let s=!1;const r=e.get(n);return r&&r.parent_id&&(s=!0),t.set(n,s),s}}{const t=new Map;f.getTermParentId=n=>{if(t.has(n))return t.get(n);let s;const r=e.get(n);return r&&r.parent_id&&(s=r.parent_id),t.set(n,s),s}}{const e=new Map;f.getTermParent=t=>{if(e.has(t))return e.get(t);const n=f.getTermParentId(t);let s;return n&&(s=f.termjsonByOneid(n)),e.set(t,s),s}}}{const e=n.prepare("SELECT id, name, type, jsondata, s.included_types, s.child_types \n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=? \n\t\t\tWHERE id IN (SELECT id FROM terms WHERE parent_id=?)\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),t=new Map;f.getTermChildren=(n,s="")=>{const r=n+";;"+s;if(t.has(r))return t.get(r);const o=e.all([s,n]);let i;return o&&(i=o.map((e=>{const t=JSON.parse(e.jsondata);return t.id=e.id,t.name=e.name||t.name,t.included_types=e.included_types?e.included_types.split(","):[],t.child_types=e.child_types?e.child_types.split(","):[],t}))),t.set(r,i),i}}{const e=n.prepare("SELECT id, name, jsondata, s.included_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE name LIKE ?");f.findTermByName=(t,n="",s=null,r=null)=>{const o=e.all([n,"%"+t+"%"]);if(o){const e=[];for(const t of o){if(!t.jsondata)continue;const n=JSON.parse(t.jsondata);n.id=t.id,n.name=t.name||n.name,n.included_types=t.included_types?t.included_types.split(","):[],r&&!(0,i.CG)(n,r).has("plot")||e.push(n)}return e}}}{const e=n.prepare("SELECT MAX(value) AS v FROM anno_integer WHERE term_id=?"),t=n.prepare("SELECT MAX(value) AS v FROM anno_float WHERE term_id=?"),s=new Map;f.findTermMaxvalue=(n,r)=>{if(s.has(n))return s.get(n);const o=(r?e:t).get(n);return o?(s.set(n,o.v),o.v):void 0}}{const e={float:n.prepare("SELECT sample,value FROM anno_float WHERE term_id=?"),integer:n.prepare("SELECT sample,value FROM anno_integer WHERE term_id=?"),categorical:n.prepare("SELECT sample,value FROM anno_categorical WHERE term_id=?")};f.getAllValues4term=t=>{const n=f.termjsonByOneid(t);if(!n)return;const s=e[n.type];if(!s)return;const r=s.all(t);if(!r||0==r.length)return;const o=new Map;for(const e of r)o.set(e.sample,e.value);return o}}{const e=n.prepare("SELECT ancestor_id FROM ancestry WHERE term_id=?"),t=new Map;f.getAncestorIDs=n=>{if(t.has(n))return t.get(n);const s=e.all(n).map((e=>e.ancestor_id));return t.set(n,s),s}}{const e=n.prepare("SELECT t.name FROM ancestry as a, terms as t WHERE a.term_id=? AND t.id=a.ancestor_id"),t=new Map;f.getAncestorNames=n=>{if(t.has(n))return t.get(n);const s=e.all(n).map((e=>e.name));return t.set(n,s),s}}{const e={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=?")},t={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=? AND sample=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=? AND sample=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=? AND sample=?")},s={categorical:n.prepare("SELECT value FROM anno_categorical a,sampleidmap s WHERE term_id=? AND s.name=?"),integer:n.prepare("SELECT value FROM anno_integer a,sampleidmap s WHERE term_id=? AND s.name=?"),float:n.prepare("SELECT value FROM anno_float a, sampleidmap s WHERE term_id=? AND s.name=?")};f.getSample2value=(n,r=null)=>{const o=f.termjsonByOneid(n);return r?"string"==typeof r?s[o.type].all(n,r):t[o.type].all(n,r):e[o.type].all(n)}}if(s.has("termhtmldef")){const e=n.prepare("SELECT jsonhtml FROM termhtmldef WHERE id=?"),t=new Map;f.getTermInfo=n=>{if(t.has(n))return t.get(n);const s=e.get(n);if(s){const e=JSON.parse(s.jsonhtml);return e.id=n,t.set(n,e),e}}}f.getSupportedChartTypes=t=>{u(e);r().dsCredentials?.[e.label];const n={},s={};for(const o of e.cohort.termdb.termtypeByCohort)if(o.type){if(!(o.cohort in n)){n[o.cohort]=new Set(["regression","summary"]),e.cohort.scatterplots&&n[o.cohort].add("sampleScatter"),s[o.cohort]=0,e.cohort.allowedChartTypes?.includes("matrix")&&n[o.cohort].add("matrix");const r=a.i.getForbiddenRoutesForDsEmbedder(e.label,t);r.includes("termdb")||r.includes("*")||(n[o.cohort].add("dataDownload"),n[o.cohort].add("sampleView"),e.queries?.singleCell&&n[o.cohort].add("singleCellPlot"))}r().features?.draftChartTypes&&n[o.cohort].add(...r().features.draftChartTypes),"survival"!=o.type||n[o.cohort].has("survival")||n[o.cohort].add("survival"),"condition"!=o.type||n[o.cohort].has("cuminc")||n[o.cohort].add("cuminc"),"float"!=o.type&&"integer"!=o.type||(s[o.cohort]+=o.samplecount)}for(const e in s)s[e]>1&&n[e].add("sampleScatter");for(const e in n)n[e]=[...n[e]];if(e.cohort.allowedChartTypes)for(const t in n)n[t]=n[t].filter((t=>e.cohort.allowedChartTypes.includes(t)));if(e.queries){if(e.queries.snvindel||e.queries.trackLst)for(const e in n)n[e].push("genomeBrowser");if(e.queries.geneExpression)for(const e in n)n[e].push("hierCluster");if(e.queries.rnaseqGeneCount)for(const e in n)n[e].push("DEanalysis");if(e.queries.singleCell)for(const e in n)n[e].push("singleCellPlot")}return n},f.getSingleSampleData=function(e,t=[]){const s=t.length?`and term_id in (${t.map((e=>"?")).join(",")})`:"",r=`select term_id, value, jsondata from ( select term_id, value \n\t\tfrom anno_categorical \n\t\twhere sample=? ${s}\n\t\tunion all \n\t\tselect term_id, \n\t\tvalue from anno_float \n\t\twhere sample=? ${s}\n\t\tunion all \n\t\tselect term_id, value \n\t\tfrom anno_integer \n\t\twhere sample=? ${s}\n\t\tunion all \n\t\tselect term_id, (min_years_to_event || ' ' || value) as value \n\t\tfrom precomputed_chc_grade \n\t\twhere max_grade=1 and sample=? ${s}\n\t\tunion all \n\t\tselect term_id, (tte || ' ' || exit_code) as value \n\t\tfrom survival \n\t\twhere sample=? ${s}) join terms on terms.id = term_id`;return n.prepare(r).all([e,...t,e,...t,e,...t,e,...t,e,...t])},f.getProfileFacilities=function(){return n.prepare("select name from sampleidmap join \n\t\tanno_categorical on sampleidmap.id = anno_categorical.sample\n\t\twhere term_id = 'sampleType' and value = 'Facility'").all()}}function c(e){const t=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();return new Set(t.map((e=>e.name)))}function u(e){if(e.cohort.termdb.termtypeByCohort){if(!Array.isArray(e.cohort.termdb.termtypeByCohort))throw"termtypeByCohort is not array"}else{if(!e.cohort?.db?.connection)throw"termtypeByCohort[] not set but cohort.db.connection missing";e.cohort.termdb.termtypeByCohort=e.cohort.db.connection.prepare("WITH c AS (\n\t\t\tSELECT cohort, term_id\n\t\t\tFROM subcohort_terms s\n\t\t\tGROUP BY cohort, term_id\n\t\t) \n\t\tSELECT cohort, type, count(*) as samplecount\n\t\tFROM terms t\n\t\tJOIN c ON c.term_id = t.id\n\t\tGROUP BY cohort, type").all()}}},3795:(e,t,n)=>{"use strict";n.d(t,{G:()=>g,u:()=>y});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(8907),c=(n(2826),n(4521),n(334)),u=n.n(c),f=n(3625);const d="%CHROM\t%POS\t%REF\t%ALT[\t%TGT]\n",p="%POS\t%ID\t%REF\t%ALT\t%INFO[\t%TGT]\n",m="./.",h=1e3;async function g(e,t,n,s){try{if(e.sumSamples)return await async function(e,t,n,s){if(!e.cacheid)throw"cacheid missing";if(u().cache_snpgt.fileNameRegexp.test(e.cacheid))throw"invalid cacheid";let r,o;if(n.track){if(r=n.track.vcf,!r)throw"ds.track.vcf missing"}else r=n.queries.snvindel.byrange._tk;if(e.filter){const t=new Set((await l.cf(e.filter,n)).map((e=>e.id)));if(0==t.size)throw"no samples from filter";o=r.samples.map((e=>t.has(e.name)))}else o=r.samples.map((e=>!0));const c=(await a.b5(i().join(u().cache_snpgt.dir,e.cacheid))).split("\n"),f=new Set,d=[];for(let e=1;e<c.length;e++){const t=c[e].split("\t"),n=t[0],s=t[3],i={},a={};for(let e=u().cache_snpgt.sampleColumn;e<t.length;e++){const n=t[e];if(!n)continue;if(!o[e-u().cache_snpgt.sampleColumn])continue;f.add(r.samples[e-u().cache_snpgt.sampleColumn].name),a[n]=1+(a[n]||0);const s=n.split("/");for(const e of s)i[e]=1+(i[e]||0)}const l=[];for(const e in i)l.push({allele:e,count:i[e],isRef:e==s});d.push({snpid:n,alleles:l,gt2count:a})}return{numOfSampleWithAnyValidGT:f.size,snps:d}}(e,0,n);if(e.snptext)return await async function(e,t,n){if(!n.snp)throw"snp not supported by genome";if(!e.snptext)throw".snptext missing";const s=function(e){const t=[];for(const n of e.trim().split("\n")){const[e,s]=n.trim().split(/[\s\t]/);if(e&&e.startsWith("rs")){if(t.find((t=>t.rsid==e)))continue;const n={rsid:e,snpid:e};s&&(n.effectAllele=s),t.push(n)}else t.push({rsid:e,snpid:e,invalid:"INVALID RSID"})}return t}(e.snptext);if(!s.length)throw"no snps";await async function(e,t){for(const n of e)if(!n.invalid)if(n.chr&&"string"==typeof n.chr){const e=t.chrlookup[n.chr.toUpperCase()];if(!e){n.invalid=!0;continue}if(!Number.isInteger(n.pos)){n.invalid=!0;continue}if(n.pos<=0||n.pos>=e.len){n.invalid=!0;continue}}else if(n.rsid){const e=await a.mr(t.snp.bigbedfile,n.rsid),s=[];for(const n of e){const e=n.split("\t"),r=t.chrlookup[e[0].toUpperCase()];r&&r.major&&s.push(e)}if(0==s.length){n.invalid=!0;continue}const r=s[0];n.chr=r[0],n.pos=Number.parseInt(r[1]),n.dbsnpRef=r[4],n.dbsnpAlts=r[6].split(",").filter(Boolean)}else n.invalid=!0;if(!e.find((e=>!e.invalid)))throw"no valid variants"}(s,n);const o=await async function(e,t,n){let s;if(n.track){if(s=n.track.vcf,!s)throw"ds.track.vcf missing"}else s=n.queries.snvindel.byrange._tk;const o=new Set,l=[];for(const e of t){if(e.invalid)continue;let t;if(s.chr2files){if(t=s.chr2files?.[e.chr].file,!t)throw"chr not in chr2files"}else if(s.chr2bcffile){if(t=s.chr2bcffile[e.chr],!t)throw"chr not in chr2bcffile"}else t=s.file||s.url;o.add(t);const n=(s.nochr?e.chr.replace("chr",""):e.chr)+"\t"+(e.pos+1);l.push(n)}const c=i().join(u().cachedir,await a.tG(l.join("\n"))),f=i().join(u().cachedir,await a.tG([...o].join("\n")));await a.UE({isbcf:!0,args:["query","-R",c,"-f",d,"-v",f],dir:s.dir,callback:e=>{const n=e.split("\t"),r=(s.nochr?"chr":"")+n[0],o=n[1],i=n[2],a=n[3].split(","),l=t.find((e=>{if(e.chr==r&&e.pos===o-1&&e.dbsnpRef==i&&e.dbsnpAlts.some((e=>a.includes(e))))return e}));if(l){l.referenceAllele=i,l.altAlleles=a,l.gtlst=[];for(let e=4;e<n.length;e++)l.gtlst.push(n[e]==m?"":n[e])}}}),r().unlink(c,(()=>{})),r().unlink(f,(()=>{}));const p=["snpid\tchr\tpos\tref\talt\teff\t"+s.samples.map((e=>e.name)).join("\t")];for(const e of t)e.invalid||e.gtlst&&(p.push(e.snpid+"\t"+e.chr+"\t"+e.pos+"\t"+e.referenceAllele+"\t"+e.altAlleles.join(",")+"\t"+(e.effectAllele||"")+"\t"+e.gtlst.join("\t")),delete e.gtlst);const h=e.genome+"_"+e.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random());return await a.Sf(i().join(u().cache_snpgt.dir,h),p.join("\n")),h}(e,s,t);return{snps:s,cacheid:o}}(e,n,s);if(e.chr)return await async function(e,t,n){const s=Number(e.start),r=Number(e.stop);if(!Number.isInteger(s)||!Number.isInteger(r))throw"start/stop are not integers";if(s>r||s<0)throw"invalid start/stop coordinate";let o,l;if(t.track){if(o=t.track.vcf,!o)throw"ds.track.vcf missing";if(l=o.chr2bcffile[e.chr],!l)throw"chr not in chr2bcffile"}else if(o=t.queries.snvindel.byrange._tk,l=o.chr2files?o.chr2files?.[e.chr].file:o.file||o.url,!l)throw"no bcf file";const c=(o.nochr?e.chr.replace("chr",""):e.chr)+":"+s+"-"+r,d=["query",l,"-r",c,"-f",p];e.variant_filter&&y(e.variant_filter,d);const g={snps:[]},b=["snpid\tchr\tpos\tref\talt\teff\t"+o.samples.map((e=>e.name)).join("\t")];return await a.UE({isbcf:!0,args:d,dir:o.dir,callback:(t,n)=>{if(g.snps.length>=h)return n.kill(),void(g.reachedVariantLimit=!0);const s=t.split("\t"),r=Number(s[0])-1,i=s[1],a=s[2],l=s[3].split(","),c=i&&"."!=i?i:r+"."+a+"."+l.join(","),u={snpid:c,chr:e.chr,pos:r};(0,f.H)(o,a,l,u,s[4],s[1]);for(const e of u.mlst)e.vcf_id&&(e.mname=e.vcf_id);g.snps.push(u);const d=[c,e.chr,r,a,l.join(","),""];for(let e=5;e<s.length;e++)d.push(s[e]==m?"":s[e]);b.push(d.join("\t"))}}),g.cacheid=e.genome+"_"+e.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random()),await a.Sf(i().join(u().cache_snpgt.dir,g.cacheid),b.join("\n")),g}(e,n);throw"unknown how to validate"}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}function y(e,t){const n=[];for(const t of e.lst)if(t.tvs.values){const e=t.tvs.isnot?"!=":"=";for(const s of t.tvs.values){const r=isNaN(s.key)?`"${s.key}"`:Number(s.key);n.push(`INFO/${t.tvs.term.id}${e}${r}`)}}else{if(!t.tvs.ranges)throw`unknown tvs spec for info_field: type=${t.type}, term.id=${t.tvs.term.id}`;for(const e of t.tvs.ranges)"start"in e&&n.push(`INFO/${t.tvs.term.id} ${e.startinclusive?">=":">"} ${e.start}`),"stop"in e&&n.push(`INFO/${t.tvs.term.id} ${e.stopinclusive?"<=":"<"} ${e.stop}`)}0!=n.length&&t.push("-i",n.join(" && "))}},8907:(e,t,n)=>{"use strict";n.d(t,{yT:()=>C,YG:()=>T,g5:()=>S,J4:()=>N,B9:()=>q,cf:()=>k,tt:()=>x,Bi:()=>A,ig:()=>M});var s={};n.r(s),n.d(s,{binary:()=>f,continuous:()=>l,cubicSpline:()=>c,discrete:()=>u});var r={};n.r(r),n.d(r,{groupset:()=>m,values:()=>d});var o={};n.r(o),n.d(o,{binary:()=>g,cox:()=>b,cuminc:()=>y,discrete:()=>h});var i=n(4048),a=n(5257);const l={getCTE(e,t,n,s,r,o,i){r.push(t.id);const a=C(t,s);return r.push(...a.values),{sql:`${e} AS (\n\t\t\t\tSELECT \n\t\t\t\t\tsample,\n\t\t\t\t\tvalue as key, \n\t\t\t\t\tvalue\n\t\t\t\tFROM anno_${t.type}\n\t\t\t\tWHERE term_id=? ${a.clause}\n\t\t\t)`,tablename:e}}},c=l,u={getCTE(e,t,n,s,r,o,i){r.push(t.id);const a=T(s,t,n,o,i),l=[],c=new Map;s.bin_size;for(const e of a)!("name"in e)&&e.label&&(e.name=e.label),c.set(e.name,e),l.push(`SELECT '${e.name}' AS name,\n\t\t\t\t${null==e.start?0:e.start} AS start,\n\t\t\t\t${null==e.stop?0:e.stop} AS stop,\n\t\t\t\t0 AS unannotated,\n\t\t\t\t${e.startunbounded?1:0} AS startunbounded,\n\t\t\t\t${e.stopunbounded?1:0} AS stopunbounded,\n\t\t\t\t${e.startinclusive?1:0} AS startinclusive,\n\t\t\t\t${e.stopinclusive?1:0} AS stopinclusive`);const u=[];if(t.values)for(const e in t.values){const n=t.values[e].uncomputable;if(s.computableValuesOnly&&n)continue;if(!s.computableValuesOnly&&!n)continue;u.push(e);const r=t.values[e];l.push(`SELECT '${r.label}' AS name,\n\t ${e} AS start,\n\t 0 AS stop,\n\t 1 AS unannotated,\n\t 0 AS startunbounded,\n\t 0 AS stopunbounded,\n\t 0 AS startinclusive,\n\t 0 AS stopinclusive`),c.set(r.label,{is_unannotated:!0,value:e,label:r.label})}const f="bin_defs_"+o,d=C(t,s,"a");r.push(...d.values);return{sql:`${f} AS (\n\t\t\t\t${l.join("\nUNION ALL\n")}\n\t\t\t),\n\t\t\t${e} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tb.name AS key,\n\t\t\t\t\tvalue\n\t\t\t\tFROM\n\t\t\t\t\tanno_${t.type} a\n\t\t\t\tJOIN ${f} b ON\n\t\t\t\t\t( b.unannotated=1 AND value=b.start )\n\t\t\t\t\tOR\n\t\t\t\t\t(\n\t\t\t\t\t\tb.unannotated=0 AND\n\t\t\t\t\t\t${u.length?"value NOT IN ("+u.join(",")+") AND":""}\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.startunbounded = 1\n\t\t\t\t\t\t\tOR value > b.start\n\t\t\t\t\t\t\tOR (b.startinclusive=1 AND value = b.start)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.stopunbounded\n\t\t\t\t\t\t\tOR value < b.stop\n\t\t\t\t\t\t\tOR (b.stopinclusive=1 AND value = b.stop)\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\tWHERE\n\t\t\t\tterm_id=? ${d.clause}\n\t\t\t)`,tablename:e,name2bin:c,bins:a}}},f=u,d={getCTE(e,t,n,s,r){r.push(t.id);const o=C(t,s);return r.push(...o.values),{sql:`${e} AS (\n\t\t\t\tSELECT sample,value as key, value as value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id=? ${o.clause}\n\t\t\t)`,tablename:e}}};let p=0;const m={async getCTE(e,t,n,s,r,o){if(!o.groups)throw`.groups[] missing from a group-set, term.id='${t.id}'`;const i=[],a=[];for(const e of o.groups)if("values"==e.type)i.push(`SELECT sample, ? as key, value\n\t\t\t\t\tFROM anno_categorical a\n\t\t\t\t\tWHERE term_id=?\n\t\t\t\t\t\tAND value IN (${e.values.map((e=>"?")).join(",")})\n\t\t\t\t`),r.push(e.name,t.id,...e.values.map((e=>e.key.toString())));else{if("filter"!=e.type)throw`unsupported groupset type='${e.type}'`;if(!("activeCohort"in s.groupsetting)||!e.filter4activeCohort)throw`activeCohort error: cannot construct filter statement for group name='${e.name}', term.id=${t.id}`;{const o=e.filter4activeCohort[s.groupsetting.activeCohort],l=await getFilterCTEs(o,n,"xf"+p++);if(!l)throw`unable to construct a group='${e.name}' filter for term.id='${t.id}'`;a.push(l.filters),r.push(...l.values.slice(),e.name,e.name),i.push(`SELECT sample, ? AS key, ? AS value\n\t\t\t\t\t\tFROM ${l.CTEname}`)}}return{sql:`${a.length?a.join("\n,")+",":""}\n\t\t\t${e} AS (\n\t\t\t\t${i.join("\nUNION ALL\n")}\n\t\t\t)`,tablename:e}}},h={getCTE(e,t,n,s,r){if(s.breaks&&s.breaks.length>0)return w(e,t,s,r);{const[n,o]=v(s);r.push(t.id);const i=C(t,s);return r.push(...i.values),{sql:`${e} AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tsample,\n\t\t\t\t\t\tvalue as key,\n\t\t\t\t\t\tvalue\n\t\t\t\t\tFROM\n\t\t\t\t\t\t${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tterm_id = ?\n\t\t\t\t\t\tAND ${o} = 1\n\t\t\t\t\t\t${i.clause}\n\t\t\t\t)`,tablename:e}}}},g={getCTE(e,t,n,s,r){if(1!=s.breaks?.length)throw"binary mode requires one break";return w(e,t,s,r)}},y={getCTE(e,t,n,s,r){if(1!=s.breaks?.length)throw"cuminc mode requires one break";return r.push(t.id,s.breaks[0]),{sql:`${e} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\ttime AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cuminc\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:e}}},b={getCTE(e,t,n,s,r){if(1!=s.breaks?.length)throw"cox mode requires one break";r.push(t.id,s.breaks[0]);const o=Object.keys(t.values).map(Number),i=Math.max(...o);return{sql:`${e} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\tjson_object('age_start', age_start, 'age_end', age_end) AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cox\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:e,events:[{event:1,label:`Event (grade ${s.breaks[0]===i?s.breaks[0]:`${s.breaks[0]}-${i}`})`},{event:0,label:"Censored/death"},{event:-1,label:"Event before entry into the cohort"}]}}};function v(e){const t=e.bar_by_children?"child":e.bar_by_grade?"grade":"";if(!t)throw"must set the bar_by_grade or bar_by_children query parameter";const n=e.value_by_max_grade?"max_grade":e.value_by_most_recent?"most_recent":e.value_by_computable_grade?"computable_grade":"";if(!n)throw"must set a valid value_by_*";return[t,n]}function w(e,t,n,s){const[r,o]=v(n);if("grade"!=r)throw"breaks must be used on grade values";const i=[];for(const e of n.groups)i.push(`SELECT sample, ? as key, value\n\t\t\tFROM precomputed_chc_grade\n\t\t\tWHERE\n\t\t\t\tterm_id=?\n\t\t\t\tAND ${o}=1\n\t\t\t\tAND value IN (${e.values.map((e=>"?")).join(",")})\n\t\t`),s.push(e.name,t.id,...e.values.map((e=>e.toString())));return{sql:`${e} AS (\n\t\t\t${i.join("\nUNION ALL\n")}\n\t\t)`,tablename:e}}const _={getCTE(e,t,n){let s,r,o="";for(const[e,i]of t.q.groups.entries())"in"in i||(i.in=!0),s=i.values.map((e=>e.sampleId)),r=s.map((()=>"?")).join(","),o+=`SELECT id as sample, ? as key, ? as value\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE sample ${i.in?"":"NOT"} IN (${r})\n\t\t\t`,e!=t.q.groups.length-1&&(o+="UNION ALL "),n.push(i.name,i.name,...s);return{sql:`${e} AS (${o})`,tablename:e}}};n(334),n(3345);async function k(e,t,n=!1){const s=await(0,a.w)(e,t),r=t.cohort.db.connection.prepare(s?`WITH ${s.filters} SELECT sample as id, name FROM ${s.CTEname} join sampleidmap on sample = sampleidmap.id`:"SELECT id, name FROM sampleidmap");let o;if(o=s?r.all(s.values):r.all(),n)return o;for(const e of o)delete e.name;return o}async function q(e,t){if(!e.filter)throw"filter missing";let n;if("object"==typeof e.filter)n=e.filter;else{if("string"!=typeof e.filter)throw"q.filter not obj or str";n=JSON.parse(e.filter)}const s=await(0,a.w)(n,t),r=`WITH ${s.filters}\n\t\tSELECT 'FILTERED_COHORT' as subcohort, count(distinct sample) as samplecount \n\t\tFROM ${s.CTEname}`;return t.cohort.db.connection.prepare(r).all(s.values)}async function x(e){const t=e.ds.cohort.termdb.q.termjsonByOneid(e.term_id);if("integer"!=t.type&&"float"!=t.type)throw"term is not numeric";if(!t.values)return[];const n=await(0,a.w)(e.filter,e.ds),s=n?n.values.slice():[];s.push(e.term_id);const r=[];for(const e in t.values)r.push("?"),s.push(Number(e));const o=`\n\t\t${n?"WITH "+n.filters:""}\n\t\tSELECT count(sample) AS samplecount,value\n\t\tFROM anno_${t.type}\n\t\tWHERE term_id=?\n\t\t${n?"AND sample IN "+n.CTEname:""}\n\t\tAND value IN (${r.join(",")})\n\t\tGROUP BY value`;return e.ds.cohort.db.connection.prepare(o).all(s)}async function N(e){if(!e.key)throw".key missing";if(!e.ds)throw".ds{} missing";const t=await(0,a.w)(e.filter,e.ds),n=t?t.values.slice():[],s=e.ds.cohort.termdb.q.termjsonByOneid(e.key);n.push(e.key);const r=`\n\t\t${t?"WITH "+t.filters:""}\n\t\tSELECT sample, value\n\t\tFROM anno_${s.type}\n\t\tWHERE term_id=?\n\t\t${t?" AND sample IN "+t.CTEname:""}`;return e.ds.cohort.db.connection.prepare(r).all(n)}async function S(e,t={}){"string"==typeof e.filter&&(e.filter=JSON.parse(decodeURIComponent(e.filter)));const n=Object.assign({withCTEs:!0,columnas:"t1.sample AS sample",groupby:""},t),s=await(0,a.w)(e.filter,e.ds),r=s?s.values.slice():[],o=await A(e,r,0,s),i=await A(e,r,1,s),l=await A(e,r,2,s),c=[o,i,l].map(((e,t)=>`\n\t\tSELECT sample, key, value, ${t} as termNum\n\t\tFROM ${e.tablename}\n\t\t${s?"WHERE sample IN "+s.CTEname:""}\n\t`)).join("\nUNION ALL\n"),u=`WITH\n\t\t${s?s.filters+",":""}\n\t\t${o.sql},\n\t\t${i.sql},\n\t\t${l.sql}\n\t\t${c}`;try{const t=e.ds.cohort.db.connection.prepare(u).all(r),a=new Map;for(const e of t){a.has(e.sample)||a.set(e.sample,{sample:e.sample});const t=a.get(e.sample),n=`key${e.termNum}`;n in t||(t[n]=[]),t[n].push(e)}const c=[],f=new Map;for(const t of a.values())if("key1"in t){if(e.term0_q&&e.term0_id){if(!("key0"in t))continue}else t.key0=[{key:"",value:""}];if(e.term2_q&&(e.term2_id||"samplelst"===e.term2.type)){if(!("key2"in t))continue}else t.key2=[{key:"",value:""}];t.rows=[];for(const e of t.key0)for(const n of t.key1)for(const s of t.key2)t.rows.push({sample:t.sample,key0:e.key,val0:e.value,key1:n.key,val1:n.value,key2:s.key,val2:s.value});for(const e of t.rows)if(n.groupby){if(!f.has(e[n.groupby])){const t=Object.assign({samplecount:0},e);c.push(t),f.set(e[n.groupby],t)}f.get(e[n.groupby]).samplecount++}else c.push(e)}return n.withCTEs?{lst:c,CTE0:o,CTE1:i,CTE2:l,filter:s}:c}catch(e){throw console.log("error in sql:\n",M(u,r)),e}}async function A(e,t,n,i,a=null){const l=a&&a.term||e[`term${n}`],c=l?l.id:e["term"+n+"_id"];if("samplelst"!=l?.type)if(a||1!=n){if(!c){const e="samplekey_"+n;return{tablename:e,sql:`${e} AS (\nSELECT null AS sample, '' as key, '' as value\n)`}}}else if(!c)throw"missing term1 id";const u=l&&l.type?l:e.ds.cohort.termdb.q.termjsonByOneid(c);if(!u)throw`no term found by id='${c}'`;let f=a&&a.q||e["term"+n+"_q"]||{};"string"==typeof f&&(f=JSON.parse(decodeURIComponent(f)));const d="samplekey_"+n;let p;if("categorical"==u.type){const n=j(u,f);p=await r[n?"groupset":"values"].getCTE(d,u,e.ds,f,t,n)}else if("integer"==u.type||"float"==u.type){const r="spline"==f.mode?"cubicSpline":f.mode||"discrete";p=await s[r].getCTE(d,u,e.ds,f,t,n,i)}else if("condition"==u.type){const n=f.mode||"discrete";p=await o[n].getCTE(d,u,e.ds,f,t)}else if("survival"==u.type)p=function(e,t,n,s,r){return s.push(t.id),{sql:`${e} AS (\n\t\t\tSELECT sample, exit_code as key, tte AS value\n\t\t\tFROM survival s\n\t\t\tWHERE s.term_id=?\n\t\t\t${r?"AND s.sample IN "+r.CTEname:""}\n\t\t)`,tablename:e}}(d,u,0,t,i);else{if("samplelst"!=u.type)throw"unknown term type";p=await _.getCTE(d,a||{term:u,q:f},t)}return p}function C(e,t,n=""){if(!e.values||!t.computableValuesOnly)return{values:[],clause:""};const s=Object.keys(e.values).filter((t=>e.values[t].uncomputable)),r=n?`${n}.value`:"value";return{values:s,clause:s.length?`AND ${r} NOT IN (${s.map((()=>"?")).join(",")})`:""}}function j(e,t){if(t.groupsetting&&!t.groupsetting.disabled&&t.groupsetting.inuse){if(Number.isInteger(t.groupsetting.predefined_groupset_idx)){if(t.groupsetting.predefined_groupset_idx<0)throw"q.predefined_groupset_idx out of bound";if(!e.groupsetting)throw"term.groupsetting missing when q.predefined_groupset_idx in use";if(!e.groupsetting.lst)throw"term.groupsetting.lst missing when q.predefined_groupset_idx in use";const n=e.groupsetting.lst[t.groupsetting.predefined_groupset_idx];if(!n)throw"q.predefined_groupset_idx out of bound";return n}if(t.groupsetting.customset)return t.groupsetting.customset;throw"do not know how to get groupset"}}function T(e,t,n,s,r){if("continuous"!=e.mode&&"spline"!=e.mode)return i.gp(e,(e=>function(e,t,n,s=[]){const r=[];n&&r.push(...n.values);r.push(t.id);const o=t.values?Object.keys(t.values).filter((e=>t.values[e].uncomputable)):[],i=[],a=[],l=[];let c;for(const e of s)c="pct_"+e,i.push(`\n\t\t${c} AS (\n\t\t SELECT value\n\t\t FROM vals\n\t\t LIMIT 1\n\t\t OFFSET (\n\t\t SELECT cast ( x as int ) - ( x < cast ( x as int ))\n\t\t FROM (\n\t\t SELECT cast(?*pct as int) as x \n\t\t FROM p\n\t\t )\n\t\t )\n\t\t)`),r.push(e),a.push(c),l.push(`${c}.value AS ${"p"+e}`);const u=`WITH\n\t\t${n?n.filters+", ":""} \n\t\tvals AS (\n\t\t\tSELECT value\n\t\t\tFROM anno_${t.type}\n\t\t\tWHERE\n\t\t\t${n?"sample IN "+n.CTEname+" AND ":""}\n\t\t\tterm_id=?\n\t\t\t${o.length?"AND value NOT IN ("+o.join(",")+")":""}\n\t\t\tORDER BY value ASC\n\t\t),\n\t\tp AS (\n\t\t\tSELECT count(value)/100 as pct\n\t\t\tFROM vals\n\t\t)\n\t\t${i.length?",\n"+i.join(","):""}\n\t\tSELECT \n\t\t\tmin(vals.value) as vmin,\n\t\t\tmax(vals.value) as vmax\n\t\t\t${l.length?",\n"+l.join(",\n"):""} \n\t\tFROM vals ${a.length?","+a.join(","):""}`,f=e.cohort.db.connection.prepare(u).all(r),d=f.length?f[0]:{};return d.max=f[0].vmax,d.min=f[0].vmin,d}(n,t,r,e)))}function M(e,t){const n=t.slice();let s;return e.split("").map((e=>{if("?"==e){s=e;const t=n.shift();return"string"==typeof t?`'${t}'`:t}return"\t"==e?"":"\n"!=e&&" "!=e||s!==e?(s=e,e):""})).join("")}},3345:(e,t,n)=>{"use strict";n.d(t,{Dp:()=>Q,JC:()=>oe,d1:()=>M,fk:()=>le,sE:()=>V,Ic:()=>F,yE:()=>P,t7:()=>G,ZX:()=>O,EO:()=>K,Kf:()=>W,ZD:()=>U,UE:()=>B,lY:()=>E,_H:()=>$,L0:()=>X,Y5:()=>re,z5:()=>ee,mr:()=>te,b5:()=>H,cl:()=>Y,Jy:()=>L,sI:()=>ne,aS:()=>se,LC:()=>D,Sf:()=>z,tG:()=>J});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(2081),l=n(4521),c=n.n(l),u=n(2273),f=n(6819);const d=require("node-fetch");var p=n.n(d);const m=require("better-sqlite3");var h=n.n(m),g=n(334),y=n.n(g);n(2781);const b=require("minimatch");var v=n.n(b),w=n(6113),_=n.n(w),k=n(6452),q=n.n(k);const x=y(),{tabix:N,samtools:S,bcftools:A,bigBedToBed:C,bigBedNamedItems:j,bigBedInfo:T}=x;async function M(e,t){if(!e)throw".gz file URL missing";if("string"!=typeof e)throw".gz file URL not string";if(t&&"string"!=typeof t)throw"index URL not string";const[n,s,o]=R(e);if(n)throw".gz file URL error: "+n;const a=i().join(x.cachedir,s,o);try{await r().promises.stat(a)}catch(n){if("ENOENT"!=n.code)throw"stating gz url dir: "+n.code;try{await r().promises.mkdir(a,{recursive:!0})}catch(n){throw"url dir: cannot mkdir"}}if(!t)return a;{const[e,s,o]=R(t);if(e)throw"indexl url error: "+e;const l=i().join(a,i().basename(o));try{return await r().promises.stat(l),a}catch(n){if("ENOENT"==n.code)return await async function(e,t){try{const o=await p()(e);if(200!=o.status)throw"index file not accessible from url with status code "+o.status;await(n=o.body,s=t,new Promise(((e,t)=>{const o=r().createWriteStream(s);n.pipe(o),n.on("end",(()=>e()))})))}catch(e){throw"cannot download from url"}var n,s}(t,l),a;throw"stating indexl url file: "+n.code}}}function O(e,t=!0){let n=null,s=!1;if(e.query.file){if(n=e.query.file,E(n,t,!1))return["illegal file path"];n=i().join(x.tpmasterdir,n)}else if(e.query.url){if(n=e.query.url,n.includes(" "))return["url must not contain whitespace"];if(n.includes('"')||n.includes("'"))return["url must not contain single or double quotes"];s=!0}return n?[null,n,s]:["file unspecified"]}const I=Object.freeze([".bam",".bai",".gz",".tbi",".csi",".bw",".bb"]);function E(e,t=!1,n=!0){if("/"==e[0])return!0;if(e.includes('"')||e.includes("'"))return!0;if(e.includes("|")||e.includes("&"))return!0;if(e.includes(" "))return!0;if(-1!=e.indexOf(".."))return!0;if(e.match(/(\<script|script\>)/i))return!0;if(t&&x.whiteListPaths){let t=!0;for(const n of x.whiteListPaths){if(e.startsWith(n)||"!"!=n[0]&&v()(e,n)){t=!1;break}if("!"==n[0]&&!v()(e,n)){t=!0;break}}if(t)return!0}if(n)for(const t of I)if(t===i().extname(e).toLowerCase())return!0;return!1}function R(e){const t=e.split("://");return 2!=t.length?["improper url"]:t[0].length<3?["protocol string length too short"]:t[1].length<5?["body string length too short"]:[null,t[0],t[1]]}async function F(e){try{await r().promises.stat(e)}catch(t){const n=x.debugmode?`file='${e}'`:"";if("EACCES"==t.code)throw`Permission denied ${n}`;if("ENOENT"==t.code)throw`No such file or directory ${n}`;if("EPERM"==t.code)throw`Operation not permitted ${n}`;throw`cannot access file (' + e.code + ') ${n}`}}async function $(e,t,n){let s;if(e.file)e.file.startsWith(x.tpmasterdir)||(e.file=i().join(x.tpmasterdir,e.file)),s=e.file,await D(e.file);else{if(!e.url)throw"no file or url given for vcf file";s=e.url,e.dir=await utils.cache_index(e.url,e.indexURL)}const[r,o,l,c]=n?await(u=s,d=e.dir,new Promise(((e,t)=>{const n=(0,a.spawn)(A,["view","-h",u],{cwd:d}),s=[];n.stdout.on("data",(e=>s.push(e))),n.on("close",(()=>{e(f.e(s.join("").trim().split("\n")))}))}))):await async function(e,t){return f.e(await U(e,t))}(s,e.dir);var u,d;if(c)throw console.log(c.join("\n")),"got above errors parsing vcf";e.info=r,e.format=o,e.samples=l,await L(s,e.dir,t)&&(e.nochr=!0)}async function D(e){if(!e.endsWith(".gz"))throw"tabix file not ending with .gz";if(await P(e))throw e+" file not exist";if(await G(e))throw".gz file not readable";const t=e+".tbi";if(await P(t)){const t=e+".csi";if(await P(t))throw"neither .tbi .csi index file exist for "+e;if(await G(t))throw".csi index file not readable"}else if(await G(t))throw".tbi index file not readable"}async function L(e,t,n){const s=[];return await B({args:["-l",e],dir:t,callback:e=>{s.push(e)}}),u.contigNameNoChr(n,s)}function P(e){return new Promise(((t,n)=>{r().access(e,r().constants.F_OK,(e=>{e&&t(!0),t(!1)}))}))}function G(e){return new Promise(((t,n)=>{r().access(e,r().constants.R_OK,(e=>{e&&t(!0),t(!1)}))}))}async function U(e,t){const n=[];return await B({args:["-H",e],dir:t,callback:e=>{n.push(e)}}),n}function B({args:e,dir:t,callback:n,isbcf:s,isbam:r}){if(!e)throw"args is missing";if(!Array.isArray(e))throw"args[] is not array";if(0==e.length)throw"args[] empty array";if(!n)throw"callback is missing";if("function"!=typeof n)throw"callback() not a function";return new Promise(((o,i)=>{const l=(0,a.spawn)(s?A:r?S:N,e,{cwd:t}),u=c().createInterface({input:l.stdout}),f=[];u.on("line",(e=>n(e,l))),l.stderr.on("data",(e=>f.push(e))),l.on("close",(()=>{const e=f.join("").trim();e&&!ne(e)&&i(e),o()}))}))}function z(e,t){return new Promise(((n,s)=>{r().writeFile(e,t,(e=>{e&&s("cannot write"),n()}))}))}async function J(e){const t=Math.random().toString();return await z(i().join(x.cachedir,t),e),t}function H(e){return new Promise(((t,n)=>{r().readFile(e,{encoding:"utf8"},((s,r)=>{s&&n("cannot read file: "+e),t(r)}))}))}async function W(e,t){if("NA"==e.genomefile){const e=t.split(/[:-]/),n=[];for(let t=Number(e[1]);t<=Number(e[2]);t++)n.push("N");return`>${t}\n${n.join("")}`}const n=[];return await B({isbam:!0,args:["faidx",e.genomefile,t],callback:e=>n.push(e)}),n.join("\n")}function V(e,t={}){const n="/"==e[0]?e:i().join(x.tpmasterdir,e);try{return new(h())(n,Object.assign({readonly:!0,fileMustExist:!0},t))}catch(e){throw`error connecting to ${n}: ${e}`}}const Z=new Set(["Homozygous reference","Homozygous alternative","Heterozygous"]),K={href:"Homozygous reference",halt:"Homozygous alternative",het:"Heterozygous"};async function X(e,t){const n=await H(i().join(x.cachedir_ssid,e)),s=new Map,r=new Map;for(const e of n.trim().split("\n")){if(!e)continue;const[n,o]=e.split("\t");if(!o)continue;if(!Z.has(n))throw"unknown hardcoded genotype label: "+n;const i=o.split(",").map((e=>Number(e))),a=t?i.filter((e=>t.has(e))):i;for(const e of a)s.set(e,n);r.set(n,new Set(a))}return[s,r]}function Y(e){return e.replace(/\<script|\bon[\w]{1,38}\b[\ \t\n]*\=/gi," _")}async function Q(e,t,n){const s=[];if(await B({isbam:!0,args:["view","-H",e],dir:n,callback:e=>s.push(e)}),0==s.length)throw"cannot list bam header lines";const r=[];for(const e of s){if(!e.startsWith("@SQ"))continue;const t=e.split("\t")[1];t||reject("2nd field missing from @SQ line");const n=t.split(":");"SN"!=n[0]&&reject('@SQ line 2nd field is not "SN" but '+n[0]),n[1]||reject("@SQ line no value for SN"),r.push(n[1])}return u.contigNameNoChr(t,r)}function ee(e,t,n,s){return new Promise(((r,o)=>{const i=(0,a.spawn)(C,[`-chrom=${t}`,`-start=${n}`,`-end=${s}`,e,"stdout"]),l=[],c=[];i.stdout.on("data",(e=>l.push(e))),i.stderr.on("data",(e=>c.push(e))),i.on("close",(e=>{0!==e&&o(`bigBed query exited with non-zero status and this standard error:\n${c.join("")}`),c.length>0&&o(c.join(""));const t=l.join("").trim();r(t?t.split("\n"):[])}))}))}function te(e,t){return new Promise(((n,s)=>{const r=(0,a.spawn)(j,[e,t,"stdout"]),o=[],i=[];r.stdout.on("data",(e=>o.push(e))),r.stderr.on("data",(e=>i.push(e))),r.on("close",(e=>{0!==e&&s(`bigBed query exited with non-zero status and this standard error:\n${i.join("")}`),i.length>0&&s(i.join(""));const t=o.join("").trim();n(t?t.split("\n"):[])}))}))}function ne(e){return e.startsWith("[E::idx_test_and_fetch]")}async function se(e){return new Promise(((t,n)=>{const s=(0,a.spawn)(T,[e]),r=[],o=[];s.stdout.on("data",(e=>r.push(e))),s.stderr.on("data",(e=>o.push(e))),s.on("close",(e=>{const n=o.join("");n&&(n.includes("is not a big bed file")||n.includes("Couldn't open"),t(!1));r.join("").trim().startsWith("version")&&t(!0)}))}))}function re(e,t){if(t.sessionid){if("sessionid"in e)throw"q.sessionid already exists so cannot copy from cookies.sessionid";e.sessionid=t.sessionid}}function oe(e){const t=e.length;if(t<5)return{out:e};const n=e[Math.floor(t/2)].value,s=e[Math.floor(t/4)].value,r=e[Math.floor(3*t/4)].value,o=e[Math.floor(.05*t)].value,i=e[Math.floor(.95*t)].value,a=(e[Math.floor(.01*t)].value,r-s);let l,c;if(0==a)l=0,c=0;else{const n=e.findIndex((e=>e.value>s-1.5*a));l=e[-1==n?0:n].value;const o=e.findIndex((e=>e.value>r+1.5*a));c=e[-1==o?t-1:o-1].value}const u=e.filter((e=>e.value<s-1.5*a||e.value>r+1.5*a));return{w1:l,w2:c,p05:o,p25:s,p50:n,p75:r,p95:i,iqr:a,out:u}}const ie=x.features?.extApiCache||{},ae=i().join(x.cachedir,"extApiResponse");if(x.features?.extApiCache){r().existsSync(ae)||r().mkdirSync(ae,{recursive:!0});for(const e in ie){const t=i().join(ae,ie[e]);r().existsSync(t)||r().mkdirSync(t,{recursive:!0})}}async function le(e,t={},n={}){let s;for(const t in ie)e.includes(t)&&(s=i().join(ae,ie[t]));if(!e.includes(":/"))throw`cannot use cachedFetch wuth a relative URL: ${e}`;const o=s&&_().createHash("sha1").update(`${e} ${JSON.stringify(t.body)}`).digest("hex"),a=s&&i().join(s,o);let l;if(a&&r().existsSync(a))try{const e=r().readFileSync(a)?.toString("utf-8").trim();l=JSON.parse(e)}catch(e){throw console.log(e),e}else try{const s={"content-type":"application/json",accept:"application/json"};if(t.headers)for(const e in t.headers)s[e.toLowerCase()]=t.headers[e].toLowerCase();const o=t.method?.toLowerCase()||"get",i=n.client||q(),c=await i[o](e,{headers:s,body:"get"==o?void 0:s["content-type"].includes("json")?JSON.stringify(t.body||{}):t.body});if(a){const e="string"==typeof c.body?c.body:s.accept.includes("json")?JSON.stringify(c.body):t.response;r().writeFileSync(a,e,{encoding:"utf8"})}l="string"==typeof c.body&&s.accept.includes("json")?JSON.parse(c.body):c.body}catch(e){throw e}return n.metaKey&&(l[n.metaKey]={id:o,cacheFile:a}),{body:l}}},3625:(e,t,n)=>{"use strict";n.d(t,{H:()=>a});var s=n(9380),r=n(4298),o=n(736),i=n(2273);function a(e,t,n,a,l,c,u){const f=(0,s.w)(l);for(const t in e.info){if("A"==e.info[t].Number&&t in f&&(f[t]=f[t].split(",")),e.info[t].separator&&t in f){const n=f[t].split(e.info[t].separator);n.length>1&&(f[t]=n)}if("Float"==e.info[t].Type||"Integer"==e.info[t].Type)if(Array.isArray(f[t])){const e=f[t].map(Number);f[t]=e}else f[t]=Number(f[t])}a.mlst=n.map((e=>{const[n,s,r]=function(e,t,n){for(;t.length>1&&n.length>1&&t[t.length-1]==n[n.length-1];)t=t.substring(0,t.length-1),n=n.substring(0,n.length-1);for(;t.length>1&&n.length>1&&t[0]==n[0];)t=t.substring(1),n=n.substring(1),e++;return[e,t,n]}(a.pos,t,e),i={allele_original:e,ref:s,alt:r,pos:n,type:(0,o.P)(s,r)};return c&&"."!=c&&(i.vcf_id=c),i})),e.info?.CSQ&&f.CSQ&&(0,r.A)(f.CSQ,e.info.CSQ.csqheader,a);const d={};u&&(d.usegm={isoform:u});for(const[n,s]of a.mlst.entries()){(0,i.vcfcopymclass)(s,d),delete s.csq,s.mname||(s.mname="."!=c?c:a.pos+":"+t+">"+s.allele_original),s.altAlleleIdx=n+1,s.info={};for(const t in f)"A"==e.info?.[t]?.Number?s.info[t]=f[t][n]:s.info[t]=f[t]}}},126:(e,t,n)=>{var s={"./burden":5037,"./burden.ts":5037,"./gdc.maf":2538,"./gdc.maf.ts":2538,"./gdc.mafBuild":86,"./gdc.mafBuild.ts":86,"./gdc.topMutatedGenes":889,"./gdc.topMutatedGenes.ts":889,"./genelookup":3202,"./genelookup.ts":3202,"./healthcheck":1746,"./healthcheck.ts":1746,"./hicdata":3932,"./hicdata.ts":3932,"./hicstat":6310,"./hicstat.ts":6310,"./termdb.categories":5852,"./termdb.categories.ts":5852,"./termdb.cluster":4924,"./termdb.cluster.ts":4924,"./termdb.getdescrstats":2262,"./termdb.getdescrstats.ts":2262,"./termdb.getnumericcategories":5961,"./termdb.getnumericcategories.ts":5961,"./termdb.getpercentile":2630,"./termdb.getpercentile.ts":2630,"./termdb.getrootterm":7095,"./termdb.getrootterm.ts":7095,"./termdb.gettermchildren":3967,"./termdb.gettermchildren.ts":3967,"./termdb.singleSampleMutation":3677,"./termdb.singleSampleMutation.ts":3677,"./termdb.singlecellData":5707,"./termdb.singlecellData.ts":5707,"./termdb.singlecellSamples":7934,"./termdb.singlecellSamples.ts":7934,"./termdb.termsbyids":605,"./termdb.termsbyids.ts":605,"./termdb.topVariablyExpressedGenes":5057,"./termdb.topVariablyExpressedGenes.ts":5057,"./termdb.violin":2386,"./termdb.violin.ts":2386};function r(e){var t=o(e);return n(t)}function o(e){if(!n.o(s,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return s[e]}r.keys=function(){return Object.keys(s)},r.resolve=o,e.exports=r,r.id=126},1271:e=>{"use strict";e.exports=require("@sjcrh/proteinpaint-rust")},6718:e=>{"use strict";e.exports=require("canvas")},6452:e=>{"use strict";e.exports=require("got")},7219:e=>{"use strict";e.exports=require("image-size")},9344:e=>{"use strict";e.exports=require("jsonwebtoken")},8088:e=>{"use strict";e.exports=require("micromatch")},6464:e=>{"use strict";e.exports=require("util")},2081:e=>{"use strict";e.exports=require("child_process")},6113:e=>{"use strict";e.exports=require("crypto")},7147:e=>{"use strict";e.exports=require("fs")},1017:e=>{"use strict";e.exports=require("path")},4521:e=>{"use strict";e.exports=require("readline")},2781:e=>{"use strict";e.exports=require("stream")},9263:(e,t,n)=>{"use strict";function s(e,t){return null==e||null==t?NaN:e<t?-1:e>t?1:e>=t?0:NaN}n.d(t,{Z:()=>s})},5519:(e,t,n)=>{"use strict";n.d(t,{Nw:()=>l,ZP:()=>u,ZR:()=>c,ml:()=>a});var s=n(9263),r=n(3292),o=n(3745);const i=(0,r.Z)(s.Z),a=i.right,l=i.left,c=(0,r.Z)(o.Z).center,u=a},3292:(e,t,n)=>{"use strict";n.d(t,{Z:()=>o});var s=n(9263),r=n(788);function o(e){let t,n,o;function a(e,s,r=0,o=e.length){if(r<o){if(0!==t(s,s))return o;do{const t=r+o>>>1;n(e[t],s)<0?r=t+1:o=t}while(r<o)}return r}return 2!==e.length?(t=s.Z,n=(t,n)=>(0,s.Z)(e(t),n),o=(t,n)=>e(t)-n):(t=e===s.Z||e===r.Z?e:i,n=e,o=e),{left:a,center:function(e,t,n=0,s=e.length){const r=a(e,t,n,s-1);return r>n&&o(e[r-1],t)>-o(e[r],t)?r-1:r},right:function(e,s,r=0,o=e.length){if(r<o){if(0!==t(s,s))return o;do{const t=r+o>>>1;n(e[t],s)<=0?r=t+1:o=t}while(r<o)}return r}}}function i(){return 0}},788:(e,t,n)=>{"use strict";function s(e,t){return null==e||null==t?NaN:t<e?-1:t>e?1:t>=e?0:NaN}n.d(t,{Z:()=>s})},9724:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Adder:()=>q,InternMap:()=>S.L,InternSet:()=>S.H,ascending:()=>r.Z,bin:()=>K,bisect:()=>s.ZP,bisectCenter:()=>s.ZR,bisectLeft:()=>s.Nw,bisectRight:()=>s.ml,bisector:()=>o.Z,blur:()=>i,blur2:()=>a,blurImage:()=>l,count:()=>p,cross:()=>y,cumsum:()=>b,descending:()=>v.Z,deviation:()=>_,difference:()=>Re,disjoint:()=>Fe,every:()=>je,extent:()=>k,fcumsum:()=>N,filter:()=>Me,flatGroup:()=>M,flatRollup:()=>O,fsum:()=>x,greatest:()=>re,greatestIndex:()=>_e,group:()=>C,groupSort:()=>B,groups:()=>j,histogram:()=>K,index:()=>R,indexes:()=>F,intersection:()=>$e,least:()=>ve,leastIndex:()=>we,map:()=>Oe,max:()=>X,maxIndex:()=>Y,mean:()=>ue,median:()=>fe,medianIndex:()=>de,merge:()=>pe,min:()=>Q,minIndex:()=>ee,mode:()=>me,nice:()=>V,pairs:()=>he,permute:()=>L,quantile:()=>oe,quantileIndex:()=>ae,quantileSorted:()=>ie,quickselect:()=>te,range:()=>ye,rank:()=>be,reduce:()=>Ie,reverse:()=>Ee,rollup:()=>I,rollups:()=>E,scan:()=>ke,shuffle:()=>qe,shuffler:()=>xe,some:()=>Te,sort:()=>P,subset:()=>Ge,sum:()=>Ne,superset:()=>Le,thresholdFreedmanDiaconis:()=>le,thresholdScott:()=>ce,thresholdSturges:()=>Z,tickIncrement:()=>W.G9,tickStep:()=>W.ly,ticks:()=>W.ZP,transpose:()=>Se,union:()=>Ue,variance:()=>w,zip:()=>Ce});var s=n(5519),r=n(9263),o=n(3292);function i(e,t){if(!((t=+t)>=0))throw new RangeError("invalid r");let n=e.length;if(!((n=Math.floor(n))>=0))throw new RangeError("invalid length");if(!n||!t)return e;const s=d(t),r=e.slice();return s(e,r,0,n,1),s(r,e,0,n,1),s(e,r,0,n,1),e}const a=c(d),l=c((function(e){const t=d(e);return(e,n,s,r,o)=>{t(e,n,(s<<=2)+0,(r<<=2)+0,o<<=2),t(e,n,s+1,r+1,o),t(e,n,s+2,r+2,o),t(e,n,s+3,r+3,o)}}));function c(e){return function(t,n,s=n){if(!((n=+n)>=0))throw new RangeError("invalid rx");if(!((s=+s)>=0))throw new RangeError("invalid ry");let{data:r,width:o,height:i}=t;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((i=Math.floor(void 0!==i?i:r.length/o))>=0))throw new RangeError("invalid height");if(!o||!i||!n&&!s)return t;const a=n&&e(n),l=s&&e(s),c=r.slice();return a&&l?(u(a,c,r,o,i),u(a,r,c,o,i),u(a,c,r,o,i),f(l,r,c,o,i),f(l,c,r,o,i),f(l,r,c,o,i)):a?(u(a,r,c,o,i),u(a,c,r,o,i),u(a,r,c,o,i)):l&&(f(l,r,c,o,i),f(l,c,r,o,i),f(l,r,c,o,i)),t}}function u(e,t,n,s,r){for(let o=0,i=s*r;o<i;)e(t,n,o,o+=s,1)}function f(e,t,n,s,r){for(let o=0,i=s*r;o<s;++o)e(t,n,o,o+i,s)}function d(e){const t=Math.floor(e);if(t===e)return function(e){const t=2*e+1;return(n,s,r,o,i)=>{if(!((o-=i)>=r))return;let a=e*s[r];const l=i*e;for(let e=r,t=r+l;e<t;e+=i)a+=s[Math.min(o,e)];for(let e=r,c=o;e<=c;e+=i)a+=s[Math.min(o,e+l)],n[e]=a/t,a-=s[Math.max(r,e-l)]}}(e);const n=e-t,s=2*e+1;return(e,r,o,i,a)=>{if(!((i-=a)>=o))return;let l=t*r[o];const c=a*t,u=c+a;for(let e=o,t=o+c;e<t;e+=a)l+=r[Math.min(i,e)];for(let t=o,f=i;t<=f;t+=a)l+=r[Math.min(i,t+c)],e[t]=(l+n*(r[Math.max(o,t-u)]+r[Math.min(i,t+u)]))/s,l-=r[Math.max(o,t-c)]}}function p(e,t){let n=0;if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&++n;else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&(r=+r)>=r&&++n}return n}function m(e){return 0|e.length}function h(e){return!(e>0)}function g(e){return"object"!=typeof e||"length"in e?e:Array.from(e)}function y(...e){const t="function"==typeof e[e.length-1]&&function(e){return t=>e(...t)}(e.pop()),n=(e=e.map(g)).map(m),s=e.length-1,r=new Array(s+1).fill(0),o=[];if(s<0||n.some(h))return o;for(;;){o.push(r.map(((t,n)=>e[n][t])));let i=s;for(;++r[i]===n[i];){if(0===i)return t?o.map(t):o;r[i--]=0}}}function b(e,t){var n=0,s=0;return Float64Array.from(e,void 0===t?e=>n+=+e||0:r=>n+=+t(r,s++,e)||0)}var v=n(788);function w(e,t){let n,s=0,r=0,o=0;if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&(n=t-r,r+=n/++s,o+=n*(t-r));else{let i=-1;for(let a of e)null!=(a=t(a,++i,e))&&(a=+a)>=a&&(n=a-r,r+=n/++s,o+=n*(a-r))}if(s>1)return o/(s-1)}function _(e,t){const n=w(e,t);return n?Math.sqrt(n):n}function k(e,t){let n,s;if(void 0===t)for(const t of e)null!=t&&(void 0===n?t>=t&&(n=s=t):(n>t&&(n=t),s<t&&(s=t)));else{let r=-1;for(let o of e)null!=(o=t(o,++r,e))&&(void 0===n?o>=o&&(n=s=o):(n>o&&(n=o),s<o&&(s=o)))}return[n,s]}class q{constructor(){this._partials=new Float64Array(32),this._n=0}add(e){const t=this._partials;let n=0;for(let s=0;s<this._n&&s<32;s++){const r=t[s],o=e+r,i=Math.abs(e)<Math.abs(r)?e-(o-r):r-(o-e);i&&(t[n++]=i),e=o}return t[n]=e,this._n=n+1,this}valueOf(){const e=this._partials;let t,n,s,r=this._n,o=0;if(r>0){for(o=e[--r];r>0&&(t=o,n=e[--r],o=t+n,s=n-(o-t),!s););r>0&&(s<0&&e[r-1]<0||s>0&&e[r-1]>0)&&(n=2*s,t=o+n,n==t-o&&(o=t))}return o}}function x(e,t){const n=new q;if(void 0===t)for(let t of e)(t=+t)&&n.add(t);else{let s=-1;for(let r of e)(r=+t(r,++s,e))&&n.add(r)}return+n}function N(e,t){const n=new q;let s=-1;return Float64Array.from(e,void 0===t?e=>n.add(+e||0):r=>n.add(+t(r,++s,e)||0))}var S=n(8828);function A(e){return e}function C(e,...t){return D(e,A,A,t)}function j(e,...t){return D(e,Array.from,A,t)}function T(e,t){for(let n=1,s=t.length;n<s;++n)e=e.flatMap((e=>e.pop().map((([t,n])=>[...e,t,n]))));return e}function M(e,...t){return T(j(e,...t),t)}function O(e,t,...n){return T(E(e,t,...n),n)}function I(e,t,...n){return D(e,A,t,n)}function E(e,t,...n){return D(e,Array.from,t,n)}function R(e,...t){return D(e,A,$,t)}function F(e,...t){return D(e,Array.from,$,t)}function $(e){if(1!==e.length)throw new Error("duplicate key");return e[0]}function D(e,t,n,s){return function e(r,o){if(o>=s.length)return n(r);const i=new S.L,a=s[o++];let l=-1;for(const e of r){const t=a(e,++l,r),n=i.get(t);n?n.push(e):i.set(t,[e])}for(const[t,n]of i)i.set(t,e(n,o));return t(i)}(e,0)}function L(e,t){return Array.from(t,(t=>e[t]))}function P(e,...t){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");e=Array.from(e);let[n]=t;if(n&&2!==n.length||t.length>1){const s=Uint32Array.from(e,((e,t)=>t));return t.length>1?(t=t.map((t=>e.map(t))),s.sort(((e,n)=>{for(const s of t){const t=U(s[e],s[n]);if(t)return t}}))):(n=e.map(n),s.sort(((e,t)=>U(n[e],n[t])))),L(e,s)}return e.sort(G(n))}function G(e=r.Z){if(e===r.Z)return U;if("function"!=typeof e)throw new TypeError("compare is not a function");return(t,n)=>{const s=e(t,n);return s||0===s?s:(0===e(n,n))-(0===e(t,t))}}function U(e,t){return(null==e||!(e>=e))-(null==t||!(t>=t))||(e<t?-1:e>t?1:0)}function B(e,t,n){return(2!==t.length?P(I(e,t,n),(([e,t],[n,s])=>(0,r.Z)(t,s)||(0,r.Z)(e,n))):P(C(e,n),(([e,n],[s,o])=>t(n,o)||(0,r.Z)(e,s)))).map((([e])=>e))}var z=Array.prototype,J=z.slice;z.map;function H(e){return()=>e}var W=n(6106);function V(e,t,n){let s;for(;;){const r=(0,W.G9)(e,t,n);if(r===s||0===r||!isFinite(r))return[e,t];r>0?(e=Math.floor(e/r)*r,t=Math.ceil(t/r)*r):r<0&&(e=Math.ceil(e*r)/r,t=Math.floor(t*r)/r),s=r}}function Z(e){return Math.ceil(Math.log(p(e))/Math.LN2)+1}function K(){var e=A,t=k,n=Z;function r(r){Array.isArray(r)||(r=Array.from(r));var o,i,a,l=r.length,c=new Array(l);for(o=0;o<l;++o)c[o]=e(r[o],o,r);var u=t(c),f=u[0],d=u[1],p=n(c,f,d);if(!Array.isArray(p)){const e=d,n=+p;if(t===k&&([f,d]=V(f,d,n)),(p=(0,W.ZP)(f,d,n))[0]<=f&&(a=(0,W.G9)(f,d,n)),p[p.length-1]>=d)if(e>=d&&t===k){const e=(0,W.G9)(f,d,n);isFinite(e)&&(e>0?d=(Math.floor(d/e)+1)*e:e<0&&(d=(Math.ceil(d*-e)+1)/-e))}else p.pop()}for(var m=p.length;p[0]<=f;)p.shift(),--m;for(;p[m-1]>d;)p.pop(),--m;var h,g=new Array(m+1);for(o=0;o<=m;++o)(h=g[o]=[]).x0=o>0?p[o-1]:f,h.x1=o<m?p[o]:d;if(isFinite(a)){if(a>0)for(o=0;o<l;++o)null!=(i=c[o])&&f<=i&&i<=d&&g[Math.min(m,Math.floor((i-f)/a))].push(r[o]);else if(a<0)for(o=0;o<l;++o)if(null!=(i=c[o])&&f<=i&&i<=d){const e=Math.floor((f-i)*a);g[Math.min(m,e+(p[e]<=i))].push(r[o])}}else for(o=0;o<l;++o)null!=(i=c[o])&&f<=i&&i<=d&&g[(0,s.ZP)(p,i,0,m)].push(r[o]);return g}return r.value=function(t){return arguments.length?(e="function"==typeof t?t:H(t),r):e},r.domain=function(e){return arguments.length?(t="function"==typeof e?e:H([e[0],e[1]]),r):t},r.thresholds=function(e){return arguments.length?(n="function"==typeof e?e:Array.isArray(e)?H(J.call(e)):H(e),r):n},r}function X(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n<t||void 0===n&&t>=t)&&(n=t);else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&(n<r||void 0===n&&r>=r)&&(n=r)}return n}function Y(e,t){let n,s=-1,r=-1;if(void 0===t)for(const t of e)++r,null!=t&&(n<t||void 0===n&&t>=t)&&(n=t,s=r);else for(let o of e)null!=(o=t(o,++r,e))&&(n<o||void 0===n&&o>=o)&&(n=o,s=r);return s}function Q(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function ee(e,t){let n,s=-1,r=-1;if(void 0===t)for(const t of e)++r,null!=t&&(n>t||void 0===n&&t>=t)&&(n=t,s=r);else for(let o of e)null!=(o=t(o,++r,e))&&(n>o||void 0===n&&o>=o)&&(n=o,s=r);return s}function te(e,t,n=0,s=e.length-1,r){for(r=void 0===r?U:G(r);s>n;){if(s-n>600){const o=s-n+1,i=t-n+1,a=Math.log(o),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(o-l)/o)*(i-o/2<0?-1:1);te(e,t,Math.max(n,Math.floor(t-i*l/o+c)),Math.min(s,Math.floor(t+(o-i)*l/o+c)),r)}const o=e[t];let i=n,a=s;for(ne(e,n,t),r(e[s],o)>0&&ne(e,n,s);i<a;){for(ne(e,i,a),++i,--a;r(e[i],o)<0;)++i;for(;r(e[a],o)>0;)--a}0===r(e[n],o)?ne(e,n,a):(++a,ne(e,a,s)),a<=t&&(n=a+1),t<=a&&(s=a-1)}return e}function ne(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}var se=n(3745);function re(e,t=r.Z){let n,s=!1;if(1===t.length){let o;for(const i of e){const e=t(i);(s?(0,r.Z)(e,o)>0:0===(0,r.Z)(e,e))&&(n=i,o=e,s=!0)}}else for(const r of e)(s?t(r,n)>0:0===t(r,r))&&(n=r,s=!0);return n}function oe(e,t,n){if(s=(e=Float64Array.from((0,se.K)(e,n))).length){if((t=+t)<=0||s<2)return Q(e);if(t>=1)return X(e);var s,r=(s-1)*t,o=Math.floor(r),i=X(te(e,o).subarray(0,o+1));return i+(Q(e.subarray(o+1))-i)*(r-o)}}function ie(e,t,n=se.Z){if(s=e.length){if((t=+t)<=0||s<2)return+n(e[0],0,e);if(t>=1)return+n(e[s-1],s-1,e);var s,r=(s-1)*t,o=Math.floor(r),i=+n(e[o],o,e);return i+(+n(e[o+1],o+1,e)-i)*(r-o)}}function ae(e,t,n){if(s=(e=Float64Array.from((0,se.K)(e,n))).length){if((t=+t)<=0||s<2)return ee(e);if(t>=1)return Y(e);var s,r=Math.floor((s-1)*t),o=te(Uint32Array.from(e,((e,t)=>t)),r,0,s-1,((t,n)=>U(e[t],e[n])));return re(o.subarray(0,r+1),(t=>e[t]))}}function le(e,t,n){return Math.ceil((n-t)/(2*(oe(e,.75)-oe(e,.25))*Math.pow(p(e),-1/3)))}function ce(e,t,n){return Math.ceil((n-t)*Math.cbrt(p(e))/(3.49*_(e)))}function ue(e,t){let n=0,s=0;if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&(++n,s+=t);else{let r=-1;for(let o of e)null!=(o=t(o,++r,e))&&(o=+o)>=o&&(++n,s+=o)}if(n)return s/n}function fe(e,t){return oe(e,.5,t)}function de(e,t){return ae(e,.5,t)}function pe(e){return Array.from(function*(e){for(const t of e)yield*t}(e))}function me(e,t){const n=new S.L;if(void 0===t)for(let t of e)null!=t&&t>=t&&n.set(t,(n.get(t)||0)+1);else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&r>=r&&n.set(r,(n.get(r)||0)+1)}let s,r=0;for(const[e,t]of n)t>r&&(r=t,s=e);return s}function he(e,t=ge){const n=[];let s,r=!1;for(const o of e)r&&n.push(t(s,o)),s=o,r=!0;return n}function ge(e,t){return[e,t]}function ye(e,t,n){e=+e,t=+t,n=(r=arguments.length)<2?(t=e,e=0,1):r<3?1:+n;for(var s=-1,r=0|Math.max(0,Math.ceil((t-e)/n)),o=new Array(r);++s<r;)o[s]=e+s*n;return o}function be(e,t=r.Z){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");let n=Array.from(e);const s=new Float64Array(n.length);2!==t.length&&(n=n.map(t),t=r.Z);const o=(e,s)=>t(n[e],n[s]);let i,a;return Uint32Array.from(n,((e,t)=>t)).sort(t===r.Z?(e,t)=>U(n[e],n[t]):G(o)).forEach(((e,t)=>{const n=o(e,void 0===i?e:i);n>=0?((void 0===i||n>0)&&(i=e,a=t),s[e]=a):s[e]=NaN})),s}function ve(e,t=r.Z){let n,s=!1;if(1===t.length){let o;for(const i of e){const e=t(i);(s?(0,r.Z)(e,o)<0:0===(0,r.Z)(e,e))&&(n=i,o=e,s=!0)}}else for(const r of e)(s?t(r,n)<0:0===t(r,r))&&(n=r,s=!0);return n}function we(e,t=r.Z){if(1===t.length)return ee(e,t);let n,s=-1,o=-1;for(const r of e)++o,(s<0?0===t(r,r):t(r,n)<0)&&(n=r,s=o);return s}function _e(e,t=r.Z){if(1===t.length)return Y(e,t);let n,s=-1,o=-1;for(const r of e)++o,(s<0?0===t(r,r):t(r,n)>0)&&(n=r,s=o);return s}function ke(e,t){const n=we(e,t);return n<0?void 0:n}const qe=xe(Math.random);function xe(e){return function(t,n=0,s=t.length){let r=s-(n=+n);for(;r;){const s=e()*r--|0,o=t[r+n];t[r+n]=t[s+n],t[s+n]=o}return t}}function Ne(e,t){let n=0;if(void 0===t)for(let t of e)(t=+t)&&(n+=t);else{let s=-1;for(let r of e)(r=+t(r,++s,e))&&(n+=r)}return n}function Se(e){if(!(r=e.length))return[];for(var t=-1,n=Q(e,Ae),s=new Array(n);++t<n;)for(var r,o=-1,i=s[t]=new Array(r);++o<r;)i[o]=e[o][t];return s}function Ae(e){return e.length}function Ce(){return Se(arguments)}function je(e,t){if("function"!=typeof t)throw new TypeError("test is not a function");let n=-1;for(const s of e)if(!t(s,++n,e))return!1;return!0}function Te(e,t){if("function"!=typeof t)throw new TypeError("test is not a function");let n=-1;for(const s of e)if(t(s,++n,e))return!0;return!1}function Me(e,t){if("function"!=typeof t)throw new TypeError("test is not a function");const n=[];let s=-1;for(const r of e)t(r,++s,e)&&n.push(r);return n}function Oe(e,t){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof t)throw new TypeError("mapper is not a function");return Array.from(e,((n,s)=>t(n,s,e)))}function Ie(e,t,n){if("function"!=typeof t)throw new TypeError("reducer is not a function");const s=e[Symbol.iterator]();let r,o,i=-1;if(arguments.length<3){if(({done:r,value:n}=s.next()),r)return;++i}for(;({done:r,value:o}=s.next()),!r;)n=t(n,o,++i,e);return n}function Ee(e){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(e).reverse()}function Re(e,...t){e=new S.H(e);for(const n of t)for(const t of n)e.delete(t);return e}function Fe(e,t){const n=t[Symbol.iterator](),s=new S.H;for(const t of e){if(s.has(t))return!1;let e,r;for(;({value:e,done:r}=n.next())&&!r;){if(Object.is(t,e))return!1;s.add(e)}}return!0}function $e(e,...t){e=new S.H(e),t=t.map(De);e:for(const n of e)for(const s of t)if(!s.has(n)){e.delete(n);continue e}return e}function De(e){return e instanceof S.H?e:new S.H(e)}function Le(e,t){const n=e[Symbol.iterator](),s=new Set;for(const e of t){const t=Pe(e);if(s.has(t))continue;let r,o;for(;({value:r,done:o}=n.next());){if(o)return!1;const e=Pe(r);if(s.add(e),Object.is(t,e))break}}return!0}function Pe(e){return null!==e&&"object"==typeof e?e.valueOf():e}function Ge(e,t){return Le(t,e)}function Ue(...e){const t=new S.H;for(const n of e)for(const e of n)t.add(e);return t}},3745:(e,t,n)=>{"use strict";function s(e){return null===e?NaN:+e}function*r(e,t){if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&(yield t);else{let n=-1;for(let s of e)null!=(s=t(s,++n,e))&&(s=+s)>=s&&(yield s)}}n.d(t,{K:()=>r,Z:()=>s})},6106:(e,t,n)=>{"use strict";n.d(t,{G9:()=>a,ZP:()=>i,ly:()=>l});var s=Math.sqrt(50),r=Math.sqrt(10),o=Math.sqrt(2);function i(e,t,n){var s,r,o,i,l=-1;if(n=+n,(e=+e)===(t=+t)&&n>0)return[e];if((s=t<e)&&(r=e,e=t,t=r),0===(i=a(e,t,n))||!isFinite(i))return[];if(i>0){let n=Math.round(e/i),s=Math.round(t/i);for(n*i<e&&++n,s*i>t&&--s,o=new Array(r=s-n+1);++l<r;)o[l]=(n+l)*i}else{i=-i;let n=Math.round(e*i),s=Math.round(t*i);for(n/i<e&&++n,s/i>t&&--s,o=new Array(r=s-n+1);++l<r;)o[l]=(n+l)/i}return s&&o.reverse(),o}function a(e,t,n){var i=(t-e)/Math.max(0,n),a=Math.floor(Math.log(i)/Math.LN10),l=i/Math.pow(10,a);return a>=0?(l>=s?10:l>=r?5:l>=o?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=s?10:l>=r?5:l>=o?2:1)}function l(e,t,n){var i=Math.abs(t-e)/Math.max(0,n),a=Math.pow(10,Math.floor(Math.log(i)/Math.LN10)),l=i/a;return l>=s?a*=10:l>=r?a*=5:l>=o&&(a*=2),t<e?-a:a}},1696:(e,t,n)=>{"use strict";function s(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function r(e,t){var n=Object.create(e.prototype);for(var s in t)n[s]=t[s];return n}function o(){}n.d(t,{ZP:()=>_,B8:()=>x});var i=.7,a=1/i,l="\\s*([+-]?\\d+)\\s*",c="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",u="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",f=/^#([0-9a-f]{3,8})$/,d=new RegExp(`^rgb\\(${l},${l},${l}\\)$`),p=new RegExp(`^rgb\\(${u},${u},${u}\\)$`),m=new RegExp(`^rgba\\(${l},${l},${l},${c}\\)$`),h=new RegExp(`^rgba\\(${u},${u},${u},${c}\\)$`),g=new RegExp(`^hsl\\(${c},${u},${u}\\)$`),y=new RegExp(`^hsla\\(${c},${u},${u},${c}\\)$`),b={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function v(){return this.rgb().formatHex()}function w(){return this.rgb().formatRgb()}function _(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=f.exec(e))?(n=t[1].length,t=parseInt(t[1],16),6===n?k(t):3===n?new N(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===n?q(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===n?q(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=d.exec(e))?new N(t[1],t[2],t[3],1):(t=p.exec(e))?new N(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=m.exec(e))?q(t[1],t[2],t[3],t[4]):(t=h.exec(e))?q(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=g.exec(e))?M(t[1],t[2]/100,t[3]/100,1):(t=y.exec(e))?M(t[1],t[2]/100,t[3]/100,t[4]):b.hasOwnProperty(e)?k(b[e]):"transparent"===e?new N(NaN,NaN,NaN,0):null}function k(e){return new N(e>>16&255,e>>8&255,255&e,1)}function q(e,t,n,s){return s<=0&&(e=t=n=NaN),new N(e,t,n,s)}function x(e,t,n,s){return 1===arguments.length?((r=e)instanceof o||(r=_(r)),r?new N((r=r.rgb()).r,r.g,r.b,r.opacity):new N):new N(e,t,n,null==s?1:s);var r}function N(e,t,n,s){this.r=+e,this.g=+t,this.b=+n,this.opacity=+s}function S(){return`#${T(this.r)}${T(this.g)}${T(this.b)}`}function A(){const e=C(this.opacity);return`${1===e?"rgb(":"rgba("}${j(this.r)}, ${j(this.g)}, ${j(this.b)}${1===e?")":`, ${e})`}`}function C(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function j(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function T(e){return((e=j(e))<16?"0":"")+e.toString(16)}function M(e,t,n,s){return s<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new I(e,t,n,s)}function O(e){if(e instanceof I)return new I(e.h,e.s,e.l,e.opacity);if(e instanceof o||(e=_(e)),!e)return new I;if(e instanceof I)return e;var t=(e=e.rgb()).r/255,n=e.g/255,s=e.b/255,r=Math.min(t,n,s),i=Math.max(t,n,s),a=NaN,l=i-r,c=(i+r)/2;return l?(a=t===i?(n-s)/l+6*(n<s):n===i?(s-t)/l+2:(t-n)/l+4,l/=c<.5?i+r:2-i-r,a*=60):l=c>0&&c<1?0:a,new I(a,l,c,e.opacity)}function I(e,t,n,s){this.h=+e,this.s=+t,this.l=+n,this.opacity=+s}function E(e){return(e=(e||0)%360)<0?e+360:e}function R(e){return Math.max(0,Math.min(1,e||0))}function F(e,t,n){return 255*(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)}s(o,_,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:v,formatHex:v,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return O(this).formatHsl()},formatRgb:w,toString:w}),s(N,x,r(o,{brighter(e){return e=null==e?a:Math.pow(a,e),new N(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?i:Math.pow(i,e),new N(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new N(j(this.r),j(this.g),j(this.b),C(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:S,formatHex:S,formatHex8:function(){return`#${T(this.r)}${T(this.g)}${T(this.b)}${T(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:A,toString:A})),s(I,(function(e,t,n,s){return 1===arguments.length?O(e):new I(e,t,n,null==s?1:s)}),r(o,{brighter(e){return e=null==e?a:Math.pow(a,e),new I(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?i:Math.pow(i,e),new I(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,s=n+(n<.5?n:1-n)*t,r=2*n-s;return new N(F(e>=240?e-240:e+120,r,s),F(e,r,s),F(e<120?e+240:e-120,r,s),this.opacity)},clamp(){return new I(E(this.h),R(this.s),R(this.l),C(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=C(this.opacity);return`${1===e?"hsl(":"hsla("}${E(this.h)}, ${100*R(this.s)}%, ${100*R(this.l)}%${1===e?")":`, ${e})`}`}}))},670:(e,t,n)=>{"use strict";n.d(t,{WU:()=>f,jH:()=>d});var s=n(2313);var r=n(7259);var o,i=n(4218);function a(e,t){var n=(0,i.V)(e,t);if(!n)return e+"";var s=n[0],r=n[1];return r<0?"0."+new Array(-r).join("0")+s:s.length>r+1?s.slice(0,r+1)+"."+s.slice(r+1):s+new Array(r-s.length+2).join("0")}const l={"%":(e,t)=>(100*e).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:i.Z,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>a(100*e,t),r:a,s:function(e,t){var n=(0,i.V)(e,t);if(!n)return e+"";var s=n[0],r=n[1],a=r-(o=3*Math.max(-8,Math.min(8,Math.floor(r/3))))+1,l=s.length;return a===l?s:a>l?s+new Array(a-l+1).join("0"):a>0?s.slice(0,a)+"."+s.slice(a):"0."+new Array(1-a).join("0")+(0,i.V)(e,Math.max(0,t+a-1))[0]},X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function c(e){return e}var u,f,d,p=Array.prototype.map,m=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function h(e){var t,n,i=void 0===e.grouping||void 0===e.thousands?c:(t=p.call(e.grouping,Number),n=e.thousands+"",function(e,s){for(var r=e.length,o=[],i=0,a=t[0],l=0;r>0&&a>0&&(l+a+1>s&&(a=Math.max(1,s-l)),o.push(e.substring(r-=a,r+a)),!((l+=a+1)>s));)a=t[i=(i+1)%t.length];return o.reverse().join(n)}),a=void 0===e.currency?"":e.currency[0]+"",u=void 0===e.currency?"":e.currency[1]+"",f=void 0===e.decimal?".":e.decimal+"",d=void 0===e.numerals?c:function(e){return function(t){return t.replace(/[0-9]/g,(function(t){return e[+t]}))}}(p.call(e.numerals,String)),h=void 0===e.percent?"%":e.percent+"",g=void 0===e.minus?"−":e.minus+"",y=void 0===e.nan?"NaN":e.nan+"";function b(e){var t=(e=(0,r.Z)(e)).fill,n=e.align,s=e.sign,c=e.symbol,p=e.zero,b=e.width,v=e.comma,w=e.precision,_=e.trim,k=e.type;"n"===k?(v=!0,k="g"):l[k]||(void 0===w&&(w=12),_=!0,k="g"),(p||"0"===t&&"="===n)&&(p=!0,t="0",n="=");var q="$"===c?a:"#"===c&&/[boxX]/.test(k)?"0"+k.toLowerCase():"",x="$"===c?u:/[%p]/.test(k)?h:"",N=l[k],S=/[defgprs%]/.test(k);function A(e){var r,a,l,c=q,u=x;if("c"===k)u=N(e)+u,e="";else{var h=(e=+e)<0||1/e<0;if(e=isNaN(e)?y:N(Math.abs(e),w),_&&(e=function(e){e:for(var t,n=e.length,s=1,r=-1;s<n;++s)switch(e[s]){case".":r=t=s;break;case"0":0===r&&(r=s),t=s;break;default:if(!+e[s])break e;r>0&&(r=0)}return r>0?e.slice(0,r)+e.slice(t+1):e}(e)),h&&0==+e&&"+"!==s&&(h=!1),c=(h?"("===s?s:g:"-"===s||"("===s?"":s)+c,u=("s"===k?m[8+o/3]:"")+u+(h&&"("===s?")":""),S)for(r=-1,a=e.length;++r<a;)if(48>(l=e.charCodeAt(r))||l>57){u=(46===l?f+e.slice(r+1):e.slice(r))+u,e=e.slice(0,r);break}}v&&!p&&(e=i(e,1/0));var A=c.length+e.length+u.length,C=A<b?new Array(b-A+1).join(t):"";switch(v&&p&&(e=i(C+e,C.length?b-u.length:1/0),C=""),n){case"<":e=c+e+u+C;break;case"=":e=c+C+e+u;break;case"^":e=C.slice(0,A=C.length>>1)+c+e+u+C.slice(A);break;default:e=C+c+e+u}return d(e)}return w=void 0===w?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w)),A.toString=function(){return e+""},A}return{format:b,formatPrefix:function(e,t){var n=b(((e=(0,r.Z)(e)).type="f",e)),o=3*Math.max(-8,Math.min(8,Math.floor((0,s.Z)(t)/3))),i=Math.pow(10,-o),a=m[8+o/3];return function(e){return n(i*e)+a}}}}u=h({thousands:",",grouping:[3],currency:["$",""]}),f=u.format,d=u.formatPrefix},2313:(e,t,n)=>{"use strict";n.d(t,{Z:()=>r});var s=n(4218);function r(e){return(e=(0,s.V)(Math.abs(e)))?e[1]:NaN}},4218:(e,t,n)=>{"use strict";function s(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function r(e,t){if((n=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"))<0)return null;var n,s=e.slice(0,n);return[s.length>1?s[0]+s.slice(2):s,+e.slice(n+1)]}n.d(t,{V:()=>r,Z:()=>s})},7259:(e,t,n)=>{"use strict";n.d(t,{Z:()=>r});var s=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function r(e){if(!(t=s.exec(e)))throw new Error("invalid format: "+e);var t;return new o({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}function o(e){this.fill=void 0===e.fill?" ":e.fill+"",this.align=void 0===e.align?">":e.align+"",this.sign=void 0===e.sign?"-":e.sign+"",this.symbol=void 0===e.symbol?"":e.symbol+"",this.zero=!!e.zero,this.width=void 0===e.width?void 0:+e.width,this.comma=!!e.comma,this.precision=void 0===e.precision?void 0:+e.precision,this.trim=!!e.trim,this.type=void 0===e.type?"":e.type+""}r.prototype=o.prototype,o.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},8486:(e,t,n)=>{"use strict";n.d(t,{Z:()=>s});const s=e=>()=>e},8403:(e,t,n)=>{"use strict";function s(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}n.d(t,{Z:()=>s})},4314:(e,t,n)=>{"use strict";n.d(t,{ZP:()=>c});var s=n(1696);function r(e,t,n,s,r){var o=e*e,i=o*e;return((1-3*e+3*o-i)*t+(4-6*o+3*i)*n+(1+3*e+3*o-3*i)*s+i*r)/6}var o=n(8486);function i(e,t){return function(n){return e+n*t}}function a(e){return 1==(e=+e)?l:function(t,n){return n-t?function(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(s){return Math.pow(e+s*t,n)}}(t,n,e):(0,o.Z)(isNaN(t)?n:t)}}function l(e,t){var n=t-e;return n?i(e,n):(0,o.Z)(isNaN(e)?t:e)}const c=function e(t){var n=a(t);function r(e,t){var r=n((e=(0,s.B8)(e)).r,(t=(0,s.B8)(t)).r),o=n(e.g,t.g),i=n(e.b,t.b),a=l(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=o(t),e.b=i(t),e.opacity=a(t),e+""}}return r.gamma=e,r}(1);function u(e){return function(t){var n,r,o=t.length,i=new Array(o),a=new Array(o),l=new Array(o);for(n=0;n<o;++n)r=(0,s.B8)(t[n]),i[n]=r.r||0,a[n]=r.g||0,l[n]=r.b||0;return i=e(i),a=e(a),l=e(l),r.opacity=1,function(e){return r.r=i(e),r.g=a(e),r.b=l(e),r+""}}}u((function(e){var t=e.length-1;return function(n){var s=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),o=e[s],i=e[s+1],a=s>0?e[s-1]:2*o-i,l=s<t-1?e[s+2]:2*i-o;return r((n-s/t)*t,a,o,i,l)}})),u((function(e){var t=e.length;return function(n){var s=Math.floor(((n%=1)<0?++n:n)*t),o=e[(s+t-1)%t],i=e[s%t],a=e[(s+1)%t],l=e[(s+2)%t];return r((n-s/t)*t,o,i,a,l)}}))},9009:(e,t,n)=>{"use strict";n.d(t,{Z:()=>i});var s=n(8403),r=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,o=new RegExp(r.source,"g");function i(e,t){var n,i,a,l=r.lastIndex=o.lastIndex=0,c=-1,u=[],f=[];for(e+="",t+="";(n=r.exec(e))&&(i=o.exec(t));)(a=i.index)>l&&(a=t.slice(l,a),u[c]?u[c]+=a:u[++c]=a),(n=n[0])===(i=i[0])?u[c]?u[c]+=i:u[++c]=i:(u[++c]=null,f.push({i:c,x:(0,s.Z)(n,i)})),l=o.lastIndex;return l<t.length&&(a=t.slice(l),u[c]?u[c]+=a:u[++c]=a),u.length<2?f[0]?function(e){return function(t){return e(t)+""}}(f[0].x):function(e){return function(){return e}}(t):(t=f.length,function(e){for(var n,s=0;s<t;++s)u[(n=f[s]).i]=n.x(e);return u.join("")})}},4090:(e,t,n)=>{"use strict";function s(e){for(var t=e.length/6|0,n=new Array(t),s=0;s<t;)n[s]="#"+e.slice(6*s,6*++s);return n}n.d(t,{Z:()=>s})},6169:(e,t,n)=>{"use strict";n.d(t,{JG:()=>_,ZP:()=>q,l4:()=>k});var s=n(5519),r=n(1696),o=n(4314);function i(e,t){var n,s=t?t.length:0,r=e?Math.min(s,e.length):0,o=new Array(r),i=new Array(s);for(n=0;n<r;++n)o[n]=p(e[n],t[n]);for(;n<s;++n)i[n]=t[n];return function(e){for(n=0;n<r;++n)i[n]=o[n](e);return i}}function a(e,t){var n=new Date;return e=+e,t=+t,function(s){return n.setTime(e*(1-s)+t*s),n}}var l=n(8403);function c(e,t){var n,s={},r={};for(n in null!==e&&"object"==typeof e||(e={}),null!==t&&"object"==typeof t||(t={}),t)n in e?s[n]=p(e[n],t[n]):r[n]=t[n];return function(e){for(n in s)r[n]=s[n](e);return r}}var u=n(9009),f=n(8486);function d(e,t){t||(t=[]);var n,s=e?Math.min(t.length,e.length):0,r=t.slice();return function(o){for(n=0;n<s;++n)r[n]=e[n]*(1-o)+t[n]*o;return r}}function p(e,t){var n,s,p=typeof t;return null==t||"boolean"===p?(0,f.Z)(t):("number"===p?l.Z:"string"===p?(n=(0,r.ZP)(t))?(t=n,o.ZP):u.Z:t instanceof r.ZP?o.ZP:t instanceof Date?a:(s=t,!ArrayBuffer.isView(s)||s instanceof DataView?Array.isArray(t)?i:"function"!=typeof t.valueOf&&"function"!=typeof t.toString||isNaN(t)?c:l.Z:d))(e,t)}function m(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}function h(e){return+e}var g=[0,1];function y(e){return e}function b(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:(n=isNaN(t)?NaN:.5,function(){return n});var n}function v(e,t,n){var s=e[0],r=e[1],o=t[0],i=t[1];return r<s?(s=b(r,s),o=n(i,o)):(s=b(s,r),o=n(o,i)),function(e){return o(s(e))}}function w(e,t,n){var r=Math.min(e.length,t.length)-1,o=new Array(r),i=new Array(r),a=-1;for(e[r]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++a<r;)o[a]=b(e[a],e[a+1]),i[a]=n(t[a],t[a+1]);return function(t){var n=(0,s.ZP)(e,t,1,r)-1;return i[n](o[n](t))}}function _(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function k(){var e,t,n,s,r,o,i=g,a=g,c=p,u=y;function f(){var e,t,n,l=Math.min(i.length,a.length);return u!==y&&(e=i[0],t=i[l-1],e>t&&(n=e,e=t,t=n),u=function(n){return Math.max(e,Math.min(t,n))}),s=l>2?w:v,r=o=null,d}function d(t){return null==t||isNaN(t=+t)?n:(r||(r=s(i.map(e),a,c)))(e(u(t)))}return d.invert=function(n){return u(t((o||(o=s(a,i.map(e),l.Z)))(n)))},d.domain=function(e){return arguments.length?(i=Array.from(e,h),f()):i.slice()},d.range=function(e){return arguments.length?(a=Array.from(e),f()):a.slice()},d.rangeRound=function(e){return a=Array.from(e),c=m,f()},d.clamp=function(e){return arguments.length?(u=!!e||y,f()):u!==y},d.interpolate=function(e){return arguments.length?(c=e,f()):c},d.unknown=function(e){return arguments.length?(n=e,d):n},function(n,s){return e=n,t=s,f()}}function q(){return k()(y,y)}},2998:(e,t,n)=>{"use strict";function s(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}n.d(t,{o:()=>s})},8877:(e,t,n)=>{"use strict";n.d(t,{Z:()=>u});var s=n(6106),r=n(6169),o=n(2998),i=n(7259),a=n(2313);var l=n(670);function c(e,t,n,r){var o,c=(0,s.ly)(e,t,n);switch((r=(0,i.Z)(null==r?",f":r)).type){case"s":var u=Math.max(Math.abs(e),Math.abs(t));return null!=r.precision||isNaN(o=function(e,t){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,a.Z)(t)/3)))-(0,a.Z)(Math.abs(e)))}(c,u))||(r.precision=o),(0,l.jH)(r,u);case"":case"e":case"g":case"p":case"r":null!=r.precision||isNaN(o=function(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,(0,a.Z)(t)-(0,a.Z)(e))+1}(c,Math.max(Math.abs(e),Math.abs(t))))||(r.precision=o-("e"===r.type));break;case"f":case"%":null!=r.precision||isNaN(o=function(e){return Math.max(0,-(0,a.Z)(Math.abs(e)))}(c))||(r.precision=o-2*("%"===r.type))}return(0,l.WU)(r)}function u(){var e=(0,r.ZP)();return e.copy=function(){return(0,r.JG)(e,u())},o.o.apply(e,arguments),function(e){var t=e.domain;return e.ticks=function(e){var n=t();return(0,s.ZP)(n[0],n[n.length-1],null==e?10:e)},e.tickFormat=function(e,n){var s=t();return c(s[0],s[s.length-1],null==e?10:e,n)},e.nice=function(n){null==n&&(n=10);var r,o,i=t(),a=0,l=i.length-1,c=i[a],u=i[l],f=10;for(u<c&&(o=c,c=u,u=o,o=a,a=l,l=o);f-- >0;){if((o=(0,s.G9)(c,u,n))===r)return i[a]=c,i[l]=u,t(i);if(o>0)c=Math.floor(c/o)*o,u=Math.ceil(u/o)*o;else{if(!(o<0))break;c=Math.ceil(c*o)/o,u=Math.floor(u*o)/o}r=o}return e},e}(e)}},5540:(e,t,n)=>{"use strict";n.d(t,{Z:()=>i});var s=n(8828),r=n(2998);const o=Symbol("implicit");function i(){var e=new s.L,t=[],n=[],a=o;function l(s){let r=e.get(s);if(void 0===r){if(a!==o)return a;e.set(s,r=t.push(s)-1)}return n[r%n.length]}return l.domain=function(n){if(!arguments.length)return t.slice();t=[],e=new s.L;for(const s of n)e.has(s)||e.set(s,t.push(s)-1);return l},l.range=function(e){return arguments.length?(n=Array.from(e),l):n.slice()},l.unknown=function(e){return arguments.length?(a=e,l):a},l.copy=function(){return i(t,n).unknown(a)},r.o.apply(l,arguments),l}},1868:(e,t,n)=>{"use strict";n.d(t,{Wem:()=>s.extent,J69:()=>s.mean,BYU:()=>Ut.Z,p2C:()=>tn,XgA:()=>sn,xHP:()=>rn});var s=n(9724);function r(){}function o(e){return null==e?r:function(){return this.querySelector(e)}}function i(){return[]}function a(e){return null==e?i:function(){return this.querySelectorAll(e)}}function l(e){return function(){return null==(t=e.apply(this,arguments))?[]:Array.isArray(t)?t:Array.from(t);var t}}function c(e){return function(){return this.matches(e)}}function u(e){return function(t){return t.matches(e)}}var f=Array.prototype.find;function d(){return this.firstElementChild}var p=Array.prototype.filter;function m(){return Array.from(this.children)}function h(e){return new Array(e.length)}function g(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function y(e,t,n,s,r,o){for(var i,a=0,l=t.length,c=o.length;a<c;++a)(i=t[a])?(i.__data__=o[a],s[a]=i):n[a]=new g(e,o[a]);for(;a<l;++a)(i=t[a])&&(r[a]=i)}function b(e,t,n,s,r,o,i){var a,l,c,u=new Map,f=t.length,d=o.length,p=new Array(f);for(a=0;a<f;++a)(l=t[a])&&(p[a]=c=i.call(l,l.__data__,a,t)+"",u.has(c)?r[a]=l:u.set(c,l));for(a=0;a<d;++a)c=i.call(e,o[a],a,o)+"",(l=u.get(c))?(s[a]=l,l.__data__=o[a],u.delete(c)):n[a]=new g(e,o[a]);for(a=0;a<f;++a)(l=t[a])&&u.get(p[a])===l&&(r[a]=l)}function v(e){return e.__data__}function w(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function _(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}g.prototype={constructor:g,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};var k="http://www.w3.org/1999/xhtml";const q={svg:"http://www.w3.org/2000/svg",xhtml:k,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function x(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),q.hasOwnProperty(t)?{space:q[t],local:e}:e}function N(e){return function(){this.removeAttribute(e)}}function S(e){return function(){this.removeAttributeNS(e.space,e.local)}}function A(e,t){return function(){this.setAttribute(e,t)}}function C(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function j(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function T(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function M(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function O(e){return function(){this.style.removeProperty(e)}}function I(e,t,n){return function(){this.style.setProperty(e,t,n)}}function E(e,t,n){return function(){var s=t.apply(this,arguments);null==s?this.style.removeProperty(e):this.style.setProperty(e,s,n)}}function R(e,t){return e.style.getPropertyValue(t)||M(e).getComputedStyle(e,null).getPropertyValue(t)}function F(e){return function(){delete this[e]}}function $(e,t){return function(){this[e]=t}}function D(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function L(e){return e.trim().split(/^|\s+/)}function P(e){return e.classList||new G(e)}function G(e){this._node=e,this._names=L(e.getAttribute("class")||"")}function U(e,t){for(var n=P(e),s=-1,r=t.length;++s<r;)n.add(t[s])}function B(e,t){for(var n=P(e),s=-1,r=t.length;++s<r;)n.remove(t[s])}function z(e){return function(){U(this,e)}}function J(e){return function(){B(this,e)}}function H(e,t){return function(){(t.apply(this,arguments)?U:B)(this,e)}}function W(){this.textContent=""}function V(e){return function(){this.textContent=e}}function Z(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function K(){this.innerHTML=""}function X(e){return function(){this.innerHTML=e}}function Y(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function Q(){this.nextSibling&&this.parentNode.appendChild(this)}function ee(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function te(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===k&&t.documentElement.namespaceURI===k?t.createElement(e):t.createElementNS(n,e)}}function ne(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function se(e){var t=x(e);return(t.local?ne:te)(t)}function re(){return null}function oe(){var e=this.parentNode;e&&e.removeChild(this)}function ie(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ae(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function le(e){return function(){var t=this.__on;if(t){for(var n,s=0,r=-1,o=t.length;s<o;++s)n=t[s],e.type&&n.type!==e.type||n.name!==e.name?t[++r]=n:this.removeEventListener(n.type,n.listener,n.options);++r?t.length=r:delete this.__on}}}function ce(e,t,n){return function(){var s,r=this.__on,o=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var i=0,a=r.length;i<a;++i)if((s=r[i]).type===e.type&&s.name===e.name)return this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=o,s.options=n),void(s.value=t);this.addEventListener(e.type,o,n),s={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(s):this.__on=[s]}}function ue(e,t,n){var s=M(e),r=s.CustomEvent;"function"==typeof r?r=new r(t,n):(r=s.document.createEvent("Event"),n?(r.initEvent(t,n.bubbles,n.cancelable),r.detail=n.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function fe(e,t){return function(){return ue(this,e,t)}}function de(e,t){return function(){return ue(this,e,t.apply(this,arguments))}}G.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var pe=[null];function me(e,t){this._groups=e,this._parents=t}function he(){return new me([[document.documentElement]],pe)}me.prototype=he.prototype={constructor:me,select:function(e){"function"!=typeof e&&(e=o(e));for(var t=this._groups,n=t.length,s=new Array(n),r=0;r<n;++r)for(var i,a,l=t[r],c=l.length,u=s[r]=new Array(c),f=0;f<c;++f)(i=l[f])&&(a=e.call(i,i.__data__,f,l))&&("__data__"in i&&(a.__data__=i.__data__),u[f]=a);return new me(s,this._parents)},selectAll:function(e){e="function"==typeof e?l(e):a(e);for(var t=this._groups,n=t.length,s=[],r=[],o=0;o<n;++o)for(var i,c=t[o],u=c.length,f=0;f<u;++f)(i=c[f])&&(s.push(e.call(i,i.__data__,f,c)),r.push(i));return new me(s,r)},selectChild:function(e){return this.select(null==e?d:function(e){return function(){return f.call(this.children,e)}}("function"==typeof e?e:u(e)))},selectChildren:function(e){return this.selectAll(null==e?m:function(e){return function(){return p.call(this.children,e)}}("function"==typeof e?e:u(e)))},filter:function(e){"function"!=typeof e&&(e=c(e));for(var t=this._groups,n=t.length,s=new Array(n),r=0;r<n;++r)for(var o,i=t[r],a=i.length,l=s[r]=[],u=0;u<a;++u)(o=i[u])&&e.call(o,o.__data__,u,i)&&l.push(o);return new me(s,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,v);var n,s=t?b:y,r=this._parents,o=this._groups;"function"!=typeof e&&(n=e,e=function(){return n});for(var i=o.length,a=new Array(i),l=new Array(i),c=new Array(i),u=0;u<i;++u){var f=r[u],d=o[u],p=d.length,m=w(e.call(f,f&&f.__data__,u,r)),h=m.length,g=l[u]=new Array(h),_=a[u]=new Array(h);s(f,d,g,_,c[u]=new Array(p),m,t);for(var k,q,x=0,N=0;x<h;++x)if(k=g[x]){for(x>=N&&(N=x+1);!(q=_[N])&&++N<h;);k._next=q||null}}return(a=new me(a,r))._enter=l,a._exit=c,a},enter:function(){return new me(this._enter||this._groups.map(h),this._parents)},exit:function(){return new me(this._exit||this._groups.map(h),this._parents)},join:function(e,t,n){var s=this.enter(),r=this,o=this.exit();return"function"==typeof e?(s=e(s))&&(s=s.selection()):s=s.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==n?o.remove():n(o),s&&r?s.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,s=t._groups,r=n.length,o=s.length,i=Math.min(r,o),a=new Array(r),l=0;l<i;++l)for(var c,u=n[l],f=s[l],d=u.length,p=a[l]=new Array(d),m=0;m<d;++m)(c=u[m]||f[m])&&(p[m]=c);for(;l<r;++l)a[l]=n[l];return new me(a,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var s,r=e[t],o=r.length-1,i=r[o];--o>=0;)(s=r[o])&&(i&&4^s.compareDocumentPosition(i)&&i.parentNode.insertBefore(s,i),i=s);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=_);for(var n=this._groups,s=n.length,r=new Array(s),o=0;o<s;++o){for(var i,a=n[o],l=a.length,c=r[o]=new Array(l),u=0;u<l;++u)(i=a[u])&&(c[u]=i);c.sort(t)}return new me(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var s=e[t],r=0,o=s.length;r<o;++r){var i=s[r];if(i)return i}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,n=0,s=t.length;n<s;++n)for(var r,o=t[n],i=0,a=o.length;i<a;++i)(r=o[i])&&e.call(r,r.__data__,i,o);return this},attr:function(e,t){var n=x(e);if(arguments.length<2){var s=this.node();return n.local?s.getAttributeNS(n.space,n.local):s.getAttribute(n)}return this.each((null==t?n.local?S:N:"function"==typeof t?n.local?T:j:n.local?C:A)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?O:"function"==typeof t?E:I)(e,t,null==n?"":n)):R(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?F:"function"==typeof t?D:$)(e,t)):this.node()[e]},classed:function(e,t){var n=L(e+"");if(arguments.length<2){for(var s=P(this.node()),r=-1,o=n.length;++r<o;)if(!s.contains(n[r]))return!1;return!0}return this.each(("function"==typeof t?H:t?z:J)(n,t))},text:function(e){return arguments.length?this.each(null==e?W:("function"==typeof e?Z:V)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?K:("function"==typeof e?Y:X)(e)):this.node().innerHTML},raise:function(){return this.each(Q)},lower:function(){return this.each(ee)},append:function(e){var t="function"==typeof e?e:se(e);return this.select((function(){return this.appendChild(t.apply(this,arguments))}))},insert:function(e,t){var n="function"==typeof e?e:se(e),s=null==t?re:"function"==typeof t?t:o(t);return this.select((function(){return this.insertBefore(n.apply(this,arguments),s.apply(this,arguments)||null)}))},remove:function(){return this.each(oe)},clone:function(e){return this.select(e?ae:ie)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var s,r,o=function(e){return e.trim().split(/^|\s+/).map((function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}}))}(e+""),i=o.length;if(!(arguments.length<2)){for(a=t?ce:le,s=0;s<i;++s)this.each(a(o[s],t,n));return this}var a=this.node().__on;if(a)for(var l,c=0,u=a.length;c<u;++c)for(s=0,l=a[c];s<i;++s)if((r=o[s]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?de:fe)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var s,r=e[t],o=0,i=r.length;o<i;++o)(s=r[o])&&(yield s)}};const ge=he;var ye={value:()=>{}};function be(){for(var e,t=0,n=arguments.length,s={};t<n;++t){if(!(e=arguments[t]+"")||e in s||/[\s.]/.test(e))throw new Error("illegal type: "+e);s[e]=[]}return new ve(s)}function ve(e){this._=e}function we(e,t){for(var n,s=0,r=e.length;s<r;++s)if((n=e[s]).name===t)return n.value}function _e(e,t,n){for(var s=0,r=e.length;s<r;++s)if(e[s].name===t){e[s]=ye,e=e.slice(0,s).concat(e.slice(s+1));break}return null!=n&&e.push({name:t,value:n}),e}ve.prototype=be.prototype={constructor:ve,on:function(e,t){var n,s,r=this._,o=(s=r,(e+"").trim().split(/^|\s+/).map((function(e){var t="",n=e.indexOf(".");if(n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!s.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}}))),i=-1,a=o.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++i<a;)if(n=(e=o[i]).type)r[n]=_e(r[n],e.name,t);else if(null==t)for(n in r)r[n]=_e(r[n],e.name,null);return this}for(;++i<a;)if((n=(e=o[i]).type)&&(n=we(r[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new ve(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,s,r=new Array(n),o=0;o<n;++o)r[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=0,n=(s=this._[e]).length;o<n;++o)s[o].value.apply(t,r)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var s=this._[e],r=0,o=s.length;r<o;++r)s[r].value.apply(t,n)}};const ke=be;var qe,xe,Ne=0,Se=0,Ae=0,Ce=1e3,je=0,Te=0,Me=0,Oe="object"==typeof performance&&performance.now?performance:Date,Ie="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ee(){return Te||(Ie(Re),Te=Oe.now()+Me)}function Re(){Te=0}function Fe(){this._call=this._time=this._next=null}function $e(e,t,n){var s=new Fe;return s.restart(e,t,n),s}function De(){Te=(je=Oe.now())+Me,Ne=Se=0;try{!function(){Ee(),++Ne;for(var e,t=qe;t;)(e=Te-t._time)>=0&&t._call.call(void 0,e),t=t._next;--Ne}()}finally{Ne=0,function(){var e,t,n=qe,s=1/0;for(;n;)n._call?(s>n._time&&(s=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:qe=t);xe=e,Pe(s)}(),Te=0}}function Le(){var e=Oe.now(),t=e-je;t>Ce&&(Me-=t,je=e)}function Pe(e){Ne||(Se&&(Se=clearTimeout(Se)),e-Te>24?(e<1/0&&(Se=setTimeout(De,e-Oe.now()-Me)),Ae&&(Ae=clearInterval(Ae))):(Ae||(je=Oe.now(),Ae=setInterval(Le,Ce)),Ne=1,Ie(De)))}function Ge(e,t,n){var s=new Fe;return t=null==t?0:+t,s.restart((n=>{s.stop(),e(n+t)}),t,n),s}Fe.prototype=$e.prototype={constructor:Fe,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?Ee():+n)+(null==t?0:+t),this._next||xe===this||(xe?xe._next=this:qe=this,xe=this),this._call=e,this._time=n,Pe()},stop:function(){this._call&&(this._call=null,this._time=1/0,Pe())}};var Ue=ke("start","end","cancel","interrupt"),Be=[],ze=0,Je=1,He=2,We=3,Ve=4,Ze=5,Ke=6;function Xe(e,t,n,s,r,o){var i=e.__transition;if(i){if(n in i)return}else e.__transition={};!function(e,t,n){var s,r=e.__transition;function o(e){n.state=Je,n.timer.restart(i,n.delay,n.time),n.delay<=e&&i(e-n.delay)}function i(o){var c,u,f,d;if(n.state!==Je)return l();for(c in r)if((d=r[c]).name===n.name){if(d.state===We)return Ge(i);d.state===Ve?(d.state=Ke,d.timer.stop(),d.on.call("interrupt",e,e.__data__,d.index,d.group),delete r[c]):+c<t&&(d.state=Ke,d.timer.stop(),d.on.call("cancel",e,e.__data__,d.index,d.group),delete r[c])}if(Ge((function(){n.state===We&&(n.state=Ve,n.timer.restart(a,n.delay,n.time),a(o))})),n.state=He,n.on.call("start",e,e.__data__,n.index,n.group),n.state===He){for(n.state=We,s=new Array(f=n.tween.length),c=0,u=-1;c<f;++c)(d=n.tween[c].value.call(e,e.__data__,n.index,n.group))&&(s[++u]=d);s.length=u+1}}function a(t){for(var r=t<n.duration?n.ease.call(null,t/n.duration):(n.timer.restart(l),n.state=Ze,1),o=-1,i=s.length;++o<i;)s[o].call(e,r);n.state===Ze&&(n.on.call("end",e,e.__data__,n.index,n.group),l())}function l(){for(var s in n.state=Ke,n.timer.stop(),delete r[t],r)return;delete e.__transition}r[t]=n,n.timer=$e(o,0,n.time)}(e,n,{name:t,index:s,group:r,on:Ue,tween:Be,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:ze})}function Ye(e,t){var n=et(e,t);if(n.state>ze)throw new Error("too late; already scheduled");return n}function Qe(e,t){var n=et(e,t);if(n.state>We)throw new Error("too late; already running");return n}function et(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}var tt,nt=n(8403),st=180/Math.PI,rt={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ot(e,t,n,s,r,o){var i,a,l;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(l=e*n+t*s)&&(n-=e*l,s-=t*l),(a=Math.sqrt(n*n+s*s))&&(n/=a,s/=a,l/=a),e*s<t*n&&(e=-e,t=-t,l=-l,i=-i),{translateX:r,translateY:o,rotate:Math.atan2(t,e)*st,skewX:Math.atan(l)*st,scaleX:i,scaleY:a}}function it(e,t,n,s){function r(e){return e.length?e.pop()+" ":""}return function(o,i){var a=[],l=[];return o=e(o),i=e(i),function(e,s,r,o,i,a){if(e!==r||s!==o){var l=i.push("translate(",null,t,null,n);a.push({i:l-4,x:(0,nt.Z)(e,r)},{i:l-2,x:(0,nt.Z)(s,o)})}else(r||o)&&i.push("translate("+r+t+o+n)}(o.translateX,o.translateY,i.translateX,i.translateY,a,l),function(e,t,n,o){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),o.push({i:n.push(r(n)+"rotate(",null,s)-2,x:(0,nt.Z)(e,t)})):t&&n.push(r(n)+"rotate("+t+s)}(o.rotate,i.rotate,a,l),function(e,t,n,o){e!==t?o.push({i:n.push(r(n)+"skewX(",null,s)-2,x:(0,nt.Z)(e,t)}):t&&n.push(r(n)+"skewX("+t+s)}(o.skewX,i.skewX,a,l),function(e,t,n,s,o,i){if(e!==n||t!==s){var a=o.push(r(o)+"scale(",null,",",null,")");i.push({i:a-4,x:(0,nt.Z)(e,n)},{i:a-2,x:(0,nt.Z)(t,s)})}else 1===n&&1===s||o.push(r(o)+"scale("+n+","+s+")")}(o.scaleX,o.scaleY,i.scaleX,i.scaleY,a,l),o=i=null,function(e){for(var t,n=-1,s=l.length;++n<s;)a[(t=l[n]).i]=t.x(e);return a.join("")}}}var at=it((function(e){const t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?rt:ot(t.a,t.b,t.c,t.d,t.e,t.f)}),"px, ","px)","deg)"),lt=it((function(e){return null==e?rt:(tt||(tt=document.createElementNS("http://www.w3.org/2000/svg","g")),tt.setAttribute("transform",e),(e=tt.transform.baseVal.consolidate())?ot((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):rt)}),", ",")",")");function ct(e,t){var n,s;return function(){var r=Qe(this,e),o=r.tween;if(o!==n)for(var i=0,a=(s=n=o).length;i<a;++i)if(s[i].name===t){(s=s.slice()).splice(i,1);break}r.tween=s}}function ut(e,t,n){var s,r;if("function"!=typeof n)throw new Error;return function(){var o=Qe(this,e),i=o.tween;if(i!==s){r=(s=i).slice();for(var a={name:t,value:n},l=0,c=r.length;l<c;++l)if(r[l].name===t){r[l]=a;break}l===c&&r.push(a)}o.tween=r}}function ft(e,t,n){var s=e._id;return e.each((function(){var e=Qe(this,s);(e.value||(e.value={}))[t]=n.apply(this,arguments)})),function(e){return et(e,s).value[t]}}var dt=n(1696),pt=n(4314),mt=n(9009);function ht(e,t){var n;return("number"==typeof t?nt.Z:t instanceof dt.ZP?pt.ZP:(n=(0,dt.ZP)(t))?(t=n,pt.ZP):mt.Z)(e,t)}function gt(e){return function(){this.removeAttribute(e)}}function yt(e){return function(){this.removeAttributeNS(e.space,e.local)}}function bt(e,t,n){var s,r,o=n+"";return function(){var i=this.getAttribute(e);return i===o?null:i===s?r:r=t(s=i,n)}}function vt(e,t,n){var s,r,o=n+"";return function(){var i=this.getAttributeNS(e.space,e.local);return i===o?null:i===s?r:r=t(s=i,n)}}function wt(e,t,n){var s,r,o;return function(){var i,a,l=n(this);if(null!=l)return(i=this.getAttribute(e))===(a=l+"")?null:i===s&&a===r?o:(r=a,o=t(s=i,l));this.removeAttribute(e)}}function _t(e,t,n){var s,r,o;return function(){var i,a,l=n(this);if(null!=l)return(i=this.getAttributeNS(e.space,e.local))===(a=l+"")?null:i===s&&a===r?o:(r=a,o=t(s=i,l));this.removeAttributeNS(e.space,e.local)}}function kt(e,t){var n,s;function r(){var r=t.apply(this,arguments);return r!==s&&(n=(s=r)&&function(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}(e,r)),n}return r._value=t,r}function qt(e,t){var n,s;function r(){var r=t.apply(this,arguments);return r!==s&&(n=(s=r)&&function(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}(e,r)),n}return r._value=t,r}function xt(e,t){return function(){Ye(this,e).delay=+t.apply(this,arguments)}}function Nt(e,t){return t=+t,function(){Ye(this,e).delay=t}}function St(e,t){return function(){Qe(this,e).duration=+t.apply(this,arguments)}}function At(e,t){return t=+t,function(){Qe(this,e).duration=t}}var Ct=ge.prototype.constructor;function jt(e){return function(){this.style.removeProperty(e)}}var Tt=0;function Mt(e,t,n,s){this._groups=e,this._parents=t,this._name=n,this._id=s}function Ot(){return++Tt}var It=ge.prototype;Mt.prototype=function(e){return ge().transition(e)}.prototype={constructor:Mt,select:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=o(e));for(var s=this._groups,r=s.length,i=new Array(r),a=0;a<r;++a)for(var l,c,u=s[a],f=u.length,d=i[a]=new Array(f),p=0;p<f;++p)(l=u[p])&&(c=e.call(l,l.__data__,p,u))&&("__data__"in l&&(c.__data__=l.__data__),d[p]=c,Xe(d[p],t,n,p,d,et(l,n)));return new Mt(i,this._parents,t,n)},selectAll:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=a(e));for(var s=this._groups,r=s.length,o=[],i=[],l=0;l<r;++l)for(var c,u=s[l],f=u.length,d=0;d<f;++d)if(c=u[d]){for(var p,m=e.call(c,c.__data__,d,u),h=et(c,n),g=0,y=m.length;g<y;++g)(p=m[g])&&Xe(p,t,n,g,m,h);o.push(m),i.push(c)}return new Mt(o,i,t,n)},selectChild:It.selectChild,selectChildren:It.selectChildren,filter:function(e){"function"!=typeof e&&(e=c(e));for(var t=this._groups,n=t.length,s=new Array(n),r=0;r<n;++r)for(var o,i=t[r],a=i.length,l=s[r]=[],u=0;u<a;++u)(o=i[u])&&e.call(o,o.__data__,u,i)&&l.push(o);return new Mt(s,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,s=t.length,r=n.length,o=Math.min(s,r),i=new Array(s),a=0;a<o;++a)for(var l,c=t[a],u=n[a],f=c.length,d=i[a]=new Array(f),p=0;p<f;++p)(l=c[p]||u[p])&&(d[p]=l);for(;a<s;++a)i[a]=t[a];return new Mt(i,this._parents,this._name,this._id)},selection:function(){return new Ct(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,n=Ot(),s=this._groups,r=s.length,o=0;o<r;++o)for(var i,a=s[o],l=a.length,c=0;c<l;++c)if(i=a[c]){var u=et(i,t);Xe(i,e,n,c,a,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new Mt(s,this._parents,e,n)},call:It.call,nodes:It.nodes,node:It.node,size:It.size,empty:It.empty,each:It.each,on:function(e,t){var n=this._id;return arguments.length<2?et(this.node(),n).on.on(e):this.each(function(e,t,n){var s,r,o=function(e){return(e+"").trim().split(/^|\s+/).every((function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e}))}(t)?Ye:Qe;return function(){var i=o(this,e),a=i.on;a!==s&&(r=(s=a).copy()).on(t,n),i.on=r}}(n,e,t))},attr:function(e,t){var n=x(e),s="transform"===n?lt:ht;return this.attrTween(e,"function"==typeof t?(n.local?_t:wt)(n,s,ft(this,"attr."+e,t)):null==t?(n.local?yt:gt)(n):(n.local?vt:bt)(n,s,t))},attrTween:function(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;var s=x(e);return this.tween(n,(s.local?kt:qt)(s,t))},style:function(e,t,n){var s="transform"==(e+="")?at:ht;return null==t?this.styleTween(e,function(e,t){var n,s,r;return function(){var o=R(this,e),i=(this.style.removeProperty(e),R(this,e));return o===i?null:o===n&&i===s?r:r=t(n=o,s=i)}}(e,s)).on("end.style."+e,jt(e)):"function"==typeof t?this.styleTween(e,function(e,t,n){var s,r,o;return function(){var i=R(this,e),a=n(this),l=a+"";return null==a&&(this.style.removeProperty(e),l=a=R(this,e)),i===l?null:i===s&&l===r?o:(r=l,o=t(s=i,a))}}(e,s,ft(this,"style."+e,t))).each(function(e,t){var n,s,r,o,i="style."+t,a="end."+i;return function(){var l=Qe(this,e),c=l.on,u=null==l.value[i]?o||(o=jt(t)):void 0;c===n&&r===u||(s=(n=c).copy()).on(a,r=u),l.on=s}}(this._id,e)):this.styleTween(e,function(e,t,n){var s,r,o=n+"";return function(){var i=R(this,e);return i===o?null:i===s?r:r=t(s=i,n)}}(e,s,t),n).on("end.style."+e,null)},styleTween:function(e,t,n){var s="style."+(e+="");if(arguments.length<2)return(s=this.tween(s))&&s._value;if(null==t)return this.tween(s,null);if("function"!=typeof t)throw new Error;return this.tween(s,function(e,t,n){var s,r;function o(){var o=t.apply(this,arguments);return o!==r&&(s=(r=o)&&function(e,t,n){return function(s){this.style.setProperty(e,t.call(this,s),n)}}(e,o,n)),s}return o._value=t,o}(e,t,null==n?"":n))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=null==t?"":t}}(ft(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw new Error;return this.tween(t,function(e){var t,n;function s(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&function(e){return function(t){this.textContent=e.call(this,t)}}(s)),t}return s._value=e,s}(e))},remove:function(){return this.on("end.remove",function(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}(this._id))},tween:function(e,t){var n=this._id;if(e+="",arguments.length<2){for(var s,r=et(this.node(),n).tween,o=0,i=r.length;o<i;++o)if((s=r[o]).name===e)return s.value;return null}return this.each((null==t?ct:ut)(n,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?xt:Nt)(t,e)):et(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?St:At)(t,e)):et(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw new Error;return function(){Qe(this,e).ease=t}}(t,e)):et(this.node(),t).ease},easeVarying:function(e){if("function"!=typeof e)throw new Error;return this.each(function(e,t){return function(){var n=t.apply(this,arguments);if("function"!=typeof n)throw new Error;Qe(this,e).ease=n}}(this._id,e))},end:function(){var e,t,n=this,s=n._id,r=n.size();return new Promise((function(o,i){var a={value:i},l={value:function(){0==--r&&o()}};n.each((function(){var n=Qe(this,s),r=n.on;r!==e&&((t=(e=r).copy())._.cancel.push(a),t._.interrupt.push(a),t._.end.push(l)),n.on=t})),0===r&&o()}))},[Symbol.iterator]:It[Symbol.iterator]};var Et={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};function Rt(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}ge.prototype.interrupt=function(e){return this.each((function(){!function(e,t){var n,s,r,o=e.__transition,i=!0;if(o){for(r in t=null==t?null:t+"",o)(n=o[r]).name===t?(s=n.state>He&&n.state<Ze,n.state=Ke,n.timer.stop(),n.on.call(s?"interrupt":"cancel",e,e.__data__,n.index,n.group),delete o[r]):i=!1;i&&delete e.__transition}}(this,e)}))},ge.prototype.transition=function(e){var t,n;e instanceof Mt?(t=e._id,e=e._name):(t=Ot(),(n=Et).time=Ee(),e=null==e?null:e+"");for(var s=this._groups,r=s.length,o=0;o<r;++o)for(var i,a=s[o],l=a.length,c=0;c<l;++c)(i=a[c])&&Xe(i,e,t,c,a,n||Rt(i,t));return new Mt(s,this._parents,e,t)};const{abs:Ft,max:$t,min:Dt}=Math;function Lt(e){return[+e[0],+e[1]]}function Pt(e){return[Lt(e[0]),Lt(e[1])]}["w","e"].map(Gt),["n","s"].map(Gt),["n","w","e","s","nw","ne","sw","se"].map(Gt);function Gt(e){return{type:e}}var Ut=n(8877),Bt=n(6106),zt=n(7259),Jt=n(670);var Ht=n(6169),Wt=n(2998);function Vt(e){return Math.log(e)}function Zt(e){return Math.exp(e)}function Kt(e){return-Math.log(-e)}function Xt(e){return-Math.exp(-e)}function Yt(e){return isFinite(e)?+("1e"+e):e<0?0:e}function Qt(e){return(t,n)=>-e(-t,n)}function en(e){const t=e(Vt,Zt),n=t.domain;let s,r,o=10;function i(){return s=function(e){return e===Math.E?Math.log:10===e&&Math.log10||2===e&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}(o),r=function(e){return 10===e?Yt:e===Math.E?Math.exp:t=>Math.pow(e,t)}(o),n()[0]<0?(s=Qt(s),r=Qt(r),e(Kt,Xt)):e(Vt,Zt),t}return t.base=function(e){return arguments.length?(o=+e,i()):o},t.domain=function(e){return arguments.length?(n(e),i()):n()},t.ticks=e=>{const t=n();let i=t[0],a=t[t.length-1];const l=a<i;l&&([i,a]=[a,i]);let c,u,f=s(i),d=s(a);const p=null==e?10:+e;let m=[];if(!(o%1)&&d-f<p){if(f=Math.floor(f),d=Math.ceil(d),i>0){for(;f<=d;++f)for(c=1;c<o;++c)if(u=f<0?c/r(-f):c*r(f),!(u<i)){if(u>a)break;m.push(u)}}else for(;f<=d;++f)for(c=o-1;c>=1;--c)if(u=f>0?c/r(-f):c*r(f),!(u<i)){if(u>a)break;m.push(u)}2*m.length<p&&(m=(0,Bt.ZP)(i,a,p))}else m=(0,Bt.ZP)(f,d,Math.min(d-f,p)).map(r);return l?m.reverse():m},t.tickFormat=(e,n)=>{if(null==e&&(e=10),null==n&&(n=10===o?"s":","),"function"!=typeof n&&(o%1||null!=(n=(0,zt.Z)(n)).precision||(n.trim=!0),n=(0,Jt.WU)(n)),e===1/0)return n;const i=Math.max(1,o*e/t.ticks().length);return e=>{let t=e/r(Math.round(s(e)));return t*o<o-.5&&(t*=o),t<=i?n(e):""}},t.nice=()=>n(function(e,t){var n,s=0,r=(e=e.slice()).length-1,o=e[s],i=e[r];return i<o&&(n=s,s=r,r=n,n=o,o=i,i=n),e[s]=t.floor(o),e[r]=t.ceil(i),e}(n(),{floor:e=>r(Math.floor(s(e))),ceil:e=>r(Math.ceil(s(e)))})),t}function tn(){const e=en((0,Ht.l4)()).domain([1,10]);return e.copy=()=>(0,Ht.JG)(e,tn()).base(e.base()),Wt.o.apply(e,arguments),e}var nn=n(4090);const sn=(0,nn.Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),rn=(0,nn.Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function on(e,t,n){this.k=e,this.x=t,this.y=n}on.prototype={constructor:on,scale:function(e){return 1===e?this:new on(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new on(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};new on(1,0,0);on.prototype},8828:(e,t,n)=>{"use strict";n.d(t,{H:()=>r,L:()=>s});class s extends Map{constructor(e,t=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const[t,n]of e)this.set(t,n)}get(e){return super.get(o(this,e))}has(e){return super.has(o(this,e))}set(e,t){return super.set(i(this,e),t)}delete(e){return super.delete(a(this,e))}}class r extends Set{constructor(e,t=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const t of e)this.add(t)}has(e){return super.has(o(this,e))}add(e){return super.add(i(this,e))}delete(e){return super.delete(a(this,e))}}function o({_intern:e,_key:t},n){const s=t(n);return e.has(s)?e.get(s):n}function i({_intern:e,_key:t},n){const s=t(n);return e.has(s)?e.get(s):(e.set(s,n),n)}function a({_intern:e,_key:t},n){const s=t(n);return e.has(s)&&(n=e.get(s),e.delete(s)),n}function l(e){return null!==e&&"object"==typeof e?e.valueOf():e}}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var o=t[s]={exports:{}};return e[s](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e=n(334),t=n.n(e),s=n(3936),r=n(7147),o=n.n(r),i=n(1017),a=n.n(i);{const e=o().readdirSync(a().join(t().binpath,"/routes")).filter((e=>e.endsWith(".ts"))).map((e=>{const t=n(126)(`./${e}`);return t.file=e,t}));!function(e,t,n={}){const s=Object.assign({basepath:""},n);for(const n of t){const t=n.api;for(const n in t.methods){const r=t.methods[n];e[n](`${s.basepath}/${t.endpoint}`,r.init(s))}}!function(e,t){if(t.apiJson){const n=JSON.stringify(e.map((e=>e.api))),s=i.dirname(t.apiJson);r.existsSync(s)||r.mkdirSync(s,{recursive:!0}),r.writeFileSync(t.apiJson,n)}if(t.types){const n=function(e,t){const n={};for(const{file:t,route:s}of e){const e=s.api;for(const s in e.methods){const r=e.methods[s];r.alternativeFor||(n[t]||(n[t]=new Set),r.request.typeId&&n[t].add(r.request.typeId),r.response.typeId&&n[t].add(r.response.typeId))}}const s=["import { createValidate } from 'typia'"],r=[];for(const e in n){const o=Array.from(n[e]);s.push(`import { ${o.join(", ")} } from '${t}/${e}'`);for(const e of o)r.push(`export const valid${e} = createValidate<${e}>()`)}return s.join("\n")+"\n\n"+r.join("\n")}(e.map((e=>({file:e.file,route:e}))),t.types.importDir),s=i.dirname(t.types.outputFile);r.existsSync(s)||r.mkdirSync(s,{recursive:!0}),r.writeFileSync(t.types.outputFile,n)}}(t,s)}(s.l2,e,{app:s.l2,genomes:s.g_,basepath:s.LJ,apiJson:a().join(__dirname,"../../public/docs/server-api.json"),types:{importDir:"../types/routes",outputFile:a().join(__dirname,"./shared/checkers-raw/index.ts")}})}(0,s.lE)(t()).then((async()=>{if(console.log(`\n${new Date} ${t().commitHash||""}`),console.log("\nValidation succeeded.\n"),"validate"!=process.argv[2])if("phewas-precompute"!=process.argv[2])await(0,s.OG)();else{const e=process.argv[3],t=process.argv[4],n=s.g_[e];if(!n)throw"invalid genome name: "+e;const r=n.datasets[t];if(!r)throw"invalid dataset: "+t;s.U_.do_precompute(r)}else console.log("You may now run the server.")})).catch((e=>{let n=1;if(!o().existsSync(t().tpmasterdir)){const e=t().maintenance||{};if("start"in e&&"stop"in e&&"tpErrorCode"in e){const t=+new Date(e.start),s=+new Date(e.stop),r=+new Date;t<=r&&r<=s&&(n=e.tpErrorCode)}}e.stack&&console.log(e.stack),n?console.error("\n!!!\n"+e+"\n\n"):console.log("\n!!!\n"+e+"\n\n"),process.exit(n)}))})()})();
|
|
1
|
+
(()=>{var e={5037:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>c});var s=n(9157),r=n(1017),o=n.n(r),i=n(334),a=n.n(i),l=n(3345);const c={endpoint:"burden",methods:{get:{init:({genomes:e})=>async(t,n)=>{try{const r=e[t.query.genome];if(!r)throw`invalid q.genome=${t.query.genome}`;const i=t.query,c=r.datasets[i.dslabel];if(!c)throw`invalid q.genome=${t.query.dslabel}`;if(!c.cohort.cumburden?.files)throw"missing ds.cohort.cumburden.files";const f=await async function(e,t){const n=o().join(a().cachedir,Math.random().toString()+".json");for(const t in e.query)e.query[t]=Number(e.query[t]);const r=Object.assign({},u,e.query);await(0,l.Sf)(n,JSON.stringify(r));const{fit:i,surv:c,sample:f}=t.cohort.cumburden.files;if(!i||!c||!f)throw"missing one or more of ds.cohort.burden.files.{fit, surv, sample}";const d=[n,`${a().tpmasterdir}/${i}`,`${a().tpmasterdir}/${c}`,`${a().tpmasterdir}/${f}`],p=await(0,s.default)(o().join(a().binpath,"utils/burden.R"),[],d),m=JSON.parse(p[0]);return m}(t,c),{keys:d,rows:p}=function(e){const t=Object.keys(e[0]),n=[],s=[];for(const e of t)if("chc"==e)s.push(e),n.push(e);else{const t=Number(e.slice(1).split(",")[0]);t<=60&&t%2==0&&(s.push(e),n.push(`burden${t}`))}const r=[];for(const t of e)r.push(s.map((e=>t[e])));return{keys:n,rows:r}}(f);n.send({status:"ok",keys:d,rows:p})}catch(e){n.send({status:"error",error:e.message||e})}},request:{typeId:"BurdenRequest"},response:{typeId:"BurdenResponse"},examples:[{request:{body:{genome:"hg38",dslabel:"SJLife",diaggrp:5,sex:1,white:1,agedx:1,bleo:0,etop:0,cisp:0,carbo:0,steriod:0,vcr:0,hdmtx:0,itmt:0,ced:0,dox:0,heart:0,brain:0,abd:0,pelvis:0,chest:0}},response:{header:{status:200}}}]}}};const u=Object.freeze({diaggrp:5,sex:0,white:1,agedx:1,steriod:0,bleo:0,vcr:0,etop:0,itmt:0,ced:0,cisp:0,dox:0,carbo:0,hdmtx:0,brain:0,chest:0,heart:0,pelvis:0,abd:0})},2538:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f,maxTotalSizeCompressed:()=>u});var s=n(1017),r=n.n(s),o=n(6452),i=n.n(o),a=n(334);const l=1e3,c="Aliquot Ensemble Somatic Variant Merging and Masking",u=n.n(a)().features.gdcMafMaxFileSize||4e8,f={endpoint:"gdc/maf",methods:{all:{init:function({genomes:e}){return async(t,n)=>{try{const s=e.hg38;if(!s)throw"hg38 missing";const o=s.datasets.GDC;if(!o)throw"hg38 GDC missing";const a=await async function(e,t){const n={op:"and",content:[{op:"=",content:{field:"data_format",value:"MAF"}},{op:"=",content:{field:"experimental_strategy",value:e.experimentalStrategy}},{op:"=",content:{field:"analysis.workflow_type",value:c}},{op:"=",content:{field:"access",value:"open"}}]},s={op:"and",content:[]};e.filter0&&s.content.push(e.filter0);const{host:o,headers:a}=t.getHostHeaders(e),d={filters:n,case_filters:s,size:l,fields:["id","file_size","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},p=await i().post(r().join(o.rest,"files"),{headers:a,body:JSON.stringify(d)});let m;try{m=JSON.parse(p.body)}catch(e){throw"invalid JSON from "+f.endpoint}if(!Number.isInteger(m.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(m.data?.hits))throw"re.data.hits[] not array";const h=[];for(const e of m.data.hits){const t=e.cases?.[0];if(!t)throw"h.cases[0] missing";const n={id:e.id,project_id:t.project.project_id,file_size:e.file_size};n.case_submitter_id=t.submitter_id,t.samples&&(n.sample_types=t.samples.map((e=>e.sample_type)).sort()),h.push(n)}return{files:h,filesTotal:m.data.pagination.total,maxTotalSizeCompressed:u}}(t.query,o);n.send(a)}catch(e){n.send({status:"error",error:e.message||e})}}},request:{typeId:"GdcMafRequest"},response:{typeId:"GdcMafResponse"},examples:[{request:{body:{experimentalStrategy:"WXS",embedder:"localhost"}},response:{header:{status:200}}}]}}}},86:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f});var s=n(6452),r=n.n(s),o=n(1017),i=n.n(o),a=n(1271),l=n(334),c=n.n(l),u=n(2538);const f={endpoint:"gdc/mafBuild",methods:{all:{init:function({genomes:e}){return async(t,n)=>{try{const s=e.hg38;if(!s)throw"hg38 missing";const o=s.datasets.GDC;if(!o)throw"hg38 GDC missing";await async function(e,t,n){const s=Date.now(),{host:o,headers:l}=n.getHostHeaders(e),f=await async function(e,t,n){if(0==e.length)throw"fileIdLst[] not array or blank";const s={filters:{op:"in",content:{field:"file_id",value:e}},size:1e4,fields:"file_size"},o=await r().post(i().join(t.rest,"files"),{headers:n,body:JSON.stringify(s)});let a;try{a=JSON.parse(o.body)}catch(e){throw"invalid json from getFileLstUnderSizeLimit"}if(!Array.isArray(a.data?.hits))throw"re.data.hits[] not array";const l=[];let c=0;for(const e of a.data.hits){if(c>=u.maxTotalSizeCompressed)break;if(!e.id)throw".id missing";if(!Number.isInteger(e.file_size))throw".file_size not integer";c+=e.file_size,l.push(e.id)}if(0==l.length)throw"no file available";return l}(e.fileIdLst,o,l);c().debugmode&&console.log(`${f.length} out of ${e.fileIdLst.length} input MAF files accepted by size limit`,Date.now()-s);const d={fileIdLst:f,columns:e.columns,host:i().join(o.rest,"data")},p=(0,a.run_rust_stream)("gdcmaf",JSON.stringify(d));t.setHeader("Content-Type","application/octet-stream"),t.setHeader("Content-Disposition","attachment; filename=cohort.maf.gz"),p.pipe(t),p.on("end",(()=>{c().debugmode&&console.log("rust gdcmaf",Date.now()-s),t.end()})),p.on("error",(e=>{console.error(e),t.statusCode=500,t.end("Internal Server Error")}))}(t.query,n,o)}catch(e){e.stack&&console.log(e.stack),n.send({status:"error",error:e.message||e})}}},request:{typeId:"GdcMafBuildRequest"},response:{typeId:null}}}}},889:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>l});var s=n(2273),r=n(6452),o=n.n(r),i=n(334),a=n.n(i);const l={endpoint:"gdc/topMutatedGenes",methods:{all:{init:function({genomes:e}){return async(t,n)=>{const r=t.query,i=e.hg38;if(!i)throw"hg38 missing";const l=i.datasets.GDC;if(!l)throw"hg38 GDC missing";try{const e=await async function(e,t){let n,r;const{host:i,headers:l}=t.getHostHeaders(e);a().features?.geneExpHost?(n=c.query,r=c.getVariables(e)):(n=u.query,r=u.getVariables(e));const f=await o().post(i.graphql,{headers:l,body:JSON.stringify({query:n,variables:r})}),d=JSON.parse(f.body),p=[];for(const e of d.data.genesTableViewer.explore.genes.hits.edges){if("object"!=typeof e.node)throw"node missing from re.data.genesTableViewer.explore.genes.hits.edges[]";const t=[];Number.isInteger(e.node.case_cnv_gain?.hits?.total)&&e.node.case_cnv_gain.hits.total>0&&t.push({class:s.mclasscnvgain,count:e.node.case_cnv_gain.hits.total}),Number.isInteger(e.node.case_cnv_loss?.hits?.total)&&e.node.case_cnv_loss.hits.total>0&&t.push({class:s.mclasscnvloss,count:e.node.case_cnv_loss.hits.total}),Number.isInteger(e.node.ssm_case?.hits?.total)&&e.node.ssm_case.hits.total>0&&t.push({dt:s.dtsnvindel,count:e.node.ssm_case.hits.total}),p.push({gene:e.node.symbol,mutationStat:t})}return p}(r,l),t={genes:e};n.send(t)}catch(e){n.send({status:"error",error:e.message||e})}}},request:{typeId:"GdcTopMutatedGeneRequest"},response:{typeId:"GdcTopMutatedGeneResponse"}}}};const c={query:"\nquery GenesTable_relayQuery(\n $genesTable_filters: FiltersArgument\n $genesTable_size: Int\n $genesTable_offset: Int\n $score: String\n $ssmCase: FiltersArgument\n $geneCaseFilter: FiltersArgument\n $ssmTested: FiltersArgument\n $cnvTested: FiltersArgument\n $cnvGainFilters: FiltersArgument\n $cnvLossFilters: FiltersArgument\n) {\n genesTableViewer: viewer {\n explore {\n cases {\n hits(first: 0, filters: $ssmTested) {\n total\n }\n }\n filteredCases: cases {\n hits(first: 0, filters: $geneCaseFilter) {\n total\n }\n }\n cnvCases: cases {\n hits(first: 0, filters: $cnvTested) {\n total\n }\n }\n genes {\n hits(first: $genesTable_size, offset: $genesTable_offset, filters: $genesTable_filters, score: $score) {\n total\n edges {\n node {\n id\n numCases: score\n symbol\n name\n cytoband\n biotype\n gene_id\n is_cancer_gene_census\n ssm_case: case {\n hits(first: 0, filters: $ssmCase) {\n total\n }\n }\n cnv_case: case {\n hits(first: 0, filters: $cnvTested) {\n total\n }\n }\n case_cnv_gain: case {\n hits(first: 0, filters: $cnvGainFilters) {\n total\n }\n }\n case_cnv_loss: case {\n hits(first: 0, filters: $cnvLossFilters) {\n total\n }\n }\n }\n }\n }\n }\n }\n }\n}\n",getVariables:e=>{const t={genesTable_filters:{op:"and",content:[]},genesTable_size:e.maxGenes||50,genesTable_offset:0,score:"case.project.project_id",ssmCase:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}},{op:"NOT",content:{field:"genes.case.ssm.observation.observation_id",value:"MISSING"}}]},geneCaseFilter:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},ssmTested:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},cnvTested:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"}]},cnvGainFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Gain"]},op:"in"}]},cnvLossFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Loss"]},op:"in"}]}};return e.filter0&&(t.genesTable_filters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.geneCaseFilter.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvTested.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvGainFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvLossFilters.content.push(JSON.parse(JSON.stringify(e.filter0)))),"CGC"==e.geneFilter&&(t.genesTable_filters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.geneCaseFilter.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvTested.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvGainFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvLossFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"})),t}},u={query:"\n query GenesTable(\n $caseFilters: FiltersArgument\n $genesTable_filters: FiltersArgument\n $genesTable_size: Int\n $genesTable_offset: Int\n $score: String\n $ssmCase: FiltersArgument\n $geneCaseFilter: FiltersArgument\n $ssmTested: FiltersArgument\n $cnvTested: FiltersArgument\n $cnvGainFilters: FiltersArgument\n $cnvLossFilters: FiltersArgument\n $sort: [Sort]\n ) {\n genesTableViewer: viewer {\n explore {\n cases {\n hits(first: 0, case_filters: $ssmTested) {\n total\n }\n }\n filteredCases: cases {\n hits(first: 0, case_filters: $geneCaseFilter) {\n total\n }\n }\n cnvCases: cases {\n hits(first: 0, case_filters: $cnvTested) {\n total\n }\n }\n genes {\n hits(\n first: $genesTable_size\n offset: $genesTable_offset\n filters: $genesTable_filters\n case_filters: $caseFilters\n score: $score\n sort: $sort\n ) {\n total\n edges {\n node {\n id\n numCases: score\n symbol\n name\n cytoband\n biotype\n gene_id\n is_cancer_gene_census\n ssm_case: case {\n hits(first: 0, filters: $ssmCase) {\n total\n }\n }\n cnv_case: case {\n hits(first: 0, filters: $cnvTested) {\n total\n }\n }\n case_cnv_gain: case {\n hits(first: 0, filters: $cnvGainFilters) {\n total\n }\n }\n case_cnv_loss: case {\n hits(first: 0, filters: $cnvLossFilters) {\n total\n }\n }\n }\n }\n }\n }\n }\n }\n }",getVariables:e=>{const t={caseFilters:{op:"and",content:[]},genesTable_filters:{op:"and",content:[]},genesTable_size:e.maxGenes||50,genesTable_offset:0,score:"case.project.project_id",ssmCase:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}},{op:"NOT",content:{field:"genes.case.ssm.observation.observation_id",value:"MISSING"}}]},geneCaseFilter:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},ssmTested:{content:[{content:{field:"cases.available_variation_data",value:["ssm"]},op:"in"}],op:"and"},cnvTested:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"}]},cnvGainFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Gain"]},op:"in"}]},cnvLossFilters:{op:"and",content:[{content:{field:"cases.available_variation_data",value:["cnv"]},op:"in"},{content:{field:"cnvs.cnv_change",value:["Loss"]},op:"in"}]}};return e.filter0&&(t.caseFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.geneCaseFilter.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvLossFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvGainFilters.content.push(JSON.parse(JSON.stringify(e.filter0))),t.cnvTested.content.push(JSON.parse(JSON.stringify(e.filter0)))),"CGC"==e.geneFilter&&(t.genesTable_filters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvLossFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),t.cnvGainFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"})),t}}},3202:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(4065);function r({genomes:e}){return(t,n)=>{try{t.query;const r=e[t.query.genome];if(!r)throw"invalid genome name";const o=(0,s.S)(r,t.query);n.send(o)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}const o={endpoint:"genelookup",methods:{get:{init:r,request:{typeId:"GeneLookupRequest"},response:{typeId:"GeneLookupResponse"},examples:[{request:{body:{input:"kr",genome:"hg38-test"}},response:{header:{status:200},body:{hits:["KRAS"]}}}]},post:{alternativeFor:"get",init:r}}}},1746:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2062);const r={endpoint:"healthcheck",methods:{get:{init:({genomes:e})=>async(t,n)=>{try{const t=await(0,s.W)(e);n.send(t)}catch(e){n.send({status:"error",error:e.message||e})}},request:{typeId:null},response:{typeId:"HealthCheckResponse"}}}}},3932:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>c});var s=n(3345),r=n(2081),o=n(4521),i=n.n(o),a=n(334),l=n.n(a);const c={endpoint:"hicdata",methods:{get:{init:u,request:{typeId:"HicdataRequest"},response:{typeId:"HicdataResponse"}},post:{alternativeFor:"get",init:u}}};function u(){return async(e,t)=>{try{const n=await function(e){return new Promise(((t,n)=>{const[o,a,c]=(0,s.ZX)({query:e});o&&n({error:"illegal file name"});const u=["log(oe)"==e.matrixType?"oe":e.matrixType?e.matrixType:"observed",e.nmeth||"NONE",a,e.pos1,e.pos2,e.isfrag?"FRAG":"BP",e.resolution],f=(0,r.spawn)(l().hicstraw,u),d=i().createInterface({input:f.stdout}),p=[],m=[];let h=0,g=0;d.on("line",(t=>{const n=t.split("\t");if(3!=n.length)return void h++;const s=Number.parseInt(n[0]),r=Number.parseInt(n[1]),o="log(oe)"==e.matrixType?Math.log(Number.parseFloat(n[2])):Number.parseFloat(n[2]);Number.isNaN(s)||Number.isNaN(r)||Number.isNaN(o)?g++:null!=e.mincutoff&&o<=e.mincutoff||p.push([s,r,o])})),f.stderr.on("data",(e=>m.push(e))),f.on("close",(()=>{const e=m.join("");e&&n({error:e}),h&&n({error:h+" lines have other than 3 fields"}),g&&n({error:g+" lines have non-numerical values in any of the 3 fields"}),t({items:p})}))}))}(e.query);t.send(n)}catch(e){t.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},6310:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>u});var s=n(3345),r=n(7147),o=n.n(r),i=n(6464),a=n.n(i),l=n(6452),c=n.n(l);const u={endpoint:"hicstat",methods:{get:{init:f,request:{typeId:"HicstatRequest"},response:{typeId:"HicstatResponse"},examples:[{request:{body:{genome:"hg19",file:"proteinpaint_demo/hg19/hic/hic_demo.hic",embedder:"localhost"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:f}}};function f(){return async(e,t)=>{try{const[n,r,i]=(0,s.ZX)(e);if(n)throw"illegal file name";i||await(0,s.Ic)(r);const l=await async function(e,t){const n={},s=t?await S(e,0,32e3):await N(e,0,32e3),r=new DataView(s);let i=0;if("HIC"!==A())throw Error("Unsupported hic file");const l=C();if(7!==l&&8!==l&&9!=l)throw Error("Unsupported hic version: "+l);n.version=l;const u=Number(j());let f=[];const d=1e5;if(8==l||7==l){let t=await q(e,u,d);const n=t.getInt32(0,!0);n>0&&(t=await q(e,u+n+4,d),f=await x(t,u+n+4))}const p=A();if(n["Genome ID"]=p,9==l){const t=Number(j()),n=Number(j());if(t>0&&n>0){const s=await q(e,t,n);f=await x(s,0)}}const m={},h=C();let g=0;for(;g!==h;)m[A()]=A(),g++;n.Chromosomes={},n.chrorder=[];const y=C();let b=0;for(;b!==y;){const e=A();n.chrorder.push(e),n.Chromosomes[e]=7==l||8==l?C():j(),b++}n["Base pair-delimited resolutions"]=[];const v=C();let w=0;for(;w!==v;){const e=C();n["Base pair-delimited resolutions"].push(e),w++}n["Fragment-delimited resolutions"]=[];const _=C();let k=0;for(;k!==_;){const e=C();n["Fragment-delimited resolutions"].push(e),k++}return BigInt.prototype.toJSON||Object.defineProperty(BigInt.prototype,"toJSON",{get(){return()=>String(this)}}),n.normalization=f,n;async function q(e,n,s){const r=t?await S(e,n,s):await N(e,n,s);return new DataView(r)}async function x(t,n){const s=Date.now();let r=[];const o=t.getInt32(0,!0);let i=4;for(let e=1;e<=o;e++){let e=await f("string");r.push(e),8==l||7==l?(e=await f("string"),c(4),c(8*await f("int32")),c(12*await f("int32"))):9==l&&(i+=4,e=await f("string"),i+=20)}r=[...new Set(r)];const a=Date.now()-s;return console.log(`Read normalization on ${e} on ${a/1e3} seconds`),r;async function c(e){i+e>d&&u(),i+=e}async function u(){t=await q(e,n+i,d),n+=i,i=0}async function f(e){let n;if("string"==e){let e,s="";for(;i<t.byteLength&&0!=(e=t.getUint8(i++));)i>d&&await u(),s+=String.fromCharCode(e);n=s}else{if("int32"!=e)throw"No value assigned [server/src/hicstat.ts getViewValue()]";if(i<0)return;i+4>t.byteLength&&await u(),n=t.getInt32(i,!0),i+=4}return n}}async function N(e,t,n){const s=a().promisify(o().open),r=a().promisify(o().read),i=Buffer.alloc(n),l=await s(e,"r"),c=await r(l,i,0,n,t);o().close(l,(function(e){return e}));const u=c.buffer;return u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength)}async function S(e,t,n){try{const s=t+"-"+(t+n-1);return(await c()(e,{headers:{Range:"bytes="+s}}).buffer()).buffer}catch(e){throw console.log(e.response),"error reading file, check file details"}}function A(){let e,t="";for(;0!=(e=r.getUint8(i++));)t+=String.fromCharCode(e);return t}function C(){const e=r.getInt32(i,!0);return i+=4,e}function j(){const e=r.getBigInt64(i,!0);return i+=8,e}}(r,i);t.send({out:l})}catch(e){t.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},5852:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(938),r=n(2974);const o={endpoint:"termdb/categories",methods:{get:{init:i,request:{typeId:"getcategoriesRequest"},response:{typeId:"getcategoriesResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getcategories:1,tid:"diaggrp",term1_q:{isAtomic:!0,hiddenValues:{},type:"values",groupsetting:{disabled:!0},mode:"discrete"},filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:i}}};function i({genomes:e}){return async(t,n)=>{const o=t.query;try{const i=e[t.query.genome];if(!i)throw"invalid genome name";const l=i.datasets[t.query.dslabel];if(!l)throw"invalid dataset name";const c=l.cohort.termdb;if(!c)throw"invalid termdb object";await async function(e,t,n,o,i){if(!e.tid)throw".tid missing";const l="geneVariant"==e.type?{name:e.tid,type:"geneVariant",isleaf:!0}:n.q.termjsonByOneid(e.tid),c={filter:e.filter,terms:"geneVariant"==e.type?[{term:l,q:{isAtomic:!0}}]:[{id:e.tid,term:l,q:e.term1_q||a(l,e)}],currentGeneNames:e.currentGeneNames,rglst:e.rglst},u=await(0,r.Yu)(c,o,i);if(u.error)throw u.error;const f=[];if("geneVariant"==e.type){const t=u.samples,n=new Map;if(o.assayAvailability?.byDt)for(const[e,t]of Object.entries(o.assayAvailability.byDt))t.byOrigin&&n.set(parseInt(e),{byOrigin:{germline:{},somatic:{}}});const s=new Set;for(const[r,o]of Object.entries(t)){const t=o[e.tid].values;s.clear();for(const e of t){n.has(e.dt)||n.set(e.dt,{});const t=n.get(e.dt);t.byOrigin?(t.byOrigin[e.origin][e.class]||(t.byOrigin[e.origin][e.class]=1,s.add(`${e.dt} ${e.origin} ${e.class}`)),s.has(`${e.dt} ${e.origin} ${e.class}`)||(s.add(`${e.dt} ${e.origin} ${e.class}`),t.byOrigin[e.origin][e.class]+=1)):(t[e.class]||(s.add(`${e.dt} ${e.class}`),t[e.class]=1),s.has(`${e.dt} ${e.class}`)||(s.add(`${e.dt} ${e.class}`),t[e.class]+=1))}}for(const[e,t]of n)f.push({dt:e,classes:t})}else{const t=new Map;for(const n in u.samples){const s=u.samples[n][e.tid];s&&("key"in s&&t.set(s.key,1+(t.get(s.key)||0)))}for(const[n,s]of t)f.push({samplecount:s,key:n,label:u.refs?.byTermId?.[e.tid]?.events?.find((e=>e.event===n)).label||l?.values?.[n]?.label||n})}const d=(0,s.Tt)(l,u.refs?.byTermId?.[e.tid]?.bins||[],u.refs?.byTermId?.[e.tid]?.events,e.term1_q);d.length&&f.sort(((e,t)=>d.indexOf(e.label)-d.indexOf(t.label)));t.send({lst:f,orderedLabels:d})}(o,n,c,l,i)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}function a(e,t){if("categorical"==e.type)return{};if("survival"==e.type)return{};if("integer"==e.type||"float"==e.type)return e.bins.default;if("condition"==e.type)return{mode:t.mode,breaks:t.breaks,bar_by_grade:t.bar_by_grade,bar_by_children:t.bar_by_children,value_by_max_grade:t.value_by_max_grade,value_by_most_recent:t.value_by_most_recent,value_by_computable_grade:t.value_by_computable_grade};if("geneVariant"==e.type)return{};throw"unknown term type"}},4924:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>m,validate_query_geneExpression:()=>g});var s=n(1017),r=n.n(s),o=n(7147),i=n.n(o),a=n(9157),l=n(3345),c=n(334),u=n.n(c),f=n(4555),d=n(901),p=n(2273);const m={endpoint:"termdb/cluster",methods:{all:{init:function({genomes:e}){return async(t,n)=>{const s=t.query;let o;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(n.__gdc&&!n.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";if(s.dataType!=p.dtgeneexpression)throw"unknown q.dataType "+s.dataType;if(!n.queries?.geneExpression)throw"no geneExpression data on this dataset";o=await async function(e,t){const{gene2sample2value:n,byTermId:s,bySampleId:o}=await t.queries.geneExpression.get(e);if(0==n.size)throw"no data";if(1==n.size){const e=Array.from(n.keys())[0];return{gene:e,data:n.get(e)}}const c=Date.now(),f=await async function(e,t){const n=new Set;for(const t of e.values()){for(const e in t)n.add(e);break}const s={matrix:[],row_names:[],col_names:[...n],cluster_method:t.clusterMethod,plot_image:!1};for(const[t,n]of e){s.row_names.push(t);const e=[];for(const t of s.col_names)e.push(n[t]||0);s.matrix.push(h(e))}const o=r().join(u().cachedir,Math.random().toString()+".json");await l.Sf(o,JSON.stringify(s));const c=JSON.parse(await(0,a.default)(r().join(u().binpath,"utils/hclust.R"),[],[o]));await i().promises.unlink(o);const f=c.RowOrder.map((e=>s.row_names.indexOf(e.name))),d=c.ColOrder.map((e=>s.col_names.indexOf(e.name))),p=[];for(const e of f){const t=[];for(const n of d)t.push(s.matrix[e][n]);p.push(t)}return{row:{merge:c.RowMerge,height:c.RowHeight,order:c.RowOrder,inputOrder:s.row_names},col:{merge:c.ColumnMerge,height:c.ColumnHeight,order:c.ColOrder,inputOrder:s.col_names},matrix:p}}(n,e);u().debugmode&&console.log("clustering done:",Date.now()-c,"ms");return{clustering:f,byTermId:s,bySampleId:o}}(s,n)}catch(e){e.stack&&console.log(e.stack),o={status:e.status||400,error:e.message||e}}n.send(o)}},request:{typeId:"TermdbClusterRequest"},response:{typeId:"TermdbClusterResponse"}}}};function h(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,n=Math.sqrt(e.reduce(((e,n)=>e+Math.pow(n-t,2)),0)/e.length);return 0==n?e:e.map((e=>(e-t)/n))}async function g(e,t){const n=e.queries.geneExpression;if(n)if("gdcapi"!=n.src){if("native"!=n.src)throw"unknown queries.geneExpression.src";await async function(e,t,n){e.file.startsWith(u().tpmasterdir)||(e.file=r().join(u().tpmasterdir,e.file));e.samples||(e.samples=[]);await l.LC(e.file),e.nochr=await l.Jy(e.file,null,n),e.samples=[];{const n=await l.ZD(e.file);if(!n[0])throw"header line missing from "+e.file;const s=n[0].split("\t");if("#chr\tstart\tstop\tgene"!=s.slice(0,4).join("\t"))throw"header line has wrong content for columns 1-4";for(let n=4;n<s.length;n++){const r=t.cohort.termdb.q.sampleName2id(s[n]);if(null==r)throw"queries.geneExpression: unknown sample from header: "+s[n];e.samples.push(r)}console.log(e.samples.length,"samples from geneExpression of",t.label)}e.get=async s=>{const r=await(0,d.T)(s,e.samples,t);if(0==r?.size)return{gene2sample2value:new Set,byTermId:{},bySampleId:{}};const o={},i=e.samples||[];if(r)for(const e of r)o[e]={label:t.cohort.termdb.q.id2sampleName(e)};else for(const e of i)o[e]={label:t.cohort.termdb.q.id2sampleName(e)};const a=new Map;for(const t of s.genes){if(!t.gene)continue;if(!t.chr){const e=n.genedb.getjsonbyname.all(t.gene);if(0==e.length)continue;const s=JSON.parse(e.find((e=>e.isdefault)).genemodel||e[0].genemodel);t.start=s.start,t.stop=s.stop,t.chr=s.chr}const s={};await l.UE({args:[e.file,(e.nochr?t.chr?.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],callback:e=>{const n=e.split("\t");if(n[3].toLowerCase()==t.gene.toLowerCase())for(let e=4;e<n.length;e++){const t=i[e-4];if(r&&!r.has(t))continue;if(!n[e])continue;const o=Number(n[e]);if(Number.isNaN(o))throw"exp value not number";s[t]=o}}}),Object.keys(s).length&&a.set(t.gene,s)}return{gene2sample2value:a,byTermId:{},bySampleId:o}}}(n,e,t)}else(0,f.eG)(e,t)}},2262:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(8907),r=n(8615);const o={endpoint:"termdb/descrstats",methods:{all:{init:function({genomes:e}){return async(t,n)=>{const o=t.query;try{const i=e[t.query.genome];if(!i)throw"invalid genome name";const a=i.datasets[t.query.dslabel];if(!a)throw"invalid dataset name";if(!a.cohort.termdb)throw"invalid termdb object";await async function(e,t,n){const o=n.cohort.termdb.q.termjsonByOneid(e.tid);if(!o)throw"invalid termid";if("float"!=o.type&&"integer"!=o.type)throw"not numerical term";const i=await(0,s.J4)({ds:n,key:e.tid,filter:e.filter}),a=[];for(const{value:t}of i)o.values?.[t]?.uncomputable||"log"===e.settings?.violin?.unit&&0===t||a.push(t);t.send((0,r.Z)(a))}(o,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}},request:{typeId:"getdescrstatsRequest"},response:{typeId:"getdescrstatsResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",tid:"hrtavg",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]}}}},5961:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(8907);const r={endpoint:"termdb/numericcategories",methods:{get:{init:o,request:{typeId:"getnumericcategoriesRequest"},response:{typeId:"getnumericcategoriesResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",tid:"aaclassic_5",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const i=o.datasets[t.query.dslabel];if(!i)throw"invalid dataset name";const a=i.cohort.termdb;if(!a)throw"invalid termdb object";await async function(e,t,n,r){if(!e.tid)throw".tid missing";n.q.termjsonByOneid(e.tid);const o={ds:r,term_id:e.tid,filter:e.filter},i=await s.tt(o);t.send({lst:i})}(r,n,a,i)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},2630:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>o});var s=n(8907),r=n(7027);const o={endpoint:"termdb/getpercentile",methods:{get:{init:i,request:{typeId:"getpercentileRequest"},response:{typeId:"getpercentileResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getpercentile:[50],tid:"agedx",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:i}}};function i({genomes:e}){return async(t,n)=>{const o=t.query;try{const i=e[t.query.genome];if(!i)throw"invalid genome name";const a=i.datasets[t.query.dslabel];if(!a)throw"invalid dataset name";await async function(e,t,n){const o=n.cohort.termdb.q.termjsonByOneid(e.tid);if(!o)throw"invalid termid";if("float"!=o.type&&"integer"!=o.type)throw"not numerical term";const i=e.getpercentile,a=[],l=[],c=await s.J4({ds:n,key:e.tid,filter:e.filter?"string"==typeof e.filter?JSON.parse(e.filter):e.filter:null});for(const{value:e}of c)o.values&&o.values[e]&&o.values[e].uncomputable||o.skip0forPercentile&&0==e||l.push(Number(e));for(const e of i){const t=(0,r.Z)(l,e);a.push(t)}t.send({values:a})}(o,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},7095:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2826);const r={endpoint:"termdb/rootterm",methods:{get:{init:o,request:{typeId:"getroottermRequest"},response:{typeId:"getroottermResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",default_rootterm:1,cohortValues:"ABC"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;r.cohortValues&&r.cohortValues,r.treeFilter&&r.treeFilter;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const[i,a]=(0,s.pq)(o,r);if(!i)throw"invalid dataset name";if(!a)throw"invalid termdb object";await async function(e,t,n){const s=e.cohortValues?e.cohortValues:"",r=e.treeFilter?e.treeFilter:"";t.send({lst:await n.q.getRootTerms(s,r)})}(r,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},3967:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2826);const r={endpoint:"termdb/termchildren",methods:{get:{init:o,request:{typeId:"gettermchildrenRequest"},response:{typeId:"gettermchildrenResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",get_children:1,cohortValues:"ABC",tid:"GO:0000001"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const[i,a]=await(0,s.pq)(o,r);if(!i)throw"invalid dataset name";if(!a)throw"invalid termdb object";await async function(e,t,n){if(!e.tid)throw"no parent term id";const r=e.cohortValues?e.cohortValues:"",o=e.treeFilter?e.treeFilter:"",i=await n.q.getTermChildren(e.tid,r,o);t.send({lst:i.map(s.iK)})}(r,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},3677:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f,validate_query_singleSampleMutation:()=>d});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(334),c=n.n(l),u=n(4555);const f={endpoint:"termdb/singleSampleMutation",methods:{get:{init:function({genomes:e}){return async(t,n)=>{const s=t.query;let r;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleSampleMutation)throw"not supported on this dataset";r=await n.queries.singleSampleMutation.get(s)}catch(e){e.stack&&console.log(e.stack),r={status:e.status||400,error:e.message||e}}n.send(r)}},request:{typeId:"TermdbSingleSampleMutationRequest"},response:{typeId:"TermdbSingleSampleMutationResponse"}}}};async function d(e,t){const n=e.queries.singleSampleMutation;if(n)if("gdcapi"==n.src)(0,u.sV)(e,t);else{if("native"!=n.src)throw"unknown singleSampleMutation.src";n.get=async t=>{let s=t.sample;if(e.cohort?.termdb?.q?.sampleName2id&&(s=e.cohort.termdb.q.sampleName2id(t.sample),null==s))return[];const o=i().join(c().tpmasterdir,n.folder,s.toString());try{await r().promises.stat(o)}catch(e){if("EACCES"==e.code)throw"cannot read file, permission denied";if("ENOENT"==e.code)throw"no data for this sample";throw"failed to load data"}const l=await(0,a.b5)(o);return{mlst:JSON.parse(l)}}}}},5707:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>s});const s={endpoint:"termdb/singlecellData",methods:{get:{init:r,request:{typeId:"TermdbSinglecellDataRequest"},response:{typeId:"TermdbSinglecellDataResponse"}},post:{alternativeFor:"get",init:r}}};function r({genomes:e}){return async(t,n)=>{const s=t.query;let r;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleCell)throw"no singlecell data on this dataset";r=await n.queries.singleCell.data.get(s)}catch(e){e.stack&&console.log(e),r={status:e.status||400,error:e.message||e}}n.send(r)}}},7934:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>f,validate_query_singleCell:()=>p});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(334),c=n.n(l),u=n(4555);const f={endpoint:"termdb/singlecellSamples",methods:{get:{init:d,request:{typeId:"TermdbSinglecellsamplesRequest"},response:{typeId:"TermdbSinglecellsamplesResponse"}},post:{alternativeFor:"get",init:d}}};function d({genomes:e}){return async(t,n)=>{const s=t.query;let r;try{const t=e[s.genome];if(!t)throw"invalid genome name";const n=t.datasets[s.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleCell)throw"no singlecell data on this dataset";r=await n.queries.singleCell.samples.get(s)}catch(e){e.stack&&console.log(e.stack),r={status:e.status||400,error:e.message||e}}n.send(r)}}async function p(e,t){const n=e.queries.singleCell;if(n){if("gdcapi"==n.samples.src)(0,u.z7)(e,t);else{if("native"!=n.samples.src)throw"unknown singleCell.samples.src";!async function(e,t){const n=t.cohort.termdb.q.getAllValues4term(e.isSampleTerm);if(0==n.size)throw"no samples found that are identified by isSampleTerm";const s=[];for(const e of n.keys())"1"==n.get(e)&&s.push({sample:t.cohort.termdb.q.id2sampleName(e),sampleid:e});if(e.sampleColumns)for(const n of e.sampleColumns){const e=t.cohort.termdb.q.getAllValues4term(n.termid);for(const t of s)e.has(t.sampleid)&&(t[n.termid]=e.get(t.sampleid))}for(const e of s)delete e.sampleid;e.get=()=>({samples:s})}(n.samples,e)}if("gdcapi"==n.data.src)(0,u.r8)(e,t);else{if("native"!=n.data.src)throw"unknown singleCell.data.src";!function(e,t){const n=new Set;for(const t of e.plots){if(n.has(t.name))throw"duplicate plot.name";n.add(t.name)}const s=[];for(const n of e.termIds){const e=t.cohort.termdb.q.termjsonByOneid(n);if(!e)throw"invalid term id from queries.singleCell.data.termIds[]";s.push(e)}e.get=async t=>{try{const n={};for(const t of e.termIds)n[t]={};const o=[];for(const s of e.plots){const l=i().join(c().tpmasterdir,s.folder,t.sample+s.fileSuffix);try{await r().promises.stat(l)}catch(e){if("ENOENT"==e.code)continue;if("EACCES"==e.code)throw"cannot read file, permission denied";throw"failed to load sc data file"}const u=(await(0,a.b5)(l)).trim().split("\n"),f=[];for(let t=1;t<u.length;t++){const r=u[t].split("\t"),o=r[0],i=Number(r[s.coordsColumns.x]),a=Number(r[s.coordsColumns.y]),l=r[s.colorColumn?.index]||"";if(!o)throw"cell id missing";if(!Number.isFinite(i)||!Number.isFinite(a))throw"x/y not number";f.push({cellId:o,x:i,y:a,category:l});for(const t of e.termIds)n[t][o]=r[1]}o.push({name:s.name,cells:f,colorBy:s.colorColumn?.name,colorMap:s.colorMap})}return 0==o.length?{nodata:!0}:{plots:o,terms:s,tid2cellvalue:n}}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}}(n.data,e)}}}},605:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>r});var s=n(2826);const r={endpoint:"termdb/termsbyids",methods:{get:{init:o,request:{typeId:"gettermsbyidsRequest"},response:{typeId:"gettermsbyidsResponse"}},post:{alternativeFor:"get",init:o}}};function o({genomes:e}){return async(t,n)=>{const r=t.query;try{const o=e[t.query.genome];if(!o)throw"invalid genome name";const i=o.datasets[t.query.dslabel];if(!i)throw"invalid dataset name";const a=i.cohort.termdb;if(!a)throw"invalid termdb object";await async function(e,t,n){const r={};for(const t of e.ids){const e=n.q.termjsonByOneid(t);e&&("categorical"!=e.type||e.values||e.groupsetting?.inuse||(e.values={},e.samplecount={})),r[t]=e?(0,s.iK)(e):void 0}t.send({terms:r})}(r,n,a)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},5057:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>d,validate_query_TopVariablyExpressedGenes:()=>p});var s=n(4555),r=n(1017),o=n.n(r),i=n(1271),a=n(6452),l=n.n(a),c=n(334),u=n.n(c),f=n(8907);const d={endpoint:"termdb/topVariablyExpressedGenes",methods:{all:{init:function({genomes:e}){return async(t,n)=>{try{const s=t.query,r=e[s.genome];if(!r)throw"invalid genome";const o=r.datasets?.[s.dslabel];if(!o)throw"invalid dslabel";if(!o.queries?.topVariablyExpressedGenes)throw"not supported on dataset";const i=Date.now(),a=await o.queries.topVariablyExpressedGenes.getGenes(s);u().debugmode&&console.log("topVariablyExpressedGenes",Date.now()-i,"ms"),n.send({genes:a})}catch(e){n.send({status:"error",error:e.message||e})}}},request:{typeId:"TermdbTopVariablyExpressedGenesRequest"},response:{typeId:"TermdbTopVariablyExpressedGenesResponse"}}}};function p(e,t){const n=e.queries.topVariablyExpressedGenes;if(n)if("gdcapi"==n.src)!function(e,t){function n(e,n){return{case_ids:n,gene_ids:m(t),selection_size:Number(e.maxGenes)}}e.queries.topVariablyExpressedGenes.getGenes=async r=>{if(u().features.gdcGenes)return console.log("!!GDC!! using serverconfig.features.gdcGenes[]"),u().features.gdcGenes;if(!e.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";const i=await(0,s.Z5)(r,e);if(0==i.length)return[];const{host:a,headers:c}=e.getHostHeaders(r),f=o().join(a.geneExp,"/gene_expression/gene_selection");try{const e=await l().post(f,{headers:c,body:JSON.stringify(n(r,i))}),s=JSON.parse(e.body),o=[];if(!Array.isArray(s.gene_selection))throw"re.gene_selection[] is not array";for(const e of s.gene_selection)if(e.gene_id&&"string"==typeof e.gene_id){const n=t.genedb.getNameByAlias.get(e.gene_id);n&&o.push(n.name)}else{if(!e.symbol||"string"!=typeof e.symbol)throw"one of re.gene_selection[] is missing both gene_id and symbol";o.push(e.symbol)}return o}catch(e){throw console.log(e.stack||e),e}}}(e,t);else{if("native"!=n.src)throw"unknown topVariablyExpressedGenes.src";!function(e,t){const n=e.queries.geneExpression;if(!n)throw"topVariablyExpressedGenes query given but geneExpression missing";if("native"!=n.src)throw"topVariablyExpressedGenes is native but geneExpression.src is not native";e.queries.topVariablyExpressedGenes.getGenes=async t=>{const s=[];if(t.filter){const r=await(0,f.cf)(t.filter,e);for(const t of r)if(n.samples.includes(t.id)){const n=e.cohort.termdb.q.id2sampleName(t.id);if(!n)throw"sample id cannot convert to string name";s.push(n)}}else for(const t of n.samples){const n=e.cohort.termdb.q.id2sampleName(t.id);if(!n)throw"sample id cannot convert to string name";s.push(n)}const r=await async function(e,t,n,s){const r={input_file:n,samples:s.join(","),filter_extreme_values:!0,num_genes:Number(e.maxGenes),param:"var"},o=(await(0,i.run_rust)("topGeneByExpressionVariance",JSON.stringify(r))).split("\n");let a;for(const e of o)e.includes("output_json:")?a=JSON.parse(e.replace("output_json:","")):console.log(e);return a.map((e=>e.gene_symbol))}(t,0,n.file,s);return r}}(e)}}function m(e){const t=[];for(const n of e.geneset[0].lst){const s=e.genedb.getAliasByName.all(n);if(s)for(const e of s)e.alias.startsWith("ENSG")&&t.push(e.alias)}return t}},2386:(e,t,n)=>{"use strict";n.r(t),n.d(t,{api:()=>v});var s=n(7147),r=n(1868),o=n(334),i=n.n(o),a=n(9157),l=n(1017),c=n.n(l),u=n(3345),f=n(2974),d=n(6718),p=n(7011),m=n(8615),h=n(938);async function g(e,t,n,o){const l=n.cohort.termdb.q.termjsonByOneid(e.termid);if(!l)throw".termid invalid";if("integer"!=l.type&&"float"!=l.type)throw"term type is not integer/float.";const g=[{id:e.termid,term:l,q:{mode:"continuous"}}];e.divideTw&&(null===e.divideTw||void 0===e.divideTw||"object"!=typeof e.divideTw||"id"in e.divideTw||(e.divideTw.id=e.divideTw.term.name,e.divideTw.term.id=e.divideTw.term.name),g.push(e.divideTw),e.term2_q=e.divideTw.q);const v=await(0,f.Yu)({terms:g,filter:e.filter,currentGeneNames:e.currentGeneNames},n,o);if(v.error)throw v.error;e.divideTw&&v.refs.byTermId[e.divideTw?.id]&&(v.refs.byTermId[e.divideTw?.id].orderedLabels=(0,h.Tt)(e.divideTw,v.refs.byTermId[e.divideTw?.id]?.bins,void 0,e.divideTw.q)),e.scale&&function(e,t,n){if(!e.scale)return;const s=Number(e.scale);for(const[e,r]of Object.entries(t.samples))r[n.id]&&(n.values?.[r[n.id]?.value]?.uncomputable||(r[n.id].key=r[n.id].key/s,r[n.id].value=r[n.id].value/s))}(e,v,l);const w=function(e,t,n,s){const r="log"==e.unit,o=new Map;let i=1/0,a=-1/0;const l={};let c=0;for(const[e,u]of Object.entries(t.samples)){const e=u[n.id]?.value;if(Number.isFinite(e))if(n.values?.[e]?.uncomputable){const t=n.values[e].label;l[t]=(l[t]||0)+1}else if(r&&e<=0)c++;else if(i>e&&(i=e),a<e&&(a=e),"log"===r&&0===i&&(i=Math.max(i,e)),s){if(!u[s?.id])continue;if(s.term?.values?.[u[s.id]?.key]?.uncomputable){const e=s.term.values[u[s.id]?.value]?.label;l[e]=(l[e]||0)+1}o.has(u[s.id]?.key)||o.set(u[s.id]?.key,[]),o.get(u[s.id]?.key).push(e)}else o.has("All samples")||o.set("All samples",[]),o.get("All samples").push(e)}return{key2values:o,minMaxValues:{min:i,max:a},uncomputableValueObj:b(l),skipNonPositiveCount:c}}(e,v,l,e.divideTw),_=function(e,t,n){const s=n.divideTw,r={min:e.minMaxValues.min,max:e.minMaxValues.max,plots:[],pvalues:[],uncomputableValueObj:Object.keys(e.uncomputableValueObj).length>0?e.uncomputableValueObj:null};for(const[n,o]of function(e,t,n){const s=e.refs.byTermId[n?.term?.id]?.orderedLabels;return t=new Map([...t].sort(s?(e,t)=>s.indexOf(e[0])-s.indexOf(t[0]):"categorical"===n?.term?.type?(e,t)=>t[1].length-e[1].length:"condition"===n?.term?.type?(e,t)=>e[0]-t[0]:(e,t)=>e.toString().replace(/[^a-zA-Z0-9<]/g,"").localeCompare(t.toString().replace(/[^a-zA-Z0-9<]/g,""),void 0,{numeric:!0}))),t}(t,e.key2values,s))s?r.plots.push({label:s?.term?.values?.[n]?.label||n,values:o,seriesId:n,plotValueCount:o?.length,color:s?.term?.values?.[n]?.color||null,divideTwBins:y(s,t).has(n)?y(s,t).get(n):null,uncomputableValueObj:Object.keys(e.uncomputableValueObj).length>0?e.uncomputableValueObj:null}):r.plots.push({label:"All samples",values:o,plotValueCount:o.length});return r}(w,v,e);if(await async function(e,t){if(!e)return;const n=t.plots.length;if(n<2)return;const r=[];for(let e=0;e<n;e++){const s=t.plots[e].label,o=t.plots[e].values;for(let i=e+1;i<n;i++){const e=t.plots[i].label,n=t.plots[i].values;r.push({group1_id:s,group1_values:o,group2_id:e,group2_values:n})}}const o=c().join(i().cachedir,Math.random().toString()+".json");await(0,u.Sf)(o,JSON.stringify(r));const l=await(0,a.default)(c().join(i().binpath,"utils/wilcoxon.R"),[],[o]);(0,s.unlink)(o,(()=>{}));const f=JSON.parse(l);for(const e of f)null==e.pvalue||"null"==e.pvalue?t.pvalues.push([{value:e.group1_id},{value:e.group2_id},{html:"NA"}]):t.pvalues.push([{value:e.group1_id},{value:e.group2_id},{html:e.pvalue.toPrecision(4)}])}(e.divideTw,_),function(e,t,n){e.radius||(e.radius=5);if(e.radius<=0)throw"q.radius is not a number";e.radius=+e.radius;e.strokeWidth||(e.strokeWidth=.2);const s=4*e.radius;let o;const i="log"==e.unit;o=i?(0,r.p2C)().base(n.cohort.termdb.logscaleBase2?2:10).domain([t.min,t.max]).range("horizontal"===e.orientation?[0,e.svgw]:[e.svgw,0]):(0,r.BYU)().domain([t.min,t.max]).range("horizontal"===e.orientation?[0,e.svgw]:[e.svgw,0]);const[a,l]="horizontal"==e.orientation?[e.svgw*e.devicePixelRatio,s*e.devicePixelRatio]:[s*e.devicePixelRatio,e.svgw*e.devicePixelRatio],c=e.radius/e.devicePixelRatio,u=c*Math.PI;let f=0;for(const n of t.plots){const t=(0,d.createCanvas)(a,l),s=t.getContext("2d");s.strokeStyle="rgba(0,0,0,0.8)",s.lineWidth=e.strokeWidth/e.devicePixelRatio,s.globalAlpha=.5,s.fillStyle="#ffe6e6",1!=e.devicePixelRatio&&s.scale(e.devicePixelRatio,e.devicePixelRatio),"rug"===e.datasymbol?n.values.forEach((t=>{s.beginPath(),"horizontal"==e.orientation?(s.moveTo(+o(t),0),s.lineTo(+o(t),2*c)):(s.moveTo(0,+o(t)),s.lineTo(2*c,+o(t))),s.stroke()})):"bean"===e.datasymbol&&n.values.forEach((t=>{s.beginPath(),"horizontal"===e.orientation?s.arc(+o(t),e.radius,c,0,u):s.arc(e.radius,+o(t),c,0,u),s.fill(),s.stroke()})),n.src=t.toDataURL();const r=e.isKDE;n.density=(0,p.q)(o,n,r,e.ticks,e.bandwidth),n.summaryStats=(0,m.Z)(n.values),delete n.values}t.biggestBin=f}(e,_,n),!t)return _;t.send(_)}function y(e,t){const n=new Map,s=t.refs.byTermId[e?.term?.id]?.bins;if(s)for(const e of s)n.set(e.label,e);return n}function b(e){return Object.fromEntries(Object.entries(e).sort((([,e],[,t])=>e-t)))}const v={endpoint:"termdb/violin",methods:{get:{init:w,request:{typeId:"getViolinRequest"},response:{typeId:"getViolinResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",devicePixelRatio:2.200000047683716,maxThickness:150,screenThickness:1218,filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{id:"subcohort",type:"categorical"},values:[{key:"ABC",label:"ABC"}]}}]},svgw:227.27272234672367,orientation:"horizontal",datasymbol:"bean",radius:5,strokeWidth:.2,axisHeight:60,rightMargin:50,unit:"abs",termid:"agedx"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:w}}};function w({genomes:e}){return async(t,n)=>{t.query;try{const s=e[t.query.genome],r=s.datasets[t.query.dslabel];if(!s)throw"invalid genome name";const o=await g(t.query,null,r,s);n.send(o)}catch(e){n.send({error:e?.message||e}),e instanceof Error&&e.stack&&console.log(e)}}}},6733:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for CNV";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");return-1==r?"gene missing from header":(n[r]="gene",r=s("cnv"),-1==r?"CNV missing from header":(n[r]="cnv",r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.cnv.header=n,t.cnv.loaded=!0,!1))}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.cnv.header.length;e++)i[n.cnv.header[e]]=o[e];if(!i.gene)return void n.cnv.badlines.push([e,"missing gene",o]);if(!i.cnv)return void n.cnv.badlines.push([e,"missing cnv value",o]);switch(i.cnv.toLowerCase()){case"amplification":case"gain":i.class=s.mclasscnvgain;break;case"deletion":case"loss":i.class=s.mclasscnvloss;break;case"loh":i.class=s.mclasscnvloh;break;default:n.cnv.badlines.push([e,"invalid cnv value: "+i.cnv,o]),i.class=null}if(!i.class)return;if(r.EJ(i,n,e,o,n.cnv.badlines))return;i.dt=s.dtcnv,n.good++;const a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}},5558:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for intragenic deletion";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");if(-1==r)return"gene missing from header";if(n[r]="gene",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r)return"isoform missing from header";if(n[r]="isoform",r=s("rnaposition"),-1!=r){if(n[r]="rnaposition",r=s("rnadellength"),-1==r)return"rnadellength is required when rnaPosition is used";n[r]="rnadellength"}if(r=s("chromosome","chr"),-1!=r){if(n[r]="chr",r=s("chr_start"),-1==r)return"chr_start is required when chr is used";if(n[r]="chrpos1",r=s("chr_stop"),-1==r)return"chr_stop is required when chr is used";n[r]="chrpos2"}return r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.del.header=n,t.del.loaded=!0,!1}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.del.header.length&&null!=o[e];e++)i[n.del.header[e]]=o[e];if(i.gene){if(i.rnaposition){let t=Number.parseInt(i.rnaposition);if(Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid rnaPosition value",o]);if(i.rnaposition=t,!i.rnadellength)return void n.del.badlines.push([e,"missing rnaDellength value",o]);if(t=Number.parseInt(i.rnadellength),Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid rnaDellength value",o]);i.rnadellength=t}if(i.chr){let t=Number.parseInt(i.chrpos1);if(Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid chr_start value",o]);if(i.chrpos1=t,t=Number.parseInt(i.chrpos2),Number.isNaN(t)||t<0)return void n.del.badlines.push([e,"invalid chr_stop value",o]);i.chrpos2=t}if(!r.EJ(i,n,e,o,n.del.badlines)){i.dt=s.dtdel,i.class=s.mclassdel,i.mname="DEL",n.good++;var a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}}else n.del.badlines.push([e,"missing gene",o])}},3602:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for ITD";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");if(-1==r)return"gene missing from header";if(n[r]="gene",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r)return"isoform missing from header";if(n[r]="isoform",r=s("rnaposition"),-1!=r){if(n[r]="rnaposition",r=s("rnaduplength"),-1==r)return"rnaduplength is required when rnaposition is present";n[r]="rnaduplength"}if(r=s("chromosome","chr"),-1!=r){if(n[r]="chr",r=s("chr_start"),-1==r)return"chr_start is required when chr is present";if(n[r]="chrpos1",r=s("chr_stop"),-1==r)return"chr_stop is required when chr is present";n[r]="chrpos2"}return r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.itd.header=n,t.itd.loaded=!0,!1}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.itd.header.length&&null!=o[e];e++)i[n.itd.header[e]]=o[e];if(i.gene){if(i.rnaposition){let t=Number.parseInt(i.rnaposition);if(Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid rnaPosition value",o]);if(i.rnaposition=t,!i.rnaduplength)return void n.itd.badlines.push([e,"missing rnaDuplength value",o]);if(t=Number.parseInt(i.rnaduplength),Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid rnaDuplength value",o]);i.rnaduplength=t}if(i.chr){let t=Number.parseInt(i.chrpos1);if(Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid chr_start value",o]);if(i.chrpos1=t,t=Number.parseInt(i.chrpos2),Number.isNaN(t)||t<0)return void n.itd.badlines.push([e,"invalid chr_stop value",o]);i.chrpos2=t}if(!r.EJ(i,n,e,o,n.itd.badlines)){i.dt=s.dtitd,i.class=s.mclassitd,i.mname="ITD",n.good++;var a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}}else n.itd.badlines.push([e,"missing gene",o])}},8064:(e,t,n)=>{"use strict";n.d(t,{Dz:()=>r,EJ:()=>o});var s=n(2273);function r(e){if(!e)return null;const t={};for(const e in s.mclass)t[s.mclass[e].label.toUpperCase()]=e;return{genome:e,mclasslabel2key:t,data:{},sample2disease:{},patient2st:{},good:0,geneToUpper:!0,snv:{loaded:!1,header:null,badlines:[],missense:0,silent:0},svjson:{loaded:!1,header:null,badlines:[]},fusion:{loaded:!1,header:null,badlines:[],original:[]},sv:{loaded:!1,header:null,badlines:[],original:[]},cnv:{loaded:!1,header:null,badlines:[]},itd:{loaded:!1,header:null,badlines:[]},del:{loaded:!1,header:null,badlines:[]},truncation:{loaded:!1,header:null,badlines:[]}}}function o(e,t,n,r,o){let i=s.moriginsomatic;if(e.sampletype){switch(e.sampletype.toLowerCase()){case"relapse":i=s.moriginrelapse;break;case"germline":i=s.morigingermline}e.sample?e.patient||(e.patient=e.sample+" "+e.sampletype):e.patient&&(e.sample=e.patient+" "+e.sampletype)}else e.patient?e.sample?e.sampletype=e.sample:e.sample=e.sampletype=e.patient:e.sample&&(e.sampletype=e.sample);if(e.origin){switch(e.origin.toLowerCase()){case"r":case"relapse":i=s.moriginrelapse,e.isrim2=!0;break;case"g":case"germline":i=s.morigingermline,e.isrim1=!0;break;case"gp":case"germline pathogenic":i=s.morigingermlinepathogenic,e.isrim1=!0;break;case"gnp":case"germline nonpathogenic":case"germline non-pathogenic":i=s.morigingermlinenonpathogenic,e.isrim1=!0;break;case"s":case"somatic":case"diagnosis":i=s.moriginsomatic}}if(e.origin=i,!e.sample&&!e.patient)return;const a="no patient/individual name";if(e.patient?(t.patient2st[e.patient]||(t.patient2st[e.patient]={}),t.patient2st[e.patient][e.sampletype]=e.sample):(t.patient2st[a]||(t.patient2st[a]={}),t.patient2st[a][e.sampletype]=e.sample),e.sample&&e.disease)if(e.sample in t.sample2disease){if(e.disease!=t.sample2disease[e.sample])return t.snv.badlines.push([n,'conflict of disease types for sample "'+e.sample+'": '+e.disease+", "+t.sample2disease[e.sample],r]),!0}else t.sample2disease[e.sample]=e.disease;return!1}},5494:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for snv/indel";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("annovar_gene","annovar_sj_gene","gene","genename","gene_symbol","hugo_symbol");return-1==r?"gene missing from header":(n[r]="gene",r=s("annovar_aachange","amino_acid_change","annovar_sj_aachange","aachange","protein_change","variant"),-1==r?"amino_acid_change missing from header":(n[r]="mname",r=s("annovar_class","class","mclass","variant_class","variant_classification","annovar_sj_class"),-1==r?"variant_class missing from header":(n[r]="class",r=s("chromosome","chr"),-1==r?"chromosome missing from header":(n[r]="chr",r=s("wu_hg19_pos","start","start_position","chr_position","position"),-1==r?"start missing from header":(n[r]="pos",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r?"isoform missing from header":(n[r]="isoform",r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("quantitative_measurements"),-1!=r&&(n[r]="qmset"),r=s("mutant_reads_in_case","mutant_in_tumor","tumor_readcount_alt"),-1!=r&&(n[r]="maf_tumor_v1"),r=s("total_reads_in_case","total_in_tumor","tumor_readcount_total"),-1!=r&&(n[r]="maf_tumor_v2"),r=s("mutant_reads_in_control","mutant_in_normal","normal_readcount_alt"),-1!=r&&(n[r]="maf_normal_v1"),r=s("total_reads_in_control","total_in_normal","normal_readcount_total"),-1!=r&&(n[r]="maf_normal_v2"),r=s("cdna_change"),-1!=r&&(n[r]="cdna_change"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("cancer","disease","diagnosis"),-1!=r&&(n[r]="disease"),t.snv.header=n,t.snv.loaded=!0,!1))))))}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.snv.header.length&&null!=o[e];e++)i[n.snv.header[e]]=o[e];if(!i.gene)return void n.snv.badlines.push([e,"missing gene",o]);if("UNKNOWN"==i.gene.toUpperCase())return void n.snv.badlines.push([e,"gene name is UNKNOWN",o]);if(!i.isoform)return void n.snv.badlines.push([e,"missing isoform",o]);if(i.mname)0==i.mname.indexOf("p.")&&(i.mname=i.mname.replace(/^p\./,""));else if(i.mname=i.cdna_change,!i.mname)return void n.snv.badlines.push([e,"missing amino acid change",o]);if(!i.class)return void n.snv.badlines.push([e,"missing mutation class",o]);let a=n.mclasslabel2key[i.class.toUpperCase()];if(a)i.class=a;else{if(a=s.mclasstester(i.class),!a)return void n.snv.badlines.push([e,"wrong mutation class: "+i.class,o]);i.class=a}if(r.EJ(i,n,e,o,n.snv.badlines))return;if(!i.chr)return void n.snv.badlines.push([e,"missing chromosome",o]);if(0!=i.chr.toLowerCase().indexOf("chr")&&(i.chr="chr"+i.chr),!i.pos)return void n.snv.badlines.push([e,"missing chromosome position",o]);const l=Number.parseInt(i.pos);if(Number.isNaN(l))return void n.snv.badlines.push([e,"invalid chromosome position",o]);if(i.pos=l-1,null!=i.maf_tumor_v2&&null!=i.maf_tumor_v1){if(""==i.maf_tumor_v2);else{let t=Number.parseInt(i.maf_tumor_v1),s=Number.parseInt(i.maf_tumor_v2);if(Number.isNaN(t)||Number.isNaN(s))return void n.snv.badlines.push([e,"invalid maf_tumor mutant and/or total read count",o]);i.maf_tumor={f:t/s,v1:t,v2:s}}delete i.maf_tumor_v1,delete i.maf_tumor_v2}if(null!=i.maf_normal_v1&&null!=i.maf_normal_v2){if(""==i.maf_normal_v2);else{let t=Number.parseInt(i.maf_normal_v1),s=Number.parseInt(i.maf_normal_v2);if(Number.isNaN(t)||Number.isNaN(s))return void n.snv.badlines.push([e,"invalid maf_normal mutant and/or total read count",o]);i.maf_normal={f:t/s,v1:t,v2:s}}delete i.maf_normal_v1,delete i.maf_normal_v2}n.good++,"M"==i.class?n.snv.missense++:"S"==i.class&&n.snv.silent++;const c=n.geneToUpper?i.gene.toUpperCase():i.gene;n.data[c]||(n.data[c]=[]),i.dt=s.dtsnvindel,n.data[c].push(i)}},6279:(e,t,n)=>{"use strict";n.r(t),n.d(t,{duplicate:()=>a,parseheader:()=>o,parseline:()=>i});var s=n(8064),r=n(2273);function o(e,t,n){const s=e.toLowerCase().split("\t");if(s.length<=1)return"invalid file header for fusions";const r=(...e)=>{for(const t of e){const e=s.indexOf(t);if(-1!=e)return e}return-1};let o=r("gene_a","gene1","genea");return-1==o?"gene_a missing from header":(s[o]="gene1",o=r("gene_b","gene2","geneb"),-1==o?"gene_b missing from header":(s[o]="gene2",o=r("chr_a","chr1","chra"),-1==o?"chr_a missing from header":(s[o]="chr1",o=r("chr_b","chr2","chrb"),-1==o?"chr_b missing from header":(s[o]="chr2",o=r("pos_a","position_a","position1","posa"),-1==o?"pos_a missing from header":(s[o]="position1",o=r("pos_b","position_b","position2","posb"),-1==o?"pos_b missing from header":(s[o]="position2",o=r("isoform_a","refseq_a","refseq1","isoform1","sv_refseqa"),-1==o?"isoform_a missing from header":(s[o]="isoform1",o=r("isoform_b","refseq_b","refseq2","isoform2","sv_refseqb"),-1==o?"isoform_b missing from header":(s[o]="isoform2",o=r("strand_a","orta"),-1==o?"strand_a missing from header":(s[o]="strand1",o=r("strand_b","ortb"),-1==o?"strand_b missing from header":(s[o]="strand2",o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(s[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(s[o]="patient"),o=r("sampletype","sample type","sample_type"),-1!=o&&(s[o]="sampletype"),o=r("disease"),-1!=o&&(s[o]="disease"),o=r("origin"),-1!=o&&(s[o]="origin"),n?(t.sv.loaded=!0,t.sv.header=s):(t.fusion.loaded=!0,t.fusion.header=s),!1))))))))))}function i(e,t,n,o){if(""==t||"#"==t[0])return;const i=t.split("\t"),a={},l=o?n.sv.header:n.fusion.header,c=o?n.sv.badlines:n.fusion.badlines;for(let e=0;e<l.length;e++)a[l[e]]=i[e];if(!a.chr1)return void c.push([e,"missing chr1",i]);if(0!=a.chr1.toLowerCase().indexOf("chr")&&(a.chr1="chr"+a.chr1),!a.chr2)return void c.push([e,"missing chr2",i]);0!=a.chr2.toLowerCase().indexOf("chr")&&(a.chr2="chr"+a.chr2);let u=a.position1;if(!u)return void c.push([e,"missing position1",i]);let f=Number.parseInt(u);if(Number.isNaN(f)||f<=0)c.push([e,"invalid value for position1",i]);else if(a.position1=f,u=a.position2,u){if(f=Number.parseInt(u),Number.isNaN(f)||f<=0)c.push([e,"invalid value for position2",i]);else if(a.position2=f,!s.EJ(a,n,e,i,c)){if(a.isoform1&&-1!=a.isoform1.indexOf(",")){const e=a.isoform1.split(",");a.isoform1=void 0;for(const t of e)""!=t&&(a.isoform1=t)}if(a.isoform2&&-1!=a.isoform2.indexOf(",")){const e=a.isoform2.split(",");a.isoform2=void 0;for(const t of e)""!=t&&(a.isoform2=t)}if(a.gene1||(a.isoform1=void 0),a.gene2||(a.isoform2=void 0),a.gene1){n.good++;const e={dt:o?r.dtsv:r.dtfusionrna,class:o?r.mclasssv:r.mclassfusionrna,isoform:a.isoform1,mname:a.gene2||a.chr2,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},t=n.geneToUpper?a.gene1.toUpperCase():a.gene1;n.data[t]||(n.data[t]=[]),n.data[t].push(e)}if(a.gene2&&a.gene2!=a.gene1){n.good++;const e={dt:o?r.dtsv:r.dtfusionrna,class:o?r.mclasssv:r.mclassfusionrna,isoform:a.isoform2,mname:a.gene1||a.chr1,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},t=n.geneToUpper?a.gene2.toUpperCase():a.gene2;n.data[t]||(n.data[t]=[]),n.data[t].push(e)}}}else c.push([e,"missing position2",i])}function a(e){const t={};for(const n in e){if("pairlst"==n)continue;const s=e[n];"object"!=typeof s&&(t[n]=s)}if(e.pairlst){t.pairlst=[];for(const n of e.pairlst){const e={};for(const t in n)"a"!=t&&"b"!=t&&"interstitial"!=t&&(e[t]=n[t]);if(n.a){e.a={};for(const t in n.a){const s=n.a[t];"object"!=typeof s&&(e.a[t]=s)}}if(n.b){e.b={};for(const t in n.b){const s=n.b[t];"object"!=typeof s&&(e.b[t]=s)}}if(n.interstitial){e.interstitial={};for(const t in n.interstitial){const s=n.interstitial[t];"object"!=typeof s&&(e.interstitial[t]=s)}}t.pairlst.push(e)}}return t}},8423:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for svjson";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("sample");return-1!=r&&(n[r]="sample"),r=s("sampletype"),-1!=r&&(n[r]="sampletype"),r=s("patient"),-1!=r&&(n[r]="patient"),r=s("json","jsontext"),-1==r?["json missing from header"]:(n[r]="jsontext",[null,n])}function i(e,t,n,o){if(""==t||"#"==t[0])return;const i=t.split("\t"),l={},c=n.svjson.badlines;for(let e=0;e<o.length;e++)l[o[e]]=i[e];if(!l.jsontext)return void c.push([e,"missing jsontext",i]);if(r.EJ(l,n,e,i,c))return;let u;try{u=JSON.parse(l.jsontext)}catch(t){return void c.push([e,"invalid JSON text",i])}if(Array.isArray(u))for(const e of u){if(e.a&&e.a.name&&e.a.isoform){n.good++;const t={dt:s.dtfusionrna,class:s.mclassfusionrna,isoform:e.a.isoform,mname:e.b.name};for(const e in l)"jsontext"!=e&&(t[e]=l[e]);t.pairlst=a(u);const r=e.a.name.toUpperCase();n.data[r]||(n.data[r]=[]),n.data[r].push(t)}if(e.b&&e.b.name&&e.b.isoform){n.good++;const t={dt:s.dtfusionrna,class:s.mclassfusionrna,isoform:e.b.isoform,mname:e.a.name};for(const e in l)"jsontext"!=e&&(t[e]=l[e]);t.pairlst=a(u);const r=e.b.name.toUpperCase();n.data[r]||(n.data[r]=[]),n.data[r].push(t)}}else{switch(u.dt=u.typecode,delete u.typecode,u.dt){case s.dtitd:u.class=s.mclassitd,u.mname="ITD";break;case s.dtnloss:u.class=s.mclassnloss,u.mname="N-loss";break;case s.dtcloss:u.class=s.mclasscloss,u.mname="C-loss";break;case s.dtdel:u.class=s.mclassdel,u.mname="Del";break;case s.dtsv:u.class=s.mclasssv,u.mname="SV";break;default:return void c.push([e,"unknown datatype",i])}if(!u.gene)return void c.push([e,"json.gene missing",i]);n.good++;for(const e in l)"jsontext"!=e&&(u[e]=l[e]);const t=(n.geneToUpper,u.gene.toUpperCase());n.data[t]||(n.data[t]=[]),n.data[t].push(u)}}function a(e){const t=[];for(const n of e){const e={a:{},b:{}};for(const t in n)"a"!=t&&"b"!=t&&(e[t]=n[t]);for(const t in n.a)e.a[t]=n.a[t];for(const t in n.b)e.b[t]=n.b[t];t.push(e)}return t}},8235:(e,t,n)=>{"use strict";n.r(t),n.d(t,{parseheader:()=>o,parseline:()=>i});var s=n(2273),r=n(8064);function o(e,t){const n=e.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for truncation";const s=(...e)=>{for(const t of e){const e=n.indexOf(t);if(-1!=e)return e}return-1};let r=s("gene");if(-1==r)return"gene missing from header";if(n[r]="gene",r=s("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==r)return"isoform missing from header";n[r]="isoform";let o=!1;if(r=s("rnaposition"),-1!=r&&(n[r]="rnaposition",o=!0),r=s("losstype"),-1==r)return"lossType missing from header";n[r]="losstype";let i=!1;if(r=s("chromosome","chr"),-1!=r){if(n[r]="chr",r=s("start","start_position","wu_hg19_pos","chr_position","position"),-1==r)return"genomic position missing from header";n[r]="pos",i=!0}return o||i?(r=s("sample","sample_name","tumor_sample_barcode"),-1!=r&&(n[r]="sample"),r=s("patient","donor","target_case_id"),-1!=r&&(n[r]="patient"),r=s("disease"),-1!=r&&(n[r]="disease"),r=s("origin"),-1!=r&&(n[r]="origin"),r=s("sampletype","sample type","sample_type"),-1!=r&&(n[r]="sampletype"),t.truncation.header=n,t.truncation.loaded=!0,!1):"neither rnaposition nor genomic position is given"}function i(e,t,n){if(""==t||"#"==t[0])return;const o=t.split("\t"),i={};for(let e=0;e<n.truncation.header.length;e++)i[n.truncation.header[e]]=o[e];if(!i.gene)return void n.truncation.badlines.push([e,"missing gene",o]);if(i.rnaposition){const t=Number.parseInt(i.rnaposition);if(Number.isNaN(t)||t<0)return void n.truncation.badlines.push([e,"invalid rnaPosition value",o]);i.rnaposition=t}if(i.pos){const t=Number.parseInt(i.pos);if(Number.isNaN(t)||t<0)return void n.truncation.badlines.push([e,"invalid genomic position",o]);i.pos=t}if(!i.losstype)return void n.truncation.badlines.push([e,"missing lossType value",o]);if("n"!=i.losstype&&"c"!=i.losstype)return void n.truncation.badlines.push([e,'lossType value not "n" or "c"',o]);if(r.EJ(i,n,e,o,n.truncation.badlines))return;"n"==i.losstype?(i.dt=s.dtnloss,i.class=s.mclassnloss,i.mname="N-loss"):(i.dt=s.dtcloss,i.class=s.mclasscloss,i.mname="C-loss"),n.good++;const a=n.geneToUpper?i.gene.toUpperCase():i.gene;a in n.data||(n.data[a]=[]),n.data[a].push(i)}},2273:(e,t,n)=>{"use strict";n.r(t),n.d(t,{IN_frame:()=>c,OUT_frame:()=>u,alleleInGenotypeStr:()=>he,applyOverrides:()=>z,basecolor:()=>ie,basecompliment:()=>ae,bplen:()=>oe,codon:()=>ne,codon_stop:()=>se,contigNameNoChr:()=>de,contigNameNoChr2:()=>pe,custommdstktype:()=>te,default_text_color:()=>a,defaultcolor:()=>i,dt2color:()=>U,dt2label:()=>k,dtcloss:()=>v,dtcnv:()=>m,dtdel:()=>y,dtfusionrna:()=>d,dtgeneexpression:()=>p,dtitd:()=>g,dtloh:()=>w,dtnloss:()=>b,dtsnvindel:()=>f,dtsv:()=>h,exoncolor:()=>l,fasta2gmframecheck:()=>ue,germlinelegend:()=>J,getColorScheme:()=>qe,getColors:()=>xe,getMax_byiqr:()=>me,gmmode:()=>ge,kernelDensityEstimator:()=>ve,kernelEpanechnikov:()=>we,mclass:()=>q,mclasscloss:()=>A,mclasscnvgain:()=>R,mclasscnvloh:()=>$,mclasscnvloss:()=>F,mclassdel:()=>N,mclassdeletion:()=>G,mclassfusionrna:()=>I,mclassinsertion:()=>P,mclassitd:()=>x,mclassmnv:()=>L,mclassnloss:()=>S,mclassnoncoding:()=>M,mclassnonstandard:()=>T,mclasssnv:()=>D,mclasssv:()=>E,mclasstester:()=>O,mclassutr3:()=>C,mclassutr5:()=>j,mdsvcftype:()=>ee,morigin:()=>H,morigingermline:()=>V,morigingermlinenonpathogenic:()=>X,morigingermlinepathogenic:()=>K,moriginrelapse:()=>Z,moriginsomatic:()=>W,not_annotated:()=>be,nt2aa:()=>re,plotColor:()=>_,proteinChangingMutations:()=>Se,reversecompliment:()=>le,schemeCategory2:()=>ke,schemeCategory20:()=>_e,spliceeventchangegmexon:()=>ce,tkt:()=>Y,truncatingMutations:()=>Ne,validate_vcfinfofilter:()=>fe,validtkt:()=>Q,vcfcopymclass:()=>ye,vepinfo:()=>B});var s=n(1696),r=n(5540),o=n(1868);const i=(0,s.B8)("#8AB1D4").darker(),a=(0,s.B8)("#aaa").darker().darker(),l="#4F8053",c=!0,u=!1,f=1,d=2,p=3,m=4,h=5,g=6,y=7,b=8,v=9,w=10,_="#ce768e",k={[f]:"SNV/indel",[d]:"Fusion RNA",[m]:"CNV",[h]:"SV",[g]:"ITD",[y]:"Deletion",[b]:"N-loss",[v]:"C-loss",[w]:"LOH",[p]:"Gene Expression"},q={M:{label:"MISSENSE",color:"#3987CC",dt:f,desc:"A substitution variant in the coding region resulting in altered protein coding.",key:"M"},E:{label:"EXON",color:"#bcbd22",dt:f,desc:"A variant in the exon of a non-coding RNA.",key:"E"},F:{label:"FRAMESHIFT",color:"#db3d3d",dt:f,desc:"An insertion or deletion variant that alters the protein coding frame.",key:"F"},N:{label:"NONSENSE",color:"#ff7f0e",dt:f,desc:"A variant altering protein coding to produce a premature stopgain or stoploss.",key:"N"},S:{label:"SILENT",color:"#2ca02c",dt:f,desc:"A substitution variant in the coding region that does not alter protein coding.",key:"S"},D:{label:"PROTEINDEL",color:"#7f7f7f",dt:f,desc:"A deletion resulting in a loss of one or more codons from the product, but not altering the protein coding frame.",key:"D"},I:{label:"PROTEININS",color:"#8c564b",dt:f,desc:"An insertion introducing one or more codons into the product, but not altering the protein coding frame.",key:"I"},P:{label:"SPLICE_REGION",color:"#9467bd",dt:f,desc:"A variant in an intron within 10 nt of an exon boundary.",key:"P"},L:{label:"SPLICE",color:"#6633FF",dt:f,desc:"A variant near an exon edge that may affect splicing functionality.",key:"L"},Intron:{label:"INTRON",color:"#656565",dt:f,desc:"An intronic variant.",key:"Intron"},Blank:{label:"Not tested",color:"#fff",dt:f,desc:"This gene is not tested.",key:"Blank"},WT:{label:"Wildtype",color:"#D3D3D3",dt:f,desc:"Wildtype",key:"WT"}},x="ITD";q[x]={label:"ITD",color:"#ff70ff",dt:g,desc:"In-frame internal tandem duplication.",key:x};const N="DEL";q[N]={label:"DELETION, intragenic",color:"#858585",dt:y,desc:"Intragenic deletion.",key:N};const S="NLOSS";q[S]={label:"N-terminus loss",color:"#545454",dt:b,desc:"N-terminus loss due to translocation",key:S};const A="CLOSS";q[A]={label:"C-terminus loss",color:"#545454",dt:v,desc:"C-terminus loss due to translocation",key:A};const C="Utr3";q[C]={label:"UTR_3",color:"#998199",dt:f,desc:"A variant in the 3' untranslated region.",key:C};const j="Utr5";q[j]={label:"UTR_5",color:"#819981",dt:f,desc:"A variant in the 5' untranslated region.",key:j};const T="X";q[T]={label:"NONSTANDARD",color:"black",dt:f,desc:"A mutation class that either does not match our notation, or is unspecified.",key:T};const M="noncoding";function O(e){switch(e.toLowerCase()){case"missense_mutation":return"M";case"nonsense_mutation":case"nonstop_mutation":return"N";case"splice_site":return"L";case"rna":case"3'flank":case"5'flank":return M;case"frame_shift_del":case"frame_shift_ins":return"F";case"in_frame_del":return"D";case"in_frame_ins":return"I";case"translation_start_site":return T;case"3'utr":return C;case"5'utr":return j;case"blank":return"Blank";default:return null}}q[M]={label:"NONCODING",color:"black",dt:f,desc:"Noncoding mutation.",key:M};const I="Fuserna";q[I]={label:"Fusion transcript",color:"#545454",dt:d,desc:"Marks the break points leading to fusion transcripts.<br><span style=\"font-size:150%\">◐</span> - 3' end of the break point is fused to the 5' end of another break point in a different gene.<br><span style=\"font-size:150%\">◑</span> - 5' end of the break point is fused to the 3' end of another break point in a different gene.",key:I};const E="SV";q[E]={label:"Structural variation",color:"#858585",dt:h,desc:"Structural variation detected in genomic DNA.",key:E};const R="CNV_amp";q[R]={label:"Copy number gain",color:"#e9a3c9",dt:m,desc:"Copy number gain",key:R};const F="CNV_loss";q[F]={label:"Copy number loss",color:"#a1d76a",dt:m,desc:"Copy number loss",key:F};const $="CNV_loh";q[$]={label:"LOH",color:"#12EDFC",dt:m,desc:"Loss of heterozygosity",key:$};const D="snv";q[D]={label:"SNV",color:"#92a2d4",dt:f,desc:"Single nucleotide variation",key:D};const L="mnv";q[L]={label:"MNV",color:"#92a2d4",dt:f,desc:"Multiple nucleotide variation",key:L};const P="insertion";q[P]={label:"Sequence insertion",color:"#bd8e91",dt:f,desc:"Sequence insertion",key:P};const G="deletion";q[G]={label:"Sequence deletion",color:"#b5a174",dt:f,desc:"Sequence deletion",key:G};const U={[f]:q.M.color};function z(e={}){if(e.mclass)for(const t in e.mclass){q[t]||(q[t]={});for(const n in e.mclass[t])q[t][n]=e.mclass[t][n]}}const B=function(e){const t=e.toLowerCase().split(",");let n=1;return-1!=t.indexOf("transcript_ablation")?[y,N,n]:(n++,-1!=t.indexOf("splice_acceptor_variant")?[f,"L",n]:(n++,-1!=t.indexOf("splice_donor_variant")?[f,"L",n]:(n++,-1!=t.indexOf("stop_gained")?[f,"N",n]:(n++,-1!=t.indexOf("frameshift_variant")?[f,"F",n]:(n++,-1!=t.indexOf("stop_lost")?[f,"N",n]:(n++,-1!=t.indexOf("start_lost")?[f,"N",n]:(n++,-1!=t.indexOf("transcript_amplification")?[f,T,n]:(n++,-1!=t.indexOf("inframe_insertion")||-1!=t.indexOf("conservative_inframe_insertion")||-1!=t.indexOf("disruptive_inframe_insertion")?[f,"I",n]:(n++,-1!=t.indexOf("inframe_deletion")||-1!=t.indexOf("conservative_inframe_deletion")||-1!=t.indexOf("disruptive_inframe_deletion")?[f,"D",n]:(n++,-1!=t.indexOf("missense_variant")?[f,"M",n]:(n++,-1!=t.indexOf("protein_altering_variant")?[f,"N",n]:(n++,-1!=t.indexOf("splice_region_variant")?[f,"P",n]:(n++,-1!=t.indexOf("incomplete_terminal_codon_variant")?[f,"N",n]:(n++,-1!=t.indexOf("stop_retained_variant")?[f,"S",n]:(n++,-1!=t.indexOf("synonymous_variant")?[f,"S",n]:(n++,-1!=t.indexOf("coding_sequence_variant")?[f,T,n]:(n++,-1!=t.indexOf("mature_mirna_variant")?[f,"E",n]:(n++,-1!=t.indexOf("5_prime_utr_variant")?[f,j,n]:(n++,-1!=t.indexOf("3_prime_utr_variant")?[f,C,n]:(n++,-1!=t.indexOf("non_coding_transcript_exon_variant")?[f,"E",n]:(n++,-1!=t.indexOf("intron_variant")?[f,"Intron",n]:(n++,-1!=t.indexOf("nmd_transcript_variant")?[f,"S",n]:(n++,-1!=t.indexOf("non_coding_transcript_variant")?[f,"E",n]:(n++,-1!=t.indexOf("upstream_gene_variant")?[f,M,n]:(n++,-1!=t.indexOf("downstream_gene_variant")?[f,M,n]:(n++,-1!=t.indexOf("tfbs_ablation")?[f,M,n]:(n++,-1!=t.indexOf("tfbs_amplification")?[f,M,n]:(n++,-1!=t.indexOf("tf_binding_site_variant")?[f,M,n]:(n++,-1!=t.indexOf("regulatory_region_ablation")?[f,M,n]:(n++,-1!=t.indexOf("regulatory_region_amplification")?[f,M,n]:(n++,-1!=t.indexOf("feature_elongation")?[f,M,n]:(n++,-1!=t.indexOf("regulatory_region_variant")?[f,M,n]:(n++,-1!=t.indexOf("feature_truncation")?[f,M,n]:(n++,-1!=t.indexOf("intergenic_variant")?[f,M,n]:(n++,[f,T,n])))))))))))))))))))))))))))))))))))},J='<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="#858585" stroke="none"></path>',H={},W="S";H[W]={label:"Somatic",desc:"A variant found only in a tumor sample. The proportion is indicated by lack of any arc.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle>'};const V="G";H[V]={label:"Germline",desc:"A constitutional variant found in a normal sample. The proportion is indicated by the span of the solid arc within the whole circle.",legend:J},H.germline=H[V],H.somatic=H[W];const Z="R";H[Z]={label:"Relapse",desc:"A somatic variant found only in a relapse sample. The proportion is indicated by the span of the hollow arc within the whole circle.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="none" stroke="#858585"></path>'};const K="GP";H[K]={label:"Germline pathogenic",desc:"A constitutional variant with pathogenic allele.",legend:J};const X="GNP";H[X]={label:"Germline non-pathogenic",desc:"A constitutional variant with non-pathogenic allele.",legend:J,hidden:!0};const Y={usegm:"usegm",ds:"dataset",bigwig:"bigwig",bigwigstranded:"bigwigstranded",junction:"junction",mdsjunction:"mdsjunction",mdscnv:"mdscnv",mdssvcnv:"mdssvcnv",mdsexpressionrank:"mdsexpressionrank",mdsvcf:"mdsvcf",bedj:"bedj",pgv:"profilegenevalue",bampile:"bampile",hicstraw:"hicstraw",expressionrank:"expressionrank",aicheck:"aicheck",ase:"ase",mds2:"mds2",mds3:"mds3",bedgraphdot:"bedgraphdot",bam:"bam",ld:"ld"};function Q(e){for(const t in Y)if(e==Y[t])return!0;return!1}const ee={vcf:"vcf"},te={vcf:"vcf",svcnvitd:"svcnvitd",geneexpression:"geneexpression"},ne={GCT:"A",GCC:"A",GCA:"A",GCG:"A",CGT:"R",CGC:"R",CGA:"R",CGG:"R",AGA:"R",AGG:"R",AAT:"N",AAC:"N",GAT:"D",GAC:"D",TGT:"C",TGC:"C",CAA:"Q",CAG:"Q",GAA:"E",GAG:"E",GGT:"G",GGC:"G",GGA:"G",GGG:"G",CAT:"H",CAC:"H",ATT:"I",ATC:"I",ATA:"I",TTA:"L",TTG:"L",CTT:"L",CTC:"L",CTA:"L",CTG:"L",AAA:"K",AAG:"K",ATG:"M",TTT:"F",TTC:"F",CCT:"P",CCC:"P",CCA:"P",CCG:"P",TCT:"S",TCC:"S",TCA:"S",TCG:"S",AGT:"S",AGC:"S",ACT:"T",ACC:"T",ACA:"T",ACG:"T",TGG:"W",TAT:"Y",TAC:"Y",GTT:"V",GTC:"V",GTA:"V",GTG:"V"},se="*";function re(e){if(!e.genomicseq)return;const t=[];if(e.coding)for(const[n,s]of e.coding.entries()){const n=e.genomicseq.substr(s[0]-e.start,s[1]-s[0]);"-"==e.strand?t.push(le(n)):t.push(n)}const n=t.join(""),s=[];for(let t=e.startCodonFrame?3-e.startCodonFrame:0;t<n.length;t+=3){const e=ne[n.substr(t,3)];s.push(e||se)}return e.cdseq=n,s.join("")}function oe(e,t){return e>=1e9?(e/1e9).toFixed(1)+" Gb":e>=1e7?Math.ceil(e/1e6)+" Mb":e>=1e6?(e/1e6).toFixed(1)+" Mb":e>=1e4?Math.ceil(e/1e3)+" Kb":e>=1e3?(e/1e3).toFixed(1)+" Kb":e+(t?"bytes":" bp")}const ie={A:"#ca0020",T:"#f4a582",C:"#92c5de",G:"#0571b0"};function ae(e){switch(e){case"A":return"T";case"T":return"A";case"C":return"G";case"G":return"C";case"a":return"t";case"t":return"a";case"c":return"g";case"g":return"c";default:return e}}function le(e){const t=[];for(let n=e.length-1;n>=0;n--)t.push(ae(e[n]));return t.join("")}function ce(e,t){const n={chr:e.chr,start:e.start,stop:e.stop,strand:e.strand,coding:[]};if(t.isskipexon||t.isaltexon)for(let s=0;s<e.exon.length;s++){const r=Math.max(e.codingstart,e.exon[s][0]),o=Math.min(e.codingstop,e.exon[s][1]);r>o||-1==t.skippedexon.indexOf(s)&&n.coding.push([r,o])}else if(t.a5ss||t.a3ss){const s=e.exon.map((e=>[e[0],e[1]])),r="+"==e.strand;t.a5ss?r?s[t.exon5idx][1]=t.junctionB.start:s[t.exon5idx+1][0]=t.junctionB.stop:r?s[t.exon5idx+1][0]=t.junctionB.stop:s[t.exon5idx][1]=t.junctionB.start;for(const t of s){const s=Math.max(e.codingstart,t[0]),r=Math.min(e.codingstop,t[1]);s>r||n.coding.push([s,r])}}return n}function ue(e,t){const n=t.split("\n");n.shift(),e.genomicseq=n.join("").toUpperCase();const s=re(e);let r=u;return s.indexOf(se)==s.length-1&&(r=c),r}function fe(e){if(!e.lst)return".lst missing";if(!Array.isArray(e.lst))return"input is not an array";for(const t of e.lst){if(!t.name)return"name missing from a set of .vcfinfofilter.lst";if(t.autocategory||t.categories){if(!t.autocategory)for(const e in t.categories){const n=t.categories[e];if(!t.autocolor&&!n.color)return".color missing for class "+e+" from .categories of set "+t.name;n.label||(n.label=e)}if(t.categoryhidden){for(const e in t.categoryhidden)if(!t.categories[e])return"unknown hidden-by-default category "+e+" from set "+t.name}else t.categoryhidden={}}else if(t.numericfilter){const e=[];for(const n of t.numericfilter)"number"==typeof n?e.push({side:"<",value:n}):e.push({side:n.side||"<",value:n.value});t.numericfilter=e}if(t.altalleleinfo){if(!t.altalleleinfo.key)return".key missing from .altalleleinfo from set "+t.name}else{if(!t.locusinfo)return"neither .altalleleinfo or .locusinfo is available from set "+t.name;if(!t.locusinfo.key)return".key missing from .locusinfo from set "+t.name}}}function de(e,t){for(const n in e.majorchr)if(-1!=t.indexOf(n.replace("chr","")))return!0;if(e.minorchr)for(const n in e.minorchr)if(-1!=t.indexOf(n.replace("chr","")))return!0;return!1}function pe(e,t){let n=0,s=0;for(const r in e.majorchr)t.includes(r)?s++:t.includes(r.replace("chr",""))&&n++;if(e.minorchr)for(const r in e.minorchr)t.includes(r)?s++:t.includes(r.replace("chr",""))&&n++;return[n,s]}function me(e,t){if(0==e.length)return t;e.sort(((e,t)=>e-t));const n=e[e.length-1];if(e.length<=5)return n;const s=e[Math.floor(e.length/4)],r=e[Math.floor(3*e.length/4)];return Math.min(r+1.5*(r-s),n)}function he(e,t){return!!e&&(-1!=e.indexOf("/")?-1!=e.split("/").indexOf(t):-1!=e.split("|").indexOf(t))}const ge={genomic:"genomic",splicingrna:"splicing RNA",exononly:"exon only",protein:"protein",gmsum:"aggregated exons"};function ye(e,t){if(e.csq){let n;if(t.usegm&&(n=e.csq.find((e=>e._isoform==t.usegm.isoform))),!n&&(n=e.csq.find((e=>e.CANONICAL)),!n)){n=e.csq[0];for(const t of e.csq)t._csqrank<n._csqrank&&(n=t)}n&&(e.gene=n._gene,e.isoform=n._isoform,e.class=n._class,e.dt=n._dt,e.mname=n._mname,e.class==M&&delete e.class)}else if(e.ann){let n=null;if(t.usegm){for(const s of e.ann)s._isoform==t.usegm.isoform&&(n?s._csqrank<n._csqrank&&(n=s):n=s);n||t.gmmode!=ge.genomic||(n=e.ann[0])}else{n=e.ann[0];for(const t of e.ann)t._csqrank<n._csqrank&&(n=t)}n&&(e.gene=n._gene,e.isoform=n._isoform,e.class=n._class,e.dt=n._dt,e.mname=n._mname,e.class==M&&delete e.class)}null==e.class&&(q[e.type]?(e.class=e.type,e.dt=q[e.type].dt,e.mname=e.id&&"."!=e.id?e.id:e.ref+">"+e.alt,e.mname.length>15&&(e.mname=e.type)):(e.class=T,e.dt=f,e.mname=e.type)),delete e.type}const be="Unannotated";function ve(e,t){return function(n){return t.map((t=>[t,n.map((n=>e(t-n))).reduce(((e,t)=>e+t),0)/n.length]))}}function we(e){return function(t){return Math.abs(t/=e)<=1?.75*(1-t*t)/e:0}}const _e=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],ke=["#e75480","blue"];function qe(e){return e>12?_e:e>8?o.xHP:e>2?o.XgA:ke}function xe(e){return r.Z(qe(e))}const Ne=["F","N","D","I","L"],Se=["F","N","D","I","L","M","P"]},7027:(e,t,n)=>{"use strict";function s(e,t){e.sort(((e,t)=>e-t));const n=Math.abs(t/100*e.length-1);return Number.isInteger(n)?(e[n]+e[n+1])/2:e[Math.ceil(n)]}n.d(t,{Z:()=>s})},8615:(e,t,n)=>{"use strict";n.d(t,{Z:()=>o});var s=n(7027);function r(e,t){const n=Number(e);return Number.isInteger(n)?n:Math.abs(n)<1?Number(n.toPrecision(t)):Number(n.toFixed(t))}function o(e){let t=e;"string"==typeof e[0]&&(t=e.map(Number));const n=t.length;function o(e){return e.reduce(((e,t)=>e+t))/n}const i=(0,s.Z)(t,50),a=t.map((e=>(e-o(t))**2)).reduce(((e,t)=>e+t),0)/(n-1),l=Math.sqrt(a),c=(0,s.Z)(t,25),u=(0,s.Z)(t,75),f=u-c,d=Math.min(...t),p=Math.max(...t);return{values:[{id:"total",label:"Total",value:n},{id:"min",label:"Minimum",value:r(d,2)},{id:"p25",label:"1st quartile",value:r(c,2)},{id:"median",label:"Median",value:r(i,2)},{id:"mean",label:"Mean",value:r(o(t),2)},{id:"p75",label:"3rd quartile",value:r(u,2)},{id:"max",label:"Maximum",value:r(p,2)},{id:"SD",label:"Standard deviation",value:r(l,2)},{id:"variance",label:"Variance",value:r(a,2)},{id:"IQR",label:"Inter-quartile range",value:r(f,2)}]}}},478:(e,t,n)=>{"use strict";function s(e){if(!e||0==e.length)return;let t=JSON.parse(JSON.stringify(e[0]));if(1==e.length)return t;if(t.lst.length<2){if(""!==t.join)throw'filter.join must be an empty string "" when filter.lst.length < 2';t.join="and"}else if("or"==t.join)t={type:"tvslst",join:"and",in:!0,lst:[t]};else if("and"!=t.join)throw'filter.join must be either "and" or "or" when .lst length > 1';for(let n=1;n<e.length;n++){const s=JSON.parse(JSON.stringify(e[n]));"or"==s.join?t.lst.push(s):t.lst.push(...s.lst)}return 1==t.lst.length&&"tvs"==t.lst[0].type&&(t.join=""),t}n.d(t,{xH:()=>s})},4048:(e,t,n)=>{"use strict";n.d(t,{gp:()=>a});var s=n(670),r=n(2273);function o(e){return!isNaN(parseFloat(e))&&isFinite(e)}function i(e,t,n,s,r){if(s>=1){const t=Math.floor(e*s);return r?`${t}${n.charAt(0)}`:`${t} ${t>1?n+"s":""}`}const o=Math.floor(e*s),i=Math.ceil(e%(1/s));return 0==i?r?`${o}${n.charAt(0)}`:`${o} ${o>1?n+"s":""}`:r?`${o}${n.charAt(0)}${i}${t.charAt(0)}`:`${o} ${o>1?n+"s":""} ${i} ${i>1?t+"s":""}`}function a(e,t,n){const s=e;if(function(e){const t=e;if(!t||"object"!=typeof t)throw"bin schema must be an object";if("type"in t||(t.type="regular-bin"),"custom-bin"==t.type){if(!Array.isArray(t.lst))throw"binconfig.lst must be an array";if(!t.lst.length)throw"binconfig.lst must have entries";const e=t.lst[0],n=t.lst[t.lst.length-1];for(const s of t.lst){if(!("startinclusive"in s)&&!("stopinclusive"in s))throw"custom bin.startinclusive and/or bin.stopinclusive must be defined";if(s==e){if("startunbounded"in s&&!s.startunbounded)throw"a custom first bin must not set bin.startunbounded to false";if(s.startunbounded=!0,"start"in s)throw"a custom first bin must not set a bin.start value";if("start_percentile"in s)throw"the first bin must not set a bin.start_percentile value";if(!("stop"in s))throw"a custom first bin must define a bin.stop value";if(!o(s.stop))throw"a custom first bin.stop value should be numeric"}else if(s==n){if(!("start"in s))throw"a custom last bin must define a bin.start value";if(!o(s.start))throw"a custom last bin.start must be numeric";if("stopunbounded"in s&&!s.stopunbounded)throw"a custom last bin must not set bin.stopunbounded to false";if(s.stopunbounded=!0,"stop"in s)throw"a custom last bin must not set a bin.stop value"}else{if(!o(s.start))throw"bin.start must be numeric for a non-first bin";if(!o(s.stop))throw"bin.stop must be numeric for a non-last bin"}}}else{if("regular-bin"!=t.type)throw`invalid binconfig.type="${t.type}"`;if(!Number.isFinite(t.bin_size))throw"non-numeric bin_size";if(t.bin_size<=0)throw"bin_size must be greater than 0";if(t.startinclusive||t.stopinclusive||(t.startinclusive=1,t.stopinclusive=0),!t.first_bin)throw"first_bin{} missing";if("object"!=typeof t.first_bin)throw"first_bin{} is not an object";if(!Object.keys(t.first_bin).length)throw"first_bin is an empty object";{const e=t.first_bin;if(e.startunbounded=!0,e.stop_percentile){if(!Number.isInteger(e.stop_percentile))throw"first_bin.stop_percentile should be integer";if(e.stop_percentile<=0||e.stop_percentile>=100)throw"first_bin.stop_percentile out of bound (0-100)"}else if(!Number.isFinite(e.stop))throw"first_bin.stop not a number when stop_percentile is not set"}if(t.last_bin){const e=t.last_bin;if(e.start_percentile){if(!Number.isInteger(e.start_percentile))throw"last_bin.start_percentile should be integer";if(e.start_percentile<=0||e.start_percentile>=100)throw"last_bin.start_percentile out of bound (0-100)"}else if(!Number.isFinite(e.start))throw"last_bin.start not a number when start_percentile is not set";if(e.stopunbounded=!0,"stop"in e)throw"a regular last bin must not set a bin.stop value"}}}(s),s.lst){const e=(0,r.getColors)(s.lst.length);for(const t of s.lst)t.color=e(t.label)}if("custom-bin"==s.type)return JSON.parse(JSON.stringify(s.lst));if("function"!=typeof t)throw"summaryfxn required for modules/termdb.bins.js compute_bins()";const i=function(e){const t=[],n=e.first_bin;n&&o(n.start_percentile)&&t.push(n.start_percentile);n&&o(n.stop_percentile)&&t.push(n.stop_percentile);const s=e.last_bin;s&&o(s.start_percentile)&&t.push(s.start_percentile);s&&o(s.stop_percentile)&&t.push(s.stop_percentile);return t}(s),a=t(i);if(!a||"object"!=typeof a)throw"invalid returned value by summaryfxn";s.results={summary:a},s.binLabelFormatter||(s.binLabelFormatter=l(s));const u=Math.floor(100*a.min)/100,f=Math.ceil(100*a.max)/100,d=s.first_bin.startunbounded?u:s.first_bin.start_percentile?a["p"+s.first_bin.start_percentile]:s.first_bin.start;let p,m,h=f;if(s.last_bin)h=s.last_bin.stopunbounded?f:s.last_bin.stop_percentile?a["p"+s.last_bin.stop_percentile]:o(s.last_bin.stop)&&s.last_bin.stop<=a.max?s.last_bin.stop:f,p=o(s.last_bin.start_percentile)?a["p"+s.last_bin.start_percentile]:o(s.last_bin.start)?s.last_bin.start:void 0,m=s.last_bin.stopunbounded?null:s.last_bin.stop_percentile?a["p"+s.last_bin.stop_percentile]:o(s.last_bin.stop)?s.last_bin.stop:null;else if(s.lst){const e=s.lst[s.lst.length-1];p=e.start,m="stop"in e&&!e.stopunbounded?e.stop:f,h=m}else p=f,m=f;const g=o(h),y=o(p),b=o(m);if(!g&&!y)return[];const v=[];let w={startunbounded:s.first_bin.startunbounded,start:s.first_bin.startunbounded?void 0:d,stop:o(s.first_bin.stop_percentile)?+a["p"+s.first_bin.stop_percentile]:o(s.first_bin.stop)?+s.first_bin.stop:d+s.bin_size,startinclusive:s.startinclusive,stopinclusive:s.stopinclusive};if(!o(w.stop))throw"the computed first_bin.stop is non-numeric"+w.stop;for(;(g&&w.stop<=h||w.startunbounded&&!v.length||w.stopunbounded)&&(v.push(w),w.stop>=h&&(w.stopunbounded=!0,v.length>1&&delete w.stop),w.label=c(w,s,n),!w.stopunbounded);){const e=w.stop+s.bin_size,t=w.stop;if(w={startinclusive:s.startinclusive,stopinclusive:s.stopinclusive,start:t,stop:b&&(t==p||e>m)?m:y&&e>p&&t!=p?p:e},w.stop>=h&&(w.stop=h,s.last_bin&&s.last_bin.stopunbounded&&(w.stopunbounded=1),s.last_bin&&s.last_bin.stopinclusive&&(w.stopinclusive=1)),y&&w.start==p&&s.last_bin&&s.last_bin.stopunbounded&&(w.stopunbounded=1),w.start>w.stop){if(!(y&&w.stop==p&&s.last_bin&&s.last_bin.stopunbounded))break;w.stopunbounded=!0}if(v.length+1>=100){s.error="max_num_bins_reached";break}}delete s.binLabelFormatter,v.length>1&&delete v[v.length-1].stop;const _=(0,r.getColors)(v.length);for(const e of v)e.color=_(e.label);return v}function l(e){return"rounding"in e?(0,s.WU)(e.rounding):e=>e}function c(e,t,n){const s=t;s.binLabelFormatter||(s.binLabelFormatter=l(s)),e.startunbounded||e.stopunbounded||"startinclusive"in e||"stopinclusive"in e||(s.startinclusive?e.startinclusive=!0:s.stopinclusive&&(e.stopinclusive=!0));const r="bins"==s.use_as||e.start,o="bins"==s.use_as||e.stop;let a=0;if("label_offset"in s?(s.label_offset_ignored="bin_size"in s&&s.bin_size<s.label_offset,s.label_offset_ignored||(a=s.label_offset)):1===s.bin_size&&"integer"==s.termtype&&(a=1),e.startunbounded){return(e.stopinclusive?"≤":"<")+(n?i(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(o))}if(e.stopunbounded||r===o){return(e.startinclusive?"≥":">")+(n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(r))}if(a&&e.startinclusive&&!e.stopinclusive){if(Number.isInteger(s.bin_size)&&Math.abs(r-o)===a)return""+(n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(r));{const e=n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(r),t=n?i(o-a,n.fromUnit,n.toUnit,n.scaleFactor,!0):s.binLabelFormatter(o-a);return+e>=+t?e.toString():e+" to "+t}}{const t=e.startinclusive?"":">",a=e.stopinclusive?"":"<",l=n?i(r,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(r)?r:s.binLabelFormatter(r),c=n?i(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(o)?o:s.binLabelFormatter(o);if(+l>=+c){return(e.startinclusive?"≥":">")+l}return t+l+" to "+a+c}}},1575:(e,t,n)=>{"use strict";n.d(t,{CG:()=>r});new Set(["snplst","prs","snplocus","geneVariant","samplelst"]);const s=new Set(["categorical","integer","float","condition","survival","snplst","snplocus","geneVariant","samplelst"]);function r(e,t,n){const r=t||{};if(n&&n.usecase&&use.target in n.usecase)return n.usecase[use.target](e,use);const a=new Set,l=e.child_types||[];switch(r.target){case"barchart":case"summary":case"matrix":return"term0"==r.detail&&"geneVariant"==e.type||("term2"==r.detail&&"geneVariant"==e.type&&"geneVariant"==r.term1type||(e.type&&"survival"!==e.type&&a.add("plot"),o(l)&&a.add("branch"))),a;case"table":return"term"==r.detail&&a.add("plot"),l.length>1&&a.add("branch"),a;case"scatterplot":return"float"!=e.type&&"integer"!=e.type||a.add("plot"),i(l)&&a.add("branch"),a;case"sampleScatter":return"numeric"==r.detail?("float"!=e.type&&"integer"!=e.type||a.add("plot"),i(l)&&a.add("branch")):(s.has(e.type)&&a.add("plot"),e.isleaf||a.add("branch")),a;case"boxplot":return"float"!=e.type&&"integer"!=e.type||a.add("plot"),"term2"===r.detail&&i(l)&&a.add("branch"),a;case"cuminc":if("term"==r.detail)return"condition"==e.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a;if("term2"===r.detail)return e.type&&"survival"!=e.type&&a.add("plot"),o(l)&&a.add("branch"),a;if("term0"==r.detail)return a.add("plot"),a;case"survival":return"term"==r.detail?("survival"==e.type&&a.add("plot"),l.includes("survival")&&a.add("branch"),a):"term2"===r.detail?("survival"!=e.type&&(e.type&&a.add("plot"),o(l)&&a.add("branch")),a):"term0"==r.detail?(e.type&&a.add("plot"),o(l)&&a.add("branch"),a):(e.isleaf?a.add("plot"):a.add("branch"),a);case"regression":if("outcome"==r.detail){if("linear"==r.regressionType)return"float"!=e.type&&"integer"!=e.type||a.add("plot"),i(l)&&a.add("branch"),a;if("logistic"==r.regressionType)return e.type&&"survival"!=e.type&&a.add("plot"),o(l)&&a.add("branch"),a;if("cox"==r.regressionType)return"condition"==e.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a}if("independent"==r.detail)return"float"!=e.type&&"integer"!=e.type&&"categorical"!=e.type||a.add("plot"),function(e,t){for(const n of t)if(e.includes(n))return!0}(l,["categorical","float","integer"])&&a.add("branch"),a;default:return s.has(e.type)&&a.add("plot"),e.isleaf||a.add("branch"),a}}function o(e){return!!e.length&&(e.length>1||"survival"!=e[0])}function i(e){return e.includes("float")||e.includes("integer")}},1881:(e,t,n)=>{"use strict";n.d(t,{N:()=>o});const s="root",r="...";function o(e,t){const n=Object.create(null),o=Object.create(null),a=Object.create(null);for(const s of e)for(const[e,r]of t.entries()){const l=i(s,e,t),c=i(s,e-1,t);if(!s[r.k]){e>0&&(a[c]+=1);break}if(n[l]=c,l in a||(a[l]=0),!(l in o)){const n={lst:[]};r.full&&(n.full=s[r.full]),n.id0=t[0].k,n.v0=s[t[0].k],1==e&&(n.id1=t[1].k,n.v1=s[t[1].k]),2==e&&(n.id2=t[2].k,n.v1=s[t[2].k]),o[l]=n}o[l].lst.push(s),e==t.length-1&&(a[l]+=1)}const l=[{id:s,name:s}];for(const e in n){const t=n[e],s=o[e],i=e.split(r);l.push({id:e,parentId:t,lst:s.lst,value:a[e],name:i[i.length-1],full:s.full,id0:s.id0,v0:s.v0,id1:s.id1,v1:s.v1,id2:s.id2,v2:s.v2})}return l}function i(e,t,n){const o=[s];for(let s=0;s<t;s++)o.push(e[n[s].k]);return t>=0&&o.push(e[n[t].k]),o.join(r)}},4298:(e,t,n)=>{"use strict";n.d(t,{A:()=>r});var s=n(2273);function r(e,t,n){if(!t)return null;for(const r of e.split(",")){const e=r.replace(/&/g,",").split("|"),o={};for(let n=0;n<t.length;n++)e[n]&&(o[t[n].name]=e[n]);if(!o.Allele)continue;let i=null;for(const e of n.mlst||n.alleles)if(e.allele_original==o.Allele){i=e;break}if(!i){if("-"==o.Allele)n.mlst?1==n.mlst.length&&(i=n.mlst[0]):n.alleles&&1==n.alleles.length&&(i=n.alleles[0]);else for(const e of n.mlst||n.alleles)if(e.allele_original.substr(1)==o.Allele){i=e;break}if(!i)continue}if(i.csq||(i.csq=[]),i.csq.push(o),o._gene=o.SYMBOL||o.Gene,o.Feature_type&&"Transcript"==o.Feature_type?o._isoform=o.Feature.split(".")[0]:o._isoform=o._gene,o.Consequence){const[e,t,n]=(0,s.vepinfo)(o.Consequence);o._dt=e,o._class=t,o._csqrank=n}else o._dt=dtsnvindel,o._class=mclassnonstandard;o.HGVSp?o._mname=decodeURIComponent(o.HGVSp.substr(o.HGVSp.indexOf(":")+1)):o.Protein_position&&o.Amino_acids?o._mname=decodeURIComponent(o.Protein_position+o.Amino_acids):o.HGVSc?o._mname=o.HGVSc.substr(o.HGVSc.indexOf(":")+1):o.Existing_variation&&(o._name=o.Existing_variation)}return!0}},9380:(e,t,n)=>{"use strict";function s(e){let t=!1,n=!0,s=0,r=0;const o={};let i;for(;s<e.length;){const a=e[s];n?"="==a?(t=!0,n=!1,i=e.substring(r,s),r=s+1):";"==a&&(o[e.substring(r,s)]=1,r=s+1):t&&";"==a&&(n=!0,t=!1,o[i]=e.substring(r,s),i=null,r=s+1),s++}const a=e.substr(r,s);return i?o[i]=a:o[a]=1,o}n.d(t,{w:()=>s})},6819:(e,t,n)=>{"use strict";n.d(t,{S:()=>d,e:()=>f});var s=n(2273),r=n(9380),o=n(4298);function a(e,t,n){if(!t)return null;for(const r of e.split(",")){const e=r.replace(/&/g,",").split("|"),o={};for(let n=0;n<t.length;n++)e[n]&&(o[t[n].name]=e[n]);if(!o.Allele)continue;let i=null;for(const e of n.alleles)if(e.allele==o.Allele){i=e;break}if(i){if(i.ann||(i.ann=[]),i.ann.push(o),o._gene=o.Gene_Name,o.Feature_Type&&"transcript"==o.Feature_Type&&o.Feature_ID&&(o._isoform=o.Feature_ID.split(".")[0]),o.Annotation){const[e,t,n]=(0,s.vepinfo)(o.Annotation);o._dt=e,o._class=t,o._csqrank=n}else o._dt=dtsnvindel,o._class=mclassnonstandard;o["HGVS.p"]?o._mname=o["HGVS.p"]:o["HGVS.c"]&&(o._mname=o["HGVS.c"])}}return!0}var l=n(736);const c=new RegExp(/<(.+)>/),u={};for(const e in s.mclass)u[s.mclass[e].label.toUpperCase()]=e;function f(e){let t=[],n=[],s={},r=!1,o={},i=!1;for(const a of e)if(a.startsWith("#"))if(a.startsWith("#C"))t=a.split("\t").slice(9);else if(a.startsWith("##INFO")){const e=m(a.substring(8,a.length-1),s);e?n.push("INFO error: "+e):r=!0}else if(a.startsWith("##FORMAT")){const e=m(a.substring(10,a.length-1),o);e?n.push("FORMAT error: "+e):i=!0}const a=[];for(const e of t){const t={name:e};a.push(t)}if(s.CSQ){const e=s.CSQ.Description.split(" Format: ");if(e[1]){const t=e[1].split("|");if(t.length>1){s.CSQ.csqheader=[];for(const e of t){const t={name:e};s.CSQ.csqheader.push(t)}}else n.push("unknown format for CSQ header: "+s.CSQ.Description)}else n.push("unknown format for CSQ header: "+s.CSQ.Description)}if(s.ANN){const e=s.ANN.Description.split("'");if(e[1]){const t=e[1].split(" | ");if(t.length){s.ANN.annheader=[];for(const e of t){const t={name:e};s.ANN.annheader.push(t)}}else n.push('no " | " joined annotation fields for ANN (snpEff annotation): '+s.ANN.Description)}else n.push("no single-quote enclosed annotation fields for ANN (snpEff annotation): "+s.ANN.Description)}return[r?s:null,i?o:null,a,n.length?n:null]}function d(e,t){const n=e.split("\t");if(n.length<8)return["line has less than 8 fields",null,null];const s=Number.parseInt(n[1]);if(!Number.isInteger(s))return["invalid value for genomic position",null,null];const i=n[3],u={vcf_ID:n[2],chr:(t.nochr?"chr":"")+n[0],pos:s-1,ref:i,altstr:n[4],alleles:[{allele:i,sampledata:[]}],info:{},name:"."==n[2]?null:n[2]},f=[];for(const e of n[4].split(",")){const t={ref:u.ref,allele:e,allele_original:e,sampledata:[],_m:u,info:{}};if(u.alleles.push(t),"<"==e[0]){const n=e.match(c);if(!n){f.push(e);continue}t.type=n[1],t.allele=n[1],t.issymbolicallele=!0}else{const[e,n,s]=p(u.pos,u.ref,t.allele);t.pos=e,t.ref=n,t.allele=s}}n[8]&&n[9]&&function(e,t,n){const s=e[8].split(":");for(let r=9;r<e.length;r++){const o=e[r].split(":");{let e=!0;for(const t of o)if("."!=t){e=!1;break}if(e)continue}const i=r-9;for(let e=1;e<t.alleles.length;e++){const s={};if(n.samples&&n.samples[i])for(const e in n.samples[i])s[e]=n.samples[i][e];else s.name="missing_samplename_from_vcf_header";t.alleles[e].sampledata.push({sampleobj:s})}for(let e=0;e<s.length;e++){const r=s[e],i=o[e];if("."==i)continue;if("GT"==r){const e=-1!=i.indexOf("/")?"/":"|";let n=0,s=!1;const r=[];for(const o of i.split(e)){if("."==o){s=!0;continue}const e=Number.parseInt(o);if(Number.isNaN(e)){s=!0;continue}n+=e;const i=t.alleles[e];i&&r.push(i.allele)}let o=!1;s||(o=0==n);const a=r.join(e);for(let e=1;e<t.alleles.length;e++){const n=t.alleles[e].sampledata[t.alleles[e].sampledata.length-1];n.GT=i,n.genotype=a,o&&(n.gtallref=!0),n.__gtalleles=r}continue}const a=n.format?n.format[r]:null;if(!a){for(let e=1;e<t.alleles.length;e++)t.alleles[e].sampledata[t.alleles[e].sampledata.length-1][r]=i;continue}const l="Integer"==a.Type,c="Float"==a.Type;if(a.Number&&"R"==a.Number||"AD"==r){const e=i.split(",").map((e=>l?Number.parseInt(e):c?Number.parseFloat(e):e));for(let n=1;n<t.alleles.length;n++)if(null!=e[n]){const s=t.alleles[n],o=s.sampledata[s.sampledata.length-1];o[r]={},o[r][s.ref]=e[0],o[r][s.allele]=e[n]}}else if(a.Number&&"A"==a.Number){const e=i.split(",").map((e=>l?Number.parseInt(e):c?Number.parseFloat(e):e));for(let n=1;n<t.alleles.length;n++)if(null!=e[n-1]){const s=t.alleles[n],o=s.sampledata[s.sampledata.length-1];o[r]={},o[r][s.allele]=e[n-1]}}else for(let e=1;e<t.alleles.length;e++)t.alleles[e].sampledata[t.alleles[e].sampledata.length-1][r]=i}}for(const e of t.alleles)for(const t of e.sampledata)if(t.AD){t.allele2readcount={};for(const e in t.AD)t.allele2readcount[e]=t.AD[e]}}(n,u,t),u.alleles.shift();const d="."==n[7]?[]:(0,r.w)(n[7]);let m=[];t.info?m=function(e,t,n){const s=[];for(const r in e){if(null==n.info[r]){s.push(r);continue}const i=e[r];if("CSQ"==r){(0,o.A)(i,n.info.CSQ.csqheader,t)||(t.info[r]=i);continue}if("ANN"==r){a(i,n.info.ANN.annheader,t)||(t.info[r]=i);continue}if("Flag"==n.info[r].Type){t.info[r]=r;continue}const l=n.info[r].Number,c="Integer"==n.info[r].Type,u="Float"==n.info[r].Type;if("0"==l){t.info[r]=r;continue}if("A"==l){const e=i.split(",");for(let n=0;n<e.length;n++)t.alleles[n]&&(t.alleles[n].info[r]=c?Number.parseInt(e[n]):u?Number.parseFloat(e[n]):e[n]);continue}if("1"==l){t.info[r]=c?Number.parseInt(i):u?Number.parseFloat(i):i;continue}if(!i.split)continue;const f=i.split(",");t.info[r]=c?f.map(Number.parseInt):u?f.map(Number.parseFloat):f}return s}(d,u,t):u.info=d;const h=[];for(const e of u.alleles){const t={};for(const e in u)"alleles"!=e&&(t[e]=u[e]);for(const n in e)"allele"==n?t.alt=e[n]:"info"==n?t.altinfo=e[n]:t[n]=e[n];t.issymbolicallele||"NON_REF"==t.alt||(t.type=(0,l.P)(t.ref,t.alt)),h.push(t)}return[m.length?"unknown info keys: "+m.join(","):null,h,f.length>0?f:null]}function p(e,t,n){for(;t.length>1&&n.length>1&&t[t.length-1]==n[n.length-1];)t=t.substr(0,t.length-1),n=n.substr(0,n.length-1);for(;t.length>1&&n.length>1&&t[0]==n[0];)t=t.substr(1),n=n.substr(1),e++;return[e,t,n]}function m(e,t){const n={},s=[];let r=0,o=!1,a=null;for(let t=0;t<e.length;t++)if('"'!=e[t])"="!=e[t]?","!=e[t]||(o?o=!1:a?(n[a]=e.substring(r,t),a=null):s.push("k undefined"),r=t+1):(a=e.substring(r,t),r=t+1);else{t++;const r=t;for(;'"'!=e[t];)t++;a?(n[a]=e.substring(r,t),a=null):s.push("k undefined before double quotes"),o=!0}return a&&(n[a]=e.substring(r,i)),n.ID?(t[n.ID]=n,s.length?s.join("\n"):void 0):"no ID"}},736:(e,t,n)=>{"use strict";n.d(t,{P:()=>r});var s=n(2273);function r(e,t){return 1==e.length&&1==t.length?"."==t?s.mclassdeletion:s.mclasssnv:e.length==t.length?s.mclassmnv:e.length<t.length?s.mclassinsertion:e.length>t.length?s.mclassdeletion:s.mclassnonstandard}},7011:(e,t,n)=>{"use strict";n.d(t,{q:()=>o});var s=n(1868);const{bin:r}=n(9724);function o(e,t,n=!1,r=20,o=5){const[a,l]=e.domain(),[c,u]=s.Wem(t.values),f=Math.abs(l-a)/r;if(c==u)return{bins:[{x0:c,x1:u,density:1}],densityMax:u};let d=n?function(e,t,n,r,o){const i=t.map((t=>[t,s.J69(n,(n=>e(t-n)))])),a=[];let l=0;for(const e of i){const t={x0:e[0],x1:e[0]+o,density:e[1]};if(t.density>l&&(l=t.density),0!=t.density||0!=l){if(t.x1>r)break;a.push(t)}}return a.push({x0:r,x1:r,density:0}),{bins:a,densityMax:l}}(function(e){return t=>Math.abs(t/=e)<=1?.75*(1-t*t)/e:0}(o),e.ticks(r),t.values,u,f):i(e,t.values,r,u);return n&&0==d.densityMax&&(console.log("using histogram as max density with KDE is 0"),d=i(e,t.values,r,u)),d.bins.unshift({x0:a,x1:a,density:0}),d}function i(e,t,n,s){const o=r().domain(e.domain()).thresholds(e.ticks(n)).value((e=>e))(t),i=[];let a=0;for(const e of o)if(e.length>a&&(a=e.length),(0!=e.length||0!=a)&&(i.push({x0:e.x0,x1:e.x1,density:e.length}),e.x1>s))break;return i.push({x0:s,x1:s,density:0}),{bins:i,densityMax:a}}},4013:(e,t,n)=>{"use strict";n.d(t,{l2:()=>Br,LJ:()=>Jr,g_:()=>Lr,U_:()=>Fr,lE:()=>To,SC:()=>Yr,OG:()=>Vr});var s=n(334),r=n.n(s);const o=require("express");var i=n.n(o);n(6464);const a=require("url");var l=n.n(a);const c=require("http");var u=n.n(c);const f=require("https");var d=n.n(f),p=n(7147),m=n.n(p),h=n(1017),g=n.n(h),y=n(6452),b=n.n(y);const v=require("lazy");var w=n.n(v);const _=require("compression");var k=n.n(_),q=n(2081),x=n.n(q),N=n(6718),S=n(1881);const A=require("body-parser");var C=n.n(A),j=n(7219),T=n.n(j),M=n(4521),O=n.n(M),I=n(9344),E=n.n(I),R=n(3345),F=n(2273),$=n(6819),D=n(8064),L=n(5494),P=n(6733),G=n(5558),U=n(3602),z=n(6279),B=n(8423),J=n(8235),H={},W={};function V(e){return new Function("d","return {"+e.map((function(e,t){return JSON.stringify(e)+": d["+t+'] || ""'})).join(",")+"}")}function Z(e){var t=Object.create(null),n=[];return e.forEach((function(e){for(var s in e)s in t||n.push(t[s]=s)})),n}function K(e,t){var n=e+"",s=n.length;return s<t?new Array(t-s+1).join(0)+n:n}function X(e){var t,n=e.getUTCHours(),s=e.getUTCMinutes(),r=e.getUTCSeconds(),o=e.getUTCMilliseconds();return isNaN(e)?"Invalid Date":((t=e.getUTCFullYear())<0?"-"+K(-t,6):t>9999?"+"+K(t,6):K(t,4))+"-"+K(e.getUTCMonth()+1,2)+"-"+K(e.getUTCDate(),2)+(o?"T"+K(n,2)+":"+K(s,2)+":"+K(r,2)+"."+K(o,3)+"Z":r?"T"+K(n,2)+":"+K(s,2)+":"+K(r,2)+"Z":s||n?"T"+K(n,2)+":"+K(s,2)+"Z":"")}var Y=function(e){var t=new RegExp('["'+e+"\n\r]"),n=e.charCodeAt(0);function s(e,t){var s,r=[],o=e.length,i=0,a=0,l=o<=0,c=!1;function u(){if(l)return W;if(c)return c=!1,H;var t,s,r=i;if(34===e.charCodeAt(r)){for(;i++<o&&34!==e.charCodeAt(i)||34===e.charCodeAt(++i););return(t=i)>=o?l=!0:10===(s=e.charCodeAt(i++))?c=!0:13===s&&(c=!0,10===e.charCodeAt(i)&&++i),e.slice(r+1,t-1).replace(/""/g,'"')}for(;i<o;){if(10===(s=e.charCodeAt(t=i++)))c=!0;else if(13===s)c=!0,10===e.charCodeAt(i)&&++i;else if(s!==n)continue;return e.slice(r,t)}return l=!0,e.slice(r,o)}for(10===e.charCodeAt(o-1)&&--o,13===e.charCodeAt(o-1)&&--o;(s=u())!==W;){for(var f=[];s!==H&&s!==W;)f.push(s),s=u();t&&null==(f=t(f,a++))||r.push(f)}return r}function r(t,n){return t.map((function(t){return n.map((function(e){return i(t[e])})).join(e)}))}function o(t){return t.map(i).join(e)}function i(e){return null==e?"":e instanceof Date?X(e):t.test(e+="")?'"'+e.replace(/"/g,'""')+'"':e}return{parse:function(e,t){var n,r,o=s(e,(function(e,s){if(n)return n(e,s-1);r=e,n=t?function(e,t){var n=V(e);return function(s,r){return t(n(s),r,e)}}(e,t):V(e)}));return o.columns=r||[],o},parseRows:s,format:function(t,n){return null==n&&(n=Z(t)),[n.map(i).join(e)].concat(r(t,n)).join("\n")},formatBody:function(e,t){return null==t&&(t=Z(e)),r(e,t).join("\n")},formatRows:function(e){return e.map(o).join("\n")},formatRow:o,formatValue:i}}("\t"),Q=Y.parse;Y.parseRows,Y.format,Y.formatBody,Y.formatRows,Y.formatRow,Y.formatValue;function ee(e){delete e.mclasslabel2key,delete e.sample2disease,delete e.patient2ori2sample}function te(e){return null==e?null:function(e){if("function"!=typeof e)throw new Error;return e}(e)}function ne(e){var t=0,n=e.children,s=n&&n.length;if(s)for(;--s>=0;)t+=n[s].value;else t=1;e.value=t}function se(e,t){e instanceof Map?(e=[void 0,e],void 0===t&&(t=oe)):void 0===t&&(t=re);for(var n,s,r,o,i,a=new le(e),l=[a];n=l.pop();)if((r=t(n.data))&&(i=(r=Array.from(r)).length))for(n.children=r,o=i-1;o>=0;--o)l.push(s=r[o]=new le(r[o])),s.parent=n,s.depth=n.depth+1;return a.eachBefore(ae)}function re(e){return e.children}function oe(e){return Array.isArray(e)?e[1]:null}function ie(e){void 0!==e.data.value&&(e.value=e.data.value),e.data=e.data.data}function ae(e){var t=0;do{e.height=t}while((e=e.parent)&&e.height<++t)}function le(e){this.data=e,this.depth=this.height=0,this.parent=null}le.prototype=se.prototype={constructor:le,count:function(){return this.eachAfter(ne)},each:function(e,t){let n=-1;for(const s of this)e.call(t,s,++n,this);return this},eachAfter:function(e,t){for(var n,s,r,o=this,i=[o],a=[],l=-1;o=i.pop();)if(a.push(o),n=o.children)for(s=0,r=n.length;s<r;++s)i.push(n[s]);for(;o=a.pop();)e.call(t,o,++l,this);return this},eachBefore:function(e,t){for(var n,s,r=this,o=[r],i=-1;r=o.pop();)if(e.call(t,r,++i,this),n=r.children)for(s=n.length-1;s>=0;--s)o.push(n[s]);return this},find:function(e,t){let n=-1;for(const s of this)if(e.call(t,s,++n,this))return s},sum:function(e){return this.eachAfter((function(t){for(var n=+e(t.data)||0,s=t.children,r=s&&s.length;--r>=0;)n+=s[r].value;t.value=n}))},sort:function(e){return this.eachBefore((function(t){t.children&&t.children.sort(e)}))},path:function(e){for(var t=this,n=function(e,t){if(e===t)return e;var n=e.ancestors(),s=t.ancestors(),r=null;e=n.pop(),t=s.pop();for(;e===t;)r=e,e=n.pop(),t=s.pop();return r}(t,e),s=[t];t!==n;)t=t.parent,s.push(t);for(var r=s.length;e!==n;)s.splice(r,0,e),e=e.parent;return s},ancestors:function(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t},descendants:function(){return Array.from(this)},leaves:function(){var e=[];return this.eachBefore((function(t){t.children||e.push(t)})),e},links:function(){var e=this,t=[];return e.each((function(n){n!==e&&t.push({source:n.parent,target:n})})),t},copy:function(){return se(this).eachBefore(ie)},[Symbol.iterator]:function*(){var e,t,n,s,r=this,o=[r];do{for(e=o.reverse(),o=[];r=e.pop();)if(yield r,t=r.children)for(n=0,s=t.length;n<s;++n)o.push(t[n])}while(o.length)}};var ce={depth:-1},ue={},fe={};function de(e){return e.id}function pe(e){return e.parentId}function me(){var e,t=de,n=pe;function s(s){var r,o,i,a,l,c,u,f,d=Array.from(s),p=t,m=n,h=new Map;if(null!=e){const t=d.map(((t,n)=>function(e){e=`${e}`;let t=e.length;ge(e,t-1)&&!ge(e,t-2)&&(e=e.slice(0,-1));return"/"===e[0]?e:`/${e}`}(e(t,n,s)))),n=t.map(he),r=new Set(t).add("");for(const e of n)r.has(e)||(r.add(e),t.push(e),n.push(he(e)),d.push(fe));p=(e,n)=>t[n],m=(e,t)=>n[t]}for(i=0,r=d.length;i<r;++i)o=d[i],c=d[i]=new le(o),null!=(u=p(o,i,s))&&(u+="")&&(f=c.id=u,h.set(f,h.has(f)?ue:c)),null!=(u=m(o,i,s))&&(u+="")&&(c.parent=u);for(i=0;i<r;++i)if(u=(c=d[i]).parent){if(!(l=h.get(u)))throw new Error("missing: "+u);if(l===ue)throw new Error("ambiguous: "+u);l.children?l.children.push(c):l.children=[c],c.parent=l}else{if(a)throw new Error("multiple roots");a=c}if(!a)throw new Error("no root");if(null!=e){for(;a.data===fe&&1===a.children.length;)a=a.children[0],--r;for(let e=d.length-1;e>=0&&(c=d[e]).data===fe;--e)c.data=null}if(a.parent=ce,a.eachBefore((function(e){e.depth=e.parent.depth+1,--r})).eachBefore(ae),a.parent=null,r>0)throw new Error("cycle");return a}return s.id=function(e){return arguments.length?(t=te(e),s):t},s.parentId=function(e){return arguments.length?(n=te(e),s):n},s.path=function(t){return arguments.length?(e=te(t),s):e},s}function he(e){let t=e.length;if(t<2)return"";for(;--t>1&&!ge(e,t););return e.slice(0,t)}function ge(e,t){if("/"===e[t]){let n=0;for(;t>0&&"\\"===e[--t];)++n;if(0==(1&n))return!0}return!1}const ye=require("express-basic-auth");var be=n.n(ye),ve=n(2826),we=n(1271),_e=n(1696);async function ke(e,t,n,s,r,o,i,a){const l=qe().height(e.query.barheight).min(s).max(r),c=t.width/(t.stop-t.start);await R.UE({args:[o,t.chr+":"+t.start+"-"+t.stop],dir:i,callback:o=>{const i=o.split("\t"),u=Number.parseInt(i[1]);if(Number.isNaN(u))return;const f=Number.parseInt(i[2]);if(Number.isNaN(f))return;const d=Number.parseFloat(i[3]);if(Number.isNaN(d))return;a.fillStyle=d>0?e.query.pcolor:e.query.ncolor;const p=l(d),m=n+(Math.max(u,t.start)-t.start)*c,h=n+(Math.min(f,t.stop)-t.start)*c,g=Math.max(1,h-m);a.fillRect(m,p.y,g,p.h),d>r?(a.fillStyle=e.query.pcolor2,a.fillRect(m,0,g,2)):d<s&&(a.fillStyle=e.query.ncolor2,a.fillRect(m,e.query.barheight-2,g,2))}})}function qe(){var e=50,t=0,n=100;function s(s){var r,o=!1,i=0;return 0==t&&0==n||t<=0&&n>=0&&(o=!0,i=e*n/(n-t)),o?s>=n?{y:0,h:i}:s>=0?{y:i-(r=i*s/n),h:r}:s<=t?{y:i,h:e-i}:{y:i,h:r=(e-i)*s/t}:s<=t?{y:e,h:0}:{y:e-(r=e*(s-t)/(n-t)),h:r}}return s.height=function(t){return e=t,s},s.min=function(e){return t=e,s},s.max=function(e){return n=e,s},s}function xe(e,t,n){return new Promise(((s,o)=>{const i=(0,q.spawn)(r().bigwigsummary,["-udcDir="+r().cachedir,n,t.chr,t.start,t.stop,Math.ceil(t.width*(e.query.dotplotfactor||1))]),a=[],l=[];i.stdout.on("data",(e=>a.push(e))),i.stderr.on("data",(e=>l.push(e))),i.on("close",(e=>{const t=l.join("");t.length?t.startsWith("no data")?s():o("Cannot read bigWig file"):s(a.join(""))}))}))}function Ne(e,t,n,s,r){const[o,i]=function(e,t){let n=e.width/t.size,s=0;n>40&&(n=40,s=(e.width-n*t.size)/2);const r=new Map,o=e.reverse?[...t].sort(((e,t)=>t-e)):[...t].sort(((e,t)=>e-t));let i=s;for(const e of o)r.set(e,i+n/2),i+=n;return[n,r]}(e,n),a=new Map;{const t=(e.stop-e.start)/e.width;for(const s of n)e.reverse?a.set(s,(e.stop-s)/t):a.set(s,(s-e.start)/t)}let l=0;for(const e of t)l=Math.max(l,(i.get(e.stop)-i.get(e.start))/2);const c=s+l+o/2,u=(0,N.createCanvas)(e.width*r,c*r),f=u.getContext("2d");r>1&&f.scale(r,r),f.strokeStyle="black";for(const e of n)f.beginPath(),f.moveTo(a.get(e),0),f.lineTo(i.get(e),s),f.closePath(),f.stroke();for(const e of t){const t=i.get(e.start),n=i.get(e.stop),r=(t+n)/2,a=s+Math.abs(n-t)/2,l=Math.floor(255*(1-e.r2));f.fillStyle="rgb(255,"+l+","+l+")",f.beginPath(),f.moveTo(r,a-o/2),f.lineTo(r-o/2,a),f.lineTo(r,a+o/2),f.lineTo(r+o/2,a),f.lineTo(r,a-o/2),f.closePath(),f.fill()}return{height:c,src:u.toDataURL()}}var Se=n(938);async function Ae(e,t,n){const s={rglst:[]};let r=0,o=0;if(e.autoscale){for(const s of e.rglst){const i=(n?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop;await R.UE({args:[e.file,i],dir:t,callback:e=>{const[t,n,s,i]=e.split("\t");for(const e of i.split(",")){const t=Number(e);r=Math.min(r,t),o=Math.max(o,t)}}})}s.minv=r,s.maxv=o}else r=e.minv,o=e.maxv;const i=app.makeyscale().height(e.barheight).min(r).max(o);for(const a of e.rglst){const l={chr:a.chr,start:a.start,stop:a.stop,width:a.width,reverse:a.reverse,xoff:a.xoff},c=(0,N.createCanvas)(a.width,e.barheight),u=c.getContext("2d"),f=(n?a.chr.replace("chr",""):a.chr)+":"+a.start+"-"+a.stop;await R.UE({args:[e.file,f],dir:t,callback:t=>{const[n,s,l,c]=t.split("\t"),f=Math.max(Number.parseInt(s),a.start),d=Math.min(Number.parseInt(l),a.stop),p=(a.reverse?a.stop-d:f-a.start)*a.width/(a.stop-a.start),m=(a.reverse?a.stop-f:d-a.start)*a.width/(a.stop-a.start);for(const t of c.split(",")){const n=Number(t);u.fillStyle=n>0?e.pcolor:e.ncolor;const s=i(n),a=Math.max(1,m-p);u.fillRect(p,s.y,a,2),n>o?(u.fillStyle=req.query.pcolor2,u.fillRect(p,0,a,2)):n<r&&(u.fillStyle=req.query.ncolor2,u.fillRect(p,e.barheight-2,a,2))}}}),l.img=c.toDataURL(),s.rglst.push(l)}return s}var Ce=n(2781);const je=require("node:stream/promises"),Te="all",Me="support_ref",Oe="support_alt",Ie="support_no",Ee="support_amb",Re="support_sv";function Fe(e){const t={};if(e.variant)if(e.grouptype)t[e.grouptype]={partstack:e.partstack};else{t[Me]={},t[Ie]={},t[Ee]={};for(let n=0;n<e.variant.length;n++)t[Oe+n.toString()]={}}else{if(!e.sv)throw"q.variant or q.sv missing";e.grouptype?t[e.grouptype]={partstack:e.partstack}:(t[Re]={},t[Me]={})}for(const n in t){const s=t[n];s.type=n,s.templates=[],s.regions=$e(e.regions),s.messages=[]}return t}function $e(e){return e.map((e=>({x:e.x,scale:e.scale,ntwidth:e.ntwidth})))}var De=n(6113),Le=n.n(De),Pe=n(4314);require("jstat"),r().features,r().clustalo;function Ge(e){return e>1e9?(e/1e9).toFixed(2)+" GB":e>1e6?(e/1e6).toFixed(2)+" MB":e>1e3?(e/1e3).toFixed(2)+" KB":e+" Bytes"}const Ue={end_point:"files/",fields:["id","file_size","data_type","experimental_strategy","cases.submitter_id","associated_entities.entity_submitter_id","associated_entities.case_id","cases.samples.sample_type","analysis.workflow_type"],size:100},ze={end_point:"cases/",fields:["case_id"]},Be=[{type:"case",field:"cases.case_id"},{type:"case",field:"cases.submitter_id"},{type:"sample",field:"cases.samples.submitter_id"},{type:"sample",field:"cases.samples.sample_id"},{type:"aliquot",field:"cases.samples.portions.analytes.aliquots.submitter_id"},{type:"aliquot",field:"cases.samples.portions.analytes.aliquots.aliquot_id"}],Je="STAR 2-Pass Transcriptome",He=100,We=1e3;let Ve;async function Ze(e,t,n,s){for(const r of Be)if(await Ke(e,r.field,n,s))return t.isCaseSample=r.type,await Xe(e,r.field,10,s);const r=await Ye(e,"file_id",s);if(r.data.hits.length)return t.is_file_uuid=!0,r;const o=await Ye(e,"file_name",s);return o.data.hits.length&&(t.is_file_id=!0),o}async function Ke(e,t,n,s){const r={op:"and",content:[{op:"=",content:{field:t,value:e}}]};return(await Ve(r,ze,null,n,s)).data.hits.length>0}async function Xe(e,t,n,s){const r={op:"and",content:[{op:"=",content:{field:"data_category",value:"Sequencing Reads"}},{op:"=",content:{field:"index_files.data_format",value:"bai"}},{op:"=",content:{field:"data_type",value:"Aligned Reads"}},{op:"=",content:{field:"data_format",value:"bam"}}]};return e&&t&&r.content.push({op:"in",content:{field:t,value:e}}),await Ve(r,Ue,n,null,s)}async function Ye(e,t,n){const s={op:"and",content:[{op:"in",content:{field:t,value:e}}]},r=await Ve(s,Ue,null,null,n),o=r.data.hits[0];if(o&&"Aligned Reads"!=o.data_type)throw"Requested file is not a BAM file.";return r}async function Qe(e,t,n){const{host:s,headers:r}=t.getHostHeaders(n);r.Range="bytes=0-0";const o=s.rest+"/data/"+e;try{const e=await b()(o,{headers:r,decompress:!1});if(!(e.statusCode>=200&&e.statusCode<400))throw console.log(`gdcCheckPermission() error for got(${o})`,e),"Invalid status code: "+e.statusCode}catch(e){throw console.log("gdcCheckPermission error: ",e?.code||e),"Permission denied"}}const et=r().clustalo,tt="rgb(120,120,120)",nt="rgb(230,230,230)",st=(0,Pe.ZP)(nt,tt),rt="#d48b37",ot=(0,Pe.ZP)("#dbc6ad",rt),it="#3B7A57",at=(0,Pe.ZP)("#E5FFCC",it),lt="#d13232",ct="#ffdbdd",ut=(0,Pe.ZP)(ct,lt),ft="#4888bf",dt="#c9e6ff",pt=(0,Pe.ZP)(dt,ft),mt="#6B4423",ht=(0,Pe.ZP)("#987654",mt),gt="#fc6df3",yt=(0,Pe.ZP)("#dea4da",gt),bt="#47FFFC",vt="#B2D7D7",wt=(0,Pe.ZP)(vt,bt),_t=12,kt=7,qt="black",xt="#ededed",Nt="blue",St="#e0e0e0",At="#FF0000",Ct="#6cc24a",jt="#ffff00",Tt="#DEB887",Mt="#CD853F",Ot="#9a92ec",It="#47C8FF",Et=1,Rt=1,Ft=.4,$t=.9,Dt=7,Lt=7,Pt=10,Gt=7,Ut=40,zt=.5,Bt=2,Jt=5,Ht=7e3,Wt=1500,Vt=2e3,Zt=7,Kt=200,Xt=20,Yt=(new Set(["A","T","C","G"]),Math.random.toString()),Qt=3e5;function en(e){const t=e.hg38?.datasets?.GDC;if(!t)throw"hg38.datasets.GDC missing";return t}async function tn(e,t,n,s,r){const o=e.diff_score_plotwidth/(s-r),i=s*o-r*o,a=(0,N.createCanvas)(i*e.devicePixelRatio,t.canvasheight*e.devicePixelRatio),l=a.getContext("2d");e.devicePixelRatio>1&&l.scale(e.devicePixelRatio,e.devicePixelRatio);const c=n.map((e=>e.__tempscore)),u=t.canvasheight/c.length;let f=0;const d=t.stackspace/t.canvasheight;for(const e of c){let t=0;for(const n of e)"alt0"==n?l.fillStyle=At:"ref"==n?l.fillStyle=It:"alt1"==n?l.fillStyle=Ct:"alt2"==n?l.fillStyle=jt:"alt3"==n?l.fillStyle=Tt:"alt4"==n?l.fillStyle=Mt:"alt5"==n&&(l.fillStyle=Ot),l.fillRect(o*t,f*u,o,u-d*u),t+=1;f+=1}return{height:t.canvasheight,width:i,src:a.toDataURL(),read_height:u}}function nn(e,t,n,s){for(const r of n)for(const n of r.segments)if(!(n.ridx!=e||Math.max(n.segstart,t.start)>Math.min(n.segstop,t.stop)))for(const e of n.boxes)if(t.ntwidth>=1){if(("S"==e.opr||"X"==e.opr)&&e.s)for(let t=0;t<e.s.length;t++){const n=e.start+t,r=s.find((e=>e.position==n));if(!r)continue;const o=e.s[t];r[o]=1+(r[o]||0),"S"==e.opr&&r.total++}}else if("S"==e.opr){const n=Math.floor((e.start-t.start)*t.ntwidth),r=Math.floor((e.start+e.len-t.start)*t.ntwidth);for(let e=n;e<=r;e++){const t=s[e];t&&(t.softclip=1+(t.softclip||0),t.total++)}}}async function sn(e){if(e.query.gdcFileUUID){const t=g().join(r().cachedir_bam,e.query.file);return await async function(e,t){try{if(!await R.yE(t))return;const n=e.query.regions,s=e.query.gdcFilePosition.split(".");e.query.regions=[{chr:s[0],start:Number(s[1]),stop:Number(s[2])}],await Nn(e),e.query.regions=n}catch(e){throw e}}(e,t),[t,null]}const[t,n,s]=R.ZX(e);if(t)throw t;return[n,s?await R.d1(n,e.query.indexURL||n+".bai"):null]}async function rn(e,t,n,s,r){const o=e.map((e=>e.segments[0].seq)),i=e.map((e=>e.segments[0].qual));let a="",l="";r&&(a+=">seq\n"+r.replace("\n","")+"\n");let c=0;for(const e of o){if(!(c<Kt))break;a+=">seq\n"+e.replace("\n","")+"\n",l+=gn(i[c].replace("\n",""))+"\n",c+=1}return await function(e,t,n,s,r,o,i,a){return new Promise(((n,l)=>{const c=(0,q.spawn)(et,["-i","-","-t","DNA","--outfmt=clu","--wrap=5000","--maxnumseq="+(t+1),"--maxseqlen=1000"]),u=[],f=[];Ce.Readable.from(e).pipe(c.stdin),c.stdout.on("data",(e=>u.push(e))),c.stderr.on("data",(e=>f.push(e))),c.on("error",(e=>{console.log("stderr (clustalo):",f),l(e)})),c.on("close",(e=>{let t=0;const c=[],f={final_read_align:[],qual_r:[],qual_g:[],qual_b:[]};let d=0;for(const e of u.toString().split("\n"))if(e.includes("seq ")){let n=0,l="",u=0,p="";0!=t&&a?p=s.split("\n")[t-1].split(","):a||(p=s.split("\n")[t].split(","));let m="",h="",g="";for(const s of e.replace("seq ",""))if(","!=s){if("-"!=s){if(n+=1,l+=s,0==t&&a)c.push(s);else if(s==c[u]&&a||!a){const e=st(p[n-1]/Ut).replace("rgb(","").replace(")","").split(",");m+=e[0]+",",h+=e[1]+",",g+=e[2]+","}else if(s!=c[u]&&a){const e=ut(p[n-1]/Ut).replace("rgb(","").replace(")","").split(",");m+=e[0]+",",h+=e[1]+",",g+=e[2]+","}}else n>0&&n<e.replace(/-/g,"").replace(/,/g,"").replace("seq ","").length?(l+=s,0==t&&(c.push(s),u<r&&(d+=1))):(l+=" ",0==t&&c.push(s)),m+="255,",h+="255,",g+="255,";u+=1}t+=1,f.gaps_before_variant=d,f.read_count=a?t-1:t,f.qual_r.push(m),f.qual_g.push(h),f.qual_b.push(g),f.final_read_align.push(l),0!=o&&0!=i&&(f.partstack_start=o,f.partstack_stop=i)}else(e.includes("FATAL:")||e.includes("ERROR:"))&&(console.log(e),l(e));n(f)}))}))}(a,Kt,o.length,l,t,n,s,r)}async function on(e,t){let n=0;for(const s of t){const t=["view","-c",e.file];e.gdc_case_id||t.push((e.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop),await R.UE({isbam:!0,args:t,dir:e.dir,callback:e=>{const t=Number(e);if(!Number.isInteger(t))throw"total number of reads from a region not integer";n+=t}})}if(n<1.1*Ht)return;const s=(n-Ht)/(.1*Ht);e.downsample={keep:10,skip:Math.floor(s),pointer:0},e.read_limit_reached=n}async function an(e,t){e.lines=[];const n=["view",t.file];t.gdc_case_id||n.push((t.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop),await R.UE({isbam:!0,args:n,dir:t.dir,callback:(n,s)=>{const r=n.split("\t")[1];if(!(1024&r&&t.drop_pcrduplicates||2048&r&&t.drop_supplementary_alignments)){if(t.downsample){const e=t.downsample;if(e.pointer++,e.pointer>=e.keep&&e.pointer<e.keep+e.skip)return;e.pointer>=e.keep+e.skip&&(e.pointer=0)}e.lines.push(n)}}})}async function ln(e,t){const n=[],s=["depth","-r",(e.nochr?t.chr.replace("chr",""):t.chr)+":"+(t.start+1)+"-"+t.stop,"-g","DUP",e.file||e.url];if(e.drop_pcrduplicates&&(s.push("-G"),s.push("0x400")),e.drop_supplementary_alignments&&(s.push("-G"),s.push("0x800")),await R.UE({isbam:!0,args:s,dir:e.dir,callback:e=>{const s=e.split("\t"),r=Number.parseInt(s[1])-1,o=Number.parseInt(s[2]);if(t.ntwidth>=1)return void n.push({position:r,total:o});const i=Math.floor((r-t.start)*t.ntwidth);n[i]||(n[i]={position:r,sum:0,count:0}),n[i].sum+=o,n[i].count++}}),t.ntwidth<1)for(const e of n)e&&(e.total=e.sum/e.count,delete e.sum,delete e.count);return n}async function cn(e,t){for(const e of t.regions)e.lines.length>0&&e.ntwidth>=$t&&(e.to_checkmismatch=!0,e.referenceseq=await mn(t.genome,e.chr+":"+(e.start+1)+"-"+e.stop));for(const n of e)for(const e of n.segments){const n=t.regions[e.ridx];if(!n.to_checkmismatch)continue;const s=[];for(const t of e.boxes)null!=t.cidx&&"M"==t.opr&&(t.s=e.seq.substr(t.cidx,t.len),bn(s,n,t,t.s));s.length&&e.boxes.push(...s)}for(const e of t.regions)delete e.to_checkmismatch,delete e.referenceseq}function un(e,t){if(!e.asPaired){const n=[];for(let s=0;s<e.regions.length;s++){const r=e.regions[s];for(const o of t.templates){o.ridx=s;const t=fn(o,r,e);t&&n.push({x1:t.x1,x2:t.x2,__tempscore:t.tempscore,segments:[t]})}}return n}const n=new Map;for(let s=0;s<e.regions.length;s++){const r=e.regions[s];for(const o of t.templates){o.ridx=s;const t=fn(o,r,e);if(!t||!t.qname)continue;const i=n.get(t.qname);i?(i.segments.push(t),i.x2=Math.max(i.x2,t.x2)):n.set(t.qname,{x1:Math.max(t.x1,r.x),x2:Math.min(t.x2,r.x+r.width),__tempscore:t.tempscore,segments:[t]})}}return[...n.values()]}function fn(e,t,n){const{sam_info:s,tempscore:r,ridx:o,keepallboxes:i,keepmatepos:a,keepunmappedread:l}=e,c=s.trim().split("\t");if(c.length<11)return;const u=c[0],f=c[1],d=Number.parseInt(c[3]),p=c[5],m=c[6],h=c[7],g=Number.parseInt(c[8]),y=c[9],b=c[10];if(Number.isNaN(d)||d<=0)return;const v=d-1,w={qname:u,segstart:v,segstart_original:v,segstop:v,boxes:[],forward:!(16&f),ridx:o,seq:y,qual:b,cigarstr:p,tlen:g,flag:f,tempscore:r};if(function(e,t,n,s,r,o){const i=e.flag;if(!(1&i))return;64&i?e.isfirst=!0:128&i&&(e.islast=!0);if("="!=t&&"*"!=t&&t!=s.chr)return e.rnext=t,void(e.pnext=n);if(8&i)return void(e.discord_unmapped2=!0);32&i&&!(16&i)&&64&i||16&i&&!(32&i)&&128&i||16&i&&!(32&i)&&64&i||32&i&&!(16&i)&&128&i||(e.discord_orientation=!0,r&&(16&i?32&i?e.discord_orientation_direction="R1R2":n>o&&(e.discord_orientation_direction="R1F2"):32&i?n<o&&(e.discord_orientation_direction="R1F2"):e.discord_orientation_direction="F1F2")),2&i||(e.discord_wrong_insertsize=!0,r&&(e.pnext=n))}(w,m,h,t,a,d),4&f)return l?(w.boxes.push({opr:p,start:v,len:y.length,cidx:0,qual:b}),w.discord_unmapped1=!0,w):void 0;if("*"!=p){let e=v,s=0,r=0;for(let n=0;n<p.length;n++){const o=p[n];if(o.match(/[0-9]/))continue;const a=Number.parseInt(p.substring(s,n));if("H"!=o)if("N"==o||"P"==o||"D"==o||(r+=a),s=n+1,"="!=o&&"M"!=o)if("I"!=o)if("N"!=o&&"D"!=o)if("X"!=o)if("S"!=o){if("P"!=o)console.log("unknown cigar: "+o);else if(i||e>t.start&&e<t.stop){const t={opr:"P",start:e,len:a,cidx:r-a};w.boxes.push(t)}}else{const n={opr:o,start:e,len:a,cidx:r-a};0==w.boxes.length?(n.start-=a,(i||Math.max(e,t.start)<=Math.min(e+a-1,t.stop))&&w.boxes.push(n)):w.boxes.push(n)}else{if(i||Math.max(e,t.start)<Math.min(e+a-1,t.stop)){const t={opr:o,start:e,len:a,cidx:r-a};w.boxes.push(t)}e+=a}else(e>=t.start&&e<=t.stop||e+a-1>=t.start&&e+a-1<=t.stop||i)&&w.boxes.push({opr:o,start:e,len:a}),e+=a;else(i||e>t.start&&e<t.stop)&&a*t.ntwidth>=Et&&w.boxes.push({opr:"I",start:e,len:a,cidx:r-a});else(i||Math.max(e,t.start)<=Math.min(e+a-1,t.stop))&&w.boxes.push({opr:o,start:e,len:a,cidx:r-a}),e+=a;else{const l={opr:o,start:e,len:a,cidx:r-a};0==w.boxes.length?(l.start-=a,l.cidx=0,(i||Math.max(e,t.start)<=Math.min(e+a-1,t.stop))&&w.boxes.push(l)):w.boxes.push(l),s=n+1}}if(0==w.boxes.length)return void(n&&n.readcount_skipped++);w.segstop=e,w.x1=t.x+t.scale(w.boxes[0].start),w.x2=t.x+t.scale((_=w.boxes,Math.max(..._.map((e=>e.start+e.len)))))}var _;return w}async function dn(e,t,n){const[s,r]=function(e,t){let n=(t.groups.length>1?Wt/2:Wt)/e;return n>10?[Math.min(15,Math.floor(n)),1]:n>7?[Math.floor(n),1]:n>3?[Math.ceil(n),0]:n>1?[Math.floor(n),0]:[n,0]}(e.stacks.length,t);e.stackheight=s,e.stackspace=r;for(const t of e.regions)t.to_printnt=e.stackheight>7&&t.ntwidth>=7,t.to_qual=t.ntwidth>=Rt;if(e.stacks.length&&(e.stackheight>=Zt&&n.length<Vt?e.returntemplatebox=[]:e.partstack||(e.allowpartstack=!0)),e.stackheight>=Dt){let t=0;for(const e of n)for(const n of e.segments)t=Math.max(t,n.x2-n.x1);t>.7*e.stackheight&&(e.canClipArrowhead=!0)}}function pn(e,t,n){if(t.asPaired){e.stacks=[];const s=[],r=[];for(const e of n){let n=e.segments[0].ridx;1==e.segments.length||2==e.segments.length&&e.segments[0].ridx==e.segments[1].ridx?(e.x1=Math.max(t.regions[n].x,e.x1),e.x2=Math.min(t.regions[n].x+t.regions[n].width,e.x2),s.push(e)):2==e.segments.length&&e.segments[0].ridx!=e.segments[1].ridx&&(e.x1=e.x1,e.x2=e.x2,r.push(e))}if(s.sort(((e,t)=>e.x1-t.x1)),r.sort(((e,t)=>e.x1-t.x1)),r.length>0){const e=[],t=[],o=r[0];for(const n of s)n.x1<o.x1&&n.x2<o.x1?e.push(n):t.push(n);n=[...e,...r,...t]}for(const s of n){let n=s.segments[0].ridx,r=null;if(!t.variant)for(let o=0;o<e.stacks.length;o++){if(s.x2==t.regions[n].x+t.regions[n].width&&e.stacks[o]<s.x1){r=o,e.stacks[o]=s.x2;break}if(e.stacks[o]+t.stacksegspacing<s.x1){r=o,e.stacks[o]=s.x2;break}}null==r&&(r=e.stacks.length,e.stacks[r]=s.x2),s.y=r}}else{n.sort(((e,t)=>e.x1-t.x1)),e.stacks=[];for(let s=0;s<t.regions.length;s++)for(const r of n)if(r.segments[0].ridx==s){let n=null;if(!t.variant&&!t.sv)for(let o=0;o<e.stacks.length;o++)if(e.stacks[o]+t.stacksegspacing<r.x1&&e.stacks[o]+t.stacksegspacing<t.regions[s].x+t.regions[s].width){n=o,e.stacks[o]=r.x2;break}null==n&&(n=e.stacks.length,e.stacks[n]=r.x2),r.y=n}}return n=function(e,t,n){if(!e.partstack)return t;const s=t.filter((t=>t.y>=e.partstack.start&&t.y<=e.partstack.stop));s.forEach((t=>t.y-=e.partstack.start)),t=s,e.stacks=[];for(let t=e.partstack.start;t<=e.partstack.stop;t++)e.stacks.push(0);return e.returntemplatebox=[],t}(e,n),n}async function mn(e,t){const n=(await R.Kf(e,t)).split("\n");return n.shift(),n.join("").toUpperCase()}function hn(e,t,n){const s=function(e,t,n){const s=[];for(let t=0;t<e.stacks.length;t++)s.push(e.stackheight);if(function(e,t){if(!t.asPaired)return;for(const t of e.regions)if(t.ntwidth<=Ft)return;e.overlapRP_multirows=!0,e.overlapRP_hlline=e.stackspace>0}(e,n),e.overlapRP_multirows)for(const n of t)n.segments.length<=1||n.segments[0].ridx!=n.segments[1].ridx||(n.height=yn(n,e.stackheight),s[n.y]=Math.max(s[n.y],n.height));const r=[];let o=e.stackspace;for(const t of s)r.push(o),o+=t+e.stackspace;return e.canvasheight=o,r}(e,t,n);for(const n of t){n.y=s[n.y];for(const t of n.segments){const n=e.regions[t.ridx].to_qual?gn(t.qual):null;for(const e of t.boxes)null!=e.cidx&&"H"!=e.opr&&(n&&(e.qual=n.slice(e.cidx,e.cidx+e.len)),"I"==e.opr?e.s=t.seq.substr(e.cidx,e.len):"X"!=e.opr&&"S"!=e.opr||(e.s=t.seq.substr(e.cidx,e.len)),delete e.cidx);delete t.seq,delete t.qual}}}function gn(e){if("*"==e)return null;const t=[];for(let n=0;n<e.length;n++){const s=e[n].charCodeAt(0)-33;t.push(s)}return t}function yn(e,t){if(2==e.segments.length){const[n,s]=e.segments;return n.x2>s.x1?(s.shiftdownrow=1,2*t):t}console.log("more than 2 segments",e.segments.length);const n=[];for(const t of e.segments){let e=null;for(let s=0;s<n.length;s++)if(n[s]<t.x1){e=s,n[s]=t.x2;break}null==e&&(e=n.length,n[e]=t.x2),t.shiftdownrow=e}return t*n.length}function bn(e,t,n,s){for(let r=0;r<s.length;r++){if(n.start+r<t.start||n.start+r>t.stop)continue;const o=s[r];if(t.referenceseq[n.start+r-t.start]!=o.toUpperCase()){const t={opr:"X",start:n.start+r,len:1,s:o,cidx:n.cidx+r};e.push(t)}}}function vn(e,t,n,s){if(n.returntemplatebox){const e=n.regions[t.segments[0].ridx];let r;if(e.width=n.widths[t.segments[0].ridx],s.asPaired)if(2==t.segments.length)r=t.segments[0].ridx!=t.segments[1].ridx?{qname:t.segments[0].qname,x1:t.x1,x2:t.x2,y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop))),multi_region:!0}:{qname:t.segments[0].qname,x1:Math.max(e.x,t.x1),x2:Math.min(t.x2,e.width),y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop)))};else{const e=t.segments[0],s=n.regions[e.ridx];s.width=n.widths[e.ridx],r={qname:t.segments[0].qname,x1:Math.max(s.x,t.x1),x2:Math.min(t.x2,s.width),y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop)))}}else r={qname:t.segments[0].qname,x1:Math.max(e.x,t.x1),x2:Math.min(t.x2,e.x+e.width),y1:t.y,y2:t.y+(t.height||n.stackheight),start:Math.min(...t.segments.map((e=>e.segstart))),stop:Math.max(...t.segments.map((e=>e.segstop)))},t.segments[0].isfirst&&(r.isfirst=!0),t.segments[0].islast&&(r.islast=!0);n.returntemplatebox.push(r)}for(let r=0;r<t.segments.length;r++){const o=t.segments[r],i=n.regions[o.ridx];if(i.width=n.widths[o.ridx],0==r){wn(e,o,t.y,n,s);continue}const a=t.segments[r-1],l=n.regions[a.ridx];if(l.width=n.widths[a.ridx],a.x2<=o.x1||t.segments[0].ridx!=t.segments[1].ridx){wn(e,o,t.y,n,s);const r=Math.floor(t.y+n.stackheight/2)+.5;if(e.strokeStyle=n.stackheight<=2?xt:tt,e.setLineDash([5,3]),e.beginPath(),l.x==i.x?(e.moveTo(a.x2,r),e.lineTo(o.x1,r)):l.x<a.x2&&o.x1<i.width&&(e.moveTo(Math.min(a.x2,l.width),r),e.lineTo(Math.max(o.x1,i.x),r)),e.stroke(),n.overlapRP_hlline){const s=a.boxes.reduce(((e,t)=>e.start+e.len>t.start+t.len?e:t));if(s.start+s.len==o.boxes[0].start){e.strokeStyle=Nt,e.setLineDash([]),e.beginPath();const s=Math.floor(o.x1)+.5;e.moveTo(s,t.y),e.lineTo(s,t.y+n.stackheight),e.stroke()}}}else if(n.overlapRP_multirows){if(wn(e,o,t.y+n.stackheight,n,s),n.overlapRP_hlline){const s=Math.floor(t.y+n.stackheight)+.5;e.strokeStyle=Nt,e.setLineDash([]),e.beginPath(),l.x<=a.x2&&o.x1<=i.width&&(e.moveTo(Math.max(o.x1,i.x),s),e.lineTo(Math.min(a.x2,l.width),s)),e.stroke()}}else wn(e,o,t.y,n,s)}null!=t.__tempscore&&r().features.indel_read_alignment_scores&&(e.fillStyle="blue",e.font=n.stackheight+"pt Arial",e.fillText(t.__tempscore,s.regions[0].width-100,t.y+n.stackheight/2))}function wn(e,t,n,s,r){const o=s.regions[t.ridx];o.width=s.widths[t.ridx];for(const r of t.boxes){const i=o.x+o.scale(r.start);if("P"!=r.opr&&"I"!=r.opr)if("H"!=r.opr)if("D"!=r.opr&&"N"!=r.opr)if("*"!=r.opr){if("X"!=r.opr&&"S"!=r.opr){if("M"!=r.opr&&"="!=r.opr)throw"unknown opr at rendering: "+r.opr;if(o.to_qual&&r.qual){let a=i;r.qual.forEach((r=>{t.rnext?e.fillStyle=ot(r/Ut):t.discord_orientation?e.fillStyle=yt(r/Ut):t.discord_wrong_insertsize?e.fillStyle=at(r/Ut):t.discord_unmapped2?e.fillStyle=ht(r/Ut):e.fillStyle=st(r/Ut),a+o.ntwidth+zt<o.width&&o.x<=a?e.fillRect(a,n,o.ntwidth+zt,s.stackheight):a<o.width&&a+o.ntwidth+zt>=o.width&&o.x<=a?e.fillRect(a,n,o.width-a,s.stackheight):a<=o.x&&a+o.ntwidth+zt>o.x&&e.fillRect(o.x,n,o.ntwidth+zt+a-o.x,s.stackheight),a+=o.ntwidth}))}else r.qual?t.rnext?e.fillStyle=rt:t.discord_orientation?e.fillStyle=gt:t.discord_wrong_insertsize?e.fillStyle=it:t.discord_unmapped2?e.fillStyle=mt:e.fillStyle=tt:o.to_printnt?e.fillStyle="white":t.rnext?e.fillStyle=rt:t.discord_orientation?e.fillStyle=gt:t.discord_wrong_insertsize?e.fillStyle=it:t.discord_unmapped2?e.fillStyle=mt:e.fillStyle=tt,i+r.len*o.ntwidth+zt<o.width&&i<o.width&&o.x<i+zt?e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight):i+r.len*o.ntwidth+zt<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+zt+i-o.x,s.stackheight):i+r.len*o.ntwidth+zt>=o.width&&o.x<i?e.fillRect(i,n,o.width-i,s.stackheight):i+r.len*o.ntwidth+zt>=o.width&&o.x>=i&&e.fillRect(o.x,n,o.width-i,s.stackheight);if(o.to_printnt){e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial",r.qual?e.fillStyle="white":e.fillStyle="black";for(let t=0;t<r.s.length;t++)i+o.ntwidth*(t+.5)<o.width&&i<o.width&&o.x<=i+o.ntwidth*(t+.5)&&e.fillText(r.s[t],i+o.ntwidth*(t+.5),n+s.stackheight/2)}}else if(o.to_qual&&r.qual){o.to_printnt&&(e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial");let t=i;for(let i=0;i<r.qual.length;i++){const a=r.qual[i]/Ut;e.fillStyle="S"==r.opr?pt(a):ut(a),t+o.ntwidth+zt<o.x+o.width&&o.x<=t?e.fillRect(t,n,o.ntwidth+zt,s.stackheight):t<o.x+o.width&&t+o.ntwidth+zt>=o.x+o.width&&o.x<=t?e.fillRect(t,n,o.width+o.x-t,s.stackheight):t<=o.x&&t+o.ntwidth+zt>o.x&&e.fillRect(o.x,n,o.ntwidth+zt+t-o.x,s.stackheight),o.to_printnt&&(r.qual?e.fillStyle="white":e.fillStyle="black",t+o.ntwidth/2<o.width&&t<o.width&&o.x<=t+o.ntwidth/2&&e.fillText(r.s[i],t+o.ntwidth/2,n+s.stackheight/2)),t+=o.ntwidth}}else if(e.fillStyle="S"==r.opr?ft:lt,i+r.len*o.ntwidth+zt<o.width&&o.x<i?e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight):i+r.len*o.ntwidth+zt<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+zt+i-o.x,s.stackheight):i+r.len*o.ntwidth+zt<=o.width&&o.x<i&&e.fillRect(i,n,o.width-i,s.stackheight),o.to_printnt&&!r.qual){e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial",r.qual?e.fillStyle="white":e.fillStyle="black";for(let t=0;t<r.s.length;t++)i+o.ntwidth*(t+.5)<o.width&&i<o.width&&o.x<=i+o.ntwidth*(t+.5)&&e.fillText(r.s[t],i+o.ntwidth*(t+.5),n+s.stackheight/2)}}else{if(o.to_qual&&r.qual){let a=i;r.qual.forEach((r=>{t.discord_unmapped2&&(e.fillStyle=ht(r/Ut)),e.fillRect(a,n,o.ntwidth+zt,s.stackheight),a+=o.ntwidth}))}else t.discord_unmapped2&&(e.fillStyle=mt),e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight);o.to_printnt&&(e.font=Math.min(o.ntwidth,s.stackheight-2)+"pt Arial")}else{"D"==r.opr?e.strokeStyle=qt:e.strokeStyle=s.stackheight<=2?xt:tt,e.setLineDash([]);const t=Math.floor(n+s.stackheight/2)+.5;if(e.beginPath(),e.moveTo(Math.max(i,o.x),t),e.lineTo(Math.min(i+r.len*o.ntwidth,o.x+o.width),t),e.stroke(),s.stackheight>Lt){const t=Math.max(o.x,i),a=Math.min(o.x+o.width,i+r.len*o.ntwidth);if(a-t>=50){const i=Math.min(Pt,Math.max(Gt,s.stackheight-2));e.font=i+"pt Arial";const l=e.measureText(r.len+" bp").width;l<a-t-20&&(e.fillStyle="white",(a+t)/2+l/2<o.width&&o.x<(a+t)/2-l/2?(e.fillRect((a+t)/2-l/2,n,l,s.stackheight),e.fillStyle=tt,e.fillText(r.len+" bp",(a+t)/2,n+s.stackheight/2)):(a+t)/2+l/2<o.width&&o.x>=(a+t)/2-l/2?(e.fillRect(o.x,n,l+(a+t)/2-l/2-o.x,s.stackheight),e.fillStyle=tt,e.fillText(r.len+" bp",(a+t)/2,n+s.stackheight/2)):(a+t)/2+l/2>=o.width&&o.x<(a+t)/2-l/2&&(e.fillRect((a+t)/2-l/2,n,o.width-(a+t)/2+l/2,s.stackheight),e.fillStyle=tt,e.fillText(r.len+" bp",(a+t)/2,n+s.stackheight/2)))}}}else e.fillStyle="white",i+r.len*o.ntwidth+zt<o.width&&o.x<i?e.fillRect(i,n,r.len*o.ntwidth+zt,s.stackheight):i+r.len*o.ntwidth+zt<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+zt+i-o.x,s.stackheight):i+r.len*o.ntwidth+zt<=o.width&&o.x<i&&e.fillRect(i,n,o.width-i,s.stackheight)}!function(e,t,n,s,r){if(!n.canClipArrowhead)return;if(t.x2-t.x1<5)return;if(t.forward){const o=Math.ceil(t.x2+zt);o<=s.width+n.stackheight/2&&(e.fillStyle="white",e.beginPath(),e.moveTo(o-n.stackheight/2,r),e.lineTo(o,r),e.lineTo(o,r+n.stackheight/2),e.lineTo(o-n.stackheight/2,r),e.closePath(),e.fill(),e.beginPath(),e.moveTo(o-n.stackheight/2,r+n.stackheight),e.lineTo(o,r+n.stackheight),e.lineTo(o,r+n.stackheight/2),e.lineTo(o-n.stackheight/2,r+n.stackheight),e.closePath(),e.fill())}else{const o=t.x1;o>=s.x&&(e.fillStyle="white",e.beginPath(),e.moveTo(o+n.stackheight/2,r),e.lineTo(o,r),e.lineTo(o,r+n.stackheight/2),e.lineTo(o+n.stackheight/2,r),e.closePath(),e.fill(),e.beginPath(),e.moveTo(o+n.stackheight/2,r+n.stackheight),e.lineTo(o,r+n.stackheight),e.lineTo(o,r+n.stackheight/2),e.lineTo(o+n.stackheight/2,r+n.stackheight),e.closePath(),e.fill())}}(e,t,s,o,n),t.rnext&&(o.to_qual||t.x2-t.x1>=20&&s.stackheight>=7&&(e.font=Math.min(_t,Math.max(kt,s.stackheight-4))+"pt Arial",e.fillStyle="white",e.fillText((r.nochr?"chr":"")+t.rnext,(t.x1+t.x2)/2,n+s.stackheight/2,t.x2-t.x1)))}function _n(e,t,n,s){for(const[e,n]of t.regions.entries()){if(!n.to_printnt)continue;const t=new Set;for(const r of s)for(const s of r.segments){if(s.ridx!=e)continue;const r=s.boxes.filter((e=>"I"==e.opr));if(r.length)for(const e of r)t.add(n.x+n.scale(e.start))}}for(const n of s)for(const s of n.segments){const r=t.regions[s.ridx],o=s.boxes.filter((e=>"I"==e.opr));if(o.length){e.font=Math.max(_t,t.stackheight-2)+"pt Arial";for(const i of o){const o=r.x+r.scale(i.start);let a;i.qual?e.fillStyle=wt(i.qual.reduce(((e,t)=>e+t),0)/i.qual.length/Ut):e.fillStyle=bt,a=""==i.s?i.len:1==i.s.length?i.s:i.s.length,e.fillText(a,o,n.y+t.stackheight*(s.on2ndrow||0)+t.stackheight/2)}}}}async function kn(e,t,n){const s=gn(e.qual),r=['<td style="color:black;text-align:left">Read</td>'];for(const t of e.boxes)for(let n=0;n<t.len;n++){e.seq[t.cidx+n];r.push('<td style="background:'+st(s[t.cidx+n]/Ut)+'">'+e.seq[t.cidx+n]+"</td>")}const o=[];o.push('<li><span style="background:'+mt+';color:white">This segment in template is unmapped</span></li>'),1&e.flag&&o.push("<li>Template has multiple segments</li>"),2&e.flag&&o.push("<li>Each segment properly aligned</li>"),16&e.flag&&o.push("<li>Reverse complemented</li>"),32&e.flag&&o.push("<li>Next segment in the template is reverse complemented</li>"),64&e.flag&&o.push("<li>This is the first segment in the template</li>"),128&e.flag&&o.push("<li>This is the last segment in the template</li>"),256&e.flag&&o.push("<li>Secondary alignment</li>"),512&e.flag&&o.push("<li>Not passing filters</li>"),1024&e.flag&&o.push("<li>PCR or optical duplicate</li>"),2048&e.flag&&o.push("<li>Supplementary alignment</li>");let i={seq:e.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center">\n\t\t\t <tr style="color:white">${r.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE</span>: ${Math.abs(e.seq.length)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${e.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${e.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${e.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${o.join("")}</ul>`};return e.discord_unmapped2&&(i.unmapped_mate=!0),i}async function qn(e,t,n){const s=e.boxes[0].start,r=e.boxes[e.boxes.length-1],o=r.start+r.len,i=await mn(t,n.chr+":"+(s+1)+"-"+o),a=gn(e.qual);let l,c;if("*"==e.seq)l=["<td>Nucleotide sequence not available for this read</td>"],c=["<td></td>"];else{l=["<td>Reference</td>"],c=['<td style="color:black;text-align:left">Read</td>'];for(const t of e.boxes)if("H"!=t.opr)if("I"!=t.opr)if("D"!=t.opr&&"N"!=t.opr)if("S"!=t.opr)if("M"!=t.opr&&"="!=t.opr&&"X"!=t.opr&&"*"!=t.opr);else for(let n=0;n<t.len;n++){const r=i[t.start-s+n],o=e.seq[t.cidx+n];l.push("<td>"+r+"</td>"),"*"==e.qual?c.push('<td style="color:black;background:'+(r.toUpperCase()==o.toUpperCase()?st:ut)+'">'+e.seq[t.cidx+n]+"</td>"):c.push('<td style="background:'+(r.toUpperCase()==o.toUpperCase()?st:ut)(a[t.cidx+n]/Ut)+'">'+e.seq[t.cidx+n]+"</td>")}else for(let n=0;n<t.len;n++)l.push("<td>"+i[t.start-s+n]+"</td>"),"*"==e.qual?c.push('<td style="background:'+pt(1)+'">'+e.seq[t.cidx+n]+"</td>"):c.push('<td style="background:'+pt(a[t.cidx+n]/Ut)+'">'+e.seq[t.cidx+n]+"</td>");else if(t.len>=Xt)l.push('<td style="font-size:.8em;opacity:.5;white-space:nowrap">'+t.len+" bp</td>"),c.push('<td style="color:black;white-space:nowrap">-----------</td>');else for(let e=0;e<t.len;e++)l.push("<td>"+i[t.start-s+e]+"</td>"),c.push('<td style="color:black">-</td>');else for(let n=t.cidx;n<t.cidx+t.len;n++)l.push("<td>-</td>"),"*"==e.qual?c.push('<td style="color:'+bt+';background:white">'+e.seq[n]+"</td>"):c.push('<td style="color:'+bt+";background:"+st(a[n]/Ut)+'">'+e.seq[n]+"</td>")}let u=0,f=0,d=[],p=[],m=0;for(const t of e.boxes)u=f,f+=t.len,"S"==t.opr&&(m=1,d.push(u),p.push(f));const h=[];e.rnext&&h.push('<li>Next segment on <span style="background:'+rt+'">'+(n.nochr?"chr":"")+e.rnext+", "+e.pnext+"</span></li>"),e.discord_wrong_insertsize&&e.discord_orientation?h.push('<li><span style="background:'+it+';color:white">Wrong insert size</span> mate position: '+e.pnext+'</li><li><span style="background:'+gt+';color:white">Segments also having wrong orientation</span> '+e.discord_orientation_direction+"</li>"):e.discord_wrong_insertsize?h.push('<li><span style="background:'+it+';color:white">Wrong insert size</span> mate position: '+e.pnext+"</li>"):e.discord_orientation?h.push('<li><span style="background:'+gt+';color:white">Segments having wrong orientation</span> '+e.discord_orientation_direction+"</li>"):e.discord_unmapped2&&h.push('<li><span style="background:'+mt+';color:white">Other segment in template is unmapped</span></li>'),1&e.flag&&h.push("<li>Template has multiple segments</li>"),2&e.flag&&h.push("<li>Each segment properly aligned</li>"),16&e.flag&&h.push("<li>Reverse complemented</li>"),32&e.flag&&h.push("<li>Next segment in the template is reverse complemented</li>"),64&e.flag&&h.push("<li>This is the first segment in the template</li>"),128&e.flag&&h.push("<li>This is the last segment in the template</li>"),256&e.flag&&h.push("<li>Secondary alignment</li>"),512&e.flag&&h.push("<li>Not passing filters</li>"),1024&e.flag&&h.push("<li>PCR or optical duplicate</li>"),2048&e.flag&&h.push("<li>Supplementary alignment</li>");let g={seq:e.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center;font-family:courier">\n\t\t\t <tr style="opacity:.6">${l.join("")}</tr>\n\t\t\t <tr style="color:white">${c.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">CHR</span>: ${n.chr.replace("chr","")},\n\t\t\t<span style="opacity:.5;font-size:.7em">START</span>: ${e.segstart_original+1},\n\t\t\t<span style="opacity:.5;font-size:.7em">STOP</span>: ${o},\n\t\t\t<span style="opacity:.5;font-size:.7em">READ LENGTH</span>: ${e.seq.length} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE LENGTH</span>: ${Math.abs(e.tlen)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${e.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${e.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${e.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${h.join("")}</ul>`,start_readpos:s+1,boxes:e.boxes,readpanel_DN_maxlength:Xt};return 1==m&&(g.soft_starts=d,g.soft_stops=p),e.discord_unmapped2&&(g.unmapped_mate=!0),g}function xn(e){const t=Le().createHmac("md5",Yt),n=[e.get("X-Auth-Token")||e.cookies.sessionid,e.query.gdcFileUUID,e.query.gdcFilePosition];return t.update(n.join("")).digest("hex")+".bam"}async function Nn(e){if(!e.query.gdcFileUUID||!e.query.gdcFilePosition||!e.query.file)throw"cannot download GDC BAM slice: request is unauthorized";const t=e.query.regions;if(!Array.isArray(t)||0==t.length)throw"req.query.regions[] not non-empty array";const n=[];for(const s of t){const t=await En(s.chr,s.start,s.stop,e.query.gdcFileUUID,xn(e),e);n.push({filesize:t})}return n}const Sn=r().features.bamCache||{},An=Sn.maxAge||72e5,Cn=Sn.maxSize||5e9,jn=Sn.checkWait||6e4;let Tn,Mn=0;function On(e=0){const t=Date.now()+e;if(Tn){if(Mn&&Mn<=t+5)return;clearTimeout(Tn),Tn=void 0}Mn=t,console.log(`will trigger mayDeleteCacheFiles() in ${e} ms`),Tn=setTimeout(In,e)}async function In(){console.log("checking for cached bam files to delete ...");try{const e=Date.now()-An,t=await m().promises.readdir(r().cachedir_bam),n=[];let s=0,o=0,i=0,a=0;for(const l of t){if(!l.endsWith(".bam")&&!l.endsWith(".bai"))continue;i++;const t=g().join(r().cachedir_bam,l),c=await m().promises.stat(t);if(!c.isFile())continue;const u=c.mtimeMs;u<e?(await m().promises.unlink(t),a++,o+=c.size):(n.push({path:t,time:u,size:c.size}),s+=c.size)}if(n.sort(((e,t)=>t.time-e.time)),s>=Cn){const e=Date.now()-jn;for(const t of n){if(t.time>e)break;if(await m().promises.unlink(t.path),t.deleted=!0,a++,o+=t.size,s-=t.size,s<Cn)break}}console.log(`deleted ${a} of ${i} cached bam files (${o} bytes deleted, ${s} remaining)`),Tn=void 0,Mn=0;const l=s&&n.find((e=>!e.deleted));if(l){On(jn+Math.round(s>=Cn?0:Math.max(0,l.time+An-Date.now())))}}catch(e){console.error("Error in mayDeleteCacheFiles(): "+e)}}async function En(e,t,n,s,o,i){On(jn);const{host:a,headers:l}=en(i.query.__genomes).getHostHeaders(i.query);l.compression=!1;const c=g().join(r().cachedir_bam,o),u=g().join(a.rest,"/slicing/view/",s+"?region="+e+":"+t+"-"+n);try{const e=Math.round(Date.now()/1e3);if(await R.yE(c)){const e=b().stream(u,{method:"GET",headers:l}),t=m().createWriteStream(c);let n=0,s=!1;const o=new Ce.Transform({transform(e,t,o){n+=e.length,n>r().features.gdcBam.cacheMaxSize?(o(null,null),s=!0):o(null,e)}});if(await(0,je.pipeline)(e,o,t),s){try{await m().promises.stat(c),await m().promises.unlink(c)}catch(e){}throw`slice file size exceeds ${Ge(r().features.gdcBam.cacheMaxSize)}. Please reduce query region size and try again.`}if(await R.yE(c))throw"BAM file slice is not found after downloading"}else await m().promises.utimes(c,e,e);const t=c+".bai";if(await R.yE(t)){if(await async function(e){await R.UE({isbam:!0,args:["index",e],callback:()=>{}})}(c),await R.yE(t))throw"index file is missing after indexing"}else await m().promises.utimes(t,e,e);const n=await m().promises.stat(c);return(0,F.bplen)(n.size,!0)}catch(e){throw e.stack&&console.log(e.stack),"Error with BAM slicing: "+(e.message||e)}}r().features.bamCache&&On(jn);const Rn="Unannotated";function Fn(e){return e.file?e.file:e.file2?e.file2:e.url}function $n(e,t,n,s){const r=[];for(const o of e.samples)if(Number.isFinite(o.readcount)&&(o.readcount=Math.floor(o.readcount),!(o.readcount<=0||t.readcountCutoff&&o.readcount<t.readcountCutoff))){if(s.samples&&n.cohort&&n.cohort.annotation){const e=s.samples[o.i];if(!e)continue;const r=n.cohort.annotation[e];if(o.anno=r,t.cohortOnlyAttr&&n.cohort&&n.cohort.annotation){if(!r)continue;let e=!1;for(const n in t.cohortOnlyAttr){const s=r[n];if(s&&t.cohortOnlyAttr[n][s]){e=!0;break}}if(!e)continue}if(t.cohortHiddenAttr&&n.cohort&&n.cohort.annotation&&n.cohort.attributes){if(!r)continue;let e=!1;for(const s in t.cohortHiddenAttr){n.cohort.attributes.lst.find((e=>e.key==s)).isNumeric;const o=r[s];if(o){if(t.cohortHiddenAttr[s][o]){e=!0;break}}else if(t.cohortHiddenAttr[s][Rn]){e=!0;break}}if(e)continue}}if(o.events&&t.spliceEventPercentage){let n=!1;for(const s in o.events){if(!e.events[s])continue;const r=e.events[s].attrValue,i=t.spliceEventPercentage[r];if(!i)continue;const a=o.events[s].percentage;if(null!=a)if(">"==i.side){if(a<=i.value){n=!0;break}}else if(a>=i.value){n=!0;break}}if(n)continue}r.push(o)}return r}function Dn(e,...t){if(0==e.length)return 0;const n=e.sort(((e,t)=>e.readcount-t.readcount)),s=[];return t.forEach((e=>{!Number.isFinite(e)||e<0||e>1?s.push(null):s.push(n[Math.floor(n.length*e)].readcount)})),s}var Ln=n(4555);function Pn(e){return new Promise(((t,n)=>{const s=O().createInterface({input:m().createReadStream(e.file,{encoding:"utf8"})}),r=[];let o=!0;s.on("line",(t=>{if(o)return void(o=!1);const n=t.split("\t"),[i,a,l,c,u,f]=n[0].split(/[:,]/);if(i!=e.chr)return;const d=Number.parseInt(a),p=Number.parseInt(u);if(Number.isNaN(d)||Number.isNaN(p))return;const m=d-1,h=p-1;if(m>e.start&&m<e.stop||h>e.start&&h<e.stop){const e=Number.parseInt(n[1]),t=n[2];r.push({chr:i,start:m,stop:h,type:t,rawdata:[e]})}else m>e.stop&&s.close()})),s.on("close",(()=>{t(r)}))}))}const Gn=new Set(["-1","0","1","2"]);function Un(e,t){e[0];const n=Number(e[1]),s=(e[2],e[3].split(".")[0]),r=e[5];if("+"!=r&&"-"!=r)return{name:s};const o="+"==r,i=Number(e[6]),a=Number(e[7]);if(!Number.isInteger(i)||!Number.isInteger(a))return{name:s,strand:r};const l=[],c=[],u=[],f=[],d=[],p=e[15],m=e[17],h=e[20];if(!e[10].includes(",")||!e[11].includes(","))return{name:s,strand:r};const g=e[10].split(",");g.pop();const y=g.map(Number),b=e[11].split(",");b.pop();const v=b.map(Number);if(y.includes(NaN)||v.includes(NaN))return{name:s,strand:r};let w=null,_=0,k=0;for(const[e,t]of y.entries()){_+=t;const s=n+v[e],r=s+t;o?d.push([s,r]):d.unshift([s,r]),e>0&&(o?f.push([w,s]):f.unshift([w,s])),w=r,s<i?r<i?o?c.push([s,r]):l.unshift([s,r]):(o?c.push([s,i]):l.unshift([s,i]),r>a?(i<a&&(o?u.push([i,a]):u.unshift([i,a]),k+=a-i),o?l.push([a,r]):c.unshift([a,r])):i<r&&(o?u.push([i,r]):u.unshift([i,r]),k+=r-i)):s<a?r<=a?s<r&&(o?u.push([s,r]):u.unshift([s,r]),k+=r-s):(s<a&&(o?u.push([s,a]):u.unshift([s,a]),k+=a-s),o?l.push([a,r]):c.unshift([a,r])):o?l.push([s,r]):c.unshift([s,r])}const q={name:m,isoform:s,strand:r,exon:d,rnalen:_};26==e.length&&(q.category=h),t&&t.has(s)&&(q.description=t.get(s)),f.length>0&&(q.intron=f),i==a||(q.cdslen=k,q.codingstart=i,q.codingstop=a,q.coding=u,c.length&&(q.utr5=c),l.length&&(q.utr3=l));const x=p.split(",");return x.pop(),x.length<1||x.some((e=>!Gn.has(e)))||function(e,t){if(!e.codingstart)return;const n="+"==e.strand?e.codingstart:e.codingstop;let s=e.exon.findIndex((e=>e[1]>=n&&e[0]<=n));if(-1==s)throw"start codon not matched to an exon: "+JSON.stringify(e);"-"==e.strand&&(s=e.exon.length-s-1);const r=t.split(",")[s];if("-1"==r)throw"start codon frame is -1: "+e.isoform;if("0"!=r){if("1"!=r&&"2"!=r)throw"start codon frame not 0/1/2: "+r+" "+e.isoform;e.startCodonFrame=Number.parseInt(r)}}(q,p),q}const zn=1,Bn=10,Jn=400,Hn=600,Wn=50,Vn="rgba(122,103,44,.7)",Zn="red",Kn="#edad0c",Xn="rgba(255,0,0,.5)",Yn="#ccc";function Qn(e,t,n,s,r){if(!e)return;if(!r.name&&!r.isoform)return;const o=[];r.name&&o.push(r.name),r.isoform&&o.push(r.isoform),e.push({chr:r.chr,start:r.start,stop:r.stop,x1:t,x2:n,y:s,isoform:r.isoform,name:o.join(" ")})}function es(e,t,n,s,r,o){const i=o/2,a=o/2,l=Math.max(o/2,6);if(r-2*i<a)return;const c=Math.ceil((r-2*i)/(a+l));if(c<=0)return;const u="+"==t;let f=Math.ceil(n+(r-a*c-l*(c-1))/2);for(let t=0;t<c;t++)e.beginPath(),u?(e.moveTo(f,s),e.lineTo(f+a,s+o/2),e.moveTo(f+a,s+o/2+1),e.lineTo(f,s+o)):(e.moveTo(f+a,s),e.lineTo(f,s+o/2),e.moveTo(f,s+o/2+1),e.lineTo(f+a,s+o)),e.stroke(),f+=a+l}function ts(e,t){return new Promise(((n,s)=>{const o=(0,q.spawn)(r().gfServer,["status",t.blat.host,t.blat.port]),i=[],a=[];o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("close",(t=>{a.join("").trim()&&n(e+" OFF");const s=i.join("").trim().split("\n");let r=0;for(const e of s)e.startsWith("blat requests")&&(r=e.split(" ")[2]);n(e+" ON, "+r+" requests")}))}))}function ns(e,t){const n=g().join(r().cachedir,Math.random().toString());return new Promise(((s,o)=>{const i=(0,q.spawn)(r().gfClient,[e.blat.host,e.blat.port,e.blat.seqDir,t,n,"-q=dna","-nohead","-minScore=20","-minIdentity=0","-out=psl"]),a=[];i.stderr.on("data",(e=>a.push(e))),i.on("close",(e=>{const t=a.join("");t&&(console.log("BLAT error",t),o("blat server problem")),s(n)}))}))}var ss=n(8877),rs=n(1575);const os="ssm_occurrence_centrics";async function is(e){const t=new Map,{host:n,headers:s}=e.getHostHeaders(),o=g().join(n.rest,"ssm_occurrences/_mapping");let i;try{const{body:e}=await(0,R.fk)(o,{headers:s});i=e}catch(e){throw console.log(e),"failed to get GDC API _mapping: "+(e.message||e)}if(!i._mapping)throw"returned data does not have ._mapping";if(!Array.isArray(i.fields))throw".fields not array";if(!Array.isArray(i.nested))throw".nested not array";const a=new Set(i.nested);let l=0,c=0,u=0,f=0,d=0,p=0;for(const e of i.fields){if(fs(e)){l++;continue}const n=e.split(".");for(let e=1;e<n.length;e++){const s=n.slice(0,e).join("."),r=s+"."+n[e],o=n[e][0].toUpperCase()+n[e].slice(1).replace(/_/g," "),l={id:r.toLowerCase(),name:o,included_types_set:new Set,child_types_set:new Set};if(e==n.length-1){l.isleaf=!0;const e=i._mapping[os+"."+r];e&&("keyword"==e.type?(l.type="categorical",u++):"long"==e.type?(l.type="integer",f++):"double"==e.type?(l.type="float",d++):console.log("GDC !!! ERR !!! Unknown variable type: "+e.type)),l.type||c++,as(l)}if(1==e);else if(l.parent_id=s,l.type){l.included_types_set.add(l.type);let e=t.get(s);for(;e&&(e.included_types_set.add(l.type),e.child_types_set.add(l.type),e.parent_id);)e=t.get(e.parent_id)}a.has(r)&&(l.isObjectList=!0),t.set(r,l)}}try{await async function(e,t){const n=[],s=new Map;for(const t of e.values()){if("integer"!=t.type&&"float"!=t.type)continue;if(cs[t.id]){t.bins=cs[t.id];continue}const e=t.id.replace("case.","").replace(/\./g,"__");s.set(e,t.id),n.push(e+" {\n\t\t stats {\n\t\t\t\tMin : min\n\t\t\t\tMax: max\n\t\t\t\tMean: avg\n\t\t\t\tSD: std_deviation\n\t\t\t\tcount\n\t\t\t}\n\t\t\trange(ranges: $filters2) {\n\t\t\t buckets {\n\t\t\t\tdoc_count\n\t\t\t\tkey\n\t\t\t }\n\t\t\t}\n\t\t}")}if(0==n.length)throw"GDC: no numeric terms, should not happen";const r=`\n\t query ContinuousAggregationQuery($caseFilters: FiltersArgument, $filters: FiltersArgument, $filters2: FiltersArgument) {\n\t viewer {\n\t\texplore {\n\t\t cases {\n\t\t\taggregations(case_filters: $caseFilters, filters: $filters) {\n\t\t\t\t${n.join("\n")}\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t}`,o={caseFilters:{},filters:{},filters2:{op:"range",content:[{ranges:[{from:0,to:1}]}]}};let i=0,a=0;const{host:l,headers:c}=t.getHostHeaders(),{body:u}=await(0,R.fk)(l.graphql,{method:"POST",body:{query:r,variables:o}});if("object"!=typeof u.data?.viewer?.explore?.cases?.aggregations)throw"return not object: re.data.viewer.explore.cases.aggregations{}";for(const[t,n]of s){const s=e.get(n);if(!(t in u.data.viewer.explore.cases.aggregations)){console.log("GDC: no stats object returned for numeric term",n),s.bins=ls,a++;continue}const r=u.data.viewer.explore.cases.aggregations[t].stats;if("object"!=typeof r){console.log("GDC: aggregations[facet].stats{} is not object"),s.bins=ls,a++;continue}if(!Number.isFinite(r.Max)||!Number.isFinite(r.Min)){s.bins=ls,a++;continue}if(r.Max<=r.Min){s.bins=ls,a++;continue}const o=(r.Max-r.Min)/5,l="integer"==s.type?Math.ceil(o):o;s.bins={default:{mode:"discrete",type:"regular-bin",bin_size:l,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:r.Min+l}}},i++}console.log(`GDC default binning: ${i} assigned, ${a} unassigned`)}(t,e)}catch(e){throw console.log(e),"assignDefaultBins() failed: "+(e.message||e)}for(const e of t.values())e.type||p++,e.included_types=[...e.included_types_set],e.child_types=[...e.child_types_set],delete e.included_types_set,delete e.child_types_set;console.log("GDC dictionary:",t.size,"total variables,",l,"lines skipped,",c,"lines with unknown term type,","categorical="+u,"integer="+f,"float="+d,"parent="+p),Object.freeze(t),function(e,t){const n=e.cohort.termdb.q={};async function s(t,n){if(0==t.length||!n)return;const s=await e.termdb.termid2totalsize2.get(t.map((e=>e.id)),JSON.parse(n));for(const e of t)if(e){const t=s.get(e.id);"categorical"==e.type&&t?t.length?e.samplecount=t.map((e=>e[1])).reduce(((e,t)=>e+t)):(e.disabled=!0,e.samplecount=0):"integer"!=e.type&&"float"!=e.type||(e.samplecount=t.total,0==t.total&&(e.disabled=!0))}}n.getRootTerms=async(e,n=null)=>{const r=[];for(const e of t.values())null==e.parent_id&&r.push(JSON.parse(JSON.stringify(e)));return await s(r,n),r},n.getTermChildren=async(e,n=null,r=null)=>{const o=[];for(const n of t.values())n.parent_id==e&&o.push(JSON.parse(JSON.stringify(n)));return await s(o,r),o},n.findTermByName=async(e,n,r=null,o=null)=>{(e=e.toLowerCase()).includes(" ")&&(e=e.replace(/\s/g,"_"));const i=[];for(const n of t.values())o&&!(0,rs.CG)(n,o)||n.id.includes(e)&&i.push(JSON.parse(JSON.stringify(n)));return await s(i,r),i},n.getAncestorIDs=e=>{if(!t.has(e))return;const n=e.split("."),s=[];for(let e=1;e<n.length;e++)s.push(n.slice(0,e+1).join("."));return s},n.getAncestorNames=n.getAncestorIDs,n.termjsonByOneid=e=>{const n=t.get(e);return n?JSON.parse(JSON.stringify(n)):null},n.getSupportedChartTypes=()=>{const e={},n={};for(const s of t.values())s.type&&(s.cohort in e||(e[s.cohort]=["barchart","table","regression"],n[s.cohort]=0),"survival"!=s.type||e[s.cohort].includes("survival")||e[s.cohort].push("survival"),"condition"!=s.type||e[s.cohort].includes("cuminc")||e[s.cohort].push("cuminc"),"float"!=s.type&&"integer"!=s.type||(n[s.cohort]+=s.samplecount));for(const t in n)n[t]>0&&e[t].push("boxplot"),n[t]>1&&e[t].push("scatterplot");return e}}(e,t),e.cohort.termdb.termtypeByCohort=[],u&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"categorical"}),f&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"integer"}),d&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"float"}),e.__gdc={aliquot2submitter:{cache:new Map,get:async t=>e.__gdc.aliquot2submitter.cache.has(t)?e.__gdc.aliquot2submitter.cache.get(t):t},map2caseid:{cache:new Map,get:t=>e.__gdc.map2caseid.cache.get(t)},caseid2submitter:new Map,caseIds:new Set,casesWithExpData:new Set,gdcOpenProjects:new Set,doneCaching:0};try{await async function(e){const t={filters:{op:"and",content:[{op:"=",content:{field:"access",value:"open"}},{op:"=",content:{field:"data_type",value:"Masked Somatic Mutation"}}]},facets:"cases.project.project_id",size:0},{host:n,headers:s}=e.getHostHeaders(),{body:r}=await(0,R.fk)(g().join(n.rest,"files"),{method:"POST",headers:s,body:t});if(!Array.isArray(r?.data?.aggregations?.["cases.project.project_id"]?.buckets))return void console.log("getting open project_id but return is not re.data.aggregations['cases.project.project_id'].buckets[]");for(const t of r.data.aggregations["cases.project.project_id"].buckets)t.key&&e.__gdc.gdcOpenProjects.add(t.key);console.log("GDC open-access projects:",e.__gdc.gdcOpenProjects.size)}(e)}catch(e){throw console.log(e),"getOpenProjects() failed: "+(e.message||e)}!async function(e){await async function(e){const{host:t,headers:n}=e.getHostHeaders();try{{const e=g().join(t.rest,"ssms"),n=await ds(e);if(n)throw`${e} returns error code: ${n}`}{const e=g().join(t.rest,"ssm_occurrences"),n=await ds(e);if(n)throw`${e} returns error code: ${n}`}{const e=g().join(t.rest,"cases"),n=await ds(e);if(n)throw`${e} returns error code: ${n}`}{const e=g().join(t.rest,"files"),n=await ds(e);if(n)throw`${e} returns error code: ${n}`}{const e=g().join(t.rest,"analysis/top_mutated_genes_by_project"),n=await ds(e);if(n)throw`${e} returns error code: ${n}`}{const e=await async function(e,t){const n=new Date;try{const n="query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\tprimary_site {buckets { doc_count, key }}\n\t\t\t\t}\n\t\t\t}\n\t\t}}",s=await b().post(e,{headers:t,body:JSON.stringify({query:n,variables:{}})});if(s.statusCode>399)return s.statusCode}catch(t){if(console.log(t),t.code)return t.code;throw"see above error from graphql API "+e}console.log("GDC GraphQL API okay: "+e,new Date-n,"ms")}(t.graphql,JSON.parse(JSON.stringify(n)));if(e)throw`${t.graphql} returns error code: ${e}`}}catch(e){throw console.log(e),`\n##########################################\n#\n# Some GDC API unavailable, see error above\n# ${t.rest}\n# ${t.graphql}\n#\n##########################################`}}(e);try{await async function(e){if("stopGdcCacheAliquot"in r().features){if(!Number.isInteger(r().features.stopGdcCacheAliquot))return void console.log("GDC: sample IDs are not cached!");console.log("GDC: running limited sample ID caching")}else console.log("GDC: caching complete sample ID mapping");const t=1e3,n=await ps(e,1,0);if(!Number.isInteger(n))throw"totalCases not integer";const s=new Date;console.log("GDC: Start to cache sample IDs of",n,"cases...");for(let s=0;s<Math.ceil(n/t)&&(await ps(e,t,1e3*s),!(Number.isInteger(r().features.stopGdcCacheAliquot)&&s>=r().features.stopGdcCacheAliquot));s++);await async function(e){const{host:t,headers:n}=e.getHostHeaders(),s=`${t.geneExp}/gene_expression/availability`;try{const t=[...e.__gdc.caseIds],{body:r}=await(0,R.fk)(s,{method:"post",headers:n,body:{case_ids:t,gene_ids:["ENSG00000141510"]}});if(!Array.isArray(r.cases?.details))throw"re.cases.details[] not array";for(const t of r.cases.details)t.has_gene_expression_values&&e.__gdc.casesWithExpData.add(t.case_id);delete e.__gdc.caseIds}catch(e){console.log("You don't have access to /gene_expression/availability/, you cannot run GDC hierCluster")}}(e),e.__gdc.doneCaching=!0,console.log("GDC: Done caching sample IDs. Time:",Math.ceil((new Date-s)/1e3),"s"),console.log("\t",e.__gdc.aliquot2submitter.cache.size,"aliquot IDs to sample submitter id,"),console.log("\t",e.__gdc.caseid2submitter.size,"case uuid to submitter id,"),console.log("\t",e.__gdc.map2caseid.cache.size,"different ids to case uuid,"),console.log("\t",e.__gdc.casesWithExpData.size,"cases with gene expression data.")}(e)}catch(e){throw e.stack&&console.log(e.stack),"cacheSampleIdMapping() failed: "+(e.message||e)}}(e)}function as(e){"case.diagnoses.age_at_diagnosis"!=e.id||(e.valueConversion={scaleFactor:1/365,fromUnit:"day",toUnit:"year"})}const ls={default:{mode:"discrete",type:"regular-bin",bin_size:1,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:0},last_bin:{start:1,stopunbounded:!0}}},cs={"case.diagnoses.age_at_diagnosis":{default:{type:"custom-bin",mode:"discrete",lst:[{startunbounded:!0,stop:10950,stopinclusive:!0,label:"<=30 years"},{start:10950,stop:21900,stopinclusive:!0,label:"30-60 years"},{start:21900,stopunbounded:!0,startinclusive:!1,label:">60years"}]}}};const us=new Set(["case.consent_type","case.days_to_consent","case.days_to_index"]);function fs(e){return!!(e.startsWith("ssm")||e.startsWith("case.observation")||e.startsWith("case.available_variation_data"))||(!(!e.endsWith("_id")||e.endsWith("project_id"))||(!!us.has(e)||void 0))}async function ds(e){try{const t=new Date,n=await b()(e);if(n.statusCode>399)return n.statusCode;console.log("GDC API okay: "+e,new Date-t,"ms")}catch(t){if(console.log("See error from",e),console.log(t),t.code)return t.code;throw"gdc api down: "+e}}async function ps(e,t,n,s){const r=["fields=submitter_id,samples.portions.analytes.aliquots.aliquot_id,samples.submitter_id"];if(s)r.push('filters={"op":"and","content":[{"op":"=","content":{"field":"samples.portions.analytes.aliquots.aliquot_id","value":["'+s+'"]}}]}');else{if(!Number.isInteger(t)||!Number.isInteger(n))throw"size and from not integers";r.push("size="+t),r.push("from="+n)}const{host:o,headers:i}=e.getHostHeaders(),{body:a}=await(0,R.fk)(o.rest+"/cases?"+r.join("&"),{headers:i});if(!Array.isArray(a?.data?.hits))throw"re.data.hits[] not array";for(const t of a.data.hits){const n=t.id;if(!n)throw"h.id (case uuid) missing";e.__gdc.caseIds.add(n);const s=t.submitter_id;if(!s)throw"h.submitter_id missing";if(e.__gdc.caseid2submitter.set(n,s),e.__gdc.map2caseid.cache.set(s,n),Array.isArray(t.samples))for(const s of t.samples){const t=s.submitter_id;if(!t)throw"sample.submitter_id missing";if(e.__gdc.map2caseid.cache.set(t,n),Array.isArray(s.portions))for(const r of s.portions)if(Array.isArray(r.analytes))for(const s of r.analytes)if(Array.isArray(s.aliquots))for(const r of s.aliquots){const s=r.aliquot_id;if(!s)throw"aliquot.aliquot_id missing";e.__gdc.aliquot2submitter.cache.set(s,t),e.__gdc.map2caseid.cache.set(s,n)}}}return a.data?.pagination?.total}var ms=n(4973),hs=n(3625),gs=n(478),ys=n(8907),bs=n(394);function vs(e,t){if(t.updateAttr&&!e.label){for(const n of t.updateAttr){let t=e;for(const e of n)if(t)if("object"==typeof e)for(const n in e)t[n]=e[n];else t=t[e]}e.label&&delete t.updateAttr}}function ws(e,t,n){if(!e.cohort?.db?.refresh)return;const s=e.cohort.db.refresh;delete e.cohort.db.refresh,t.get(`${n}/${s.route}`,(async(t,n)=>{n.send({label:e.label,files:[]})})),t.post(`${n}/${s.route}`,(async(t,n)=>{try{const s=e.cohort.db?.file?.startsWith(r().tpmasterdir)?e.cohort.db.file:g().join(r().tpmasterdir,e.cohort.db.file||""),o=t.body;if(!o.dbfile)throw"Updating input text files via the termdb-refresh page has been deprecated.Please use the buildTermdb.bundle.js. pipeline before triggering this route to replace the db file.";{const t=g().join(r().tpmasterdir,o.dbfile);if(!await m().stat(t))throw`dbfile not found: '${t}'`;const n=e.cohort.db.file_fullpath||s;if(t===n)throw"db file source and target are the same";console.log(`copying ${t} to ${n}`),await m().copyFile(t,n)}await Os(e),n.send({status:"ok"})}catch(e){console.log(e),n.send({error:e.error||e})}}))}var _s=n(2188),ks=n(2974),qs=n(3795),xs=n(7934),Ns=n(5057),Ss=n(3677),As=n(4924),Cs=n(901);const js="Unannotated";async function Ts(e,t,n,s=null,o=null){for(const t in e.serverconfigFeatures||{})t in r().features?console.warn(`!!! NO OVERWRITING SERVERCONFIG.FEATURES.${t} (from ${e.label}) !!!`):r().features[t]=e.serverconfigFeatures[t];await Os(e),e.queries&&(await async function(e,t){const n=e.queries.snvindel;if(!n)return;if(n.url){if(!n.url.base)throw".snvindel.url.base missing";if(!n.url.key)throw".snvindel.url.key missing"}if(!n.byisoform&&!n.byrange)throw"byisoform and byrange are both missing on queries.snvindel";if(n.byrange)if(n.byrange.gdcapi)Ln.xq(e);else if(n.byrange.bcffile)n.byrange.bcffile=n.byrange.bcffile.startsWith(r().tpmasterdir)?n.byrange.bcffile:g().join(r().tpmasterdir,n.byrange.bcffile),n.byrange._tk={file:n.byrange.bcffile},n.byrange.get=await Rs(e,t),n.byrange._tk?.samples.length||delete n.byrange._tk.samples,Es(e,n.byrange._tk.samples,"snvindel.byrange.bcffile");else{if(!n.byrange.chr2bcffile)throw"unknown query method for queries.snvindel.byrange";n.byrange._tk={chr2files:{}};for(const e in n.byrange.chr2bcffile)n.byrange._tk.chr2files[e]={file:g().join(r().tpmasterdir,n.byrange.chr2bcffile[e])};delete n.byrange.chr2bcffile,n.byrange.get=await Rs(e,t),n.byrange._tk.samples.length||delete n.byrange._tk.samples,Es(e,n.byrange._tk.samples,"snvindel.byrange.bcffile")}if(n.byisoform){if(!n.byisoform.gdcapi)throw"unknown query method for queries.snvindel.byisoform";Ln.CN(e)}if(n.m2csq){if(!n.m2csq.by)throw".by missing from queries.snvindel.m2csq";if("ssm_id"!=n.m2csq.by)throw"unknown value of queries.snvindel.m2csq.by";if(!n.m2csq.gdcapi)throw"unknown query method for queries.snvindel.m2csq";Ln.wm(e)}}(e,t),await async function(e,t){const n=e.queries.svfusion;if(!n)return;if(!n.byrange)throw"byrange missing from queries.svfusion";if(n.byrange){if(!n.byrange.file)throw"unknown query method for svfusion.byrange";n.byrange.file=n.byrange.file.startsWith(r().tpmasterdir)?n.byrange.file:g().join(r().tpmasterdir,n.byrange.file),n.byrange.get=await async function(e,t){const n=e.queries.svfusion.byrange;if(n.file)await R.LC(n.file);else{if(!n.url)throw"file and url both missing on svfusion.byrange{}";n.dir=await R.d1(n.url,n.indexURL)}n.nochr=await R.Jy(n.file||n.url,null,t);{const e=await R.ZD(n.file);if(!e[0])throw"header line missing from "+n.file;const t=e[0].split(" ");if("#sample"!=t[0])throw"header line not starting with #sample: "+n.file;n.samples=t.slice(1).map((e=>({name:e})))}return async t=>{if(!Array.isArray(t.rglst))throw"q.rglst[] is not array";if(0==t.rglst.length)throw"q.rglst[] blank array";const s=Fs(t),r=await(0,Cs.T)(t,n.samples,e);if(0==r?.size)return[];const o=new Map;for(const e of t.rglst)await R.UE({args:[n.file||n.url,(n.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop],dir:n.dir,callback:n=>{const i=n.split("\t"),a=Number(i[1]);let l,c,u,f,d;try{l=JSON.parse(i[3])}catch(e){return}if(l.dt!=F.dtfusionrna&&l.dt!=F.dtsv)return;if(l.class=l.dt==F.dtsv?F.mclasssv:F.mclassfusionrna,t.hiddenmclass&&t.hiddenmclass.has(l.class))return;if(l.sample&&r&&!r.has(l.sample))return;if(l.chrA)c=1,u=l.geneA||l.chrA,f=l.strandA,d=[{a:{chr:l.chrA,pos:l.posA,strand:l.strandA,name:l.geneA},b:{chr:e.chr,pos:a,strand:l.strandB,name:l.geneB}}];else if(l.chrB)c=0,u=l.geneB||l.chrB,f=l.strandB,d=[{a:{chr:e.chr,pos:a,strand:l.strandA,name:l.geneA},b:{chr:l.chrB,pos:l.posB,strand:l.strandB,name:l.geneB}}];else{if(!l.pairlst)throw"missing chrA and chrB";{d=l.pairlst;const e=l.pairlst.findIndex((e=>e.chr==chr&&e.pos==a));if(-1==e)throw"current point missing from pairlst";c=e}}const p=[l.dt,e.chr,a,f,c,encodeURIComponent(u)].join(ms.dq);let m;if(l.sample&&(m={sample_id:l.sample},l.mattr)){if(s)for(const e in s){const t=e in l.mattr?l.mattr[e]:js;if(s[e].has(t))return}t.addFormatValues&&(m.formatK2v=l.mattr)}o.has(p)||o.set(p,{ssm_id:p,dt:l.dt,class:l.class,chr:e.chr,pos:a,strand:f,pairlstIdx:c,mname:u,pairlst:d,samples:[]}),m&&o.get(p).samples.push(m)}});return[...o.values()]}}(e,t),Es(e,n.byrange.samples,"svfusion.byrange")}}(e,t),await async function(e,t){const n=e.queries.geneCnv;if(!n)return;if(!n.bygene)throw"geneCnv.bygene missing";n.bygene.gdcapi&&Ln.IK(e)}(e),await async function(e,t){const n=e.queries.cnv;if(!n)return;if(!n.byrange)throw"queries.cnv.byrange{} missing";if("native"==n.byrange.src){if(!n.byrange.file)throw"cnv.byrange.file missing when src=native";return n.byrange.file=n.byrange.file.startsWith(r().tpmasterdir)?n.byrange.file:g().join(r().tpmasterdir,n.byrange.file),n.byrange.get=await async function(e,t){const n=e.queries.cnv.byrange;if(n.file)await R.LC(n.file);else{if(!n.url)throw"file and url both missing on cnv.byrange{}";n.dir=await R.d1(n.url,n.indexURL)}n.nochr=await R.Jy(n.file||n.url,null,t);{const e=await R.ZD(n.file);if(!e[0])throw"header line missing from "+n.file;const t=e[0].split(" ");if("#sample"!=t[0])throw"header line not starting with #sample: "+n.file;n.samples=t.slice(1).map((e=>({name:e})))}return async t=>{if(!Array.isArray(t.rglst))throw"q.rglst[] is not array";if(0==t.rglst.length)throw"q.rglst[] blank array";if(t.cnvMaxLength&&!Number.isInteger(t.cnvMaxLength))throw"cnvMaxLength is not integer";if(t.cnvGainCutoff&&!Number.isFinite(t.cnvGainCutoff))throw"cnvGainCutoff is not finite";if(t.cnvLossCutoff&&!Number.isFinite(t.cnvLossCutoff))throw"cnvLossCutoff is not finite";const s=Fs(t),r=await(0,Cs.T)(t,n.samples,e);if(0==r?.size)return[];const o=[];for(const e of t.rglst)await R.UE({args:[n.file||n.url,(n.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop],dir:n.dir,callback:n=>{const i=n.split("\t"),a=Number(i[1]),l=Number(i[2]);if(t.cnvMaxLength&&l-a>=t.cnvMaxLength)return;let c;try{c=JSON.parse(i[3])}catch(e){return}if(c.dt==F.dtcnv){if(c.chr=e.chr,c.start=a,c.stop=l,Number.isFinite(c.value)){if(c.value>0&&t.cnvGainCutoff&&c.value<t.cnvGainCutoff)return;if(c.value<0&&t.cnvLossCutoff&&c.value>t.cnvLossCutoff)return;c.class=c.value>0?F.mclasscnvgain:F.mclasscnvloss}else if(c.class!=F.mclasscnvgain&&c.class!=F.mclasscnvloss)return;if(c.ssm_id=[e.chr,c.start,c.stop,c.class].join(ms.dq),(!t.hiddenmclass||!t.hiddenmclass.has(c.class))&&(!c.sample||!r||r.has(c.sample))){if(c.sample){const e={sample_id:c.sample};if(c.mattr){if(s)for(const e in s){const t=e in c.mattr?c.mattr[e]:js;if(s[e].has(t))return}t.addFormatValues&&(e.formatK2v=c.mattr)}delete c.sample,c.samples=[e]}o.push(c)}}}});return o}}(e,t),void Es(e,n.byrange.samples,"cnv.byrange")}throw"unknown cnv.byrange.src"}(e,t),await async function(e,t){const n=e.queries.ld;if(!n)return;if(!Array.isArray(n.tracks)||!n.tracks.length)throw"ld.tracks[] not nonempty array";for(const e of n.tracks){if(!e.name)throw"name missing from one of ld.tracks[]";if(!e.file)throw".file missing from one of ld.tracks[]";e.file0=e.file,e.file=g().join(r().tpmasterdir,e.file),await R.LC(e.file),e.nochr=await R.Jy(e.file,null,t)}if(!n.overlay)throw"ld.overlay{} missing";if(!n.overlay.color_0)throw"ld.overlay.color_0 missing";if(!n.overlay.color_1)throw"ld.overlay.color_1 missing"}(e,t),await(0,As.validate_query_geneExpression)(e,t),await async function(e,t){const n=e.queries.rnaseqGeneCount;if(!n)return;if(!n.file)throw"unknown data type for rnaseqGeneCount";n.file=g().join(r().tpmasterdir,n.file);{const t=(await(s=n.file,new Promise(((e,t)=>{const n=[],r=[],o=(0,q.spawn)("head",["-1",s]);o.stdout.on("data",(e=>n.push(e.toString()))),o.stderr.on("data",(e=>r.push(e.toString()))),o.on("error",(e=>{r.length&&t(r.join(""))})),o.on("close",(s=>{0!=s&&t("head command exited with non-zero status and this error: "+r.join("")),e(n.join(""))}))})))).trim().split("\t").slice(4);n.allSampleSet=new Set(t);const r=[];for(const t of n.allSampleSet)e.cohort.termdb.q.sampleName2id(t)||r.push(t);console.log(n.allSampleSet.size,`rnaseqGeneCount samples from ${e.label}`)}var s;n.get=async function(t){if(2!=t.samplelst?.groups?.length)throw".samplelst.groups.length!=2";if(t.samplelst.groups[0].values?.length<1)throw"samplelst.groups[0].values.length<1";if(t.samplelst.groups[1].values?.length<1)throw"samplelst.groups[1].values.length<1";const s=[];let o=0;for(const r of t.samplelst.groups[0].values){if(!Number.isInteger(r.sampleId))continue;const t=e.cohort.termdb.q.id2sampleName(r.sampleId);t&&(n.allSampleSet.has(t)?s.push(t):o+=1)}const i=[];let a=0;for(const s of t.samplelst.groups[1].values){if(!Number.isInteger(s.sampleId))continue;const t=e.cohort.termdb.q.id2sampleName(s.sampleId);t&&(n.allSampleSet.has(t)?i.push(t):a+=1)}const l=s.length,c=i.length;if(l<1)throw"sample size of group1 < 1";if(c<1)throw"sample size of group2 < 1";const u={case:s.map((e=>e)).join(","),control:i.map((e=>e)).join(","),input_file:n.file,output_path:g().join(r().binpath,"utils")},f=8;let d;if(s.length<=f&&i.length<=f||"edgeR"==t.method){const e=new Date,n=(await async function(e,t){return new Promise(((n,s)=>{g().join(r().Rscript,e);const o=(0,q.spawn)(r().Rscript,[e]),i=[],a=[];try{Ce.Readable.from(t).pipe(o.stdin)}catch(t){o.kill();let n=t;a.length&&(n+=`killed edgeR('${e}'), stderr: ${a.join("").trim()}`),s(n)}o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("error",(t=>{a.length&&console.log(`edgeR('${e}') ps.on('error') stderr:`,a),s(t)})),o.on("close",(t=>{0!==t?s(`spawned '${e}' exited with a non-zero status and this stderr:\n${a.join("")}`):n(i.toString())}))}))}(g().join(r().binpath,"utils","edge.R"),JSON.stringify(u)),new Date);console.log("Time taken to run edgeR:",n-e,"ms"),t.method="edgeR";const s=g().join(r().binpath,"utils","r_output.txt");d=JSON.parse(m().readFileSync(s,"utf8")),m().unlink(s,(()=>{}))}else if("wilcoxon"==t.method){const e=new Date,n=await(0,we.run_rust)("DEanalysis",JSON.stringify(u)),s=new Date;for(const e of n.split("\n"))e.startsWith("adjusted_p_values:")&&(d=JSON.parse(e.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",s-e,"ms"),t.method="wilcoxon"}else{const e=new Date,n=await(0,we.run_rust)("DEanalysis",JSON.stringify(u)),s=new Date;for(const e of n.split("\n"))e.startsWith("adjusted_p_values:")&&(d=JSON.parse(e.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",s-e,"ms"),t.method="wilcoxon"}return{data:d,sample_size1:l,sample_size2:c,method:t.method}}}(e),await(0,Ss.validate_query_singleSampleMutation)(e,t),await async function(e,t){const n=e.queries.singleSampleGenomeQuantification;if(!n)return;for(const s in n){if(!Number.isFinite(n[s].min))throw"min not a number";if(!Number.isFinite(n[s].max))throw"max not a number";if(n[s].min>=n[s].max)throw"min>=max";if(!n[s].folder)throw"unknown query method for singleSampleGenomeQuantification";n[s].get=async(o,i)=>{let a=o;if(e.cohort?.termdb?.q?.sampleName2id&&(a=e.cohort.termdb.q.sampleName2id(o),null==a))return[];const l=g().join(r().tpmasterdir,n[s].folder,a.toString());try{await m().promises.stat(l)}catch(e){if("EACCES"==e.code)throw"cannot read file, permission denied";if("ENOENT"==e.code)throw"no data for this sample";throw"failed to load data"}return await Gs(l,t,n[s],i)}}}(e,t),await async function(e,t){const n=e.queries.singleSampleGbtk;if(!n)return;for(const t in n){if(!Number.isFinite(n[t].min))throw"min not a number";if(!Number.isFinite(n[t].max))throw"max not a number";if(n[t].min>=n[t].max)throw"min>=max";if(!n[t].folder)throw"unknown query method for singleSampleGbtk";n[t].get=async s=>{let o=s;if(e.cohort?.termdb?.q?.sampleName2id&&(o=e.cohort.termdb.q.sampleName2id(s),null==o))return{};const i=g().join(n[t].folder,o+".gz");try{return await m().promises.stat(g().join(r().tpmasterdir,i)),{path:i}}catch(e){return{}}}}}(e),await(0,xs.validate_query_singleCell)(e,t),await(0,Ns.validate_query_TopVariablyExpressedGenes)(e,t),await(0,ms.uK)(e),await function(e){if(!e.ssm2canonicalisoform)return;if(e.ssm2canonicalisoform.gdcapi)return void Ln.vK(e.ssm2canonicalisoform,e.getHostHeaders);throw"ssm2canonicalisoform.gdcapi is false"}(e),await function(e,t){if(!t.genedb.hasTable_refseq2ensembl)return;e.refseq2ensembl_query=t.genedb.db.prepare("select ensembl from refseq2ensembl where refseq=?")}(e,t),await function(e,t){if(!e.queries.snvindel&&!e.queries.svfusion&&!e.queries.geneCnv)return;e.mayGetGeneVariantData=async(n,s)=>{if("object"!=typeof n.term)throw"tw.term{} is not object";if("geneVariant"!=n.term.type)throw"tw.term.type is not geneVariant";if("string"!=typeof n.term.name)throw"tw.term.name is not string";if(!n.term.name)throw"tw.term.name should be gene symbol but is empty string";const r=[];if("snp"==n.term.subtype){if(!e.queries.snvindel?.allowSNPs)throw"snvindel does not allow snp";const o=(await Bs(e,n.term,t,s)).find((e=>n.term.alleles.includes(e.ref)&&n.term.alleles.includes(e.alt)));if(o){const e=[];for(const t of o.samples){if(!t.formatK2v?.GT)continue;const n=[];for(const e of t.formatK2v.GT.split("/"))0==e?n.push(o.ref):1==e?n.push(o.alt):console.log("unknown allele idx");n.join("/"),n.join("/");e.push({sample_id:t.sample_id,GT:n.join("/")})}const t={samples:e};r.push(t)}}else{if(e.queries.snvindel){const o=await Bs(e,n.term,t,s);r.push(...o)}if(e.queries.svfusion){const o=await async function(e,t,n,s){const r={addFormatValues:!0,filter0:s.filter0,filterObj:s.filter,sessionid:s.sessionid};if(e.queries.svfusion.byrange)return await zs(t,n),r.rglst=[t],await e.queries.svfusion.byrange.get(r);throw"unknown queries.svfusion method"}(e,n.term,t,s);r.push(...o)}if(e.queries.cnv){const o=await async function(e,t,n,s){const r={addFormatValues:!0,filter0:s.filter0,filterObj:s.filter,cnvMaxLength:t?.q?.cnvMaxLength,cnvGainCutoff:t?.q?.cnvGainCutoff,cnvLossCutoff:t?.q?.cnvLossCutoff,sessionid:s.sessionid};if(e.queries.cnv.byrange)return await zs(t.term,n),r.rglst=[t.term],await e.queries.cnv.byrange.get(r);throw"unknown queries.cnv method"}(e,n,t,s);r.push(...o)}if(e.queries.geneCnv){const t=await async function(e,t,n,s){const r={filter0:s.filter0,sessionid:s.sessionid};if(e.queries.geneCnv.bygene)return t.name?(r.gene=t.name,await e.queries.geneCnv.bygene.get(r)):[];throw"unknown queries.geneCnv method"}(e,n.term,0,s);r.push(...t)}}const o=new Map;for(const e of r)if(Array.isArray(e.samples))for(const t of e.samples){o.has(t.sample_id)||o.set(t.sample_id,{sample:t.sample_id}),o.get(t.sample_id)[n.term.name]||(o.get(t.sample_id)[n.term.name]={key:n.term.name,label:n.term.name,values:[]});const s={gene:n.term.name,isoform:e.isoform,dt:e.dt,chr:n.term.chr,class:e.class,pos:e.pos||(e.start?e.start+"-"+e.stop:""),mname:e.mname};if("value"in e&&(s.value=e.value),t.formatK2v)for(const e in t.formatK2v)s[e]=t.formatK2v[e];e.dt==F.dtsnvindel?t.GT&&(s.value=t.GT,s.key=t.GT):e.dt!=F.dtfusionrna&&e.dt!=F.dtsv||(s.pairlst=e.pairlst),o.get(t.sample_id)[n.term.name].values.push(s)}return await async function(e,t,n,s){if(!t.assayAvailability?.byDt)return;const r=e.filter?new Set((await(0,ys.cf)(e.filter,t)).map((e=>e.id))):null;for(const e in t.assayAvailability.byDt){const o=t.assayAvailability.byDt[e];if(o.byOrigin)for(const t in o.byOrigin){Us(e,o.byOrigin[t],n,s,t,r)}else Us(e,o,n,s,!1,r)}}(s,e,o,n.term.name),o}}(e,t)),await function(e){if(!e.assayAvailability)return;if(e.assayAvailability.byDt)for(const t in e.assayAvailability.byDt){const n=e.assayAvailability.byDt[t];if(n.byOrigin)for(const t in n.byOrigin){const s=n.byOrigin[t];if(!s.yes||!s.no||!s.term_id)throw"ds.assayAvailability.byDt.*.byOrigin properties require .term_id .yes{} .no{}";Js(e,s)}else{if(!n.yes||!n.no||!n.term_id)throw"ds.assayAvailability.byDt properties require .term_id .yes{} .no{}";Js(e,n)}}}(e),await function(e){if(!e.viewModes)return;if(!Array.isArray(e.viewModes))throw"ds.viewModes[] not array";for(const t of e.viewModes)if(t.byInfo){if(!e?.queries?.snvindel?.info)throw"view mode byInfo but queries.snvindel.info missing";const n=e.queries.snvindel.info[t.byInfo];if(!n)throw"unknown INFO field for viewmode byInfo";if("Float"!=n.Type&&"Integer"!=n.Type)throw"viewmode byInfo Type is not numeric";t.type="numeric",t.label=t.byInfo}else if(!t.byAttribute)throw"view mode not byInfo or byAttribute"}(e),e.cohort?.db?.refresh&&s&&await ws(e,s,o)}function Ms(e){const t={isMds3:!0,label:e.label};if(e.viewModes&&(t.skewerModes=e.viewModes),e.noGenomicMode4lollipopTk&&(t.noGenomicMode4lollipopTk=!0),function(e,t){if(!e.queries)return;const n={};e.queries.singleSampleMutation&&(n.singleSampleMutation={sample_id_key:e.queries.singleSampleMutation.sample_id_key,discoSkipChrM:e.queries.singleSampleMutation.discoSkipChrM});if(e.queries.singleSampleGenomeQuantification){n.singleSampleGenomeQuantification={};for(const t in e.queries.singleSampleGenomeQuantification)n.singleSampleGenomeQuantification[t]=JSON.parse(JSON.stringify(e.queries.singleSampleGenomeQuantification[t])),delete n.singleSampleGenomeQuantification[t].folder}if(e.queries.singleSampleGbtk){n.singleSampleGbtk={};for(const t in e.queries.singleSampleGbtk)n.singleSampleGbtk[t]=JSON.parse(JSON.stringify(e.queries.singleSampleGbtk[t])),delete n.singleSampleGbtk[t].folder}const s=e.queries.snvindel;s&&(t.has_skewer=!0,n.snvindel={forTrack:s.forTrack,vcfid4skewerName:s.vcfid4skewerName,skewerRim:s.skewerRim,ssmUrl:s.ssmUrl},s.m2csq&&(n.snvindel.m2csq={by:s.m2csq.by}),s.info&&(t.bcf={info:s.info}),s.format&&(t.bcf||(t.bcf={}),t.bcf.format=s.format));if(e.queries.ld){n.ld=JSON.parse(JSON.stringify(e.queries.ld));for(const e of n.ld.tracks)delete e.file}t.queries=n}(e,t),e.cohort?.termdb&&(t.termdb={},e.cohort.termdb.allowCaseDetails&&(t.termdb.allowCaseDetails={sample_id_key:e.cohort.termdb.allowCaseDetails.sample_id_key})),e.variant2samples){const n=e.variant2samples;t.variant2samples={sunburst_twLst:n.sunburst_twLst,twLst:n.twLst,type_samples:n.type_samples,type_summary:n.type_summary,type_sunburst:n.type_sunburst,variantkey:n.variantkey}}return t}async function Os(e){if(e.cohort){if(!e.cohort.termdb)throw"ds.cohort is set but cohort.termdb{} missing";if(!e.cohort.db)throw"ds.cohort is set but cohort.db{} missing";if(!e.cohort.db.file&&!e.cohort.db.file_fullpath)throw"ds.cohort.db.file missing"}else{if(!e.termdb)return;e.cohort={},e.cohort.termdb=e.termdb,delete e.termdb}const t=e.cohort.termdb;if(t?.dictionary?.gdcapi)await is(e);else if(t?.dictionary?.dbFile)e.cohort.db={file:t.dictionary.dbFile},delete t.dictionary.dbFile,(0,bs.JV)(e);else{if(!e.cohort.db)throw"unknown method to initiate dictionary";(0,bs.JV)(e)}if(t.termid2totalsize2&&(t.termid2totalsize2.gdcapi,t.termid2totalsize2.get=async(n,s={},r=null)=>t.termid2totalsize2.gdcapi?await Ln.ws(n,s,r,e):await async function(e,t,n,s){const r=Is(t,s),o=new Map;for(const t of e)if(t.term&&"categorical"==t.term.type){const e={term1_id:t.id,term1_q:{type:"values"},filter:r},n=await(0,Se.e8)(e,s,s.cohort.termdb);if(!n?.data?.charts?.[0])continue;const i=[];for(const e of n.data.charts[0].serieses)i.push([e.seriesId,e.total]);o.set(t.id,i)}return n?[o,n]:o}(n,s,r,e)),function(e){const t=e.selectCohort;if(!t)return;if("object"!=typeof t)throw"selectCohort{} not object";if(!t.term)throw"term{} missing from termdb.selectCohort";if(!t.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof t.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=t.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';{const n=e.q.termjsonByOneid(t.term.id);if(!n)throw"termdb.selectCohort.term.id is invalid";if("categorical"!=n.type)throw"termdb.selectCohort.term type is not categorical"}if(!t.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(t.values))throw"termdb.selectCohort.values is not array";if(0==t.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const e of t.values){if(!e.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(e.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==e.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}(t),await async function(e){if(!e.restrictAncestries)return;if(!Array.isArray(e.restrictAncestries)||0==e.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const t of e.restrictAncestries){if(!t.name)throw"name missing from one of restrictAncestries";if("object"!=typeof t.tvs)throw".tvs{} missing from one of restrictAncestries";if(!t.tvs.term)throw"tvs.term{} missing from an ancestry";if(!t.tvs.term.id)throw"tvs.term.id missing from an ancestry";{const n=e.q.termjsonByOneid(t.tvs.term.id);if(!n)throw"tvs.term.id is invalid from an ancestry";if("categorical"!=n.type)throw"tvs.term.type is not categorical from an ancestry"}if(!Number.isInteger(t.PCcount))throw"PCcount is not integer";if(t.PCcount<=1)throw"PCcount must be greater than 1";if(t.PCTermId){t.pcs=new Map;for(let n=1;n<=t.PCcount;n++){const s=t.PCTermId+n,r=e.q.termjsonByOneid(s);if(!r)throw"a PC term is not found in termdb";const o=e.q.getAllValues4term(s);if(!o||!o.size)throw"no sample PC values are retrieved by restrictAncestries term: "+s;t.pcs.set(r.name,o)}}else{if(!t.PCBySubcohort)throw"unknown PC source and configuration for restrictAncestries";for(const n in t.PCBySubcohort){let s=!0;for(const t of e.selectCohort.values)if(n==t.keys.sort().join(",")){s=!1;break}if(s)throw"unknown subcohort from PCBySubcohort";const r=t.PCBySubcohort[n];if(!r.termId)throw"termId missing from a subcohort of PCBySubcohort";r.pcs=new Map;for(let n=1;n<=t.PCcount;n++){const t=r.termId+n,s=e.q.termjsonByOneid(t);if(!s)throw"a PC term is not found in termdb";const o=e.q.getAllValues4term(t);if(!o||!o.size)throw"no sample PC values are retrieved by restrictAncestries.PCBySubcohort.<>.termId";r.pcs.set(s.name,o)}}}}}(t),await(0,_s.wz)(e),await(0,ks.te)(e),"minTimeSinceDx"in t){if(!Number.isFinite(t.minTimeSinceDx))throw"termdb.minTimeSinceDx not number";if(t.minTimeSinceDx<=0)throw"termdb.minTimeSinceDx<=0"}if("ageEndOffset"in t){if(!Number.isFinite(t.ageEndOffset))throw"termdb.ageEndOffset not number";if(t.ageEndOffset<=0)throw"termdb.ageEndOffset<=0"}if(t.convertSampleId){if(!t.convertSampleId.gdcapi)throw"unknown implementation of tdb.convertSampleId";Ln.Ak(t,e)}if(await async function(e){if(!e.cohort?.cumburden)return;e.cohort.cumburden.files;const t=e.cohort.cumburden.files;for(const e of["fit","surv","sample"]){const n=t[e];if(!n)throw`missing ds.cohort.burden.files.${e}`;const s=(0,q.spawnSync)(r().Rscript,["-e",`load('${r().tpmasterdir}/${n}')`],{encoding:"utf-8"});if(s?.status||s?.stderr)throw console.log(s),`error with ds.cohort.cumburden.files.${e}`}}(e),e.cohort?.db?.connection){e.sampleName2Id=new Map,e.sampleId2Name=new Map;const t="SELECT * FROM sampleidmap",n=e.cohort.db.connection.prepare(t).all();for(const t of n)e.sampleId2Name.set(t.id,t.name),e.sampleName2Id.set(t.name,t.id);e.getSampleIdMap=t=>{const n={};for(const s in t)n[sampleId]=e.sampleId2Name.get(+sampleId);return n}}if(e.cohort.mutationset){const{mayGetGeneVariantData:t,getTermTypes:s,mayGetMatchingGeneNames:r}=n(7833);e.mayGetGeneVariantData=t,e.getTermTypes=s,e.mayGetMatchingGeneNames=r}}function Is(e,t){const n=[];if(e.filterObj&&n.push(e.filterObj),e.tid2value&&n.push((0,Cs.w)(e.tid2value,t)),0!=n.length)return 1==n.length?n[0]:(0,gs.xH)(n)}function Es(e,t,n){if(!t)return;let s;if(e?.cohort?.termdb){for(const e of t){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer sample id from "+n;e.name=t}s=", all integer IDs"}console.log(t.length,"samples from "+n+" of "+e.label+s)}async function Rs(e,t){const n=e.queries.snvindel.byrange;if(n._tk.file)await R._H(n._tk,t,!0);else if(n._tk.chr2files){let e;for(const s in n._tk.chr2files){if("chr17"!=s)continue;const r=n._tk.chr2files[s];try{await R._H(r,t,!0);const o=JSON.stringify(r.samples);if(e){if(o!=e)throw"Different samples found in bcf file of "+s}else e=o,n._tk.samples=r.samples,n._tk.format=r.format,n._tk.info=r.info,n._tk.nochr=r.nochr}catch(e){console.log("missing file ignored:",r.file)}}}if(n._tk?.samples.length){if(!n._tk.format)throw"bcf file has samples but no FORMAT"}else if(n._tk.format)throw"bcf file has FORMAT but no samples";if(n._tk.format){for(const e in n._tk.format)"GT"==e&&(n._tk.format[e].isGT=!0);if(e.queries.snvindel.format4filters){if(!Array.isArray(e.queries.snvindel.format4filters))throw"snvindel.format4filters[] is not array";for(const t of e.queries.snvindel.format4filters)n._tk.format[t]&&(n._tk.format[t].isFilter=!0);delete e.queries.snvindel.format4filters}}if(n._tk.info){if(n.infoFields){for(const e of n.infoFields){if(!e.key)throw".key missing from one of snvindel.byrange.infoFields[]";e.name||(e.name=e.key);const t=n._tk.info[e.key];if(!t)throw"invalid key from one of snvindel.byrange.infoFields[]";t.categories=e.categories,t.name=e.name,t.separator=e.separator}delete n.infoFields}if(e.queries.snvindel.infoUrl){for(const t of e.queries.snvindel.infoUrl){const e=n._tk.info[t.key];if(!e)throw"invalid key from one of snvindel.infoUrl[]";e.urlBase=t.base}delete e.queries.snvindel.infoUrl}}return e.queries.snvindel.info=n._tk.info,e.queries.snvindel.format=n._tk.format,async t=>{if(!Array.isArray(t.rglst))throw"q.rglst[] is not array";if(0==t.rglst.length)throw"q.rglst[] blank array";const s=Fs(t);let r;if(n._tk.chr2files){const e=n._tk.chr2files[t.rglst[0].chr];if(!e)throw"unknown chr for chr2files";r=e.file}else r=n._tk.file||n._tk.url;const o=["query",r,"-r",t.rglst.map((e=>(n._tk.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+(e.stop+1))).join(","),"-f","%ID\t%CHROM\t%POS\t%REF\t%ALT\t%INFO\t%FORMAT\n"],i=await(0,Cs.T)(t,n._tk.samples,e);if(i){if(0==i.size)return[];o.push("-s",[...i].join(","))}t.variantFilter&&(0,qs.u)(t.variantFilter,o);const a=[];return await R.UE({isbcf:!0,args:o,dir:n._tk.dir,callback:r=>{const o=r.split("\t"),l=o[0],c=o[1],u=Number(o[2]),f=o[3],d=o[4].split(","),p=o[5],m={pos:u-1};(0,hs.H)(n._tk,f,d,m,p,l,t.isoform);for(const r of m.mlst)t.hiddenmclass&&t.hiddenmclass.has(r.class)||$s(r,t)||m.mlst.length>1&&t.variantFilter?.lst&&Ds(r,t)||(r.chr=(n._tk.nochr?"chr":"")+c,r.ssm_id=[r.chr,r.pos,r.ref,r.alt].join(ms.dq),n._tk?.samples?.length&&(Ls(n,r,o,t.addFormatValues,e,i,s),!r.samples)||a.push(r))}}),a}}function Fs(e){const t=e.formatFilter||{};return"format"==e.skewerRim?.type&&e.skewerRim.hiddenvalues?.size&&(t[e.skewerRim.formatKey]=e.skewerRim.hiddenvalues),Object.keys(t).length?t:void 0}function $s(e,t){if(!t.infoFilter)return!1;for(const n in t.infoFilter){const s=e.info[n];if(s)if(Array.isArray(s)){for(const e of t.infoFilter[n])if(s.includes(e))return!0}else if(t.infoFilter[n].includes(s))return!0}return!1}function Ds(e,t){for(const n of t.variantFilter.lst){const t=e.info[n.tvs.term.id];if(null==t)return!0;if("integer"==n.tvs.term.type||"float"==n.tvs.term.type){const e=Number(t);if(Number.isNaN(e))return!0;const s=n.tvs.ranges?.[0];if(s){if("start"in s)if(s.startinclusive){if(e<s.start)return!0}else if(e<=s.start)return!0;if("stop"in s)if(s.stopinclusive){if(e>s.stop)return!0}else if(e>=s.stop)return!0}}}return!1}function Ls(e,t,n,s,r,o,i){if(!n[6]||"."==n[6])return;const a=[];for(const t of n[6].split(":")){const n=e._tk.format[t];if(!n)throw"invalid format field: "+n;a.push(n)}const l=[];let c=e._tk.samples;o&&(c=[...o].map((e=>({name:e}))));for(const[e,t]of c.entries()){const r=n[e+7];if(!r||"."==r)continue;const o=Ps(r.split(":"),a,t,s);if(o){if(i){let e=!1;for(const t in i){const n=t in o.formatK2v?o.formatK2v[t]:js;if(i[t].has(n)){e=!0;break}}if(e)continue}l.push(o)}}l.length&&(t.samples=l)}function Ps(e,t,n,s){const r={};for(const[n,s]of t.entries()){const t=e[n];if(t&&"."!=t)if(s.isGT){if("./."==t||".|."==t)continue;r.GT=t}else r[s.ID]=t}if(0==Object.keys(r).length)return null;const o={sample_id:n.name};return s&&(o.formatK2v=r),o}function Gs(e,t,n,s=1){s=Number(s);const r=200,o=20;let i=0;for(const e in t.majorchr)i+=t.majorchr[e];const a=800/i,l={};let c=0;const u=[];for(const e in t.majorchr){const n=t.majorchr[e];l[e]=(0,ss.Z)().domain([0,n]).range([a*c,a*(c+n)]),c+=n,u.push({chr:e,chrLen:n,xStart:a*(c-n),xStop:a*c})}const f=(0,ss.Z)().domain([n.min,n.max]).range([r,0]),d=(0,N.createCanvas)(890*s,240*s),p=d.getContext("2d");s>1&&p.scale(s,s),g(n.max),g(0),g(n.min);const h=O().createInterface({input:m().createReadStream(e)});return new Promise(((e,s)=>{h.on("line",(e=>{const t=e.split("\t"),s=t[0];if(!s)return;if(!l[s])return;const r=Number(t[1]);if(!Number.isInteger(r))return;const i=Number(t[2]);if(!Number.isFinite(i))return;if(i<n.min||i>n.max)return;p.fillStyle=i>0?n.positiveColor:n.negativeColor;const a=l[s](r),c=o+f(i);p.fillRect(70+a,c,1,1)})),h.on("close",(()=>{!function(){p.strokeStyle="black",p.beginPath();{const e=220-f(0);p.moveTo(70,e),p.lineTo(870,e),p.stroke()}let e=!0;p.fillStyle="black",p.font="12px Arial",p.textAlign="center";for(const n in l){if(p.fillText(n.replace("chr",""),70+l[n](t.majorchr[n]/2),234),e){e=!1;continue}const s=Math.floor(70+l[n](0))+.5;p.moveTo(s,o),p.lineTo(s,220),p.stroke()}p.closePath()}(),e({src:d.toDataURL(),canvasWidth:890,canvasHeight:240,xoff:70,chrLst:u})}))}));function g(e){p.fillStyle="black",p.font="12px Arial",p.textAlign="right";const t=o+f(e);p.fillText(e,64,t+5),p.strokeStyle="black",p.beginPath(),p.moveTo(66,t),p.lineTo(70,t),p.stroke(),p.closePath()}}function Us(e,t,n,s,r,o){for(const i of t.yesSamples){if(o&&!o.has(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:Number.parseInt(e),class:"WT",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:Number.parseInt(e),class:"WT",_SAMPLEID_:i})}for(const i of t.noSamples){if(o&&!o.has(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:Number.parseInt(e),class:"Blank",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:Number.parseInt(e),class:"Blank",_SAMPLEID_:i})}}async function zs(e,t){if(e.chr&&Number.isInteger(e.start)&&Number.isInteger(e.stop))return;if(!e.name)throw"both term.name and term.chr/start/stop missing";const n=t.genedb.getjsonbyname.all(e.name);if(0==n.length)throw"unknown gene name";const s=n.find((e=>e.isdefault))||n[0],r=JSON.parse(s.genemodel);if(!r.chr||!Number.isInteger(r.start)||!Number.isInteger(r.stop))throw"invalid chr/start/stop from returned gm";return e.chr=r.chr,e.start=r.start,e.stop=r.stop,r.isoform}async function Bs(e,t,n,s){const r={addFormatValues:!0,filter0:s.filter0,filterObj:s.filter,sessionid:s.sessionid,gdcUseCaseuuid:!0};if(e.queries.snvindel.byisoform)return await async function(e,t){if(e.isoform&&"string"==typeof e.isoform)return;if(!e.name)throw"both term.name and term.isoform";const n=t.genedb.getjsonbyname.all(e.name);if(0==n.length)return;const s=n.find((e=>e.isdefault))||n[0],r=JSON.parse(s.genemodel);if(!r.isoform)throw"isoform missing from returned gm";e.isoform=r.isoform}(t,n),t.isoform?(r.isoform=t.isoform,await e.queries.snvindel.byisoform.get(r)):[];if(e.queries.snvindel.byrange)return r.isoform=await zs(t,n),r.rglst=[t],await e.queries.snvindel.byrange.get(r);throw"unknown queries.snvindel method"}function Js(e,t){t.yesSamples=new Set,t.noSamples=new Set;const n=`SELECT sample, value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = '${t.term_id}'`,s=e.cohort.db.connection.prepare(n).all();for(const e of s)t.yes.value.includes(e.value)?t.yesSamples.add(e.sample):t.no.value.includes(e.value)&&t.noSamples.add(e.sample)}function Hs(e,t,n){if(t.skewerRim){if("format"!=t.skewerRim.type)throw"unknown skewerRim.type";e.rim1count=0;for(const n of e.samples)n.formatK2v?.[t.skewerRim.formatKey]==t.skewerRim.rim1value&&e.rim1count++}}function Ws(e,t){if(t.queries.snvindel?.format)for(const n in t.queries.snvindel.format)if(t.queries.snvindel.format[n].isFilter){e.formatK2count||(e.formatK2count={}),e.formatK2count[n]||(e.formatK2count[n]={v2c:{},unannotatedCount:0});for(const t of e.samples){const s=t.formatK2v?.[n];null==s?e.formatK2count[n].unannotatedCount++:e.formatK2count[n].v2c[s]=1+(e.formatK2count[n].v2c[s]||0)}}}function Vs(e,t){if(e.startunbounded){if(e.stopunbounded)throw"both start & stop are unbounded from "+t;if(!Number.isFinite(e.stop))throw".stop undefined when start is unbounded from "+t}else if(e.stopunbounded){if(!Number.isFinite(e.start))throw".start undefined when stop is unbounded from "+t}else{if(!Number.isFinite(e.start))throw".start undefined when start is not unbounded from "+t;if(!Number.isFinite(e.stop))throw".stop undefined when stop is not unbounded from "+t;if(e.start>=e.stop)throw".start is not lower than stop from "+t}}const Zs="Ancestry_PC_";async function Ks(e,t=null,s=null){if(!e.cohort.termdb)throw"cohort.termdb missing when cohort.db is used";await async function(e){if(e.phewas){if(e.phewas.samplefilter4termtype&&e.phewas.samplefilter4termtype.condition&&!e.phewas.samplefilter4termtype.condition.filter)throw"filter{} missing from tdb.phewas.samplefilter4termtype.condition";if(e.phewas.comparison_groups){if(!Array.isArray(e.phewas.comparison_groups))throw"tdb.phewas.comparison_groups is not array";if(0==e.phewas.comparison_groups.length)throw"tdb.phewas.comparison_groups[] cannot be empty"}}if(e.selectCohort){if(!e.selectCohort.term)throw"term{} missing from termdb.selectCohort";if(!e.selectCohort.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof e.selectCohort.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=e.selectCohort.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';if(!e.selectCohort.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(e.selectCohort.values))throw"termdb.selectCohort.values is not array";if(0==e.selectCohort.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const t of e.selectCohort.values){if(!t.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(t.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==t.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}if(e.restrictAncestries){if(!Array.isArray(e.restrictAncestries)||0==e.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const t of e.restrictAncestries){if(!t.name)throw"name missing from one of restrictAncestries";if("object"!=typeof t.tvs)throw".tvs{} missing from one of restrictAncestries";if(!Number.isInteger(t.PCcount))throw"PCcount is not integer";if(t.PCfile)t.pcs=await Ys(t.PCfile,t.PCcount);else if(t.PCfileBySubcohort)for(const e in t.PCfileBySubcohort){const n=t.PCfileBySubcohort[e];if(!n.file)throw".file missing for a subcohort in PCfileBySubcohort";n.pcs=await Ys(n.file,t.PCcount)}}}}(e.cohort.termdb),await async function(e){if("scatterplots"in e)for(const t of e.scatterplots.plots){const e=g().join(r().tpmasterdir,t.file);await R.Ic(e)}}(e.cohort),(0,bs.JV)(e),function(e){e.sampleName2Id=new Map,e.sampleId2Name=new Map;const t="SELECT * FROM sampleidmap",n=e.cohort.db.connection.prepare(t).all();for(const t of n)e.sampleId2Name.set(t.id,t.name),e.sampleName2Id.set(t.name,t.id);e.getSampleIdMap=t=>{const n={};for(const s in t)n[s]=e.sampleId2Name.get(+s);return n}}(e);const{mayGetGeneVariantData:o,getTermTypes:i,mayGetMatchingGeneNames:a}=n(7833);e.mayGetGeneVariantData=o,e.getTermTypes=i,e.mayGetMatchingGeneNames=a,e.cohort?.db?.refresh&&t&&ws(e,t,s)}async function Xs(e,t){if(!e.track)throw"no mds2 track; missing ds.track{}";const n=e.track;n.name||(n.name=e.label),function(e){if(!e.populations)return;if(!Array.isArray(e.populations))throw"populations should be array";for(const t of e.populations){if(!t.key)throw"key missing from a population";if(t.label||(t.label=t.key),!Array.isArray(t.sets))throw".sets is not an array in population: "+t.key;for(const e of t.sets){if(!e.infokey_AC)throw"infokey_AC missing from a set of population: "+t.key;if(!e.infokey_AN)throw"infokey_AN missing from a set of population: "+t.key;if(t.termfilter&&!e.termfilter_value)throw"termfilter_value missing from a set of population where termfilter is set: "+t.key}}}(n),await async function(e,t,n){if(!e)return;if(!e.chr2bcffile)throw"vcftk.chr2bcffile is missing";{if("object"!=typeof e.chr2bcffile)throw"chr2bcffile not an object";for(const t in e.chr2bcffile)e.chr2bcffile[t]=g().join(r().tpmasterdir,e.chr2bcffile[t]);const n={file:e.chr2bcffile[t.defaultcoord.chr]};if(!n.file)throw"default chr missing from chr2bcffile";await R._H(n,t,!0),e.info=n.info,e.format=n.format,e.samples=n.samples,e.nochr=n.nochr}if(e.AD&&e.AD.chr2bcffile){if("object"!=typeof e.AD.chr2bcffile)throw"AD.chr2bcffile not an object";for(const t in e.AD.chr2bcffile)e.AD.chr2bcffile[t]=g().join(r().tpmasterdir,e.AD.chr2bcffile[t]);const s={file:e.AD.chr2bcffile[t.defaultcoord.chr]};if(!s.file)throw"default chr missing from AD.chr2bcffile";await R._H(s,t,!0),e.AD.info=s.info,e.AD.format=s.format,e.AD.samples=s.samples,e.AD.nochr=s.nochr,console.log(n.label+" vcf: AD: "+e.AD.samples.length+" samples");for(const t of e.AD.samples){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer vcf sample: "+t.name;t.name=e}}if(e.samples){for(const t of e.samples){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer vcf sample: "+t.name;t.name=e}console.log(n.label+" vcf: "+e.samples.length+" samples")}else console.log(n.label+" vcf: no samples");if(e.numerical_axis&&e.numerical_axis.info_keys){if(!Array.isArray(e.numerical_axis.info_keys))throw"numerical_axis.info_keys should be an array";for(const t of e.numerical_axis.info_keys){const n=e.info[t.key];if(!n)throw'INFO field "'+t.key+'" not found for numerical_axis';if("Float"!=n.Type&&"Integer"!=n.Type)throw'INFO field "'+t.key+'" from numerical_axis not of integer or float type';if("1"!=n.Number&&"A"!=n.Number)throw'for numerical axis, INFO field "'+t.key+'" only allows to be Number=1 or Number=A'}}if(e.plot_mafcov){if(!e.AD)throw".plot_mafcov enabled but .AD{} missing from vcf";if(!e.AD.samples)throw".plot_mafcov enabled but no samples from vcf";if(!e.AD.format)throw".plot_mafcov enabled but no FORMAT fields from vcf";if(!e.AD.format.AD)throw".plot_mafcov enabled but the AD FORMAT field is missing";if("R"!=e.AD.format.AD.Number)throw"AD FORMAT field Number=R is not true";if("Integer"!=e.AD.format.AD.Type)throw"AD FORMAT field Type=Integer is not true";if(e.plot_mafcov.overlay_term){if(!n.cohort)throw"ds.cohort missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb)throw"ds.cohort.termdb missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb.q)throw"ERR: termdb.q{} missing while trying to access termdb helper functions";if(!n.cohort.termdb.q.termjsonByOneid)throw"ERR: q.termjsonByOneid missing";const t=n.cohort.termdb.q.termjsonByOneid(e.plot_mafcov.overlay_term);if(!t)throw'unknown term id "'+e.plot_mafcov.overlay_term+'" from vcftk.plot_mafcov.overlay_term';e.plot_mafcov.overlay_term=t}}if(e.termdb_bygenotype){if(!e.samples)throw".termdb_bygenotype enabled but no samples from vcf";if(!e.format)throw".termdb_bygenotype enabled but no FORMAT fields from vcf";if(!e.format.GT)throw".termdb_bygenotype enabled but the GT FORMAT field is missing";if(!n.cohort)throw"termdb_bygenotype but ds.cohort missing";if(!n.cohort.termdb)throw"termdb_bygenotype but ds.cohort.termdb missing";if(e.termdb_bygenotype.getAF){if(!e.termdb_bygenotype.termid_sex)throw"termid_sex missing for getAF at termdb_bygenotype";if(!e.termdb_bygenotype.value_male)throw"value_male missing for getAF at termdb_bygenotype";const t=n.cohort.termdb.q.getSample2value(e.termdb_bygenotype.termid_sex);e.termdb_bygenotype.male_samples=new Set;for(const n of t)n.value==e.termdb_bygenotype.value_male&&e.termdb_bygenotype.male_samples.add(n.sample);if(!e.termdb_bygenotype.sex_chrs)throw"sex_chrs missing for getAF at termdb_bygenotype";if(!Array.isArray(e.termdb_bygenotype.sex_chrs))throw"sex_chrs is not array";e.termdb_bygenotype.sex_chrs=new Set(e.termdb_bygenotype.sex_chrs)}}if(e.samples){e.sample2arrayidx=new Map;for(const[t,n]of e.samples.entries())e.sample2arrayidx.set(n.name,t)}}(n.vcf,t,e),function(e){if(!e.info_fields)return;if(!Array.isArray(e.info_fields))throw"tk.info_fields is not array";for(const t of e.info_fields){if(!t.key)throw".key missing from one of tk.info_fields[]";if(e.vcf&&e.vcf.info&&!e.vcf.info[t.key])throw`info field ${t.key} missing from tk.vcf.info{}`;if(t.label||(t.label=t.key),t.iscategorical){if(!Array.isArray(t.values))throw".values[] not an array of categorical INFO field: "+t.key;for(const e of t.values){if(!e.key)throw"key missing from a value of categorical INFO: "+t.key;e.label||(e.label=e.key)}}else if(t.isfloat||t.isinteger){if(!t.range)throw".range{} missing from a numerical INFO: "+t.key;Vs(t.range,"tk.info_fields[]")}else if(!t.isflag)throw"tk.info_fields unknown type: "+t.key}}(n),await async function(e,t,n){if(!e)return;if(!Array.isArray(e.tracks))throw"ld.tracks[] not an array";if(0==e.tracks.length)throw"ld.tracks[] is empty array";for(const n of e.tracks){if(!n.name)throw".name missing from a ld track";if(!Number.isInteger(n.viewrangelimit))throw'viewrangelimit missing from ld track "'+n.name+'"';if(n.file)n.file.startsWith(r().tpmasterdir)||(n.file=g().join(r().tpmasterdir,n.file)),await R.LC(n.file),n.nochr=await R.Jy(n.file,null,t),console.log(n.file+": "+(n.nochr?"no chr":"has chr"));else if(!n.chr2file)throw"ld tk has no file or chr2file"}}(n.ld,t),await async function(e,t){if(!e)return}(n.svcnv,0),function(e){const t=new Set;if(e.vcf&&e.vcf.samples)for(const n of e.vcf.samples)t.add(n.name);e.svcnv;t.size&&(e.samples=[...t])}(n),n.samples&&console.log(e.label+": mds2: "+n.samples.length+" samples")}async function Ys(e,t){const n=new Map;for(let e=1;e<=t;e++)n.set(Zs+e,new Map);let s=0;for(const o of(await R.b5(g().join(r().tpmasterdir,e))).trim().split("\n")){s++;const e=o.split("\t"),r=Number(e[0]);if(!Number.isInteger(r))throw"non-integer sample id from a line of restrictAncestries pc file";for(let s=1;s<=t;s++){const t=Zs+s,o=Number(e[s]);if(Number.isNaN(o))throw"non-numeric PC value from restrictAncestries file";n.get(t).set(r,o)}}return console.log(s,"samples loaded from "+e),Object.freeze(n)}var Qs=n(9157);const er=n(334),tr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO";async function nr(e,t,n,s){if(!e.rglst)throw".rglst[] missing";const r=n.track.vcf;if(!r)throw"ds.track.vcf missing";const o={info:r.info,format:r.format,samples:r.samples};await async function(e,t,n){if(e.querymode={},e.AFtest){if(n.iscustom)throw"custom track does not support AFtest";for(const t of e.AFtest.groups)if(!t.is_infofield)if(t.is_termdb)t.columnidx=await sr(t.filter,n);else{if(!t.is_population)throw"Cannot set query mode: unknown group type";{if(!n.track.populations)throw"ds.track.populations missing";const s=n.track.populations.find((e=>e.key==t.key));if(!s)throw"unknown population key: "+t.key;if(t.population=JSON.parse(JSON.stringify(s)),e.AFtest.termfilter&&e.AFtest.termfilter[0].term.id==t.population.termfilter){const n=t.population.sets.find((t=>t.termfilter_value==e.AFtest.termfilter[0].values[0].key));if(!n)throw"no matching set found for a termfilter from a population";t.population.sets=[n]}}}if(e.AFtest.testby_fisher&&e.AFtest.groups.find((e=>e.is_infofield)))throw"cannot do fisher test for an INFO field";{const t=e.AFtest.groups.find((e=>e.is_population));if(t&&t.adjust_race){const s=e.AFtest.groups.find((e=>e.is_termdb));if(!s)throw"cannot adjust race: termdb group missing";s.pop2average=await async function(e,t,n,s){const r=new Map;let o=0;for(const t of e){const e={infokey_AC:t.infokey_AC,infokey_AN:t.infokey_AN,average:0},s=await ys.J4({ds:n,key:t.key});for(const t of s){if(!n.track.vcf.sample2arrayidx.has(t.sample))continue;const s=Number(t.value);Number.isFinite(s)&&(e.average+=s,o+=s)}r.set(t.key,e)}for(const[e,t]of r)t.average/=o;return r}(t.population.sets,s.columnidx,n)}}return void(e.querymode.range_AFtest=!0)}e.querymode.range_variantonly=!0}(e,0,n),function(e,t){if(t.querymode.range_variantonly||t.querymode.range_AFtest){delete e.samples;for(const e of t.rglst)e.variants=[]}t.bcfformat=tr,t.exportgenotype||t.querymode.range_AFtest?t.bcfformat+="\t%FORMAT\n":t.querymode.range_variantonly&&(t.querymode.slicecolumnindex||(t.bcfformat+="\\n"))}(o,e),e.exportgenotype&&(s.mlst=[]),function(e,t){const n=(s=e.rglst[0],s.usegm_isoform?{gmmode:"protein",usegm:{isoform:s.usegm_isoform}}:{});var s;e.m_is_filtered=s=>{let r=!1;if(e.info_fields)for(const n of e.info_fields){const e=t.info_fields[n.key];let o;if(s.info&&(o=s.info[n.key]),null==o&&s.altinfo&&(o=s.altinfo[n.key]),n.iscategorical)null==o?(e.unannotated_count=1+(e.unannotated_count||0),n.unannotated_ishidden&&(r=!0)):(e.value2count[o]=1+(e.value2count[o]||0),n.hiddenvalues[o]&&(r=!0));else if(n.isnumerical)null==o&&null!=n.missing_value&&(o=n.missing_value),n.range.startunbounded||(n.range.startinclusive?o<n.range.start&&(r=!0):o<=n.range.start&&(r=!0)),n.range.stopunbounded||(n.range.stopinclusive?o>n.range.stop&&(r=!0):o>=n.range.stop&&(r=!0)),r&&e.filteredcount++;else{if(!n.isflag)throw"unknown info type";o?e.count_yes++:e.count_no++,(n.remove_yes&&o||n.remove_no&&!o)&&(r=!0)}}return!!r||(F.vcfcopymclass(s,n),t.mclass2count[s.class]=(t.mclass2count[s.class]||0)+1,e.hidden_mclass&&e.hidden_mclass.has(s.class)&&(r=!0),r)}}(e,s);for(const t of e.rglst){if(r.viewrangeupperlimit&&t.stop-t.start>=r.viewrangeupperlimit){t.rangetoobig="Zoom in under "+F.bplen(r.viewrangeupperlimit)+" to view VCF data";continue}const n=(r.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop,s=r.chr2bcffile[t.chr];if(!s)throw"chr not found in chr2bcffile";await R.UE({isbcf:!0,args:["query",s,"-r",n,"-f",e.bcfformat],dir:r.dir,callback:i(t)})}function i(t){return n=>{if(e.exportgenotype){const t=n.split("\t"),[r,i,a]=$.S(t.slice(0,8).join("\t"),o);for(const n of i){if(e.m_is_filtered(n))continue;const r=[n.chr+"."+(n.pos+1)+"."+n.ref+"."+n.alt,n.name||""];for(let e=9;e<t.length;e++){const s=t[e].split(":",1)[0];if("."==s){r.push(".");continue}const o=s.split(-1==s.indexOf("/")?"|":"/");r.push(("0"==o[0]?n.ref:n.alt)+("0"==o[1]?n.ref:n.alt))}s.mlst.push(r.join("\t"))}return}let i;if(e.querymode.range_variantonly)if(e.querymode.slicecolumnindex);else{const[t,s,r]=$.S(n,o);i=[];for(const t of s)e.m_is_filtered(t)||i.push(t)}else e.querymode.range_AFtest&&(i=function(e,t,n,s){const r=e.split("\t"),[o,i,a]=$.S(r.slice(0,8).join("\t"),n),l=i.filter((e=>!t.m_is_filtered(e)));if(0==l.length)return;const c=[r[3],...r[4].split(",")],u=[];for(const e of l){const n=or(r,e,c,t);if(rr(n)){if(u.push(e),t.AFtest.testby_AFdiff){for(const e of n)if(e.is_infofield)e.v=e.infofieldvalue;else{if(!e.is_termdb&&!e.is_population)throw"unknown group type";e.v=e.altcount/(e.refcount+e.altcount)}e.AFtest_group_values=[n[0].v,n[1].v],e.nm_axis_value=n[0].v-n[1].v}else t.AFtest.testby_fisher&&(e.contigencytable=[n[0].altcount,n[0].refcount,n[1].altcount,n[1].refcount]);{const s=t.AFtest.groups.find((e=>e.is_population));if(s&&s.adjust_race){const t=n.find((e=>e.is_population));e.popsetadjvalue=[];for(const[n,s]of t.set2value)e.popsetadjvalue.push([n,s.ACraw,s.ANraw-s.ACraw,Number.parseInt(s.ACadj),Number.parseInt(s.ANadj-s.ACadj)])}}}}return u}(n,e,o));if(i)for(const e of i)e.csq&&(e.csq_count=e.csq.length,delete e.csq),delete e._m,delete e.vcf_ID,delete e.sampledata,r.nochr&&(e.chr="chr"+e.chr),t.variants.push(e)}}await async function(e){if(!e.querymode.range_AFtest)return;if(!e.AFtest.testby_fisher)return;const t=[],n={};for(const s of e.rglst)if(s.variants)for(const e of s.variants)if(e.contigencytable){const s=e.chr+"."+e.pos+"."+e.ref+"."+e.alt;t.push(s+"\t"+e.contigencytable.join("\t")),n[s]=e}if(0==t.length)return;const s=await Qs(g().join(er.binpath,"/utils/fisher.R"),t);for(const e of s){const t=e.split("\t"),s=n[t[0]];if(s){const e=Number.parseFloat(t[5]);s.AFtest_pvalue=e,s.nm_axis_value=Number.isNaN(e)?0:-Math.log10(e)}}}(e),function(e,t,n,s){if(t.exportgenotype)return e.exportgenotype="variant\tSNP\t"+n.samples.map((e=>s.cohort.termdb.id2sampleName(e.name))).join("\t")+"\n"+e.mlst.join("\n"),void delete e.mlst;e.vcf={rglst:[]};for(const n of t.rglst){const t={chr:n.chr,start:n.start,stop:n.stop,width:n.width,reverse:n.reverse,xoff:n.xoff};e.vcf.rglst.push(t),n.rangetoobig?(t.rangetoobig=n.rangetoobig,delete n.rangetoobig):n.variants?(t.variants=n.variants,delete n.variants):n.canvas&&(t.img=n.canvas.toDataURL(),delete n.canvas)}if(t.AFtest&&t.AFtest.groups.find((e=>e.is_termdb))){e.AFtest_termdbgroup=[];let n=t.AFtest.groups[0];if(n.is_termdb&&(e.AFtest_termdbgroup[0]={samplecount:n.columnidx.length},n.pop2average)){e.AFtest_termdbgroup[0].popsetaverage=[];for(const[t,s]of n.pop2average)e.AFtest_termdbgroup[0].popsetaverage.push([t,s.average])}if(n=t.AFtest.groups[1],n.is_termdb&&(e.AFtest_termdbgroup[1]={samplecount:n.columnidx.length},n.pop2average)){e.AFtest_termdbgroup[1].popsetaverage=[];for(const[t,s]of n.pop2average)e.AFtest_termdbgroup[1].popsetaverage.push([t,s.average])}}}(s,e,r,n)}async function sr(e,t){if(!t.track)throw"ds.track{} missing";return(await ys.cf(e,t)).reduce(((e,n)=>{const s=t.track.vcf.sample2arrayidx.get(n);return s>=0&&e.push(s),e}),[])}function rr(e){if(e.find((e=>e.is_infofield)))return!0;return e[0].altcount+e[1].altcount>0}function or(e,t,n,s){return s.AFtest.groups.reduce(((r,o)=>{if(o.is_infofield)r.push({is_infofield:!0,infofieldvalue:ir(t,o)});else if(o.is_termdb){const s=function(e,t,n){let s=!0;const r=new Map;for(const t of e)r.set(t,0);for(const o of n){if(!t[9+o])continue;const n=t[9+o].split(":")[0];"."!=n&&n.split(-1==n.indexOf("/")?"|":"/").forEach((t=>{const n=Number.parseInt(t);if(Number.isNaN(n))return;const o=e[n];o&&(0!=n&&(s=!1),r.set(o,1+r.get(o)))}))}return{allref:s,alleles:r}}(n,e,o.columnidx);r.push({is_termdb:!0,allref:s.allref,refcount:s.alleles.get(t.ref)||0,altcount:s.alleles.get(t.alt)||0})}else{if(!o.is_population)throw"unknown group type";{const e=new Map;for(const n of o.population.sets)e.set(n.key,{ACraw:ir(t,{key:n.infokey_AC,missing_value:0}),ANraw:ir(t,{key:n.infokey_AN,missing_value:0})});let n=0,i=0;if(o.adjust_race)[n,i]=function(e,t){if(!t)throw"group_termdb missing";if(!t.pop2average)throw"group_termdb.pop2average missing";let n=0;for(const t of e.values())n+=t.ANraw;let s=0,r=0;for(const[o,i]of e)i.ANadj=n*t.pop2average.get(o).average,i.ACadj=0==i.ANadj?0:i.ACraw*i.ANadj/i.ANraw,s+=i.ACadj,r+=i.ANadj;return[r-s,s]}(e,s.AFtest.groups.find((e=>e.is_termdb)));else for(const t of e.values())i+=t.ACraw,n+=t.ANraw-t.ACraw;r.push({is_population:!0,refcount:n,altcount:i,set2value:e})}}return r}),[])}function ir(e,t){if(e.info){const n=e.info[t.key];if(null!=n)return n}if(e.altinfo){const n=e.altinfo[t.key];if(null!=n)return n}return t.missing_value}var ar=n(5540);const lr=(0,n(4090).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),cr="#aaa",ur="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO\t%FORMAT\n";async function fr(e,t,n,s,r){const o=s.track.ld.tracks.find((t=>t.name==e.name));if(!o)throw"ld track not found by name: "+e.name;if(!t.rglst)throw"rglst missing";r.ld[o.name]={rglst:[]};const i=t.trigger_ld.connheight||50;for(const e of t.rglst){const t={chr:e.chr,start:e.start,stop:e.stop,width:e.width,reverse:e.reverse,xoff:e.xoff};if(r.ld[o.name].rglst.push(t),e.stop-e.start>=o.viewrangelimit){t.rangetoobig="Zoom in under "+(0,F.bplen)(o.viewrangelimit)+" to view LD data";continue}const n=[],s=new Set,a=(o.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;await R.UE({args:[o.file,a],dir:o.dir,callback:t=>{const o=t.split("\t"),i=Number.parseInt(o[1]);if(i<e.start)return;const a=Number.parseInt(o[2]);if(a>e.stop)return;if(r.__mposset){if(!r.__mposset.has(i))return;if(!r.__mposset.has(a))return}const l=Number.parseFloat(o[5]);n.push({start:i,stop:a,r2:l}),s.add(i),s.add(a)}}),t.img=dr(e,n,s,i)}}function dr(e,t,n,s){const[r,o]=function(e,t){let n=e.width/t.size,s=0;n>40&&(n=40,s=(e.width-n*t.size)/2);const r=new Map,o=e.reverse?[...t].sort(((e,t)=>t-e)):[...t].sort(((e,t)=>e-t));let i=s;for(const e of o)r.set(e,i+n/2),i+=n;return[n,r]}(e,n),i=new Map;{const t=(e.stop-e.start)/e.width;for(const s of n)e.reverse?i.set(s,(e.stop-s)/t):i.set(s,(s-e.start)/t)}let a=0;for(const e of t)a=Math.max(a,(o.get(e.stop)-o.get(e.start))/2);const l=s+a+r/2,c=(0,N.createCanvas)(e.width,l),u=c.getContext("2d");u.strokeStyle="black";for(const e of n)u.beginPath(),u.moveTo(i.get(e),0),u.lineTo(o.get(e),s),u.closePath(),u.stroke();for(const e of t){const t=o.get(e.start),n=o.get(e.stop),i=(t+n)/2,a=s+Math.abs(n-t)/2,l=Math.floor(255*(1-e.r2));u.fillStyle="rgb(255,"+l+","+l+")",u.beginPath(),u.moveTo(i,a-r/2),u.lineTo(i-r/2,a),u.lineTo(i,a+r/2),u.lineTo(i+r/2,a),u.lineTo(i,a-r/2),u.closePath(),u.fill()}return{height:l,src:c.toDataURL()}}var pr=n(6191);function mr(e,t){const{filename:n,route:s,dslabel:o,embedder:i}=e,a=t.email.replace("@","_at_");return`${r().cachedir}/sessionsByCred/${i}/${a}/${s}/${o}`}const hr=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];function gr(e){const t=e.toString(16);return 1==t.length?"0"+t:t}function yr(e,t,n){return gr(e)+gr(t)+gr(n)}function br(e){if(!e.cellfile)throw"cellfile missing";{const[t,n,s]=R.ZX({query:{file:e.cellfile}});if(t)throw"cellfile error: "+t;e.cellfile=n}if(!e.delimiter)throw"delimiter missing";if(!Number.isInteger(e.barcodecolumnidx))throw"barcodecolumnidx missing";if(!Number.isInteger(e.categorycolumnidx))throw"categorycolumnidx missing";return new Promise(((t,n)=>{const s=new Map,r=O().createInterface({input:m().createReadStream(e.cellfile)});let o=!0;r.on("line",(t=>{if(o)return void(o=!1);const n=t.split(e.delimiter);s.set(n[e.barcodecolumnidx],{category:n[e.categorycolumnidx],expvalue:0})})),r.on("close",(()=>{t(s)}))}))}const vr=r().fimo||"fimo";async function wr(e,t,n){const s=g().join(r().cachedir,Math.random().toString());return await R.Sf(s,n),new Promise(((n,r)=>{const o=["--parse-genomic-coord","--verbosity",1,"--text"];e.fimo_thresh&&(o.push("--thresh"),o.push(e.fimo_thresh)),o.push(t.fimo_motif.db),o.push(s);const i=(0,q.spawn)(vr,o),a=[];i.stdout.on("data",(e=>a.push(e))),i.on("close",(r=>{m().unlink(s,(()=>{}));const o=a.join("").trim();o||n([]);const i=[],l=o.split("\n");for(let n=1;n<l.length;n++){const s=l[n].split("\t"),r=s[0].split("_")[0],o=Number.parseInt(s[3]),a=Number.parseInt(s[4]);if(o>e.m.pos||a<e.m.pos+1)continue;const c=Number.parseFloat(s[7]),u={start:o,stop:a,strand:s[5],name:r,pvalue:c,score:Number.parseFloat(s[6]),logpvalue:-Math.log10(c)};t.fimo_motif.tf2attr&&(u.attr=t.fimo_motif.tf2attr[u.name]),i.push(u)}n(i)}))}))}function _r(e){!function(e){if(!e.sample2term)throw".sample2term missing";if(!e.terms)throw".terms[] missing";if(!e.config)throw".config{} missing"}(e);const t=function(e){const t=new Map;for(const n of e.sample2term.values())for(const e of n.keys())t.set(e,1+(t.get(e)||0));if(e.config.termidorder){const n=[];for(const s of e.config.termidorder){const e=t.get(s);null!=e&&n.push({id:s,samplecount:e})}return n}return[...t].sort(((e,t)=>t[1]-e[1])).map((e=>({id:e[0],samplecount:e[1]})))}(e),n=function(e,t){const n=[];for(const[s,r]of e.sample2term)t.find((e=>r.has(e.id)))&&n.push(s);return n}(e,t);return function(e,t,n){for(const[s,r]of t.entries()){const o=0==s?[{samples:n}]:t[s-1].blocks;r.blocks=kr(o,r.id,e)}}(e,t,n),function(e,t){for(const n of e){const e=t.terms.find((e=>e.id==n.id));n.name=e.name;for(const t of n.blocks)t.samplecount=t.samples.length,delete t.samples,t.value&&(t.color=e.values[t.value].color)}}(t,e),function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];for(const e of n.blocks){let t=0;for(const n of e.children)t+=n.symbolwidth;const n=e.isgap?1:e.samplecount.toString().length;e.symbolwidth=Math.max(n,t)}}let t=0;for(const n of e[0].blocks){n.x=t;let e=t;for(const t of n.children)t.x=e,e+=t.symbolwidth;t+=n.symbolwidth}for(let t=1;t<e.length;t++)for(const n of e[t].blocks){let e=n.x;for(const t of n.children)t.x=e,e+=t.symbolwidth}for(const t of e)delete t.children}(t),t}function kr(e,t,n){const s=[];for(const r of e){const e=new Map,o=[];for(const s of r.samples){const r=n.sample2term.get(s);if(r){const n=r.get(t);null==n?o.push(s):(e.has(n)||e.set(n,[]),e.get(n).push(s))}else o.push(s)}const i=[...e].sort(((e,t)=>t[1].length-e[1].length));for(const e of i){const t={value:e[0],samples:e[1],children:[]};s.push(t),r.children&&r.children.push(t)}if(o.length){const e={isgap:!0,samples:o,children:[]};s.push(e),r.children&&r.children.push(e)}}return s}async function qr(e){const t=["futime\tfustat\trx"];for(const[n,s]of e.entries())for(const e of s.lst)t.push(e.serialtime+"\t"+e.censored+"\t"+n);const n=await(0,Qs.default)(g().join(r().binpath,"/utils/km.R"),t);return Number(n.join(""))}async function xr(e,t,n,s){const r=new Set(e.map((e=>e.name))),o=t.samplerule.set;let i,a;for(const e in n.queries){const t=n.queries[e];t.type==F.tkt.mdsvcf?i=t:t.type==F.tkt.mdssvcnv&&(a=t)}const l=new Set;if(o.cnv||o.loh||o.sv||o.fusion||o.itd){if(!a)throw"no svcnv found in ds.queries";if(s)return await Nr(a,r,t,!0);const e=await Nr(a,r,t);for(const t of e)l.add(t)}if(o.snvindel){if(!i)throw"no vcf found in ds.queries";for(const e of i.tracks)await Sr(i,e,r,l,t)}return e.filter((e=>l.has(e.name)))}async function Nr(e,t,n,s){const o=n.samplerule.set,i=e.url?await R.d1(e.url,e.indexURL):null,a=new Set,l=new Set,c=new Set;return await R.UE({args:[e.file?g().join(r().tpmasterdir,e.file):e.url,(e.nochr?o.chr.replace("chr",""):o.chr)+":"+o.start+"-"+(o.stop+1)],dir:i,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),i=Number.parseInt(n[2]),u=JSON.parse(n[3]);if(t.has(u.sample)){if(u.dt==F.dtcnv){if(!o.cnv)return;if(o.cnv.focalsizelimit&&i-r>=o.cnv.focalsizelimit)return;if(o.cnv.valuecutoff&&Math.abs(u.value)<o.cnv.valuecutoff)return;return s?u.value>0?a.add(u.sample):l.add(u.sample):c.add(u.sample),void o.samples_cnv.add(u.sample)}if(u.dt==F.dtloh){if(!o.loh)return;if(o.loh.focalsizelimit&&i-r>=o.loh.focalsizelimit)return;if(o.loh.valuecutoff&&u.segmean<o.loh.valuecutoff)return;return c.add(u.sample),void o.samples_loh.add(u.sample)}if(u.dt==F.dtsv){if(!o.sv)return;return c.add(u.sample),void o.samples_sv.add(u.sample)}if(u.dt==F.dtfusionrna){if(!o.fusion)return;return c.add(u.sample),void o.samples_fusion.add(u.sample)}if(u.dt==F.dtitd){if(!o.itd)return;return c.add(u.sample),void o.samples_itd.add(u.sample)}}}}),s?[a,l]:c}async function Sr(e,t,n,s,o){const i=o.samplerule.set,a=t.url?await R.d1(t.url,t.indexURL):null;await R.UE({args:[t.file?g().join(r().tpmasterdir,t.file):t.url,(t.nochr?i.chr.replace("chr",""):i.chr)+":"+i.start+"-"+(i.stop+1)],dir:a,callback:r=>{if(t.type==F.mdsvcftype.vcf){const[o,a,l]=$.S(r,{nochr:t.nochr,samples:t.samples,info:e.info,format:t.format});for(const e of a)if(e.sampledata&&!(i.snvindel.ref&&(e.ref!=i.snvindel.ref||e.alt!=i.snvindel.alt)||i.snvindel.hiddenclass&&(F.vcfcopymclass(e,{}),i.snvindel.hiddenclass[e.class])))for(const t of e.sampledata)n.has(t.sampleobj.name)&&(s.add(t.sampleobj.name),i.samples_snvindel.add(t.sampleobj.name))}}})}async function Ar(e,t,n){if(!n.queries)throw".queries{} missing from ds";let s;for(const e in n.queries)n.queries[e].isgenenumeric&&(s=n.queries[e]);if(!s)throw"no gene numeric query from ds";const o=s.url?await R.d1(s.url,s.indexURL):null,i=t.samplerule.set,a=new Map;await R.UE({args:[s.file?g().join(r().tpmasterdir,s.file):s.url,i.chr+":"+i.start+"-"+i.stop],dir:o,callback:e=>{const t=JSON.parse(e.split("\t")[3]);t.sample&&Number.isFinite(t.value)&&t.gene==i.gene&&a.set(t.sample,t.value)}});const l=[];for(const t of e)a.has(t.name)&&(t.genevalue=a.get(t.name),l.push(t));return l.sort(((e,t)=>e.genevalue-t.genevalue)),[s,l]}function Cr(e){e.lst.sort(((e,t)=>e.serialtime-t.serialtime));let t=e.lst.length,n=[],s=0;e.steps=[];for(const r of e.lst){if(0==r.censored){n.push(r.serialtime);continue}const o=1*(1-s)/(t-n.length);e.steps.push({x:r.serialtime,y:s,drop:o,censored:n}),s+=o,t-=n.length+1,n=[]}n.length>0&&e.steps.push({x:e.lst[e.lst.length-1].serialtime,y:s,drop:0,censored:n})}exports.do_plot=Cr;const jr={};function Tr(e,t,n){const s=+new Date;if(e.ip in jr||(jr[e.ip]={time:s,count:0}),s-jr[e.ip].time>3e4)delete jr[e.ip];else{if(jr[e.ip].count>10)return void t.send({error:"busy"});jr[e.ip].count++}throw t.send({error:n}),new Date+" "+n}const Mr={genome(e){if("string"!=typeof e)throw"genome should be a non-empty string";if(/\s+/.test(e))throw"invalid genome character";return e},chr(e){if("string"!=typeof e)throw"chr should be a string";if(/\s+/.test(e))throw"invalid chr character";return e},start:e=>Number(e),term(e){const t="string"==typeof e?JSON.parse(e):e;if(!("id"in t))throw"missing termWrapper.id";if(!("q"in t))throw"missing termWrapper.q";return t}},Or=require("cookie-parser");var Ir=n.n(Or),Er=n(2062);function Rr(e){return!isNaN(parseFloat(e))&&isFinite(e)&&""!==e}var Fr=n(5708);const $r=e=>e.startsWith("[E::idx_test_and_fetch]"),Dr=(new Map,r().features),Lr={},Pr=r().tabix,Gr=r().samtools,Ur=r().bcftools,zr=(r().bigwigsummary,r().hicstraw,"Unannotated"),Br=i()();Br.disable("x-powered-by"),r().users&&Br.use(be()({users:r().users,challenge:!0}));const Jr=r().basepath||"";function Hr(e){e.header("Vary","Origin"),e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS, HEAD"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, origin, x-requested-with, content-type, accept, authorization, X-Auth-Token, X-Ds-Access-Token, X-SjPPDs-Sessionid, x-auth-token, x-ds-access-token, x-sjppds-sessionid")}if(!r().backend_only){const e=i().static(g().join(process.cwd(),"./public"),{setHeaders:Hr});Br.use(e)}function Wr(e){const t={};for(const n in e.query)"jwt"!=n&&(t[n]=e.query[n]);console.log("%s\t%s\t%s\t%s",l().parse(e.url).pathname,new Date,e.header("x-forwarded-for")||e.connection.remoteAddress,JSON.stringify(t).replace(/\\"/g,'"'))}async function Vr(){try{if(r().preListenScript){const{cmd:e,args:t}=r().preListenScript,n=x().spawnSync(e,t,{encoding:"utf-8"});if(n.stderr.trim())throw n.stderr.trim();console.log(n.stdout)}r().appEnable&&r().appEnable.forEach((e=>Br.enable(e)));const e=r().port,t=`STANDBY AT PORT ${e}`;if(r().ssl){const n={key:m().readFileSync(r().ssl.key),cert:m().readFileSync(r().ssl.cert)},s=await d().createServer(n,Br);return s.listen(e,"0.0.0.0",(()=>{console.log(`HTTPS ${t}`)})),s}{const n=await u().createServer(Br);return n.listen(e,"0.0.0.0",(()=>{process.send&&process.send("ready"),console.log(t)})),n}}catch(e){throw e}}function Zr(e){const t=Lr[e],n={species:t.species,name:e,hasSNP:!!t.snp,hasIdeogram:t.genedb.hasIdeogram,fimo_motif:!!t.fimo_motif,blat:!!t.blat,geneset:t.geneset,defaultcoord:t.defaultcoord,isdefault:t.isdefault,majorchr:t.majorchr,majorchrorder:t.majorchrorder,minorchr:t.minorchr,tracks:t.tracks,hicenzymefragment:t.hicenzymefragment,datasets:{}};if(t.termdbs){n.termdbs={};for(const e in t.termdbs)n.termdbs[e]={label:t.termdbs[e].label}}for(const e in t.datasets){const s=t.datasets[e];s.isMds3?n.datasets[s.label]={isMds3:!0,noHandleOnClient:s.noHandleOnClient,label:s.label}:s.isMds?n.datasets[s.label]={isMds:!0,mdsIsUninitiated:!0,noHandleOnClient:s.noHandleOnClient,label:s.label}:n.datasets[s.label]={isofficial:!0,legacyDsIsUninitiated:!0,noHandleOnClient:s.noHandleOnClient,label:s.label}}if(t.hicdomain){n.hicdomain={groups:{}};for(const e in t.hicdomain.groups){const s=t.hicdomain.groups[e];n.hicdomain.groups[e]={name:s.name,reference:s.reference,sets:{}};for(const t in s.sets)n.hicdomain.groups[e].sets[t]={name:s.sets[t].name,longname:s.sets[t].longname}}}return n}function Kr(e){const t={noHandleOnClient:e.noHandleOnClient,sampleselectable:e.sampleselectable,label:e.label,dsinfo:e.dsinfo,stratify:e.stratify,cohort:e.cohort,vcfinfofilter:e.vcfinfofilter,info2table:e.info2table,info2singletable:e.info2singletable,url4variant:e.url4variant,itemlabelname:e.itemlabelname};if(e.snvindel_attributes){t.snvindel_attributes=[];for(const n of e.snvindel_attributes){const e={};for(const t in n)if("lst"==t){e.lst=[];for(const t of n.lst){const n={};for(const e in t)n[e]=t[e];e.lst.push(n)}}else e[t]=n[t];t.snvindel_attributes.push(e)}}e.snvindel_legend&&(t.snvindel_legend=e.snvindel_legend);const n={};let s=!1;for(const t of e.queries)t.vcf&&(s=!0,n[t.vcf.vcfid]=t.vcf);return s&&(t.id2vcf=n),t}function Xr(e){const t={isMds:!0,noHandleOnClient:e.noHandleOnClient,label:e.label,version:e.version,annotationsampleset2matrix:e.annotationsampleset2matrix,mutationAttribute:e.mutationAttribute,locusAttribute:e.locusAttribute,alleleAttribute:e.alleleAttribute,hide_genotypedownload:e.hide_genotypedownload,hide_phewas:e.hide_phewas,sample2bam:e.sample2bam};if(e.queries&&(t.queries={}),e.track&&(t.track=function(e){const t=e.track,n={name:t.name,info_fields:t.info_fields,sample_termfilter:t.sample_termfilter};return t.vcf&&(n.vcf={numerical_axis:t.vcf.numerical_axis,format:t.vcf.format,info:t.vcf.info,check_pecanpie:t.vcf.check_pecanpie},t.vcf.plot_mafcov&&(n.vcf.plot_mafcov={},e.cohort&&e.cohort.termdb&&(n.vcf.plot_mafcov.overlay_term=t.vcf.plot_mafcov.overlay_term||{})),t.vcf.termdb_bygenotype&&(n.vcf.termdb_bygenotype=!0),t.populations&&(n.populations=t.populations)),t.ld&&(n.ld={tracks:t.ld.tracks.map((e=>({name:e.name,shown:e.shown}))),overlay:t.ld.overlay}),n}(e)),e.singlesamplemutationjson&&(t.singlesamplemutationjson=1),e.gene2mutcount&&(t.gene2mutcount=!0,t.mutCountType=e.gene2mutcount.mutationTypes),e.assayAvailability&&(t.assayAvailability=1),e.cohort&&e.cohort.sampleAttribute){const n={};for(const t in e.cohort.sampleAttribute.attributes){const s=e.cohort.sampleAttribute.attributes[t];s.clientnoshow||(n[t]=s)}t.sampleAttribute={attributes:n}}if(e.cohort){if(e.cohort.termdb&&(t.termdb={selectCohort:e.cohort.termdb.selectCohort}),e.cohort.attributes&&e.cohort.attributes.defaulthidden&&(t.cohortHiddenAttr=e.cohort.attributes.defaulthidden),e.cohort.survivalplot){t.survivalplot={samplegroupattrlst:e.cohort.survivalplot.samplegroupattrlst,plots:[]};for(const n in e.cohort.survivalplot.plots){const s=e.cohort.survivalplot.plots[n];t.survivalplot.plots.push({key:n,name:s.name,timelabel:s.timelabel})}}if(e.cohort.mutation_signature){const n={};for(const t in e.cohort.mutation_signature.sets){const s=e.cohort.mutation_signature.sets[t];n[t]={name:s.name,signatures:s.signatures}}t.mutation_signature={sets:n}}}for(const n in e.queries){const s=e.queries[n],r={name:s.name,hideforthemoment:s.hideforthemoment};if(s.istrack){if(r.istrack=!0,r.type=s.type,r.isfull=s.isfull,null!=s.nochr&&(r.nochr=s.nochr),s.infoFilter&&(r.infoFilter=s.infoFilter),s.readcountCutoff&&(r.readcountCutoff=s.readcountCutoff),s.valueLabel&&(r.valueLabel=s.valueLabel),s.valueCutoff&&(r.valueCutoff=s.valueCutoff),s.bplengthUpperLimit&&(r.bplengthUpperLimit=s.bplengthUpperLimit),s.segmeanValueCutoff&&(r.segmeanValueCutoff=s.segmeanValueCutoff),s.lohLengthUpperLimit&&(r.lohLengthUpperLimit=s.lohLengthUpperLimit),s.type==F.tkt.mdssvcnv){if(s.groupsamplebyattr&&(r.groupsamplebyattr=s.groupsamplebyattr),r.multihidelabel_fusion=s.multihidelabel_fusion,r.multihidelabel_sv=s.multihidelabel_sv,r.multihidelabel_vcf=s.multihidelabel_vcf,r.showfullmode=s.showfullmode,r.legend_vorigin=s.legend_vorigin,r.no_loh=s.no_loh,s.expressionrank_querykey){const t=e.queries[s.expressionrank_querykey];if(r.checkexpressionrank={querykey:s.expressionrank_querykey,datatype:t.datatype},t.boxplotbysamplegroup&&t.boxplotbysamplegroup.additionals){const e=[];t.boxplotbysamplegroup.attributes&&e.push(t.boxplotbysamplegroup.attributes.map((e=>e.label)).join(", "));for(const n of t.boxplotbysamplegroup.additionals)e.push(n.label);r.checkexpressionrank.boxplotgroupers=e}}if(s.vcf_querykey){r.checkvcf={querykey:s.vcf_querykey,info:e.queries[s.vcf_querykey].info,format:{}};for(const t of e.queries[s.vcf_querykey].tracks)if(t.format)for(const e in t.format)r.checkvcf.format[e]=t.format[e]}}}else{if(!s.isgenenumeric)continue;r.isgenenumeric=!0,r.datatype=s.datatype,r.no_ase=s.no_ase}t.queries[n]=r}return t}async function Yr(e,t){if(!t)throw"invalid genome";if(!t.snp)throw"snp is not configured for this genome";const n=[];if(e.byCoord){if(t.genomicNameRegexp.test(e.chr))throw"invalid chr name";if(!Array.isArray(e.ranges))throw"ranges not an array";for(const s of e.ranges){if(!Number.isInteger(s.start)||!Number.isInteger(s.stop)||s.start<0||s.stop<s.start)throw"invalid start/stop";if(s.stop-s.start>=100)throw"range too big";const r=await R.z5(t.snp.bigbedfile,e.chr,s.start,s.stop);for(const t of r){const s=Qr(t);if(e.alleleLst){let t=!1;for(const n of e.alleleLst)if(n&&!s.alleles.includes(n)){t=!0;break}if(t)continue}n.push(s)}}}else{if(!e.byName)throw"unknown query method";if(!Array.isArray(e.lst))throw".lst[] missing";for(const s of e.lst){if(t.genomicNameRegexp.test(s))continue;const e=await R.mr(t.snp.bigbedfile,s);for(const t of e){const e=Qr(t);n.push(e)}}}return n}function Qr(e){const t=e.split("\t"),n=t[4],s=t[6].split(",").filter(Boolean),r=n+"/"+s.join("/");return{chrom:t[0],chromStart:Number(t[1]),chromEnd:Number(t[2]),name:t[3],observed:r,alleles:[n,...s]}}function eo(e,t,n){if(n.query.isoform&&Lr[n.query.genome].genomicNameRegexp.test(n.query.isoform))return;const[s,r]=t.makequery(n.query);if(!s)return;const o=e.newconn.prepare(s).all(r);let i;i=t.tidy?o.map((e=>t.tidy(e))):o;const a={};if(t.isgeneexpression){a.lst=i,a.isgeneexpression=!0,a.config=t.config;for(const t of e.queries)if(t.dsblocktracklst)for(const e of t.dsblocktracklst)e.type==F.tkt.junction&&(a.config.dsjunctiontk=e)}else a.lst=i;return a}function to(e,t){const n=[g().join(r().tpmasterdir,e.vcffile),(e.vcf.nochr?t.query.range.chr.replace("chr",""):t.query.range.chr)+":"+t.query.range.start+"-"+t.query.range.stop];return new Promise(((t,s)=>{const r=(0,q.spawn)(Pr,n),o=[],i=[];r.stdout.on("data",(e=>o.push(e))),r.stderr.on("data",(e=>i.push(e))),r.on("close",(n=>{""!=i.join("").trim()&&s("error querying vcf file");const r=o.join("").trim();t({lines:""==r?[]:r.split("\n"),vcfid:e.vcf.vcfid})}))}))}function no(e){if(!e.genome)return["no genome"];const t=Lr[e.genome];if(!t)return["invalid genome"];if(!t.datasets)return["genome is not equipped with datasets"];if(!e.dslabel)return["dslabel missing"];const n=t.datasets[e.dslabel];if(!n)return["invalid dslabel"];if(!n.queries)return["dataset is not equipped with queries"];if(!e.querykey)return["querykey missing"];const s=n.queries[e.querykey];return s?[null,t,n,s]:["invalid querykey"]}async function so(e,t,n,s,o,i){const a=await async function(e,t,n,s){const o=e.checkvcf.tracks[0],i={file:o.file,url:o.url,indexURL:o.indexURL,dir:o.dir,nochr:o.nochr,samples:o.samples,info:e.checkvcf.info,format:o.format},a=await go(i.file?g().join(r().tpmasterdir,i.file):i.url,(i.nochr?t.replace("chr",""):t)+":"+n+"-"+s,i.dir),l=[];for(const e of a||[]){const[t,n,s]=$.S(e,i);for(const e of n)F.basecolor[e.ref]&&F.basecolor[e.alt]&&e.sampledata&&l.push(e)}return l}(o,t,n,s),l=[];for(const e in o.checkrnabam.samples){const n=o.checkrnabam.samples[e];n.hetsnps=[];for(const t of a){const s=mo(t,e,o.checkrnabam);s&&s.dnacount.ishet&&n.hetsnps.push(s)}if(n.url?n.dir=await R.d1(n.url,n.indexURL||n.url+".bai"):n.file&&(n.file=g().join(r().tpmasterdir,n.file)),n.hetsnps.length>0){await io(n,n.hetsnps,t,o.checkrnabam);for(const t of n.hetsnps)t.rnacount.nocoverage||t.rnacount.ref+t.rnacount.alt<o.checkrnabam.rna_mintotalreads||l.push(e+"."+t.pos+"."+t.ref+"."+t.alt+"\t\t\t\t\t\t\t\t"+t.rnacount.ref+"\t"+t.rnacount.alt)}}l.length>0&&await async function(e,t){const n=await function(e){const t=g().join(r().cachedir,Math.random().toString());return new Promise(((n,s)=>{m().writeFile(t,e.join("\n")+"\n",(e=>{e&&s("cannot write"),n(t)}))}))}(e),s=await fo(n);await function(e,t){return new Promise(((n,s)=>{m().readFile(e,"utf8",((e,r)=>{if(e&&s("cannot read binom pvalue"),r){for(const e of r.trim().split("\n")){const n=e.split("\t"),s=n[0].split("."),r=t[s[0]];if(!r)continue;const o=r.hetsnps.find((e=>e.pos+"."+e.ref+"."+e.alt==s[1]+"."+s[2]+"."+s[3]));o&&(o.rnacount.pvalue=Number.parseFloat(n[10]))}n()}else n()}))}))}(s,t),m().unlink(n,(()=>{})),m().unlink(s,(()=>{}))}(l,o.checkrnabam.samples),i.checkrnabam=[];for(const n in o.checkrnabam.samples){const s=o.checkrnabam.samples[n],r=[];for(const[n,i]of e){const e={gene:n,chr:t,start:i.start,stop:i.stop},a=s.hetsnps.filter((e=>e.pos>=i.start&&e.pos<=i.stop)),l=a.filter((e=>!e.rnacount.nocoverage));if(l.length>0){const t=l.reduce(((e,t)=>e+Math.abs(t.rnacount.f-.5)),0);let n=null,s=0;for(const e of l)null!=e.rnacount.pvalue&&(null==n?n=e.rnacount.pvalue:n*=e.rnacount.pvalue,e.rnacount.pvalue<=o.checkrnabam.binompvaluecutoff&&s++);null!=n&&(e.ase={markers:a.filter((e=>e.dnacount.ishet)).length,ase_markers:s,mean_delta:t/l.length,geometricmean:Math.pow(n,1/l.length)})}let c;c=s.pairedend?await oo(s,t,i):await ro(s,t,i),e.fpkm=1e9*c/(s.totalreads*i.exonlength),e.snps=a,r.push(e)}r.length&&i.checkrnabam.push({sample:n,genes:r})}}async function ro(e,t,n){const s=["view","-c","-M",e.url||e.file];for(const r of n.exonunion)s.push((e.nochr?t.replace("chr",""):t)+":"+(r[0]+1)+"-"+(r[1]+1));let r;return await R.UE({isbam:!0,args:s,dir:e.dir,callback:e=>r=e}),Number.parseInt(r)}function oo(e,t,n){return new Promise(((s,r)=>{const o=["view","-M",e.url||e.file];for(const s of n.exonunion)o.push((e.nochr?t.replace("chr",""):t)+":"+(s[0]+1)+"-"+(s[1]+1));const i=(0,q.spawn)(Gr,o,{cwd:e.dir}),a=(0,q.spawn)("cut",["-f1"],{cwd:e.dir}),l=(0,q.spawn)("sort",["-u"],{cwd:e.dir}),c=(0,q.spawn)("wc",["-l"],{cwd:e.dir});i.stdout.pipe(a.stdin),a.stdout.pipe(l.stdin),l.stdout.pipe(c.stdin);const u=[],f=[];c.stdout.on("data",(e=>u.push(e))),c.stderr.on("data",(e=>f.push(e))),c.on("close",(()=>{s(Number.parseInt(u.join("")))}))}))}function io(e,t,n,s){const r=[];for(const s of t)s.rnacount={nocoverage:1},r.push((e.nochr?n.replace("chr",""):n)+":"+(s.pos+1)+"-"+(s.pos+1));return new Promise(((n,o)=>{const i=(0,q.spawn)(Ur,["mpileup","--no-reference","-a","INFO/AD","-d",999999,"-r",r.join(","),"-q",s.rnapileup_q,"-Q",s.rnapileup_Q,e.url||e.file],{cwd:e.dir});O().createInterface({input:i.stdout}).on("line",(e=>{if("#"==e[0])return;const n=po(e);if(!n)return;const s=t.find((e=>e.pos==n.pos));if(s){const e=n.allele2count[s.ref]||0,t=n.allele2count[s.alt]||0;e+t>0&&(s.rnacount={ref:e,alt:t,f:t/(e+t)})}})),i.on("close",(()=>{n()}))}))}function ao(e,t,n,s,r,o){t.hideLOHwithCNVoverlap&&lo(r);const i=[];if(o){const e=new Map;for(const[t,n]of r){const s=o.sample2group.get(t);e.has(s)||e.set(s,[]),e.get(s).push({samplename:t,items:n})}if(s)for(const t of s)if(t.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+t.dt);else for(const n of t.sampledata){const t=o.sample2group.get(n.sampleobj.name);e.has(t)||e.set(t,[]),e.get(t).find((e=>e.samplename==n.sampleobj.name))||e.get(t).push({samplename:n.sampleobj.name,items:[]})}for(const[t,n]of e)i.push({name:t,samples:n})}else if(e.cohort&&e.cohort.annotation&&t.groupsamplebyattr){const n=new Map,o=[];for(const[s,i]of r)co(s,i,n,o,e,t);if(s)for(const r of s)if(r.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf data: "+r.dt);else for(const s of r.sampledata)co(s.sampleobj.name,[],n,o,e,t);for(const e of n.values())if(i.push(e),t.groupsamplebyattr.key2group){const n=t.groupsamplebyattr.key2group.get(e.name);n&&(e.sampletotalnum=n.samples.length)}o.length&&i.push({name:"Unannotated",samples:o});for(const t of i)for(const n of t.samples)e.cohort.annotation[n.samplename]&&(n.sampletype=e.cohort.annotation[n.samplename].sample_type)}else{const e=[];for(const[t,n]of r)e.push({samplename:t,items:n});if(s)for(const t of s)if(t.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+t.dt);else for(const n of t.sampledata){let t=!0;for(const s of e)if(s.samplename==n.sampleobj.name){t=!1;break}t&&e.push({samplename:n.sampleobj.name,items:[]})}e.length&&i.push({samples:e})}return i}function lo(e){for(const[t,n]of e){const s=new Map,r=new Map,o=[];for(const e of n)e.dt!=F.dtloh?(e.dt==F.dtcnv&&(r.has(e.chr)||r.set(e.chr,[]),r.get(e.chr).push(e)),o.push(e)):(s.has(e.chr)||s.set(e.chr,[]),s.get(e.chr).push(e));if(0!=s.size){for(const[e,t]of s){const n=r.get(e);if(n)for(const e of t){let t=!0;for(const s of n)if(Math.max(e.start,s.start)<Math.min(e.stop,s.stop)){t=!1;break}t&&o.push(e)}else for(const e of t)o.push(e)}e.set(t,o)}}}function co(e,t,n,s,r,o){const i=r.cohort.annotation[e];if(!i)return void s.push({samplename:e,items:t});const a=i[o.groupsamplebyattr.attrlst[0].k];if(null==a)return void s.push({samplename:e,items:t});const l=[];for(let e=1;e<o.groupsamplebyattr.attrlst.length;e++){const t=i[o.groupsamplebyattr.attrlst[e].k];if(null==t)break;l.push(t)}l.unshift(a);const c=l.join(o.groupsamplebyattr.attrnamespacer);if(!n.has(c)){const e=[];for(const t of o.groupsamplebyattr.attrlst){const n=i[t.k];if(null==n)break;const s={k:t.k,kvalue:n};t.full&&(s.full=t.full,s.fullvalue=i[t.full]),e.push(s)}const t=[];for(const e of o.groupsamplebyattr.attrlst){const n=i[e.k];if(null==n)break;const s=(e.full?i[e.full]:null)||n;t.push(s)}n.set(c,{name:c,samples:[],attributes:e})}let u=!0;for(const s of n.get(c).samples)if(s.samplename==e){for(const e of t)s.items.push(e);u=!1;break}u&&n.get(c).samples.push({samplename:e,items:t})}function uo(e){return Number.isFinite(e.dna_mintotalreads)?Number.isFinite(e.rna_mintotalreads)?Number.isFinite(e.hetsnp_minbaf)?Number.isFinite(e.hetsnp_maxbaf)?Number.isFinite(e.rnapileup_q)?Number.isFinite(e.rnapileup_Q)?void 0:"invalid value for rnapileup_Q":"invalid value for rnapileup_q":"invalid value for hetsnp_maxbaf":"invalid value for hetsnp_minbaf":"invalid value for rna_mintotalreads":"invalid value for dna_mintotalreads"}function fo(e){const t=e+".pvalue";return new Promise(((n,s)=>{const o=(0,q.spawn)("Rscript",[g().join(r().binpath,"utils/binom.R"),e,t]);o.on("close",(()=>{n(t)})),o.on("error",(e=>{s(`cannot do binom test: ${e}`)})),o.stderr.on("data",(e=>{s(`cannot do binom test: ${e}`)}))}))}function po(e){const t=e.split("\t");if(t.length<8)return;const n={pos:Number.parseInt(t[1])-1},s=[t[3],...t[4].split(",")],r={};for(const e of t[7].split(";")){const t=e.split("=");r[t[0]]=t[1]}if(r.DP&&(n.DP=Number.parseInt(r.DP)),r.AD){n.allele2count={};const e=r.AD.split(",");for(const[t,r]of s.entries())n.allele2count[r]=Number.parseInt(e[t])}return n}function mo(e,t,n){const s=e.sampledata.find((e=>e.sampleobj.name==t));if(s){if(s.AD){const t=s.AD[e.ref]||0,r=s.AD[e.alt]||0,o={chr:e.chr,pos:e.pos,ref:e.ref,alt:e.alt,dnacount:{ref:t,alt:r}};return o.dnacount.f=r+t==0?0:r/(r+t),t+r>=n.dna_mintotalreads&&o.dnacount.f>=n.hetsnp_minbaf&&o.dnacount.f<=n.hetsnp_maxbaf&&(o.dnacount.ishet=!0),o}return null}}async function ho(e,t,n,s,o){const i=await go(g().join(r().tpmasterdir,t.file),n+":"+s+"-"+o),a=new Map;if(i)for(const e of i){const t=e.split("\t"),n=JSON.parse(t[3]),s=Number.parseInt(t[1]),r=Number.parseInt(t[2]);if(a.has(n.name)){const e=a.get(n.name);e.start=Math.min(e.start,s),e.stop=Math.max(e.stop,r)}else a.set(n.name,{gene:n.name,start:s,stop:r,exonunion:[]});const o=a.get(n.name);if(n.exon)for(const e of n.exon){const t=o.exonunion.find((t=>Math.max(t[0],e[0])<Math.min(t[1],e[1])));t?(t[0]=Math.min(e[0],t[0]),t[1]=Math.max(e[1],t[1])):o.exonunion.push([e[0],e[1]])}}for(const[e,t]of a)t.exonlength=t.exonunion.reduce(((e,t)=>e+t[1]-t[0]),0);return a}async function go(e,t,n){return new Promise(((s,r)=>{const o=(0,q.spawn)(Pr,[e,t],{cwd:n}),i=[],a=[];o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("close",(()=>{const e=a.join("");e&&r(e);const t=i.join("").trim();t||s(),s(t.split("\n"))}))}))}function yo(e,t){return new Promise(((n,s)=>{const r=(0,q.spawn)(Pr,["-H",e],{cwd:t}),o=[],i=[];r.stdout.on("data",(e=>o.push(e))),r.stderr.on("data",(e=>i.push(e))),r.on("close",(()=>{const e=i.join("");e&&s(e);const t=o.join("").trim();t||s("cannot list vcf meta lines"),n(t.split("\n"))}))}))}function bo(e,t){const n=t.findIndex((t=>t.value>=e));return-1==n||n==t.length-1?100:0==n?0:Math.ceil(100*n/t.length)}function vo(e,t,n){if(!e.key)return[".key missing"];if(!t.cohort)return["ds.cohort missing"];if(!t.cohort.annotation)return["ds.cohort.annotation missing"];return[null,Promise.resolve().then((()=>{const s=[];for(const r in t.cohort.annotation){if(n&&!n.has(r))continue;const o=t.cohort.annotation[r][e.key];null!=o&&s.push({sample:r,value:o})}return{id:e.id,items:s}}))]}function wo(e,t,n,s){if(!e.genename)return["genename missing"];const o=e.genename.toLowerCase();if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["gene feature too long (> 10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return R.d1(n.url,n.indexURL)})).then((t=>new Promise(((i,a)=>{const l=[],c=(0,q.spawn)(Pr,[n.file?g().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});O().createInterface({input:c.stdout}).on("line",(e=>{const t=e.split("\t"),n=JSON.parse(t[3]);n.gene&&n.gene.toLowerCase()==o&&n.sample&&(s&&!s.has(n.sample)||l.push(n))}));const u=[];c.stderr.on("data",(e=>u.push(e))),c.on("close",(t=>{const n=u.join("");!n||$r(n)?i({id:e.id,items:l}):a(n)}))}))))]}function _o(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];if(null!=e.valuecutoff&&!Number.isFinite(e.valuecutoff))return["invalid value for valuecutoff"];if(null!=e.focalsizelimit&&!Number.isInteger(e.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return R.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(Pr,[n.file?g().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});O().createInterface({input:l.stdout}).on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);r.dt==F.dtcnv&&(e.valuecutoff&&Math.abs(r.value)<e.valuecutoff||(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.focalsizelimit&&r.stop-r.start>=e.focalsizelimit||r.sample&&(s&&!s.has(r.sample)||a.push(r))))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||$r(n)?o({id:e.id,items:a}):i(n)}))}))))]}function ko(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];if(null!=e.valuecutoff&&!Number.isFinite(e.valuecutoff))return["invalid value for valuecutoff"];if(null!=e.focalsizelimit&&!Number.isInteger(e.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return R.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(Pr,[n.file?g().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});O().createInterface({input:l.stdout}).on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);r.dt==F.dtloh&&(e.valuecutoff&&r.segmean<e.valuecutoff||(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.focalsizelimit&&r.stop-r.start>=e.focalsizelimit||r.sample&&(s&&!s.has(r.sample)||a.push(r))))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||$r(n)?o({id:e.id,items:a}):i(n)}))}))))]}function qo(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return R.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(Pr,[n.file?g().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});O().createInterface({input:l.stdout}).on("line",(e=>{const t=e.split("\t"),n=JSON.parse(t[3]);n.dt==F.dtitd&&(n.chr=t[0],n.start=Number.parseInt(t[1]),n.stop=Number.parseInt(t[2]),n.sample&&(s&&!s.has(n.sample)||a.push(n)))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||$r(n)?o({id:e.id,items:a}):i(n)}))}))))]}function xo(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return R.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(Pr,[n.file?g().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});O().createInterface({input:l.stdout}).on("line",(e=>{const t=e.split("\t"),n=JSON.parse(t[3]);n.dt!=F.dtsv&&n.dt!=F.dtfusionrna||n.sample&&(s&&!s.has(n.sample)||(n._chr=t[0],n._pos=Number.parseInt(t[1]),n.chrA?(n.chrB=n._chr,n.posB=n._pos):(n.chrA=n._chr,n.posA=n._pos),a.push(n)))}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const n=c.join("");!n||$r(n)?o({id:e.id,items:a}):i(n)}))}))))]}function No(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return R.d1(n.url,n.indexURL)})).then((t=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(Pr,[n.file?g().join(r().tpmasterdir,n.file):n.url,e.chr+":"+e.start+"-"+e.stop],{cwd:t});O().createInterface({input:l.stdout}).on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);if(r.sample&&(!s||s.has(r.sample))){if(r.dt==F.dtsv||r.dt==F.dtfusionrna){if(r.dt==F.dtsv&&e.sv&&e.sv.hidden)return;if(r.dt==F.dtfusionrna&&e.fusion&&e.fusion.hidden)return;r._chr=n[0],r._pos=Number.parseInt(n[1]),r.chrA?(r.chrB=r._chr,r.posB=r._pos):(r.chrA=r._chr,r.posA=r._pos)}else if(r.dt==F.dtcnv){if(e.cnv&&e.cnv.hidden)return;if(e.cnv&&e.cnv.valuecutoff&&Math.abs(r.value)<e.cnv.valuecutoff)return;if(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.cnv&&e.cnv.focalsizelimit&&r.stop-r.start>=e.cnv.focalsizelimit)return}else if(r.dt==F.dtloh){if(e.loh&&e.loh.hidden)return;if(e.loh&&e.loh.valuecutoff&&r.segmean<e.loh.valuecutoff)return;if(r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2]),e.loh&&e.loh.focalsizelimit&&r.stop-r.start>=e.loh.focalsizelimit)return}else{if(r.dt!=F.dtitd)return void console.error("unknown datatype",r.dt);if(e.itd&&e.itd.hidden)return;r.chr=n[0],r.start=Number.parseInt(n[1]),r.stop=Number.parseInt(n[2])}a.push(r)}}));const c=[];l.stderr.on("data",(e=>c.push(e))),l.on("close",(t=>{const s=c.join("");if(s&&!$r(s))return void i(s);const r=new Map;for(const e of a)r.has(e.sample)||r.set(e.sample,[]),r.get(e.sample).push(e);n.hideLOHwithCNVoverlap&&lo(r);const l=[];for(const[e,t]of r)for(const e of t)l.push(e);o({id:e.id,items:l})}))}))))]}function So(e,t,n,s){if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>1e7)return["look range too big (>10Mb)"];const r=[];for(const o of n)if(o.type==F.tkt.mdsvcf){const[n,i]=Ao(e,t,o,s);if(n)return[n];r.push(i)}else{if(o.type!=F.tkt.mdssvcnv)return["unsupported track type: "+o.type];{const[t,n]=No(e,0,o,s);if(t)return[t];r.push(n)}}return[null,Promise.all(r).then((e=>{const t=[];for(const n of e)for(const e of n.items)t.push(e);return{id:e[0].id,items:t}}))]}function Ao(e,t,n,s){if(!n.tracks)return"tracks[] missing from dsquery";if(!e.chr)return["chr missing"];if(!Number.isInteger(e.start)||!Number.isInteger(e.stop))return["invalid start/stop coordinate"];if(e.stop-e.start>3e6)return["look range too big (>3Mb)"];const o=[];for(const t of n.tracks){const i=Promise.resolve().then((()=>{if(!t.file)return R.d1(t.url,t.indexURL)})).then((o=>new Promise(((i,a)=>{const l=[],c=(0,q.spawn)(Pr,[t.file?g().join(r().tpmasterdir,t.file):t.url,(t.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+(e.stop+1)],{cwd:o});O().createInterface({input:c.stdout}).on("line",(r=>{if(n.iscustom)l.push(r);else if(t.type==F.mdsvcftype.vcf){const[o,i,a]=$.S(r,{nochr:t.nochr,samples:t.samples,info:n.info,format:t.format});for(const t of i)if(t.sampledata&&(F.vcfcopymclass(t,{}),!(e.snvindel&&e.snvindel.excludeclasses&&e.snvindel.excludeclasses[t.class]))){if(s){const e=[];for(const n of t.sampledata)s.has(n.sampleobj.name)&&e.push(n);if(0==e.length)continue;t.sampledata=e}for(const e of t.sampledata)delete e.allele2readcount;delete t._m,delete t.vcf_ID,delete t.name,t.dt=F.dtsnvindel,l.push(t)}}else console.error("type not one of mdsvcftype: "+t.type)}));const u=[];c.stderr.on("data",(e=>u.push(e))),c.on("close",(e=>{const t=u.join("");!t||$r(t)?i(l):a(t)}))}))));o.push(i)}return[null,Promise.all(o).then((t=>{const n=[];for(const e of t)for(const t of e)n.push(t);return{id:e.id,items:n}}))]}function Co(e){if(!e.endsWith(".gz"))return["no .gz suffix (file should be compressed by bgzip)"];const t=g().join(r().tpmasterdir,e);return m().existsSync(t)?m().existsSync(t+".tbi")||m().existsSync(t+".csi")?[null,t]:[".tbi/.csi index missing"]:[".gz file not found"]}Br.use(k()()),Br.use(((e,t,n)=>{"POST"==e.method.toUpperCase()&&(e.headers["content-type"]="application/json");try{e.query.encoding;!function(e){const t=e.encoding;for(const[n,s]of Object.entries(e))("json"==t||"null"==s||"true"==s||"false"==s||Rr(s)||s.startsWith('"')&&s.endsWith('"')||s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))&&(e[n]=JSON.parse(s))}(e.query)}catch(e){return void t.send({error:e})}n()})),Br.use(Ir()()),Br.use(C().json({limit:"5mb"})),Br.use(C().text({limit:"5mb"})),Br.use(C().urlencoded({extended:!0})),Br.use(((e,t,n)=>{"POST"==e.method.toUpperCase()&&e.body&&"application/json"!=e.headers["content-type"]?t.send({error:"invalid HTTP request.header['content-type'], must be 'application/json'"}):("application/json"==e.headers["content-type"]&&(e.query||(e.query={}),Object.assign(e.query,e.body)),Wr(e),e.query.__protected__={},e.cookies?.sessionid&&(e.query.__protected__.sessionid=e.cookies.sessionid),Object.freeze(e.query.__protected__),Hr(t),t.header("Access-Control-Allow-Origin",e.get("origin")||e.get("referrer")||e.protocol+"://"+e.get("host").split(":")[0]||"*"),t.header("Access-Control-Allow-Credentials",!0),"GET"!=e.method||e.path.includes(".")&&!e.path.endsWith("proteinpaint.js")||t.header("Cache-control",`immutable,max-age=${r().responseMaxAge||1}`),n())})),Br.catch=Tr,Br.use((function(e,t,n){try{const t=e.query;for(const e in t)e in Mr&&(t[e]=Mr[e](t[e]));n()}catch(n){Tr(e,t,n.message||n)}})),Br.use(((e,t,n,s)=>{Wr(t),e&&(e&&"entity.parse.failed"==e.type?n.send({error:"invalid request body, must be a valid JSON-encoded object"}):n.send({error:e}))})),r().jwt&&(console.log("JWT is activated"),Br.use(((e,t,n)=>{let s={};e.body&&"POST"==e.method&&(s=e.body);const o=s.jwt?s.jwt:e.headers&&e.headers.authorization&&e.headers.authorization.startsWith("Bearer ")?e.headers.authorization.split(" ")[1]:null;if(!o)return t.send({error:"json web token missing"});E().verify(o,r().jwt.secret,((e,s)=>e?t.send({error:"Invalid token"}):s[r().jwt.permissioncheck]?void n():t.send({error:"Not authorized"})))}))),function(){if(!r().routeSetters)return;for(const e of r().routeSetters)if(e.endsWith(".js")){require(e)(Br,Jr)}}(),pr.i.maySetAuthRoutes(Br,Jr,r()),Br.get(Jr+"/cardsjson",(async function(e,t){try{if(e.query.datafile&&e.query.tabixCoord)return new Promise(((n,s)=>{const o=(0,q.spawn)(Pr,[g().join(r().tpmasterdir,e.query.datafile),e.query.tabixCoord]),i=[],a=[];o.stdout.on("data",(e=>i.push(e))),o.stderr.on("data",(e=>a.push(e))),o.on("close",(e=>{""!=a.join("").trim()&&s("error querying bedj file");const r=i.join("").trim();n(t.send({file:r.split("\n")}))}))})).catch((e=>{e.stack&&console.error(e.stack)}));throw"invalid cards request"}catch(e){t.send({error:e.message||e})}})),Br.post(Jr+"/mdsjsonform",(async function(e,t){if(!Dr.mdsjsonform)return t.send({error:"This feature is not enabled on this server."});if(e.query.deposit){const n=Math.random().toString(),s=await function(){const e=g().join(r().cachedir,"mdsjsonform");return new Promise(((t,n)=>{m().stat(e,((s,r)=>{if(s){if("ENOENT"==s.code)return void m().mkdir(e,(s=>{s&&n("error creating dir"),t(e)}));n("error checking directory")}else r.isDirectory()?t(e):n('"mdsjsonform" exists but not directory')}))}))}(),o=g().join(s,n);return await R.Sf(o,JSON.stringify(e.query.deposit)),void t.send({id:n})}if(e.query.draw){const n=g().join(r().cachedir,"mdsjsonform",e.query.draw),s=await R.b5(n);try{const e=JSON.parse(s);t.send({json:e})}catch(e){t.send({error:"Invalid JSON"})}return}t.send({})})),Br.get(Jr+"/genomes",(async function(e,t){try{await m().promises.stat(r().tpmasterdir)}catch(e){let n="Error with TP directory ("+e.code+")";const s=r().maintenance||{};if("start"in s&&"stop"in s&&s.tpMessage){const e=+new Date(s.start),t=+new Date(s.stop),r=+new Date;e<=r&&r<=t&&(n=s.tpMessage)}return void t.send({error:n})}const n={};if(e.query&&e.query.genome)n[e.query.genome]=Zr(e.query.genome);else for(const e in Lr)n[e]=Zr(e);let s=!1;for(const e in Lr)Lr[e].blat&&(s=!0);t.send({genomes:n,debugmode:r().debugmode,headermessage:r().headermessage,base_zindex:r().base_zindex,codedate:Er.A.codedate,launchdate:Er.A.launchdate,hasblat:s,features:Dr,dsAuth:pr.i.getDsAuth(e),commonOverrides:r().commonOverrides,targetPortal:r().targetPortal,cardsPath:r().cards?.path})})),Br.get(Jr+"/getDataset",(function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"unknown genome";if(!n.datasets)throw"genomeobj.datasets{} missing";let s;for(const t in n.datasets)if(t.toLowerCase()==e.query.dsname.toLowerCase()){s=n.datasets[t];break}if(!s)throw"invalid dsname";return s.isMds3?t.send({ds:Ms(s)}):s.isMds?t.send({ds:Xr(s)}):t.send({ds:Kr(s)})}catch(e){t.send({error:e.message||e})}})),Br.all(Jr+"/ntseq",(async function(e,t){try{if(!e.query.coord)throw"coord missing";const n=Lr[e.query.genome];if(!n)throw"invalid genome";if(!n.genomefile)throw"no sequence file available";const s=await R.Kf(n,e.query.coord);t.send({seq:s.split("\n").slice(1).join("")})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.post(Jr+"/pdomain",(function(e,t){try{const n=e.query.genome;if(!n)throw"no genome";const s=Lr[n];if(!s)throw"invalid genome "+n;if(!s.proteindomain)return t.send({lst:[]});if(!Array.isArray(e.query.isoforms))throw"isoforms[] missing";const r=[];for(const t of e.query.isoforms){if(s.genomicNameRegexp.test(t))continue;const e=s.proteindomain.getbyisoform.all(t);r.push({name:t,pdomains:e.map((e=>{const n=JSON.parse(e.data);return n.refseq=t,n}))})}t.send({lst:r})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.post(Jr+"/tkbedj",function(e){return async(t,n)=>{try{n.send(await async function(e,t){const[n,s,r]=R.ZX(e);if(n)throw n;let o,i,a,l,c;if(e.query.fileIsBigbed=await R.aS(s),e.query.getdata)e.query.getBED;else{if(o=Number(e.query.stackheight),i=Number(e.query.stackspace),a=Number(e.query.regionspace),l=Number(e.query.width),Number.isNaN(o))throw"stackheight is not integer";if(c=Math.max(10,o-2),Number.isNaN(i))throw"stackspace is not integer";if(Number.isNaN(a))throw"regionspace is not integer";if(Number.isNaN(l))throw"width is not a number"}if(e.query.usevalue){if(!e.query.usevalue.key)throw".key missing from .usevalue";if(e.query.usevalue.dropBelowCutoff&&(e.query.usevalue.dropBelowCutoff=Number(e.query.usevalue.dropBelowCutoff),Number.isNaN(e.query.usevalue.dropBelowCutoff)))throw".usevalue.dropBelowCutoff is not number"}if(e.query.bplengthUpperLimit&&(e.query.bplengthUpperLimit=Number(e.query.bplengthUpperLimit),Number.isNaN(e.query.bplengthUpperLimit)))throw"bplengthUpperLimit not number";if(!e.query.rglst)throw"no rglst[]";if(!Array.isArray(e.query.rglst))throw"rglst is not an array";if(0==e.query.rglst.length)throw"empty rglst";for(const t of e.query.rglst)t.reverse?t.scale=e=>Math.ceil(t.width*(t.stop-e)/(t.stop-t.start)):t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start));const u=e.query.color||"#3D7A4B",f=e.query.gmregion||null,d=e.query.isoform,p=e.query.onerow,m=e.query.categories||null,h=e.query.__isgene;let g;!e.query.fileIsBigbed&&r&&(g=await R.d1(s,e.query.indexURL));const y=await async function(e,t,n,s,r){let o;if(s){const i=[];if(e.fileIsBigbed){const n=await R.z5(t,s.chr,s.start,s.stop);for(const t of n){const n=t.split("\t"),s=Un(n);s.chr=n[0],s.start=Number(n[1]),s.stop=Number(n[2]),s.rglst=[];for(let t=0;t<e.rglst.length;t++){const n=e.rglst[t];Math.max(s.start,n.start)<Math.min(s.stop,n.stop)&&s.rglst.push({idx:t})}0!=s.rglst.length&&i.push(s)}}else await R.UE({args:[t,s.chr+":"+s.start+"-"+s.stop],dir:n,callback:t=>{const n=t.split("\t");let s={};if(e.getBED)s.rest=n.slice(3);else if(n[3])try{s=JSON.parse(n[3])}catch(e){return void(o=t)}if(!s.isoformonly||s.isoformonly==r){s.chr=n[0],s.start=Number(n[1]),s.stop=Number(n[2]),s.rglst=[];for(let t=0;t<e.rglst.length;t++){const n=e.rglst[t];Math.max(s.start,n.start)<Math.min(s.stop,n.stop)&&s.rglst.push({idx:t})}0!=s.rglst.length&&i.push(s)}}});if(o)throw"Line with invalid JSON: "+o;return[i]}const i=[];for(const[s,r]of e.rglst.entries()){const a=[];if(e.fileIsBigbed){const e=await R.z5(t,r.chr,r.start,r.stop);for(const t of e){const e=t.split("\t"),n=Un(e);n.chr=e[0],n.start=Number(e[1]),n.stop=Number(e[2]),n.rglst=[{idx:s}],a.push(n)}}else await R.UE({args:[t,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:t=>{const n=t.split("\t");let r={};if(e.getBED)r.rest=n.slice(3);else if(n[3])try{r=JSON.parse(n[3])}catch(e){return void(o=t)}r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[{idx:s}],a.push(r)}});i.push(a)}if(o)throw"Line with invalid JSON: "+o;return i}(e.query,s,g,f,d);let b;e.query.filterByName&&(b=new Set(e.query.filterByName.split(/[\s\n]/).map((e=>e.trim()))));const v=[];for(const t of y)for(const n of t){if(e.query.usevalue){const t=n[e.query.usevalue.key];if(!Number.isFinite(t))continue;if(e.query.usevalue.dropBelowCutoff&&t<e.query.usevalue.dropBelowCutoff)continue}if(!(e.query.bplengthUpperLimit&&n.stop-n.start>e.query.bplengthUpperLimit)){if(b)if(n.isoform){if(!b.has(n.isoform))continue}else{if(!n.name)continue;if(!b.has(n.name))continue}v.push(n)}}if(e.query.getdata)return{items:v};if(0==v.length){const t=(0,N.createCanvas)(l*e.query.devicePixelRatio,o*e.query.devicePixelRatio),n=t.getContext("2d");return e.query.devicePixelRatio>1&&n.scale(e.query.devicePixelRatio,e.query.devicePixelRatio),n.font=o+"px Arial",n.fillStyle="#aaa",n.textAlign="center",n.textBaseline="middle",n.fillText("No data in view range",l/2,o/2),{src:t.toDataURL(),height:o}}const w=Math.ceil(o/4)-1;if(p||v.length>=Hn){const t=v.length<200,n=(0,N.createCanvas)(l*e.query.devicePixelRatio,o*e.query.devicePixelRatio),s=n.getContext("2d");e.query.devicePixelRatio>1&&s.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);const r=v.length<=200?[]:null;for(const n of v){const i=m&&n.category&&m[n.category]?m[n.category].color:n.color||u;s.fillStyle=i;for(const i of n.rglst){let l=0;for(let t=0;t<i.idx;t++)l+=e.query.rglst[t].width+a;const c=e.query.rglst[i.idx],u=[];n.utr5&&u.push(...n.utr5),n.utr3&&u.push(...n.utr3),!n.exon||n.coding&&0!=n.coding.length||u.push(...n.exon);for(const e of u){const t=Math.max(c.start,e[0]),i=Math.min(c.stop,e[1]),a=l+c.scale(c.reverse?i:t),u=l+c.scale(c.reverse?t:i);s.fillRect(a,w,Math.max(1,u-a),o-2*w),Qn(r,a,u,1,n)}const f=[];n.exon?n.coding&&n.coding.length>0&&f.push(...n.coding):f.push([n.start,n.stop]);for(const e of f){const i=Math.max(c.start,e[0]),a=Math.min(c.stop,e[1]),u=l+c.scale(c.reverse?a:i),f=l+c.scale(c.reverse?i:a);s.fillRect(u,0,Math.max(1,f-u),o),Qn(r,u,f,1,n),n.strand&&t&&(s.strokeStyle="white",es(s,n.strand,u,w,f-u,o-2*w))}}}return{src:n.toDataURL(),height:o,mapisoform:r}}if(e.query.hideItemNames)for(const e of v)delete e.name;let _=null;if(h&&v.length<Wn){_=[];for(const e of v){const t={};for(const n in e)"canvas"!=n&&"rglst"!=n&&(t[n]=e[n]);_.push(t)}}const k=e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0),q=e.query.translatecoding&&k<3*l;let x;if(q){if(!e.query.genome)throw"genome missing for translating genes";if(x=t[e.query.genome],!x)throw"invalid genome"}const S=[],A=(0,N.createCanvas)(10,10);let C=A.getContext("2d");e.query.devicePixelRatio>1&&C.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);C.font="bold "+c+"px Arial";const j=v.length<Jn,T=v.length<Jn?[]:null;let M=!1;f&&(M=f.reverse);for(const t of e.query.rglst)t.reverse&&(M=!0);v.sort(((e,t)=>M?e.stop==t.stop?e.start-t.start:t.stop-e.stop:e.start==t.start?t.stop-e.stop:e.start-t.start));const O=v.some((e=>e.exon)),I=[0];let E=1,$=null;for(const t of v){let n=null,s=null;for(const r of t.rglst){let o=0;for(let t=0;t<r.idx;t++)o+=e.query.rglst[t].width+a;const i=e.query.rglst[r.idx],l=Math.max(t.start,i.start),c=Math.min(t.stop,i.stop);if(l<c){const e=o+i.scale(i.reverse?c:l),t=o+i.scale(i.reverse?l:c);null==n?(n=e,s=t):(n=Math.min(n,e),s=Math.max(s,t))}}if(null==n)continue;t.canvas={start:n,stop:s,stranded:null!=t.strand},t.coding&&q&&(t.willtranslate=!0,S.push(t));let r=n,o=s;if(j){const e=t.name;if(e){t.canvas.namestr=e;const n=C.measureText(e).width;t.canvas.namewidth=n,O?t.canvas.start>=n+zn?(t.canvas.namestart=t.canvas.start-zn,r=t.canvas.namestart-n,t.canvas.textalign="right"):t.canvas.stop+n+zn<=l?(t.canvas.namestart=t.canvas.stop+zn,o=t.canvas.namestart+n,t.canvas.textalign="left"):n>t.canvas.stop-t.canvas.start?t.canvas.start>l-t.canvas.stop?(t.canvas.namestart=t.canvas.start-zn,r=t.canvas.namestart-n,t.canvas.textalign="right"):(t.canvas.namestart=t.canvas.stop+zn,o=t.canvas.namestart+n,t.canvas.textalign="left"):(t.canvas.namehover=!0,t.canvas.textalign="left"):Math.min(l,t.canvas.stop)-Math.max(0,t.canvas.start)>=n+2*Bn?t.canvas.namein=!0:t.canvas.start>=n+zn?(t.canvas.namestart=t.canvas.start-zn,r=t.canvas.namestart-n,t.canvas.textalign="right"):t.canvas.stop+n+zn<=l?(t.canvas.namestart=t.canvas.stop+zn,o=t.canvas.namestart+n,t.canvas.textalign="left"):t.canvas.namein=!0}}t.canvas.stop-t.canvas.start>.3*l&&($=[]);for(let e=1;e<=E;e++)if(null==I[e]||I[e]<r){t.canvas.stack=e,I[e]=o;break}null==t.canvas.stack&&(E++,I[E]=o,t.canvas.stack=E),Qn(T,r,o,t.canvas.stack,t)}A.width=l*e.query.devicePixelRatio;const D=(o+i)*E-i;A.height=D*e.query.devicePixelRatio,C=A.getContext("2d"),e.query.devicePixelRatio>1&&C.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);C.font="bold "+c+"px Arial",C.textBaseline="middle",C.lineWidth=1;for(const t of v){const n=t.canvas;if(!n)continue;const s=m&&t.category&&m[t.category]?m[t.category].color:t.color||u,r=(o+i)*(n.stack-1);C.fillStyle=s,(t.exon||t.rglst.length>1)&&(C.strokeStyle=s,C.beginPath(),C.moveTo(n.start,Math.floor(r+o/2)+.5),C.lineTo(n.stop,Math.floor(r+o/2)+.5),C.stroke());for(const i of t.rglst){let l=0;for(let t=0;t<i.idx;t++)l+=e.query.rglst[t].width+a;const c=e.query.rglst[i.idx],u=[];t.utr3&&u.push(...t.utr3),t.utr5&&u.push(...t.utr5),!t.exon||t.coding&&0!=t.coding.length||u.push(...t.exon);for(const e of u){const n=Math.max(e[0],c.start),i=Math.min(e[1],c.stop);if(n<i){if(t.exon2color)for(const e of t.exon2color)if(n>=e.start&&i<=e.stop){C.fillStyle=e.color;break}const e=l+c.scale(c.reverse?i:n),a=l+c.scale(c.reverse?n:i);C.fillRect(e,r+w,Math.max(1,a-e),o-2*w),t.exon2color&&(C.fillStyle=s)}}const f=[];t.exon?t.coding&&t.coding.length>0&&f.push(...t.coding):f.push([t.start,t.stop]);let d=t.strand;n.stranded&&c.reverse&&(d="+"==t.strand?"-":"+");for(const e of f){const i=Math.max(e[0],c.start),a=Math.min(e[1],c.stop);if(i<a){if(t.exon2color)for(const e of t.exon2color)if(i>=e.start&&a<=e.stop){C.fillStyle=e.color;break}const e=l+c.scale(c.reverse?a:i),u=l+c.scale(c.reverse?i:a);if(C.fillRect(e,r,Math.max(1,u-e),o),t.exon2color&&(C.fillStyle=s),n.stranded&&!t.willtranslate)if(C.strokeStyle="white",n.namein){const t=(u-e-n.namewidth)/2;es(C,d,e,r+w,t,o-2*w),es(C,d,e+t+n.namewidth,r+w,t,o-2*w)}else es(C,d,e,r+w,u-e,o-2*w)}}if(n.stranded&&t.intron){C.strokeStyle=s;for(const e of t.intron){const t=Math.max(e[0],c.start),n=Math.min(e[1],c.stop);if(t<n){const e=l+c.scale(c.reverse?n:t);es(C,d,e,r+w,l+c.scale(c.reverse?t:n)-e,o-2*w)}}}if($&&t.exon){for(let e=0;e<t.exon.length;e++){const s=t.exon[e];if(s[1]<=c.start||s[0]>=c.stop)continue;const r=Math.max(s[0],c.start),o=Math.min(s[1],c.stop);if(r<o){const i=l+c.scale(c.reverse?o:r),a=l+c.scale(c.reverse?r:o);$.push({chr:t.chr,start:Math.min(s[0],s[1]),stop:Math.max(s[0],s[1]),x1:i,x2:a,y:n.stack,name:"Exon "+(e+1)+"/"+t.exon.length})}}for(let e=1;e<t.exon.length;e++){const s=t.exon["+"==t.strand?e-1:e][1],r=t.exon["+"==t.strand?e:e-1][0];if(r<=c.start||s>=c.stop)continue;const o=Math.max(s,c.start),i=Math.min(r,c.stop);if(o<i){const a=l+c.scale(c.reverse?i:o),u=l+c.scale(c.reverse?o:i);if(u<0)continue;$.push({chr:t.chr,start:s,stop:r,x1:a,x2:u,y:n.stack,name:"Intron "+e+"/"+(t.exon.length-1)})}}}}if(null!=n.namestart)C.textAlign=n.textalign,C.fillStyle=s,C.fillText(n.namestr,n.namestart,r+o/2);else if(n.namehover&&!e.query.noNameHover){const e=Math.max(10,n.start+10);C.fillStyle="white",C.fillRect(e,r,n.namewidth+10,o),C.strokeStyle=s,C.strokeRect(e+1.5,r+.5,n.namewidth+10-3,o-2),C.fillStyle=s,C.textAlign="center",C.fillText(n.namestr,e+n.namewidth/2+5,r+o/2)}else n.namein&&(C.textAlign="center",C.fillStyle="white",C.fillText(n.namestr,(Math.max(0,n.start)+Math.min(l,n.stop))/2,r+o/2))}const L={height:D,mapisoform:T,mapexon:$,returngmdata:_};if(0==S.length)return L.src=A.toDataURL(),L;const P=[];C.textAlign="center",C.textBaseline="middle";for(const[t,n]of S.entries()){const t=m&&n.category&&m[n.category]?m[n.category].color:n.color||u,s=n.canvas,r=(o+i)*(s.stack-1);n.genomicseq=(await R.Kf(x,n.chr+":"+(n.start+1)+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase();const l=(0,F.nt2aa)(n);for(const t of n.rglst){const i=e.query.rglst[t.idx];let c=0;for(let n=0;n<t.idx;n++)c+=e.query.rglst[n].width+a;const u=i.width/(i.stop-i.start),f=Math.min(o,3*u),d=f<8?null:f;let p=!1;s.stranded&&"-"==n.strand&&(p=!0);let m=0;d&&(C.font=d+"px Arial");for(const[e,t]of n.coding.entries()){let[s,a]=t;if(p){if(s>=i.stop){m+=a-s,0==e&&n.startCodonFrame&&(m-=3-n.startCodonFrame);continue}if(a<=i.start)break}else{if(a<=i.start){m+=a-s,0==e&&n.startCodonFrame&&(m-=3-n.startCodonFrame);continue}if(s>=i.stop)break}if(0==e&&n.startCodonFrame){p?a-=3-n.startCodonFrame:s+=3-n.startCodonFrame;let e=Math.max(t[0],i.start),l=Math.min(t[1],i.stop);if(p?e=Math.max(a,i.start):l=Math.min(s,i.stop),e<l){C.fillStyle=Yn;const t=c+i.scale(i.reverse?l:e),n=c+i.scale(i.reverse?e:l);C.fillRect(t,r,Math.max(1,n-t),o)}}const f=Math.max(i.start,s),h=Math.min(i.stop,a);m+=p?a-h:f-s;let g=0;for(let e=0;e<h-f;e++){let t;if(m++,g++,m%3==0)t=m/3-1;else{if(e<h-f-1)continue;t=Math.floor(m/3)}let s=l[t],a=Math.ceil(m/3)%2==0?Vn:null;s?"M"==s?a=Kn:"*"==s&&(a=Xn):(s=4,a=Zn);let y,b=u*g;if(p){const t=h-1-e;y=c+i.scale(t)}else{const t=f+e+1-g;y=c+i.scale(t)}i.reverse&&(y-=b),g=0,y>=c&&y<=c+i.width&&(a&&(C.fillStyle=a,C.fillRect(y,r,b,o)),d&&(C.fillStyle="white",C.fillText(s,y+b/2,r+o/2)),P.push({x1:y,x2:y+b,y:n.canvas.stack,name:s+(t+1)+' <span style="font-size:.7em;color:#858585">AA residue</span>'}))}}}if(s.namehover&&!e.query.noNameHover){C.font="bold "+c+"px Arial";const e=Math.max(10,s.start+10);C.fillStyle="white",C.fillRect(e,r,s.namewidth+10,o),C.strokeStyle=t,C.strokeRect(e+1.5,r+.5,s.namewidth+10-3,o-2),C.fillStyle=t,C.fillText(s.namestr,e+s.namewidth/2+5,r+o/2)}}return L.src=A.toDataURL(),L.mapaa=P,L}(t,e))}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Lr)),Br.post(Jr+"/tkbedgraphdot",function(e){return async(t,n)=>{try{const s=t.query,o=e[s.genome];if(!o)throw"unknown genome";let i=null;if(s.file)s.file=g().join(r().tpmasterdir,s.file);else{if(!s.url)throw"file or url missing";i=await R.d1(s.url,s.indexURL)}const a=await R.Jy(s.file||s.url,i,o),l=await Ae(s,i,a);n.send(l)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Lr)),Br.all(Jr+"/tkbam",function(e){return async(t,n)=>{try{if(t.query.gdcFileUUID){if("string"!=typeof t.query.gdcFileUUID)throw"gdcFileUUID not string";!function(e){if(!e.query.gdcFilePosition)throw"gdcFileUUID is present but gdcFilePosition is missing";if("string"!=typeof e.query.gdcFilePosition)throw"gdcFilePosition is not string";if("unmapped"==e.query.gdcFilePosition)return;const t=e.query.gdcFilePosition.split(/[.:-]/);if(3!=t.length)throw"gdcFilePosition not 3 fields";const n=Number(t[1]),s=Number(t[2]);if(!Number.isInteger(n)||!Number.isInteger(s)||n>s)throw"gdcFilePosition invalid start/stop";if(e.query.stream2download)return;if(s-n>Qt)throw`Slice range exceeds ${Ge(Qt)} limit. Please choose a smaller range.`}(t),t.query.__genomes=e;const s=t.get("X-Auth-Token");if(s&&(t.query.token=s),await Qe(t.query.gdcFileUUID,en(e),t.query),t.query.stream2download)return void await async function(e,t){const{host:n,headers:s}=en(e.query.__genomes).getHostHeaders(e.query);s.compression=!1;const o=g().join(n.rest,"/slicing/view/",e.query.gdcFileUUID+"?region="+e.query.gdcFilePosition);try{const e=b().stream(o,{method:"GET",headers:s});let n=0;e.on("data",(s=>{n+=s.length,n>r().features.gdcBam.streamMaxSize&&(e.destroy(),t.end())})),e.pipe(t)}catch(e){if("ERR_STREAM_PREMATURE_CLOSE"==e.code)return;e.stack&&console.log(e.stack),t.send({error:e.message||e})}}(t,n);t.query.file=xn(t)}if(t.query.downloadgdc)return void n.send(await Nn(t));if(t.query.clientdownloadgdcslice)return void await async function(e,t){if(!e.query.gdcFileUUID||!e.query.gdcFilePosition||!e.query.file)throw"clientdownloadgdcslice: unauthorized access";const n=g().join(r().cachedir_bam,e.query.file),s=await m().promises.readFile(n);t.writeHead(200,{"Content-Type":"application/octet-stream","Content-Disposition":"attachment; filename=gdc.bam","Content-Length":s.length}),t.end(Buffer.from(s,"binary"))}(t,n);if(!t.query.genome)throw".genome missing";const s=e[t.query.genome];if(!s)throw"invalid genome";if(t.query.getread)return void n.send(await async function(e,t){if(!t.query.chr)throw".chr missing";if(!t.query.qname)throw".qname missing";if(t.query.qname=decodeURIComponent(t.query.qname),!Number.isInteger(t.query.start))throw".start is not integer";if(!Number.isInteger(t.query.stop))throw".stop is not integer";const n={chr:t.query.chr,start:t.query.start,stop:t.query.stop,scale:()=>{},ntwidth:10},s=await async function(e,t){const[n,s]=await sn(e);let r,o,i,a,l;if(e.query.unknownorder){if(!Number.isInteger(e.query.readstart)||!Number.isInteger(e.query.readstop))throw"readstart/stop not provided for read with unknown order";i=e.query.readstart,a=e.query.readstop}if(await R.UE({isbam:!0,args:["view",n,(e.query.nochr?e.query.chr.replace("chr",""):e.query.chr)+":"+t.start+"-"+t.stop],dir:s,callback:(n,s)=>{if(n.split("\t")[0]!=e.query.qname)return;const c=fn({sam_info:n,keepallboxes:!0,keepmatepos:!0,keepunmappedread:!0},t);if(c&&(!e.query.show_unmapped||!c.discord_unmapped2)&&(e.query.start==c.segstart_original&&e.query.stop==c.segstop||e.query.paired||e.query.show_unmapped))if(e.query.show_unmapped&&e.query.getfirst){if(c.islast)return s.kill(),void(l=[c])}else if(e.query.show_unmapped&&e.query.getlast){if(c.isfirst)return s.kill(),void(l=[c])}else if(e.query.getfirst){if(c.isfirst)return s.kill(),void(l=[c])}else if(e.query.getlast){if(c.islast)return s.kill(),void(l=[c])}else if(e.query.unknownorder){if(c.segstart==i&&c.segstop==a)return s.kill(),void(l=[c])}else if(c.isfirst?r=c:c.islast&&(o=c),r&&o)return s.kill(),void(l=[r,o])}}),l){if(e.query.altseqs){const t={query_seq:l[0].seq,refseqs:e.query.refseqs,altseqs:e.query.altseqs,cigar_seq:l[0].cigarstr,start_position:l[0].segstart,ref_positions:e.query.ref_positions,refalleles:e.query.refalleles,altalleles:e.query.altalleles},n=(await(0,we.run_rust)("align",JSON.stringify(t))).split("\n");let s;for(let e of n)e.includes("Final_output:")?s=JSON.parse(e.replace("Final_output:","")):console.log(e);l.alignments=s}return l}l=[],r&&l.push(r);o&&l.push(o);return l.length?l:null}(t,n);if(!s){if(t.query.show_unmapped)throw"mate not found";throw"read not found"}const r=[];for(const n of s)n.discord_unmapped1?r.push(await kn(n,e,t.query)):r.push(await qn(n,e,t.query));s.alignments&&(r[0].alignments=s.alignments);return{lst:r}}(s,t));const o=r().debugmode?new Date:null,i=await async function(e,t){const[n,s]=await sn(t),r={genome:e,file:n,dir:s,asPaired:t.query.asPaired,getcolorscale:t.query.getcolorscale,devicePixelRatio:t.query.devicePixelRatio?Number(t.query.devicePixelRatio):1};if(t.query.pileupheight&&(r.pileupheight=Number(t.query.pileupheight),Number.isNaN(r.pileupheight)))throw".pileupheight is not integer";t.query.drop_pcrduplicates&&(r.drop_pcrduplicates=!0);t.query.drop_supplementary_alignments&&(r.drop_supplementary_alignments=!0);if(t.query.variant){r.diff_score_plotwidth=Number(t.query.diff_score_plotwidth),t.query.max_diff_score&&(r.max_diff_score=Number(t.query.max_diff_score),r.min_diff_score=Number(t.query.min_diff_score));const e=t.query.variant.split(".");if(r.strictness=t.query.strictness,!Number.isInteger(e.length%4))throw"invalid variant, not chr.pos.ref.alt";r.alleleAlreadyUpdated=t.query.alleleAlreadyUpdated,r.alleleAlreadyUpdated&&(r.altseqs=t.query.altseqs,r.refseqs=t.query.refseqs,r.altalleles=t.query.altalleles,r.refalleles=t.query.refalleles,r.leftflankseqs=t.query.leftflankseqs,r.rightflankseqs=t.query.rightflankseqs,r.ref_positions=t.query.ref_positions);const n=e.length/4,s=[];for(let t=0;t<n;t++)s.push({chr:e[4*t],pos:Number(e[4*t+1]),ref:e[4*t+2],alt:e[4*t+3]});if(r.variant=s,t.query.alignOneGroup&&(r.alignOneGroup=t.query.alignOneGroup),Number.isNaN(r.variant.pos))throw"variant pos not integer"}else if(t.query.sv){const e=t.query.sv.split(".");if(e.length<6)throw"invalid sv, not chrA.posA.chrB.posB";if(r.sv={chrA:e[0],startA:Number(e[1]),strandA:Number(e[2]),chrB:e[3],startB:Number(e[4]),strandB:Number(e[5])},Number.isNaN(r.sv.startA))throw"sv.startA not integer";if(Number.isNaN(r.sv.startB))throw"sv.startB not integer"}if(Number.isFinite(Number(t.query.stackstart))){if(!t.query.stackstop)throw".stackstop missing";if(r.partstack={start:Number(t.query.stackstart),stop:Number(t.query.stackstop)},Number.isNaN(r.partstack.start))throw".stackstart not integer";if(Number.isNaN(r.partstack.stop))throw".stackstop not integer";if(!t.query.grouptype)throw".grouptype required for partstack";r.grouptype=t.query.grouptype}t.query.gdc||(t.query.nochr?r.nochr="string"==typeof t.query.nochr?JSON.parse(t.query.nochr):t.query.nochr:r.nochr=await R.Dp(r.file,e,r.dir));if(r.regions=t.query.regions,!Array.isArray(r.regions)||0==r.regions.length)throw"q.regions[] not non-empty array";let o=0;for(const e of r.regions){if(!e.chr)throw".chr missing from a region";if(!Number.isInteger(e.start))throw".start not integer of a region";if(!Number.isInteger(e.stop))throw".stop not integer of a region";e.scale=t=>Math.ceil(e.width*(t-e.start)/(e.stop-e.start)),e.ntwidth=e.width/(e.stop-e.start),o=Math.max(o,e.ntwidth)}return r.stacksegspacing=Math.max(Bt,Jt*o),r.readcount_skipped=0,r}(s,t);n.send(await async function(e){await async function(e){if(e.variant){let t=0,n=0,s=0,r=e.variant[0].pos,o=e.variant[0].pos+Math.max(e.variant[0].ref.length,e.variant[0].alt.length);for(const i of e.variant){const e=Math.abs(i.pos-Math.max(i.ref.length,i.alt.length));e>t&&(t=e,n=s),r>i.pos&&(r=i.pos),o<i.pos+Math.max(i.ref.length,i.alt.length)&&(o=i.pos+Math.max(i.ref.length,i.alt.length)),s+=1}t=Math.floor(1.5*Math.max(e.variant[n].ref.length,e.variant[n].alt.length));const i={chr:e.variant[0].chr,start:r-t,stop:o+t};return await on(e,[i]),await an(i,e),void(e.regions[0].lines=i.lines)}await on(e,e.regions);for(const t of e.regions)await an(t,e)}(e),e.totalnumreads=e.regions.reduce(((e,t)=>e+t.lines.length),0);const t={nochr:e.nochr,count:{r:e.totalnumreads},groups:[]};e.read_limit_reached&&(t.count.read_limit_reached=e.read_limit_reached);e.canvaswidth=e.regions[e.regions.length-1].x+e.regions[e.regions.length-1].width;{const n=await async function(e){const t=[],n=[];let s=0;for(const r of e.regions){for(const e of r.lines)t.push({sam_info:e,tempscore:""});s=r.x+r.width,n.push(s)}if(0==t.length)return{groups:[{type:Te,regions:$e(e.regions),templates:t,messages:[],partstack:e.partstack,widths:n}]};if(e.variant){if(1==e.regions.length)return await async function(e,t,n){const s=e.regions[0].lines[0].split("\t")[9].length;let r=!1,o=[],i=[],a=[],l=[],c=[],u=[],f=[];if(e.alleleAlreadyUpdated)o=e.leftflankseqs,i=e.rightflankseqs,u=e.refseqs,f=e.altseqs,a=e.refalleles,l=e.altalleles,c=e.ref_positions,0!=u[0].toUpperCase().localeCompare((o[0]+a[0]+i[0]).toUpperCase())&&(console.log("Reference allele is not correct for variant 0"),r=!0);else{let t,n,r=0;for(const o of e.variant){let i="",u="";if(!(0!=o.ref.length&&"-"!=o.ref||"-"!=o.alt&&0!=o.alt.length))throw"Both Ref and Alt alleles are missing";if(0==o.ref.length||"-"==o.ref)i=(await R.Kf(e.genome,o.chr+":"+o.pos+"-"+o.pos)).split("\n").slice(1).join("").toUpperCase(),u=i+o.alt,o.pos-=1;else if("-"==o.alt||0==o.alt.length){const t=(await R.Kf(e.genome,o.chr+":"+o.pos+"-"+o.pos)).split("\n").slice(1).join("").toUpperCase();i=t+o.ref,u=t,o.pos-=1}else u=o.alt,i=o.ref;const f=o.pos,d=i.toUpperCase(),p=u.toUpperCase();0==r?(t=f-s,n=f+i.length+1+s):(f-s<t&&(t=f-s),f+i.length+1+s>n&&(n=f+i.length+1+s)),a.push(d),l.push(p),c.push(f),r+=1}r=0;for(const s of e.variant){const d=(await R.Kf(e.genome,s.chr+":"+t+"-"+c[r])).split("\n").slice(1).join("").toUpperCase(),p=(await R.Kf(e.genome,s.chr+":"+(c[r]+a[r].length+1)+"-"+n)).split("\n").slice(1).join("").toUpperCase(),m=d+a[r]+p,h=d+l[r]+p;console.log(s.chr+"."+c[r]+"."+a[r]+"."+l[r]),r+=1,o.push(d),i.push(p),u.push(m),f.push(h)}}const d=[];for(let e=0;e<t.length;e++){const n=t[e].sam_info.split("\t");d.push({read_sequence:n[9],start_position:Number(n[3]),cigar:n[5],flag:Number(n[1])})}const p=[];for(let e=0;e<a.length;e++)p.push({ref_position:Number(c[e]),refallele:a[e],altallele:l[e],refseq:u[e],altseq:f[e],leftflankseq:o[e],rightflankseq:i[e]});Number.isFinite(Number(e.strictness))||(e.strictness=1);const m={reads:d,alleles:p,strictness:Number(e.strictness)},h=new Date,g=await(0,we.run_rust)("indel",JSON.stringify(m)),y=new Date;console.log("Time taken to run rust indel pipeline:",y-h,"ms");const b=g.split("\n");let v,w,_,k,q,x,N=0;for(let e of b)e.includes("Final_output:")?v=JSON.parse(JSON.parse(e.replace("Final_output:",""))):1==a.length&&e.includes("fisher_strand:")?(w=JSON.parse(e.replace("fisher_strand:","")),_=w.alternate_forward_count,k=w.alternate_reverse_count,q=w.reference_forward_count,x=w.reference_reverse_count,N=w.p_value):console.log(e);if(0==v.length)throw"No reads available for variant typing";let S=!1;1==e.variant.length&&N>60&&(S=!0);const A=Fe(e);e.variant.length;let C=1;for(let n=0;n<v.length;n++){const s=v[n],r=s.read_number,o=s.categories,i=s.categories[0],a=[];if(o.length>1){for(let e=1;e<o.length;e++)a.push(o[e]);o.length-1>C&&(C=o.length-1)}if(i.includes("alt"))for(let n=0;n<e.variant.length;n++)i=="alt"+n.toString()&&A[Oe+n.toString()]&&(t[r].tempscore=["alt"+n.toString()],A[Oe+n.toString()].templates.push(t[r]));else"ref"==i?A[Me]&&(t[r].tempscore=["ref"],A[Me].templates.push(t[r])):"none"==i?A[Ie]&&(t[r].tempscore=a,A[Ie].templates.push(t[r])):"amb"==i?A[Ee]&&(t[r].tempscore=a,A[Ee].templates.push(t[r])):console.log("Unaccounted group, please check")}const j=[];for(const t in A){const s=A[t];if(0!=s.templates.length){if(t.includes(Oe))for(let n=0;n<e.variant.length;n++)t==Oe+n.toString()&&(1==e.variant.length?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read supporting the alternative allele"}):s.messages.push({isheader:!0,t:s.templates.length+" reads supporting the alternative allele"}):1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read support the alternative allele with "+l[n]+" sequence"}):s.messages.push({isheader:!0,t:s.templates.length+" reads support the alternative allele with "+l[n]+" sequence"}));else t==Ee?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" ambiguous read"}):s.messages.push({isheader:!0,t:s.templates.length+" ambiguous reads"}):t==Me?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read supporting the reference allele"}):s.messages.push({isheader:!0,t:s.templates.length+" reads supporting the reference allele"}):t==Ie?1==s.templates.length?s.messages.push({isheader:!0,t:s.templates.length+" read supporting neither reference nor alternative alleles"}):s.messages.push({isheader:!0,t:s.templates.length+" reads supporting neither reference nor alternative alleles"}):console.log("Unaccounted group, please check");s.widths=n,j.push(s)}}const T=[];for(let e=0;e<j.length;e++)j[e].type.includes("support_alt")&&T.push(j[e]);for(let e=0;e<j.length;e++)"support_ref"==j[e].type&&T.push(j[e]);for(let e=0;e<j.length;e++)"support_no"==j[e].type&&T.push(j[e]);for(let e=0;e<j.length;e++)"support_amb"==j[e].type&&T.push(j[e]);return{groups:T,refalleleerror:r,ref_positions:c,refalleles:a,altalleles:l,max_diff_score:C,min_diff_score:0,strand_probability:N,strand_significance:S,refseqs:u,altseqs:f,leftflankseqs:o,rightflankseqs:i,alternate_forward_count:_,alternate_reverse_count:k,reference_forward_count:q,reference_reverse_count:x}}(e,t,n);console.log("Indel pipeline works only in single region. Please check!")}if(e.sv&&e.regions.length>1)return async function(e,t,n){const s=Fe(t),r=[];for(let e=0;e<t.regions.length;e++){const n=t.regions[e],s=(await R.Kf(t.genome,n.chr+":"+n.start+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase(),o=[];for(const t of n.lines)o.push({sam_info:t,tempscore:"",ridx:e});const i={refseq:s,start:n.start,stop:n.stop,entries:o};0==e?(i.chr=t.sv.chrA,i.pos=t.sv.startA):1==e?(i.chr=t.sv.chrB,i.pos=t.sv.startB):console.log("More than two regions, please check"),r.push(i)}const o=new Date,i=(await(0,we.run_rust)("sv",JSON.stringify(r))).split("\n"),a=new Date;let l,c;console.log("Time taken to run rust SV pipeline:",a-o,"ms");for(let e of i)e.includes("multi_region_templates:")?l=JSON.parse(e.replace("multi_region_templates:","")):e.includes("single_region_templates:")&&(c=JSON.parse(e.replace("single_region_templates:","")));if(!t.grouptype||"support_sv"==t.grouptype)for(const e of l)s[Re].templates.push(e);if(!t.grouptype||"support_ref"==t.grouptype)for(const e of c)s[Me].templates.push(e);const u=[];for(const e in s){const t=s[e];0!=t.templates.length&&(e==Re?1==t.templates.length?t.messages.push({isheader:!0,t:t.templates.length+" read supporting SV/fusion"}):t.messages.push({isheader:!0,t:t.templates.length+" reads supporting SV/fusion"}):e==Me&&t.messages.push({isheader:!0,t:t.templates.length+" reads supporting reference allele"}),t.widths=n,u.push(t))}return{groups:u}}(0,e,n);return{groups:[{type:Te,regions:$e(e.regions),templates:t,messages:[],partstack:e.partstack,widths:n}]}}(e);e.groups=n.groups,e.variant&&(t.ref_alleles=n.refalleles,t.alt_alleles=n.altalleles,t.allele_positions=n.ref_positions,t.strand_probability=n.strand_probability,t.alternate_forward_count=n.alternate_forward_count,t.reference_forward_count=n.reference_forward_count,t.alternate_reverse_count=n.alternate_reverse_count,t.reference_reverse_count=n.reference_reverse_count,1==n.strand_significance&&(t.strand_significance=!0),e.alleleAlreadyUpdated||(t.refseqs=n.refseqs,t.altseqs=n.altseqs,t.leftflankseqs=n.leftflankseqs,t.rightflankseqs=n.rightflankseqs,t.ref_positions=n.ref_positions,t.refalleles=n.refalleles,t.altalleles=n.altalleles)),Number.isFinite(e.max_diff_score)&&e.variant?(t.max_diff_score=e.max_diff_score,t.min_diff_score=e.min_diff_score):Number.isFinite(n.max_diff_score)&&(t.max_diff_score=n.max_diff_score,t.min_diff_score=n.min_diff_score),n.refalleleerror&&(t.refalleleerror=n.refalleleerror)}if(0==t.count.r)throw"No reads in view range.";if(e.alignOneGroup){const t=e.groups.find((t=>t.type==e.alignOneGroup));if(!t)throw"cannot find group for realignment";let n=un(e,t);return n=pn(t,e,n),await async function(e,t,n){let s;if(t.variant)if("support_ref"==e.type){let r=t.leftflankseqs[0].length;s=e.partstack?await rn(n,r,e.partstack.start,e.partstack.stop,t.refseqs[0]):await rn(n,r,0,0,t.refseqs[0])}else if("support_no"==e.type){let r=t.leftflankseqs[0].length;s=e.partstack?await rn(n,r,e.partstack.start,e.partstack.stop):await rn(n,r)}else{if("support_amb"==e.type)throw"Realignment of reads in ambiguous group is not currently implemented.";if(e.type.includes("support_alt")){for(let r=0;r<t.variant.length;r++)if(e.type=="support_alt"+r.toString()){let o=t.leftflankseqs[r].length;s=e.partstack?await rn(n,o,e.partstack.start,e.partstack.stop,t.altseqs[r]):await rn(n,o,0,0,t.altseqs[r])}}else console.log("Unaccounted group, please check")}return{alignmentData:s}}(t,e,n)}let n=[];for(const s of e.groups){let r=un(e,s);r=pn(s,e,r),await dn(s,e,r),await cn(r,e),hn(s,r,e);const o={type:s.type,width:e.canvaswidth,height:s.canvasheight,stackheight:s.stackheight,stackcount:s.stacks.length,allowpartstack:s.allowpartstack,templatebox:s.returntemplatebox,count:{r:r.reduce(((e,t)=>e+t.segments.length),0)}},i=(0,N.createCanvas)(e.canvaswidth*e.devicePixelRatio,s.canvasheight*e.devicePixelRatio),a=i.getContext("2d");e.devicePixelRatio>1&&a.scale(e.devicePixelRatio,e.devicePixelRatio),a.textAlign="center",a.textBaseline="middle",o.messages=s.messages,o.messagerowheights=0;for(const t of r)vn(a,t,s,e);_n(a,s,e,r),e.asPaired&&(o.count.t=r.length),e.variant&&(o.diff_scores_img=await tn(e,s,r,t.max_diff_score,t.min_diff_score),"support_alt0"==o.type?o.group_color=At:"support_alt1"==o.type?o.group_color=Ct:"support_alt2"==o.type?o.group_color=jt:"support_alt3"==o.type?o.group_color=Tt:"support_alt4"==o.type?o.group_color=Mt:"support_alt5"==o.type?o.group_color=Ot:"support_ref"==o.type&&(o.group_color=It)),o.src=i.toDataURL(),t.groups.push(o),n=[...n,...r]}e.readcount_skipped&&(t.count.skipped=e.readcount_skipped);e.getcolorscale&&(t.colorscale=function(e){const t=160,n=20,s=1,r=12,o=5,i=100,a=4,l=i+t+10,c=2*r+o+a+4*(n+s),u=(0,N.createCanvas)(e.devicePixelRatio*l,e.devicePixelRatio*c),f=u.getContext("2d");e.devicePixelRatio>1&&f.scale(e.devicePixelRatio,e.devicePixelRatio);f.fillStyle="black",f.font=r+"pt Arial",f.textAlign="center",f.fillText("Base quality",i+t/2,r);let d=2*r+o;function p(e,s,r){const o=i,a=f.createLinearGradient(o,r,o+t,r);a.addColorStop(0,s),a.addColorStop(1,e),f.fillStyle=a,f.fillRect(o,r,t,n)}return f.strokeStyle="black",f.beginPath(),f.moveTo(i,d),f.lineTo(i,d+a),f.moveTo(i+t/4,d),f.lineTo(i+t/4,d+a),f.moveTo(i+t/2,d),f.lineTo(i+t/2,d+a),f.moveTo(i+3*t/4,d),f.lineTo(i+3*t/4,d+a),f.moveTo(i+t,d),f.lineTo(i+t,d+a),f.closePath(),f.stroke(),f.fillText(40,i,d),f.fillText(30,i+t/4,d),f.fillText(20,i+t/2,d),f.fillText(10,i+3*t/4,d),f.fillText(0,i+t,d),f.textAlign="left",f.textBaseline="middle",d+=a,f.fillText("Match",0,d+n/2),p(nt,tt,d),d+=n+s,f.fillStyle="black",f.fillText("Mismatch",0,d+n/2),p(ct,lt,d),d+=n+s,f.fillStyle="black",f.fillText("Softclip",0,d+n/2),p(dt,ft,d),d+=n+s,f.fillStyle="black",f.fillText("Insertion",0,d+n/2),p(vt,bt,d),{width:l,height:c,src:u.toDataURL()}}(e));if(!e.partstack)if(0==t.count.r);else{if(!e.pileupheight)throw"pileupheight missing";t.pileup_data=await async function(e,t){const n=(0,N.createCanvas)(e.canvaswidth*e.devicePixelRatio,e.pileupheight*e.devicePixelRatio),s=n.getContext("2d");e.devicePixelRatio>1&&s.scale(e.devicePixelRatio,e.devicePixelRatio);const r=[];let o=0;for(const[n,s]of e.regions.entries()){r[n]=await ln(e,s),nn(n,s,t,r[n]);for(const e of r[n])e&&(o=Math.max(o,e.total))}for(const[t,n]of e.regions.entries()){const i=e.pileupheight/o;for(const o of r[t]){if(!o)continue;const t=(o.position-n.start)*n.ntwidth+n.x,r=n.ntwidth>=1?t:Math.floor(t),a=Math.max(1,n.ntwidth);{s.fillStyle=St;const t=o.total*i;s.fillRect(r,e.pileupheight-t,a,t)}let l=0;if(o.A){s.fillStyle=F.basecolor.A;const t=o.A*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.C){s.fillStyle=F.basecolor.C;const t=o.C*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.G){s.fillStyle=F.basecolor.G;const t=o.G*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.T){s.fillStyle=F.basecolor.T;const t=o.T*i;s.fillRect(r,e.pileupheight-l-t,a,t),l+=t}if(o.softclip){s.fillStyle=ft;const t=o.softclip*i;s.fillRect(r,e.pileupheight-l-t,a,t)}}}return{width:e.canvaswidth,maxValue:o,src:n.toDataURL()}}(e,n)}return t}(i)),r().debugmode&&console.log("bam.js time ms",new Date-o)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Lr)),Br.get(Jr+"/gdcbam",function(e){return async function(t,n){try{const s=e.hg38;if(!s)throw"hg38 missing";const r=s.datasets.GDC;if(!r)throw"hg38 GDC missing";if(Ve||(Ve=function(e){if(Ve)throw"The gdc queryApi has already been set.";return async function(t,n,s,r,o){const{host:i,headers:a}=e.getHostHeaders(o),l=g().join(i.rest,n.end_point),c={filters:t,case_filters:r,size:s||10,fields:n.fields.join(",")},u=await b()(l,{method:"POST",headers:a,body:JSON.stringify(c)});let f;try{f=JSON.parse(u.body)}catch(e){throw"invalid JSON from "+n.end_point}if(!Array.isArray(f.data?.hits))throw"data structure not re.data.hits[]";return f}}(r)),t.query.gdc_id){const e=await async function(e){const{gdc_id:t,filter0:n}=e,s={file_metadata:[],isCaseSample:"",numFilesSkippedByWorkflow:0},r=await Ze(t,s,n,e);if(!r.data.hits.length){if(s.isCaseSample)throw`No bam files available for this ${s.isCaseSample}.`;if(n){if((await Ze(t,s,null,e)).data.hits.length)throw"Case not in current cohort.";throw"Invalid input ID."}throw"Invalid input ID."}for(const e of r.data.hits){if(e.analysis.workflow_type==Je){s.numFilesSkippedByWorkflow++;continue}const t={};t.file_uuid=e.id,t.file_size=Ge(e.file_size),t.experimental_strategy=e.experimental_strategy,t.entity_id=e.associated_entities[0].entity_submitter_id,t.case_id=e.associated_entities[0].case_id,t.sample_type=e.cases[0].samples[0].sample_type,s.file_metadata.push(t)}return s}(t.query);await async function(e,t,n){if(!e.file_metadata?.length)return;const s=t.cookies.sessionid;if(!s)return;try{await Qe(e.file_metadata[0].file_uuid,n,t.query)}catch(t){"Permission denied"==t&&(e.userHasNoAccess=!0)}}(e,t,r),n.send(e)}else{const e=await async function(e,t){const n=await async function(e,t){const n=await Ve(null,ze,He,e,t);return n.data.hits.map((e=>e.id))}(e,t);if(0==n.length)throw"No cases available";const s=await Xe(n,"cases.case_id",We,t),r={};if(!Array.isArray(s.data?.hits))throw"re.data.hits[] not array";for(const e of s.data.hits){if(e.analysis.workflow_type==Je)continue;const t=e.cases?.[0]?.submitter_id;t&&(r[t]||(r[t]=[]),r[t].push({file_uuid:e.id,sample_type:e.cases?.[0].samples?.[0].sample_type,experimental_strategy:e.experimental_strategy,file_size:Ge(Number.parseFloat(e.file_size))}))}return{case2files:r,total:s.data?.pagination?.total,loaded:We}}(t.query.filter0,t.query);n.send(e)}}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Lr)),Br.get(Jr+"/tkaicheck",(async(e,t)=>{try{t.send(await async function(e){const[t,n,s]=R.ZX(e);if(t)throw t;const r=Number(e.query.coveragemax)||100;if(!Number.isInteger(r))throw"invalid coveragemax";const o=Number(e.query.vafheight);if(!Number.isInteger(o))throw"invalid vafheight";const i=Number(e.query.coverageheight);if(!Number.isInteger(i))throw"invalid coverageheight";const a=Number(e.query.rowspace);if(!Number.isInteger(a))throw"invalid rowspace";const l=Number(e.query.dotsize)||1;if(!Number.isInteger(l))throw"invalid dotsize";if(!e.query.rglst)throw".rglst missing";"string"==typeof e.query.rglst&&(e.query.rglst=JSON.parse(e.query.rglst));const c=e.query.gtotalcutoff,u=e.query.gmafrestrict,f=(0,N.createCanvas)(e.query.width*e.query.devicePixelRatio,(3*o+4*a+2*i)*e.query.devicePixelRatio),d=f.getContext("2d");let p;e.query.devicePixelRatio>1&&d.scale(e.query.devicePixelRatio,e.query.devicePixelRatio),d.fillStyle="#f1f1f1",d.fillRect(0,0,e.query.width,o/2),d.fillRect(0,2*a+o+i,e.query.width,o/2),d.fillStyle="#FAFAD9",d.fillRect(0,o/2,e.query.width,o/2),d.fillRect(0,2*a+1.5*o+i,e.query.width,o/2),s&&(p=await R.d1(n,e.query.indexURL));let m=0;for(const t of e.query.rglst)t.x=m,m+=e.query.regionspace+t.width;const h="#786312",g="#122778",y="#858585",b="red";for(const t of e.query.rglst){const e=t.width/(t.stop-t.start);await R.UE({args:[n,t.chr+":"+t.start+"-"+t.stop],dir:p,callback:n=>{const s=n.split("\t"),f=Number.parseInt(s[1]),p=Number.parseInt(s[2]),m=Number.parseInt(s[3]),v=Number.parseInt(s[4]),w=Number.parseInt(s[5]);if(Number.isNaN(p)||Number.isNaN(m)||Number.isNaN(v)||Number.isNaN(w))return;if(c&&w<c)return;const _=Math.ceil(t.x+e*(t.reverse?t.stop-f:f-t.start)-l/2);d.fillStyle=h;const k=p/m;d.fillRect(_,o*(1-k),l,2);const q=v/w;if(u&&(q<u||q>1-u))return;d.fillRect(_,o+a+i+a+o*(1-q),l,2),d.fillStyle=g;const x=Math.abs(k-q);d.fillRect(_,2*o+4*a+2*i+o*(1-x),l,2),d.fillStyle=y;let N=(m>=r?r:m)*i/r,S=i-N;d.fillRect(_,S+o+a,l,N),d.fillStyle=y,N=(w>=r?r:w)*i/r,S=i-N,d.fillRect(_,S+3*a+2*o+i,l,N),m>=r&&(d.fillStyle=b,d.fillRect(_,o+a,l,2)),w>=r&&(d.fillStyle=b,d.fillRect(_,3*a+2*o+i,l,2))}})}return{src:f.toDataURL(),coveragemax:r}}(e))}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.get(Jr+"/blat",function(e){return async(t,n)=>{try{if(t.query.serverstat){const t=[];for(const n in e){const s=e[n];s.blat&&t.push(await ts(n,s))}if(0==t.length)throw"found no genome with blat";return void n.send({lst:t})}if(!t.query.genome)throw".genome missing";const s=e[t.query.genome];if(!s)throw"invalid genome";if(!s.blat)throw"blat not enabled";if(!t.query.seq)throw".seq missing";n.send(await async function(e,t,n,s){const o=g().join(r().cachedir,await(0,R.tG)(">query\n"+t+"\n")),i=await ns(e,o),a=(await(0,R.b5)(i)).trim();if(m().unlink(i,(()=>{})),m().unlink(o,(()=>{})),""==a)return{nohit:1};const l=a.split("\n"),c=[];for(const e of l){const t={},n=e.split(" ").filter((function(e){return""!=e}))[0].split("\t");t.query_match=n[0],t.query_startpos=(parseInt(n[11])+1).toString(),t.query_stoppos=n[12],t.query_strand=n[8],t.query_totallen=n[10],t.query_alignlen=Math.abs(parseInt(n[11])-parseInt(n[12])).toString(),t.ref_chr=n[13],t.ref_startpos=(parseInt(n[15])+1).toString(),t.ref_stoppos=n[16],t.ref_alignlen=Math.abs(n[16]-n[15]).toString(),t.ref_totallen=n[14],c.push(t)}return c.sort(((e,t)=>t.query_match-e.query_match)),{hits:c}}(s,t.query.seq,t.query.soft_starts,t.query.soft_stops))}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Lr)),Br.all(Jr+"/mds3",function(e){return async(t,n)=>{try{if(!t.query.genome)throw".genome missing";const s=e[t.query.genome];if(!s)throw"invalid genome";const r=function(e,t){const n=e.query;e.get("X-Auth-Token")&&(n.token=e.get("X-Auth-Token"));(0,R.Y5)(n,e.cookies),n.hiddenmclasslst&&(n.hiddenmclass=new Set(n.hiddenmclasslst.split(",")),delete n.hiddenmclasslst);return n}(t),o=await async function(e,t){if(e.dslabel){if(!t.datasets)throw".datasets{} missing from genome";const n=t.datasets[e.dslabel];if(!n)throw"invalid dslabel";return n}const n={queries:{}};if(e.bcffile||e.bcfurl){const[s,r,o]=(0,R.ZX)({query:{file:e.bcffile,url:e.bcfurl}});if(s)throw s;const i={};o?(i.url=r,i.indexURL=e.bcfindexURL):i.file=r,n.queries.snvindel={byrange:{_tk:i}},n.queries.snvindel.byrange.get=await Rs(n,t)}return n}(r,s);!function(e,t){if(e.filter0){const n="object"==typeof e.filter0?e.filter0:JSON.parse("string"==typeof e.filter0&&e.filter0.startsWith("%")?decodeURIComponent(e.filter0):e.filter0);e.filter0=t.validate_filter0(n)}e.filterObj&&"string"==typeof e.filterObj&&(e.filterObj=JSON.parse("string"==typeof e.filterObj&&e.filterObj.startsWith("%")?decodeURIComponent(e.filterObj):e.filterObj));if(e.skewerRim){if("format"!=e.skewerRim.type)throw"unknown skewerRim.type";if(!e.skewerRim.formatKey)throw"skewerRim.formatKey missing when type=format";if(!t.queries?.snvindel?.format)throw"snvindel.format{} not found when type=format";if(!t.queries.snvindel.format[e.skewerRim.formatKey])throw"invalid skewerRim.formatKey";if(e.skewerRim.hiddenvalues=new Set,e.skewerRim.hiddenvaluelst){if(!Array.isArray(e.skewerRim.hiddenvaluelst))throw"query.skewerRim.hiddenvaluelst is not array";for(const t of e.skewerRim.hiddenvaluelst)e.skewerRim.hiddenvalues.add(t);delete e.skewerRim.hiddenvaluelst}}if(e.formatFilter){if("object"!=typeof e.formatFilter)throw"formatFilter{} not object";if(!t.queries?.snvindel?.format)throw"snvindel.format{} not found when formatFilter is used";const n={};for(const s in e.formatFilter){if(!t.queries.snvindel.format[s])throw"invalid format key from formatFilter";if(!Array.isArray(e.formatFilter[s]))throw"formatFilter[k] value is not array";n[s]=new Set(e.formatFilter[s])}e.formatFilter=n}("format"==e.skewerRim?.type||e.formatFilter)&&(e.addFormatValues=!0)}(r,o);const i=await async function(e,t){if(e.singleSampleGenomeQuantification){if(!t.queries.singleSampleGenomeQuantification)throw"not supported on this dataset";const n=t.queries.singleSampleGenomeQuantification[e.singleSampleGenomeQuantification.dataType];if(!n)throw"invalid dataType";return await n.get(e.singleSampleGenomeQuantification.sample,e.devicePixelRatio)}if(e.singleSampleGbtk){if(!t.queries.singleSampleGbtk)throw"not supported on this dataset";const n=t.queries.singleSampleGbtk[e.singleSampleGbtk.dataType];if(!n)throw"invalid dataType";return await n.get(e.singleSampleGbtk.sample)}if(e.ssm2canonicalisoform){if(!t.ssm2canonicalisoform)throw"ssm2canonicalisoform not supported on this dataset";return{isoform:await t.ssm2canonicalisoform.get(e)}}if(e.variant2samples){if(!t.variant2samples)throw"not supported by server";return{variant2samples:await t.variant2samples.get(e)}}if(e.m2csq){if(t.queries&&t.queries.snvindel&&t.queries.snvindel.m2csq)return{csq:await t.queries.snvindel.m2csq.get(e)};throw"m2csq not supported on this dataset"}if(e.forTrack){const n={};if(e.skewer){if(n.skewer=[],t.queries.snvindel){const s=await async function(e,t){if(e.isoform&&t.queries.snvindel.byisoform)return await t.queries.snvindel.byisoform.get(e);if(e.rglst){if(!t.queries.snvindel.byrange)throw"q.rglst[] provided but .byrange{} is missing";return await t.queries.snvindel.byrange.get(e)}throw"insufficient query parameters for snvindel"}(e,t);n.skewer.push(...s)}if(t.queries.svfusion){const s=await async function(e,t){if(e.rglst){if(!t.queries.svfusion.byrange)throw"q.rglst provided but svfusion.byrange missing";return await t.queries.svfusion.byrange.get(e)}throw"insufficient query parameters for svfusion"}(e,t);n.skewer.push(...s)}if(t.queries.geneCnv){const s=await async function(e,t){if(e.gene){if(!t.queries.geneCnv.bygene)throw"q.gene provided but geneCnv.bygene missing";return await t.queries.geneCnv.bygene.get(e)}}(e,t);n.geneCnv=s}t.queries.cnv&&(n.cnv=await async function(e,t){if(e.rglst){if(!t.queries.cnv.byrange)throw"q.rglst provided but cnv.byrange missing";return await t.queries.cnv.byrange.get(e)}throw"insufficient query parameters for cnv"}(e,t)),function(e,t){if(t.skewer){const n=[];for(const s of t.skewer)e.rglst&&!e.rglst.find((e=>s.chr==e.chr&&s.pos>=e.start&&s.pos<=e.stop))||n.push(s);t.skewer=n}t.genecnvAtsample}(e,n),n.mclass2variantcount=function(e){const t=new Map;for(const n of e){const e=n.class||n.dt;t.set(e,1+(t.get(e)||0))}return[...t].sort(((e,t)=>t[1]-e[1]))}(n.skewer)}return function(e,t,n){const s=new Set;if(n.skewer)for(const r of n.skewer)if(r.samples){r.occurrence=r.samples.length,Hs(r,e,t),Ws(r,t);for(const e of r.samples)s.add(e.sample_id);delete r.samples}if(n.cnv)for(const e of n.cnv)if(e.samples)for(const n of e.samples)if(s.add(n.sample_id),t.cohort?.termdb?.q?.id2sampleName){const e=t.cohort.termdb.q.id2sampleName(n.sample_id);e&&(n.sample_id=e)}s.size&&(n.sampleTotalNumber=s.size)}(e,t,n),n}throw"do not know what client wants"}(r,o);n.send(i)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Lr)),Br.get(Jr+"/tkbampile",(async function(e,t){try{const[n,s,r]=R.ZX(e);if(n)throw n;let o=e.query.usegrade;const i=Number(e.query.allheight),a=Number(e.query.fineheight),l=Number(e.query.fineymax),c=Number(e.query.midpad),u=Number(e.query.regionspace),f=Number(e.query.width);if(!Number.isInteger(i))throw"allheight is not integer";if(!Number.isInteger(a))throw"fineheight is not integer";if(!Number.isInteger(l))throw"fineymax is not integer";if(!Number.isInteger(c))throw"midpad is not integer";if(!Number.isInteger(u))throw"regionspace is not integer";if(!Number.isFinite(f))throw"width is not a number";const d="string"==typeof e.query.rglst?JSON.parse(e.query.rglst):e.query.rglst;if(!d)throw"no rglst[]";if(!Array.isArray(d))throw"rglst is not an array";if(0==d.length)throw"empty rglst";for(const e of d)e.reverse?e.scale=t=>Math.ceil(e.width*(e.stop-t)/(e.stop-e.start)):e.scale=t=>Math.ceil(e.width*(t-e.start)/(e.stop-e.start));let p;r&&(p=await R.d1(s,e.query.indexURL));for(const e of d){e.items=[];let t=0;await R.UE({args:[s,e.chr+":"+e.start+"-"+e.stop],dir:p,callback:n=>{const s=n.split("\t");let r;try{r=JSON.parse(s[2])}catch(e){return void t++}const o=Number.parseInt(s[1]);e.items.push({pos:o,data:r})}})}const m=i+c+a,h=(0,N.createCanvas)(f,m),g=d.reduce(((e,t)=>e+t.items.length),0),y=h.getContext("2d");if(0==g)return y.font="15px Arial",y.fillStyle="#aaa",y.textAlign="center",y.textBaseline="middle",y.fillText("No data in view range",f/2,m/2),void t.send({src:h.toDataURL()});let b=null;if(!o){const e=new Set;for(const t of d)for(const n of t.items)for(const t in n.data)e.add(t);if(b=[...e],b.length>0&&(o=b[0]),!o)return void t.send({src:h.toDataURL()})}let v=0;for(const e of d)for(const t of e.items)if(t.data[o]){let e=0;for(const n in t.data[o])e+=t.data[o][n];v=Math.max(v,e)}const w="#ededed";let _=0;const k=i/v,q=a/l;for(const e of d){const t=e.width/(e.stop-e.start);for(const n of e.items){const s=n.data[o];if(!s)continue;const r=e.scale(n.pos);let a=0;const u=[];for(const e in s)u.push({nt:e,v:s[e]}),a+=s[e];y.fillStyle=w;const f=k*(v-a);if(y.fillRect(_+r,f,t,k*a),u.length>1){u.sort(((e,t)=>t.v-e.v));for(let e=1;e<u.length;e++){let n=0;for(let t=0;t<e;t++)n+=u[t].v;y.fillStyle=F.basecolor[u[e].nt],y.fillRect(_+r,f+k*n,t,k*u[e].v)}}y.fillStyle=w;const d=i+c+q*(l-Math.min(a,l));if(y.fillRect(_+r,d,t,q*Math.min(a,l)),u.length>1)for(let e=1;e<u.length;e++){let n=0;for(let t=0;t<e;t++)n+=u[t].v;y.fillStyle=F.basecolor[u[e].nt],y.fillRect(_+r,d+q*(l-Math.min(l,a-n)),t,q*Math.min(l,u[e].v))}}_+=e.width+u}t.send({src:h.toDataURL(),allgrades:b,usegrade:o,allmax:v})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/dsdata",(async function(e,t){try{if(!Lr[e.query.genome])throw"invalid genome";if(!e.query.dsname)throw".dsname missing";const n=Lr[e.query.genome].datasets[e.query.dsname];if(!n)throw"invalid dsname";const s=[];for(const t of n.queries)if((!e.query.expressiononly||t.isgeneexpression)&&!(e.query.noexpression&&t.isgeneexpression||t.dsblocktracklst))if(t.vcffile){const n=await to(t,e);s.push(n)}else{if(!t.makequery)throw"unknow type from one of ds.queries[]";{const r=eo(n,t,e);s.push(r)}}t.send({data:s})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/tkbigwig",(async function(e,t){try{let n,s,o,i,a=!1,l=!1;const[c,u,f]=R.ZX(e);if(c)throw c;if(u.endsWith(".gz")&&(l=!0,f&&(i=await R.d1(u,e.query.indexURL))),e.query.autoscale)a=!0;else if(e.query.percentile){if(o=e.query.percentile,!Number.isFinite(o))throw"invalid percentile"}else{if(n=e.query.minv,s=e.query.maxv,!Number.isFinite(n))throw"invalid minv";if(!Number.isFinite(s))throw"invalid maxv"}if(!Number.isFinite(e.query.barheight))throw"invalid barheight";if(!Number.isFinite(e.query.regionspace))throw"invalid regionspace";if(!Number.isFinite(e.query.width))throw"invalid width";if(!e.query.rglst)throw"region list missing";if(e.query.dotplotfactor&&!Number.isInteger(e.query.dotplotfactor))throw"dotplotfactor value should be positive integer";if(l)return await async function(e,t,n,s,r,o){if(null==n||null==s)throw"Y axis scale must be defined for bedgraph track";const i=(0,N.createCanvas)(e.query.width*e.query.devicePixelRatio,e.query.barheight*e.query.devicePixelRatio),a=i.getContext("2d");e.query.devicePixelRatio>1&&a.scale(e.query.devicePixelRatio,e.query.devicePixelRatio);let l=0;for(let t of e.query.rglst)await ke(e,t,l,n,s,r,o,a),l+=t.width+e.query.regionspace;t.send({src:i.toDataURL()})}(e,t,n,s,u,i);for(const t of e.query.rglst){let n;if(r().features.bigwig_rust){const s=u+","+t.chr+","+t.start+","+t.stop+","+Math.ceil(t.width*(e.query.dotplotfactor||1));n=await(0,we.run_rust)("bigwig",s)}else n=await xe(e,t,u);n&&(t.values=n.trim().split("\t").map(Number.parseFloat),e.query.dividefactor&&(t.values=t.values.map((t=>t/e.query.dividefactor))))}let d=!0;for(const t of e.query.rglst)t.values&&(d=!1);const p=(0,N.createCanvas)(e.query.width*e.query.devicePixelRatio,e.query.barheight*e.query.devicePixelRatio),m=p.getContext("2d");if(e.query.devicePixelRatio>1&&m.scale(e.query.devicePixelRatio,e.query.devicePixelRatio),d)return m.font="14px Arial",m.fillStyle="#858585",m.textAlign="center",m.textBaseline="middle",m.fillText(e.query.name+": no data in view range",e.query.width/2,e.query.barheight/2),void t.send({src:p.toDataURL(),nodata:!0});const h=1,g=e.query.dotplotfactor?1/e.query.dotplotfactor:1;let y=0,b=0;const v={};if(a||o){const t=[],n=[];for(const s of e.query.rglst)if(s.values)for(const e of s.values)Number.isNaN(e)||(e>=0&&t.push(e),e<=0&&n.push(e));t.length&&(t.sort(((e,t)=>e-t)),y=a?t[t.length-1]:t[Math.floor(t.length*o/100)]),n.length&&(n.sort(((e,t)=>t-e)),b=a?n[n.length-1]:n[Math.floor(n.length*o/100)]),v.minv=b,v.maxv=y}else b=n,y=s;if(e.query.barheight<10){let t=(0,_e.B8)(e.query.pcolor);const n=t.r+","+t.g+","+t.b;t=(0,_e.B8)(e.query.ncolor);const s=t.r+","+t.g+","+t.b;let r=0;for(const t of e.query.rglst){if(t.values)for(let o=0;o<t.values.length;o++){const i=t.values[o];if(Number.isNaN(i))continue;m.fillStyle=i>=y?e.query.pcolor2:i>=0?"rgba("+n+","+i/y+")":i<=b?e.query.ncolor2:"rgba("+s+","+i/b+")";const a=Math.ceil(r+(t.reverse?t.width-g*o:g*o));m.fillRect(a,0,h,e.query.barheight)}r+=t.width+e.query.regionspace}}else{const t=qe().height(e.query.barheight).min(b).max(y);let n=0;for(const s of e.query.rglst){if(s.values)for(let r=0;r<s.values.length;r++){const o=s.values[r];if(Number.isNaN(o))continue;m.fillStyle=o>0?e.query.pcolor:e.query.ncolor;const i=Math.ceil(n+(s.reverse?s.width-g*r:g*r)),a=t(o);if(o>0)m.fillRect(i,a.y,h,e.query.dotplotfactor?Math.min(2,a.h):a.h);else if(e.query.dotplotfactor){const e=Math.min(2,a.h);m.fillRect(i,a.y+a.h-e,h,e)}else m.fillRect(i,a.y,h,a.h);o>y?(m.fillStyle=e.query.pcolor2,m.fillRect(i,0,h,2)):o<b&&(m.fillStyle=e.query.ncolor2,m.fillRect(i,e.query.barheight-2,h,2))}n+=s.width+e.query.regionspace}}v.src=p.toDataURL(),t.send(v)}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/tkld",function(e){return async(t,n)=>{try{const s=e[t.query.genome];if(!s)throw"unknown genome";n.send(await async function(e,t){const[n,s,r]=R.ZX(e);if(n)throw n;let o;r&&(o=await R.d1(s,e.query.indexURL));if(!e.query.rglst)throw"rglst missing";const i=await R.Jy(s,o,t),a=e.query.connheight||50,l={rglst:[]};for(const t of e.query.rglst){const n={chr:t.chr,start:t.start,stop:t.stop,width:t.width,reverse:t.reverse,xoff:t.xoff};l.rglst.push(n);const r=[],c=new Set,u=(i?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;await R.UE({args:[s,u],dir:o,callback:e=>{const n=e.split("\t"),s=Number.parseInt(n[1]);if(s<t.start)return;const o=Number.parseInt(n[2]);if(o>t.stop)return;const i=Number.parseFloat(n[5]);r.push({start:s,stop:o,r2:i}),c.add(s),c.add(o)}}),n.img=Ne(t,r,c,a,e.query.devicePixelRatio||1)}return l}(t,s))}catch(e){n.send({error:e.message||e})}}}(Lr)),Br.get(Jr+"/tabixheader",(async function(e,t){try{const[n,s,r]=R.ZX(e);if(n)throw n;const o=r?await R.d1(s,e.query.indexURL):null,i=await R.ZD(s,o);t.send({lines:i})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.all(Jr+"/snp",(async function(e,t){try{const n=e.query.genome;if(!n)throw"no genome";t.send({results:await Yr(e.query,Lr[n])})}catch(e){return e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/isoformlst",(function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"invalid genome";if(!Array.isArray(e.query.lst))throw".lst missing";const s=[];for(const t of e.query.lst){if(n.genomicNameRegexp.test(t))continue;const e=n.genedb.getjsonbyisoform.all(t);s.push(e.map((e=>{const t=JSON.parse(e.genemodel);return e.isdefault&&(t.isdefault=!0),t})))}t.send({lst:s})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.post(Jr+"/dbdata",(function(e,t){})),Br.get(Jr+"/img",(async function(e,t){const[n,s,r]=R.ZX(e);try{if(n)throw"invalid image file";const e=await m().promises.readFile(s);t.send({src:"data:image/jpeg;base64,"+new Buffer.from(e).toString("base64"),size:T()(s)})}catch(n){t.send({error:n.message||n})}})),Br.post(Jr+"/svmr",(function(e,t){if(e.query.file){const[n,s,r]=R.ZX(e);if(n)return void t.send({error:"illegal file name"});m().readFile(s,"utf8",((e,n)=>{e?t.send({error:"cannot read file"}):t.send({raw:n})}))}else t.send({error:"missing file"})})),Br.post(Jr+"/study",(async function(e,t){try{if(R.lY(e.query.file))throw"invalid file path";const n=g().join(r().tpmasterdir,e.query.file.endsWith(".json")?e.query.file:e.query.file+".json"),s=JSON.parse(await R.b5(n));if(!s.genome)throw"genome missing";const o={};let i=0;for(const e of s.mutationset||[]){const t=D.Dz(s.genome);if(!t)throw"init_bulk_flag() failed";if(s.mutationset.length>1&&(t.tpsetname=e.name?e.name:"set"+ ++i),o[Math.random()]=t,e.snvindel){const n=(await R.b5(g().join(r().tpmasterdir,e.snvindel))).trim().split(/\r?\n/),s=L.parseheader(n[0],t);if(s)throw"snvindel header line error: "+s;for(let e=1;e<n.length;e++)L.parseline(e,n[e],t)}if(e.sv){const n=(await R.b5(g().join(r().tpmasterdir,e.sv))).trim().split(/\r?\n/),s=z.parseheader(n[0],t,!0);if(s)throw"sv header line error: "+s;for(let e=1;e<n.length;e++)z.parseline(e,n[e],t,!0)}if(e.fusion){const n=(await R.b5(g().join(r().tpmasterdir,e.fusion))).trim().split(/\r?\n/),s=z.parseheader(n[0],t,!1);if(s)throw"fusion header line error: "+s;for(let e=1;e<n.length;e++)z.parseline(e,n[e],t,!1)}if(e.svjson){const n=(await R.b5(g().join(r().tpmasterdir,e.svjson))).trim().split(/\r?\n/),[s,o]=B.parseheader(n[0],t);if(s)throw"svjson header line error: "+s;for(let e=1;e<n.length;e++)B.parseline(e,n[e],t,o)}if(e.cnv){const n=(await R.b5(g().join(r().tpmasterdir,e.cnv))).trim().split(/\r?\n/),s=P.parseheader(n[0],t);if(s)throw"cnv header line error: "+s;for(let e=1;e<n.length;e++)P.parseline(e,n[e],t)}if(e.itd){const n=(await R.b5(g().join(r().tpmasterdir,e.itd))).trim().split(/\r?\n/),s=U.parseheader(n[0],t);if(s)throw"itd header line error: "+s;for(let e=1;e<n.length;e++)U.parseline(e,n[e],t)}if(e.deletion){const n=(await R.b5(g().join(r().tpmasterdir,e.deletion))).trim().split(/\r?\n/),s=G.parseheader(n[0],t);if(s)throw"deletion header line error: "+s;for(let e=1;e<n.length;e++)G.parseline(e,n[e],t)}if(e.truncation){const n=(await R.b5(g().join(r().tpmasterdir,e.truncation))).trim().split(/\r?\n/),s=J.parseheader(n[0],t);if(s)throw"Truncation header line error: "+s;for(let e=1;e<n.length;e++)J.parseline(e,n[e],t)}}if(s.annotations){const e=s.annotations.idkey?s.annotations.idkey:"sample";s.annotations.data={};for(const t of s.annotations.files){const n=await R.b5(g().join(r().tpmasterdir,t));Q(n).forEach((t=>{const n=t[e].trim();s.annotations.data[n]||(s.annotations.data[n]=[]),s.annotations.data[n].push(t)}))}}for(const e in o)ee(o[e]);delete s.mutationset,t.send({cohort:s,flagset:o})}catch(e){return void t.send({error:e.message||e})}})),Br.post(Jr+"/textfile",(function(e,t){if(!e.query.file)return t.send({error:"no file"});if(R.lY(e.query.file))return t.send({error:"invalid file name"});const n=g().join(r().tpmasterdir,e.query.file);if(null!=e.query.from){if(!Number.isInteger(e.query.from))return void t.send({error:"invalid value for from"});if(!Number.isInteger(e.query.to))return void t.send({error:"invalid value for to"});const s=[];w()(m().createReadStream(n)).on("end",(()=>{t.send({text:s.join("\n")})})).lines.map(String).skip(e.query.from-1).take(e.query.to).forEach((e=>{s.push(e)}))}else m().readFile(n,{encoding:"utf8"},((e,n)=>{e?t.send({error:"error reading file"}):t.send({text:n})}))})),Br.post(Jr+"/urltextfile",(async function(e,t){const n=e.query.url.replace(r().URL,`http://127.0.0.1:${r().port}`);try{const e=await b()(n);switch(e.statusCode){case 200:return void t.send({text:R.cl(e.body)});case 404:return void t.send({error:"File not found: "+n});default:t.send({error:"unknown status code: "+e.status})}}catch(e){return t.send({error:"Error downloading file: "+n})}})),Br.get(Jr+"/junction",(async function(e,t){try{const[n,s,o]=R.ZX(e);if(n)throw n;if(!e.query.rglst)throw"rglst[] missing";if("string"==typeof e.query.rglst&&(e.query.rglst=JSON.parse(e.query.rglst)),!Array.isArray(e.query.rglst))throw"rglst[] not an array";if(e.query.rglst.reduce(((e,t)=>t.stop-t.start+e),0)>1e6)throw"Zoom in below 1 Mb to show junctions";let i;if(e.query.isrnapeg){if(!r().features.junctionrnapeg)throw"rnapeg not supported on this server";if(o)throw"rnapeg file from url is not supported";i=await async function(e,t){try{await m().promises.stat(t)}catch(e){if("EACCES"==e.code)throw"permission denied for rnapeg file";if("ENOENT"==e.code)throw"rnapeg file not found";throw"cannot access rnapeg file ("+e.code+")"}const n=[];for(const s of e.rglst){const e=await Pn({file:t,chr:s.chr,start:s.start,stop:s.stop});for(const t of e)n.push(t)}return n}(e.query,s)}else{const t=o?await R.d1(s,e.query.indexURL):null;i=await async function(e,t,n){const s=[];for(const r of e.rglst)await R.UE({args:[t,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:e=>{const t=e.split("\t"),n=Number.parseInt(t[1]),o=Number.parseInt(t[2]);if(n>=r.start&&n<=r.stop||o>=r.start&&o<=r.stop){const e={chr:r.chr,start:n,stop:o,type:t[4],rawdata:[]};for(let n=5;n<t.length;n++)e.rawdata.push(Number.parseInt(t[n]));s.push(e)}}});return s}(e.query,s,t)}t.send({lst:i})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/mdsjunction",function(e){return async(t,n)=>{try{const[s,o,i]=await async function(e,t){const n=e.query;if(!n.genome)throw"genome missing";const s=t[n.genome];if(!s)throw"invalid genome";let o={},i={};if(n.iscustom)if(i.listsamples=!0,n.url)i.url=n.url,i.dir=await R.d1(n.url,n.indexURL);else if(n.file)i.file=g().join(r().tpmasterdir,n.file);else{if(!n.file2)throw"no file or url given";i.file2=g().join(r().tpmasterdir,n.file2)}else{if(!s.datasets)throw"genome is not equipped with datasets";if(!n.dslabel)throw"dslabel missing";if(o=s.datasets[n.dslabel],!o)throw"invalid dslabel";if(!o.queries)throw"dataset is not equipped with queries";if(!n.querykey)throw"querykey missing";if(i=o.queries[n.querykey],!i)throw"invalid querykey"}return[n,o,i]}(t,e),a=await async function(e,t,n){if(e.junction)return await async function(e,t,n){const s=e.junction;if(!s.chr||!Number.isInteger(s.start)||!Number.isInteger(s.stop))throw"incomplete/invalid info about querying junction";let r;if(await R.UE({args:[Fn(n),s.chr+":"+s.start+"-"+s.stop],dir:n.dir,callback:o=>{const i=o.split("\t"),a=Number.parseInt(i[1]),l=Number.parseInt(i[2]);if(a==s.start&&l==s.stop)if(n.file2){r=[];for(let e=5;e<i.length;e++){const t=i[e];if(!t)continue;const n=Number.parseInt(t);Number.isNaN(n)||(n<=0||r.push({i:e-5,readcount:n}))}}else{const s=JSON.parse(i[5]);r=$n(s,e,t,n)}}}),0==r.length)throw"no sample passing filters";const o={};if(n.listsamples){const e=r.map((e=>{const t={readcount:e.readcount};return e.anno?t.sample_name=e.anno.sample_name:t.i=e.i,t}));e.sort(((e,t)=>t.readcount-e.readcount)),e.length>100?(o.samples=e.slice(0,100),o.sampletotalnumber=e.length):o.samples=e}else if(n.singlejunctionsummary&&n.singlejunctionsummary.readcountboxplotpercohort){o.readcountboxplotpercohort=[];for(const e of n.singlejunctionsummary.readcountboxplotpercohort.groups){const t=new Map;for(const n of r){if(!n.anno)continue;const s=n.anno[e.key];null!=s&&(t.has(s)||t.set(s,[]),t.get(s).push(n))}if(0==t.size)continue;const n=[...t].sort(((e,t)=>t[1].length-e[1].length)),s=[];for(const[e,t]of n){let n=t[0].readcount,r=n;t.forEach((e=>{n=Math.min(n,e.readcount),r=Math.max(r,e.readcount)}));const o=Dn(t,.05,.25,.5,.75,.95);s.push({label:e,samplecount:t.length,percentile:{p05:o[0],p25:o[1],p50:o[2],p75:o[3],p95:o[4]},minvalue:n,maxvalue:r})}o.readcountboxplotpercohort.push({label:e.label,boxplots:s})}}return o}(e,t,n);if(e.readcountByjBsamples)return await async function(e,t,n){if(!e.junctionAposlst)throw".junctionAposlst[] missing";let s,r=e.junctionB.start,o=e.junctionB.stop;e.junctionAposlst.forEach((e=>{r=Math.min(r,e[0]),o=Math.max(o,e[1])}));let i=[];if(await R.UE({args:[n.file||n.url,e.junctionB.chr+":"+r+"-"+o],dir:n.dir,callback:t=>{const n=t.split("\t"),r=Number.parseInt(n[1]),o=Number.parseInt(n[2]);if(r==e.junctionB.start&&o==e.junctionB.stop)s=JSON.parse(n[5]);else for(const[t,s]of e.junctionAposlst)if(t==r&&s==o){const e=JSON.parse(n[5]);e.start=r,e.stop=o,i.push(e);break}}}),!s)throw"jB not found";if(0==i.length)throw"none of jA is found";const a=$n(s,e,t,n);if(0==a.length)throw"no sample passing filters for junctionB";const l=new Set;a.forEach((e=>l.add(e.i)));const c=[];for(const t of i){const n=[];for(const s of t.samples)l.has(s.i)&&(e.readcountCutoff&&s.readcount<e.readcountCutoff||n.push(s));c.push({start:t.start,stop:t.stop,v:Math.floor(Dn(n,.5))})}return{lst:c}}(e,t,n);const s={};if(e.iscustom&&e.getsamples){const e=await R.ZD(Fn(n),n.dir);if(e[0]){const t=e[0].split("\t");t.length>5&&(s.sample2client=t.slice(5))}}if(!e.rglst)throw"rglst missing";if(n.viewrangeupperlimit){if(e.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=n.viewrangeupperlimit)throw"zoom in under "+common.bplen(n.viewrangeupperlimit)+" to view details"}let r=0,o=0;const i=[],a=new Set,l=new Set;for(const s of e.rglst)await R.UE({args:[Fn(n),s.chr+":"+s.start+"-"+s.stop],dir:n.dir,callback:c=>{const u=c.split("\t"),f=Number.parseInt(u[1]),d=Number.parseInt(u[2]);if(n.file2){u[3];const t=u[4];let n;if("known"==t)n="canonical";else{if("novel"!=t)throw"unknown rnapeg type: "+t;n=Rn}if(e.infoFilter&&e.infoFilter.type&&e.infoFilter.type[n])return;const a={chr:s.chr,start:f,stop:d,info:{type:{lst:[{attrValue:n}]}}},l=[];for(let e=5;e<u.length;e++){const t=u[e];if(!t)continue;const n=Number.parseInt(t);Number.isNaN(n)||(n<=0||(l.push({readcount:n}),r=Math.max(r,n)))}if(0==l.length)return;if(o++,a.sampleCount=l.length,1==a.sampleCount)a.medianReadCount=l[0].readcount;else{const e=Dn(l,.05,.25,.5,.75,.95);a.medianReadCount=e[2],a.readcountBoxplot={percentile:e}}i.push(a)}else{u[3],u[4];if(!(f>=s.start&&f<=s.stop||d>=s.start&&d<=s.stop))return;o++;const c={chr:s.chr,start:f,stop:d,info:{type:{lst:[]}}},p=JSON.parse(u[5]);if(p.sv){c.sv=p.sv;const e=c.chr+"."+c.start+"."+c.sv.mate.chr+"."+c.sv.mate.start;if(a.has(e))return;a.add(e),a.add(c.sv.mate.chr+"."+c.sv.mate.start+"."+c.chr+"."+c.start)}if(p.canonical&&c.info.type.lst.push({attrValue:"canonical"}),p.events)for(const e in p.events){const t=p.events[e];t.__ek=e,c.info.type.lst.push(t)}else p.canonical||c.info.type.lst.push({attrValue:Rn});if(e.infoFilter&&e.infoFilter.type)for(const t of c.info.type.lst)if(e.infoFilter.type[t.attrValue])return;const m=$n(p,e,t,n);if(0==m.length)return;if((p.exonleft||p.exonright||p.exonleftin||p.exonrightin||p.intronleft||p.intronright||p.leftout||p.rightout)&&(c.ongene={},p.exonleft&&(c.ongene.exonleft=p.exonleft),p.exonright&&(c.ongene.exonright=p.exonright),p.exonleftin&&(c.ongene.exonleftin=p.exonleftin),p.exonrightin&&(c.ongene.exonrightin=p.exonrightin),p.intronleft&&(c.ongene.intronleft=p.intronleft),p.intronright&&(c.ongene.intronright=p.intronright),p.leftout&&(c.ongene.leftout=p.leftout),p.rightout&&(c.ongene.rightout=p.rightout)),m.forEach((e=>{l.add(e.i),r=Math.max(r,e.readcount)})),c.sampleCount=m.length,1==c.sampleCount)c.medianReadCount=m[0].readcount;else{const e=Dn(m,.05,.25,.5,.75,.95);c.medianReadCount=e[2],c.readcountBoxplot={percentile:e}}i.push(c)}}});s.lst=i,s.maxreadcount=r,s.junctiontotalnumber=o,l.size;return s}(s,o,i);n.send(a)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Lr)),Br.post(Jr+"/mdscnv",(function(e,t){const[n,s,o,i]=no(e.query);if(n)return t.send({error:n});if(!e.query.rglst)return t.send({error:"rglst missing"});if(!e.query.gain)return t.send({error:".gain missing"});if(!e.query.loss)return t.send({error:".loss missing"});if(i.viewrangeupperlimit){if(e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=i.viewrangeupperlimit)return t.send({error:"zoom in under "+F.bplen(i.viewrangeupperlimit)+" to view details"})}if(e.query.permanentHierarchy){const n=function(e,t){if(!t.cohort)return".cohort missing from ds";if(!t.cohort.hierarchies)return".hierarchies missing from ds.cohort";if(!t.cohort.hierarchies.lst)return".hierarchies.lst[] missing from ds.cohort";const n=t.cohort.hierarchies.lst.find((t=>t.name==e.permanentHierarchy.hierarchyname));if(!n)return"unknown hierarchy "+e.permanentHierarchy.hierarchyname;if(!n.levels)return".levels[] missing in hierarchy "+n.name;const s=n.levels[e.permanentHierarchy.levelidx];if(!s)return"level not found by array idx "+e.permanentHierarchy.levelidx;const r=s.k;return delete e.cohortHiddenAttr,e.cohortOnlyAttr={},e.cohortOnlyAttr[r]={},e.cohortOnlyAttr[r][e.permanentHierarchy.valuekey]=1,null}(e.query,o);if(n)return t.send({error:"permanentHierarchy error: "+n})}const a=[],l={count:0,samples:new Set},c={count:0,samples:new Set};for(const t of e.query.rglst){const n=new Promise(((n,s)=>{const a=(0,q.spawn)(Pr,[i.file?g().join(r().tpmasterdir,i.file):i.url,t.chr+":"+t.start+"-"+t.stop],{cwd:i.usedir}),u=O().createInterface({input:a.stdout}),f=(t.stop-t.start)/t.width,d=[];for(let e=0;e<t.width;e++)d.push({positive:0,negative:0});u.on("line",(n=>{const s=n.split("\t"),r=Number.parseInt(s[1]),i=Number.parseInt(s[2]);if(e.query.bplengthUpperLimit&&i-r>e.query.bplengthUpperLimit)return;const a=JSON.parse(s[3]);if(e.query.valueCutoff&&Math.abs(a.value)<e.query.valueCutoff)return;if(a.sample&&o.cohort&&o.cohort.annotation){const t=o.cohort.annotation[a.sample];if(!t)return;if(e.query.cohortOnlyAttr&&o.cohort&&o.cohort.annotation){let n=!1;for(const s in e.query.cohortOnlyAttr){const r=t[s];if(r&&e.query.cohortOnlyAttr[s][r]){n=!0;break}}if(!n)return}if(e.query.cohortHiddenAttr&&o.cohort.attributes){let n=!1;for(const s in e.query.cohortHiddenAttr){o.cohort.attributes.lst.find((e=>e.key==s)).isNumeric;const r=t[s];if(r){if(e.query.cohortHiddenAttr[s][r]){n=!0;break}}else if(e.query.cohortHiddenAttr[s][zr]){n=!0;break}}if(n)return}}a.value>0?(l.count++,l.samples.add(a.sample)):a.value<0&&(c.count++,c.samples.add(a.sample));const u=Math.max(t.start,r),p=Math.min(t.stop,i);let m,h;t.reverse?(m=Math.floor((t.stop-p)/f),h=Math.floor((t.stop-u)/f)):(m=Math.floor((u-t.start)/f),h=Math.floor((p-t.start)/f));for(let e=m;e<h;e++)a.value>0?d[e].positive++:a.value<0&&d[e].negative++}));const p=[];a.stderr.on("data",(e=>p.push(e))),a.on("close",(e=>{const t=p.join("");!t||$r(t)?n(d):s(t)}))}));a.push(n)}Promise.all(a).then((n=>{const s=e.query.rglst.reduce(((t,n)=>t+n.width+e.query.regionspace),0)-e.query.regionspace,r=(0,N.createCanvas)(s,e.query.gain.barheight+e.query.loss.barheight),a=r.getContext("2d"),u={gain:{count:l.count,samplenumber:l.samples.size},loss:{count:c.count,samplenumber:c.samples.size},maxvalue:0};if(l.count+c.count==0)return a.font="15px Arial",a.fillStyle="#aaa",a.textAlign="center",a.textBaseline="middle",a.fillText("No data in view range",s/2,e.query.gain.barheight),u.src=r.toDataURL(),void t.send(u);for(const e of n)for(const t of e)u.maxvalue=Math.max(u.maxvalue,t.positive,t.negative);const f=e.query.maxvalue||u.maxvalue;let d=0;for(const t of n){for(const n of t){if(n.positive){a.fillStyle=e.query.gain.color||"#67a9cf";const t=Math.ceil(e.query.gain.barheight*Math.min(f,n.positive)/f),s=e.query.gain.barheight-t;a.fillRect(d,s,1,t)}if(n.negative){a.fillStyle=e.query.loss.color||"#ef8a62";const t=Math.ceil(e.query.loss.barheight*Math.min(f,n.negative)/f),s=e.query.gain.barheight;a.fillRect(d,s,1,t)}d++}d+=e.query.regionspace}if(u.src=r.toDataURL(),l.samples.size||c.samples.size){const e=new Set([...l.samples,...c.samples]),[t,n]=function(e,t,n){if(!e.cohort||!e.cohort.annotation||0==n.length)return[null,null];const s=[];for(const t of n){const n=e.cohort.annotation[t];n&&s.push(n)}if(0==s.length)return[null,null];let r,o;if(e.cohort.attributes){r=[];for(const n of e.cohort.attributes.lst){const o={label:n.label,key:n.key};if(n.isNumeric){o.isNumeric=!0;continue}const i=new Map;let a=0;for(const t of s){const s=t[n.key];null!=s?(i.has(s)||i.set(s,new Set),i.get(s).add(t[e.cohort.samplenamekey])):a++}const l=[...i];a&&l.push([zr,a]),l.sort(((e,t)=>t[1]-e[1])),o.values=[];for(const[e,s]of l){const r={name:e,sampleset:s};if(n.values&&n.values[e])for(const t in n.values[e])r[t]=n.values[e][t];t.attributeSummary&&t.attributeSummary[n.key]&&t.attributeSummary[n.key][e]&&(r.totalCount=t.attributeSummary[n.key][e]),o.values.push(r)}r.push(o)}}if(e.cohort.hierarchies){o={};for(const n of e.cohort.hierarchies.lst){const r=me()((0,S.N)(s,n.levels));r.sum((e=>e.value));const i=[];r.eachBefore((s=>{const r={id:s.data.id,name:s.data.name,label:s.data.full,depth:s.depth};if(s.data.lst){r.sampleset=new Set;for(const t of s.data.lst)r.sampleset.add(t[e.cohort.samplenamekey])}s.children||(r.isleaf=1),t.hierarchySummary&&t.hierarchySummary[n.name]&&(r.totalCount=t.hierarchySummary[n.name][s.id]),i.push(r)})),o[n.name]=i}}return[r,o]}(o,i,[...e]);if(t){for(const e of t)for(const t of e.values){t.gain=0,t.loss=0;for(const e of t.sampleset)l.samples.has(e)&&t.gain++,c.samples.has(e)&&t.loss++;delete t.sampleset}u.attributeSummary=t}if(n){for(const e in n)for(const t of n[e])if(t.sampleset){t.gain=0,t.loss=0;for(const e of t.sampleset)l.samples.has(e)&&t.gain++,c.samples.has(e)&&t.loss++}u.hierarchySummary=n}}t.send(u)})).catch((e=>{t.send({error:e}),e.stack&&console.error(e.stack)}))})),Br.post(Jr+"/mdssvcnv",(async function(e,t){let n,s,o,i,a,l,c,u,f;if(e.query.iscustom){if(n=Lr[e.query.genome],!n)return t.send({error:"invalid genome"});if(s={},o={iscustom:1,file:e.query.file,url:e.query.url,indexURL:e.query.indexURL,allow_getallsamples:!0},e.query.checkexpressionrank){if(!e.query.checkexpressionrank.file&&!e.query.checkexpressionrank.url)return t.send({error:"no file or url for checkexpressionrank"});o.checkexpressionrank={file:e.query.checkexpressionrank.file,url:e.query.checkexpressionrank.url,indexURL:e.query.checkexpressionrank.indexURL}}if(e.query.checkvcf){let n;try{n=JSON.parse(e.query.checkvcf)}catch(e){return t.send({error:"invalid JSON for VCF object"})}if(!n.file&&!n.url)return t.send({error:"no file or url for custom VCF track"});n.type=F.mdsvcftype.vcf,o.checkvcf={info:n.info,tracks:[n]}}if(e.query.checkrnabam){if(!e.query.checkrnabam.samples)return t.send({error:"samples{} missing from checkrnabam"});let n=0;for(const t in e.query.checkrnabam.samples)n++;if(n>13)return t.send({error:"no more than 13 BAM files allowed"});const s=uo(e.query.checkrnabam);if(s)return t.send({error:s});o.checkrnabam=e.query.checkrnabam}}else{if(n=Lr[e.query.genome],!n)return t.send({error:"invalid genome"});if(!n.datasets)return t.send({error:"genome is not equipped with datasets"});if(s=n.datasets[e.query.dslabel],!s)return t.send({error:"invalid dslabel"});if(e.query.getsample4disco)return function(e,t,n,s){if(e.query.iscustom)return t.send({error:"not for custom track"});if(!s.singlesamplemutationjson)return t.send({error:"singlesamplemutationjson not available for this dataset"});const o=e.query.getsample4disco,i=s.singlesamplemutationjson.samples[o];if(!i)return t.send({error:"no data"});const a=g().join(r().tpmasterdir,i);m().readFile(a,{encoding:"utf8"},((e,n)=>{if(e)return t.send({error:"error getting data for this sample"});t.send({text:n})}))}(e,t,0,s);if(e.query.gettrack4singlesample)return function(e,t,n){const s=e.query.gettrack4singlesample;if(e.query.iscustom)return t.send({error:"no server-side config available for custom track"});if(!n.sampleAssayTrack)return t.send({});return t.send({tracks:n.sampleAssayTrack.samples.get(s)})}(e,t,s);if(e.query.findsamplename)return function(e,t,n){if(e.query.iscustom)return t.send({error:"cannot search sample by name in custom track"});const s=e.query.findsamplename.toLowerCase(),r=[];if(!n.cohort.__samplelst){n.cohort.__samplelst=[];for(const e in n.cohort.annotation)n.cohort.__samplelst.push({name:e,low:e.toLowerCase()})}o(n.cohort.__samplelst);for(const e in n.queries){const t=n.queries[e];if(t.type==F.tkt.mdssvcnv&&t.groupsamplebyattr)for(const e of r){const s=n.cohort.annotation[e.name];if(!s)continue;const r=[];for(const e of t.groupsamplebyattr.attrlst){const t=s[e.k];t&&r.push({k:e.k,kvalue:t})}r.length&&(e.attributes=r,e.grouplabel=r.map((e=>e.kvalue)).join(t.groupsamplebyattr.attrnamespacer))}}if(n.cohort&&n.cohort.sampleAttribute&&n.cohort.sampleAttribute.attributes&&n.cohort.annotation)for(const e of r){const t=n.cohort.annotation[e.name];if(!t)continue;const s=[];for(const e in n.cohort.sampleAttribute.attributes){if(n.cohort.sampleAttribute.attributes[e].clientnoshow)continue;const r=t[e];null!=r&&s.push({k:e,v:r})}s.length&&(e.attr=s)}if(n.sampleAssayTrack)for(const e of r){const t=n.sampleAssayTrack.samples.get(e.name);t&&(e.num_assay_tracks=t.length)}if(n.cohort&&n.cohort.mutation_signature)for(const e in n.cohort.mutation_signature.sets){const t=n.cohort.mutation_signature.sets[e];if(t.samples)for(const e of r)t.samples.map.has(e.name)&&(e.mutation_signature=1)}if(n.singlesamplemutationjson)for(const e of r)n.singlesamplemutationjson.samples[e.name]&&(e.disco=1);return t.send({result:r});function o(e){for(const t of e){if(r.length>10)return;-1!=t.low.indexOf(s)&&(r.find((e=>e.name==t.name))||r.push(t))}}}(e,t,s);if(e.query.assaymap)return async function(e,t,n){try{if(!n.assayAvailability)throw"assay availability not enabled for this dataset";const s=new Set(e.query.skip_termids||[]),r=new Map;for(const t in n.cohort.annotation){if(e.query.key){if(n.cohort.annotation[t][e.query.key]!=e.query.value)continue}r.set(t,new Map)}for(const[e,t]of r){const r=n.assayAvailability.samples.get(e);if(r)for(const e of n.assayAvailability.assays)s.has(e.id)||r[e.id]&&t.set(e.id,"yes")}for(const e of r.keys())0==r.get(e).size&&r.delete(e);const o={};o.totalsample=r.size,o.terms=_r({sample2term:r,terms:n.assayAvailability.assays,config:{termidorder:e.query.termidorder}}),t.send(o)}catch(e){t.send({error:e.message||e})}}(e,t,s);if(!s.queries)return t.send({error:"dataset is not equipped with queries"});if(o=s.queries[e.query.querykey],!o)return t.send({error:"invalid querykey"})}if(e.query.getexpression4gene)return async function(e,t,n,s,o){try{const n=e.query.getexpression4gene;if(!n.chr)throw"chr missing";if(!Number.isFinite(n.start))throw"invalid start pos";if(!Number.isFinite(n.stop))throw"invalid stop pos";if(!n.name)throw"unknown gene name";if(o.checkrnabam){const s=Lr[e.query.genome],r=s.tracks.find((e=>e.__isgene)),i=(await ho(s,r,n.chr,n.start,n.stop)).get(n.name);if(!i)throw"no gene matching with "+n.name;const a={};await so(new Map([[n.name,i]]),n.chr,n.start,n.stop,o,a);const l={};for(const e of a.checkrnabam)if(e.genes){const t=e.genes.find((e=>e.gene==n.name));t&&(l[e.sample]=t)}return void t.send({sample2rnabam:l})}let i;if(o.iscustom?i=o.checkexpressionrank:o.expressionrank_querykey&&(i=s.queries[o.expressionrank_querykey]),!i)throw"missing expression data source";const a=i.file?null:await R.d1(i.url,i.indexURL),l=[];await R.UE({args:[i.file?g().join(r().tpmasterdir,i.file):i.url,n.chr+":"+n.start+"-"+n.stop],dir:a,callback:e=>{const t=e.split("\t");let s;try{s=JSON.parse(t[3])}catch(e){reject("invalid json from expression data")}s.sample&&s.gene&&Number.isFinite(s.value)&&(delete s.outlier,s.gene.toLowerCase()==n.name.toLowerCase()&&l.push(s))}});const c=function(e,t,n){const s={};if(e&&e.cohort&&e.cohort.annotation&&t.groupsamplebyattr&&t.groupsamplebyattr.attrlst){const r=new Map;for(const s of n){const n=e.cohort.annotation[s.sample];if(!n)continue;const o=[];for(const e of t.groupsamplebyattr.attrlst)o.push(n[e.k]);const i=o.join(",");r.has(i)||r.set(i,[]),r.get(i).push(s)}for(const e of r.values()){e.sort(((e,t)=>e.value-t.value));for(const t of e)t.rank=bo(t.value,e),s[t.sample]=t}}else{n.sort(((e,t)=>e.value-t.value));for(const e of n)e.rank=bo(e.value,n),s[e.sample]=e}return s}(s,o,l);t.send({sample2rank:c})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}}(e,t,0,s,o);if(e.query.ifsamplehasvcf)return function(e,t,n,s,r){if(e.query.iscustom)return t.send({no:1});if(!r.vcf_querykey)return t.send({yes:1});const o=s.queries[r.vcf_querykey];if(!o)return t.send({error:"vcf query missing"});t.send(o.singlesamples?{yes:1}:{no:1})}(e,t,0,s,o);if(!e.query.rglst)return t.send({error:"rglst missing"});if(o.viewrangeupperlimit){if(e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=o.viewrangeupperlimit)return t.send({error:"zoom in under "+F.bplen(o.viewrangeupperlimit)+" to view details"})}e.query.hiddendt&&(i=new Set(e.query.hiddendt));if(e.query.hiddenmattr){a={};for(const t in e.query.hiddenmattr)a[t]=new Set(e.query.hiddenmattr[t])}if(e.query.filteralleleattr){l={};for(const t in e.query.filteralleleattr){const n=e.query.filteralleleattr[t];n.cutoffvalue,l[t]=n}}if(e.query.filterlocusattr){c={};for(const t in e.query.filterlocusattr){const n=e.query.filterlocusattr[t];n.cutoffvalue,c[t]=n}}if(e.query.sampleset){const t=new Set,n=new Map;for(const s of e.query.sampleset)for(const e of s.samples)t.add(e),n.set(e,s.name);t.size&&(u={set:t,sample2group:n})}if(e.query.hiddensampleattr){f={};for(const t in e.query.hiddensampleattr)f[t]=new Set(e.query.hiddensampleattr[t])}if(o.url)try{o.dir=await R.d1(o.url,o.indexURL)}catch(e){return t.send({error:"svcnv file index url error"})}const d=await function(e,t,n,s,o,i,a){if(!t.file&&!t.url)return[];const l=[];for(const c of n.query.rglst){const u=new Promise(((l,u)=>{const f=[],d=(0,q.spawn)(Pr,[t.file?g().join(r().tpmasterdir,t.file):t.url,c.chr+":"+c.start+"-"+c.stop],{cwd:t.dir});O().createInterface({input:d.stdout}).on("line",(t=>{const r=t.split("\t"),l=Number.parseInt(r[1]),c=Number.parseInt(r[2]);let u;try{u=JSON.parse(r[3])}catch(e){return}if(!(null==u.dt||s&&s.has(u.dt))){if(u.dt==F.dtloh){if(u.segmean&&n.query.segmeanValueCutoff&&u.segmean<n.query.segmeanValueCutoff)return;if(n.query.lohLengthUpperLimit&&c-l>n.query.lohLengthUpperLimit)return;u.chr=r[0],u.start=l,u.stop=c}else if(u.dt==F.dtfusionrna||u.dt==F.dtsv)u._chr=r[0],u._pos=l,u.chrA?(u.chrB=r[0],u.posB=l):(u.chrA=r[0],u.posA=l);else if(u.dt==F.dtcnv){if(n.query.hide_cnvloss&&u.value<0)return;if(n.query.hide_cnvgain&&u.value>0)return;if(n.query.valueCutoff&&Math.abs(u.value)<n.query.valueCutoff)return;if(n.query.bplengthUpperLimit&&c-l>n.query.bplengthUpperLimit)return;u.chr=r[0],u.start=l,u.stop=c}else{if(u.dt!=F.dtitd)return void console.error("unknown dt from svcnv file: "+u.dt);u.chr=r[0],u.start=l,u.stop=c}if(n.query.singlesample){if(u.sample!=n.query.singlesample)return}else if(a){if(!a.set.has(u.sample))return}else if(u.sample&&e.cohort&&e.cohort.annotation){const t=e.cohort.annotation[u.sample];if(!t)return;if(o)for(const e in o){const n=t[e];if(o[e].has(n))return}}if(i)for(const e in i){let t=u.mattr?u.mattr[e]:void 0;if(null==t&&(t=F.not_annotated),i[e].has(t))return}f.push(u)}}));const p=[];d.stderr.on("data",(e=>p.push(e))),d.on("close",(e=>{const t=p.join("");!t||$r(t)?l(f):u(t)}))}));l.push(u)}return Promise.all(l)}(s,o,e,i,f,a,u),[p,h]=await function(e,t,n,s){if(n.query.singlesample)return[];let o;if(t.iscustom?o=t.checkexpressionrank:t.expressionrank_querykey&&e.queries[t.expressionrank_querykey]&&(o=e.queries[t.expressionrank_querykey]),!o)return[];let i=o.viewrangeupperlimit;if(!i&&t.iscustom&&(i=5e6),i&&n.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=i)return[i];return Promise.resolve().then((()=>o.file?"":(0,R.d1)(o.url,o.indexURL))).then((e=>{const t=new Map,s=[];for(const i of n.query.rglst){const n=new Promise(((n,s)=>{const a=(0,q.spawn)(r().tabix,[o.file?g().join(r().tpmasterdir,o.file):o.url,i.chr+":"+i.start+"-"+i.stop],{cwd:e});O().createInterface({input:a.stdout}).on("line",(e=>{const n=e.split("\t");let s;try{s=JSON.parse(n[3])}catch(e){return}s.gene&&s.sample&&Number.isFinite(s.value)&&(t.has(s.gene)||t.set(s.gene,{chr:n[0],start:Number.parseInt(n[1]),stop:Number.parseInt(n[2]),samples:new Map}),t.get(s.gene).samples.set(s.sample,{value:s.value,ase:s.ase}))}));const l=[];a.stderr.on("data",(e=>l.push(e))),a.on("close",(e=>{const t=l.join("");!t||(0,R.sI)(t)?n():s(t)}))}));s.push(n)}return Promise.all(s).then((()=>[!1,t]))}))}(s,o,e),[y,b]=await async function(e,t,n,s,o,i,a,l,c,u){let f;n.iscustom?f=n.checkvcf:n.vcf_querykey&&t.queries[n.vcf_querykey]&&(f=t.queries[n.vcf_querykey]);if(!f)return[null,null];if(s.query.singlesample&&f.singlesamples){const n=f.singlesamples.samples[s.query.singlesample];if(n){const i={file:g().join(r().tpmasterdir,n)};try{await m().promises.stat(i.file)}catch(e){return[null,null]}const a=await yo(i.file),[u,f,d,p]=$.e(a);if(p)throw p;return i.info=u,i.format=f,i.samples=d,i.nochr=await R.Jy(i.file,null,e),function(e,t,n,s,r,o,i){const a=[],l=[];for(const r of e.query.rglst){const c=new Promise(((l,c)=>{const u=(0,q.spawn)(Pr,[n.file,(n.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop]);O().createInterface({input:u.stdout}).on("line",(r=>{const[l,c,u]=$.S(r,n);for(const n of c){if(!n.sampledata)continue;const r=n.sampledata.find((t=>t.sampleobj.name==e.query.singlesample));if(r){if(delete r.allele2readcount,n.sampledata=[r],s){let e=!1;for(const t in s){const r=n.altinfo[t];if(null==r){e=!0;break}const o=s[t];if(null!=o.cutoffvalue){if(!Number.isFinite(r)){e=!0;break}if(o.keeplowerthan){if(r>o.cutoffvalue){e=!0;break}}else if(r<o.cutoffvalue){e=!0;break}}}if(e)continue}if(!r.gtallref){if(r.__gtalleles){if(-1==r.__gtalleles.indexOf(n.alt))continue;delete r.__gtalleles}if(o){const e=[];for(const t of n.sampledata){let n=!0;for(const e in o){let s=t[e];if(null==s&&(s=F.not_annotated),o[e].has(s)){n=!1;break}}n&&e.push(t)}if(0==e.length)continue;n.sampledata=e}if(i&&t.cohort&&t.cohort.annotation){const e=[];for(const s of n.sampledata){const n=t.cohort.annotation[s.sampleobj.name];if(!n)continue;let r=!0;for(const e in i){const t=n[e];if(i[e].has(t)){r=!1;break}}r&&e.push(s)}if(0==e.length)continue;n.sampledata=e}delete n._m,delete n.vcf_ID,delete n.name,n.dt=F.dtsnvindel,a.push(n)}}}}));const f=[];u.stderr.on("data",(e=>f.push(e))),u.on("close",(e=>{const t=f.join("");!t||$r(t)?l():c(t)}))}));l.push(c)}return Promise.all(l).then((()=>[null,a]))}(s,t,i,o,0,l,c)}}let d=f.viewrangeupperlimit;!d&&n.iscustom&&(d=Dr.customMdsSingleSampleVcfNoRangeLimit?0:2e6);s.query.singlesample&&(d*=5);if(d){if(s.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>=d)return[d,null]}const p=[];for(const e of f.tracks){const n=Promise.resolve().then((()=>e.file?"":R.d1(e.url,e.indexURL))).then((n=>{e.dir=n;const a=[],d=[];for(const p of s.query.rglst){const m=new Promise(((d,m)=>{const h=(0,q.spawn)(Pr,[e.file?g().join(r().tpmasterdir,e.file):e.url,(e.nochr?p.chr.replace("chr",""):p.chr)+":"+p.start+"-"+p.stop],{cwd:n});O().createInterface({input:h.stdout}).on("line",(n=>{if(e.type==F.mdsvcftype.vcf){const[r,d,p]=$.S(n,{nochr:e.nochr,samples:e.samples,info:f.info,format:e.format});for(const e of d)if(e.sampledata){if(o){let t=!1;for(const n in o){const s=e.altinfo[n];if(null==s){t=!0;break}const r=o[n];if(null!=r.cutoffvalue){if(!Number.isFinite(s)){t=!0;break}if(r.keeplowerthan){if(s>r.cutoffvalue){t=!0;break}}else if(s<r.cutoffvalue){t=!0;break}}else if(r.includes(s)){t=!0;break}}if(t)continue}if(i){let t=!1;for(const n in i){const s=e.info[n];if(null==s){t=!0;break}let r=s;if(Array.isArray(s)&&(r=s[0],"."==r)){t=!0;break}const o=i[n];if(null!=o.cutoffvalue){if(!Number.isFinite(r)){t=!0;break}if(o.keeplowerthan){if(r>o.cutoffvalue){t=!0;break}}else if(r<o.cutoffvalue){t=!0;break}}else if(o.includes(r)){t=!0;break}}if(t)continue}{const t=[];for(const n of e.sampledata)if(!n.gtallref){if(n.__gtalleles){if(-1==n.__gtalleles.indexOf(e.alt))continue;delete n.__gtalleles}t.push(n)}if(0==t.length)continue;e.sampledata=t}if(s.query.singlesample){let t=null;for(const n of e.sampledata)if(n.sampleobj.name==s.query.singlesample){t=n;break}if(!t)continue;e.sampledata=[t]}else if(u){const t=e.sampledata.filter((e=>u.set.has(e.sampleobj.name)));if(!t.length)continue;e.sampledata=t}if(l){const t=[];for(const n of e.sampledata){let e=!0;for(const t in l){let s=n[t];if(null==s&&(s=F.not_annotated),l[t].has(s)){e=!1;break}}e&&t.push(n)}if(0==t.length)continue;e.sampledata=t}if(c&&t.cohort&&t.cohort.annotation){const n=[];for(const s of e.sampledata){const e=t.cohort.annotation[s.sampleobj.name];if(!e)continue;let r=!0;for(const t in c){const n=e[t];if(c[t].has(n)){r=!1;break}}r&&n.push(s)}if(0==n.length)continue;e.sampledata=n}for(const t of e.sampledata)delete t.allele2readcount;delete e._m,delete e.vcf_ID,delete e.name,e.dt=F.dtsnvindel,a.push(e)}}else console.error('unknown "type" from a vcf file')}));const y=[];h.stderr.on("data",(e=>y.push(e))),h.on("close",(e=>{const t=y.join("");!t||$r(t)?d():m(t)}))}));d.push(m)}return Promise.all(d).then((()=>a))}));p.push(n)}return Promise.all(p).then((e=>{const t=[];for(const n of e)for(const e of n)if(e.dt!=F.dtsnvindel)console.error("unknown dt: "+e.dt);else{if(!e.sampledata)continue;let n=!0;for(const s of t)if(e.chr==s.chr&&e.pos==s.pos&&e.ref==s.ref&&e.alt==s.alt){for(const t of e.sampledata)s.sampledata.push(t);n=!1;break}n&&t.push(e)}return t.sort(((e,t)=>e.pos-t.pos)),[null,t]}))}(n,s,o,e,l,c,0,a,f,u),v=function(e){const t=new Map;for(const n of e)for(const e of n){if(!e.sample)continue;const n=e.sample;t.has(n)||t.set(n,[]),e._chr?t.get(n).push(e):(delete e.sample,delete e.sampletype,t.get(n).push(e))}return t}(d);if(e.query.singlesample){const n={lst:v.get(e.query.singlesample)};return y?n.vcfrangelimit=y:n.data_vcf=b,void t.send(n)}const w={samplegroups:ao(s,o,d,b,v,u),vcfrangelimit:y,data_vcf:b};e.query.getallsamples&&o.allow_getallsamples&&(w.getallsamples=!0);o.checkrnabam?await async function(e,t,n,s){if(!n.checkvcf)return;if(e.stop-e.start>=5e5)return void(s.expressionrangelimit=5e5);const r=t.tracks.find((e=>e.__isgene)),o=await ho(t,r,e.chr,e.start,e.stop);let i,a=null;for(const e of o.values())null==a?(a=e.start,i=e.stop):(a=Math.min(a,e.start),i=Math.max(i,e.stop));await so(o,e.chr,a,i,n,s)}(e.query.rglst[0],n,o,w):function(e,t,n,s){if(n)return void(e.expressionrangelimit=n);if(s){e.gene2coord={};for(const[t,n]of s)e.gene2coord[t]={chr:n.chr,start:n.start,stop:n.stop};if(0==e.samplegroups.length)return;if(e.getallsamples){const t=new Set(e.samplegroups[0].samples.map((e=>e.samplename))),n=new Set;for(const[e,r]of s)for(const e of r.samples.keys())t.has(e)||n.add(e);for(const t of n)e.samplegroups[0].samples.push({samplename:t,items:[]})}for(const n of e.samplegroups){const e=new Map;for(const[r,o]of s){e.set(r,[]);for(const[s,i]of o.samples)if(n.attributes&&t.cohort&&t.cohort.annotation){const o=t.cohort.annotation[s];if(!o)continue;let a=!0;for(const e of n.attributes)if(o[e.k]!=e.kvalue){a=!1;break}a&&e.get(r).push(i)}else e.get(r).push(i)}for(const[t,n]of e)n.sort(((e,t)=>e.value-t.value));for(const t of n.samples){t.expressionrank={};for(const[n,r]of e){const e=s.get(n).samples.get(t.samplename);if(null==e)continue;const o=bo(e.value,r);t.expressionrank[n]={rank:o};for(const s in e)t.expressionrank[n][s]=e[s]}}}}}(w,s,p,h);(function(e,t){if(e.cohort&&e.cohort.sampleAttribute&&e.cohort.sampleAttribute.attributes&&e.cohort.annotation){t.sampleannotation={};const n=[];for(const t in e.cohort.sampleAttribute.attributes){e.cohort.sampleAttribute.attributes[t].clientnoshow||n.push(t)}for(const s of t.samplegroups)for(const r of s.samples){const s=e.cohort.annotation[r.samplename];if(s){const e={};let o=!1;for(const t of n){const n=s[t];null!=n&&(o=!0,e[t]=n)}o&&(t.sampleannotation[r.samplename]=e)}}}})(s,w),t.send(w)})),Br.post(Jr+"/mdsgenecount",(async function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"invalid genome";if(!n.datasets)throw"no datasets from genome";const s=n.datasets[e.query.dslabel];if(!s)throw"invalid dataset";if(!s.gene2mutcount)throw"not supported on this dataset";if(!e.query.samples)throw".samples missing";let r,o;r=e.query.selectedMutTypes?e.query.selectedMutTypes.join("+"):"total",o=e.query.nGenes?e.query.nGenes:15;const i=`WITH\n\tfiltered AS (\n\t\tSELECT gene, ${r} AS total FROM genecount\n\t\tWHERE sample IN (${JSON.stringify(e.query.samples).replace(/[[\]\"]/g,"").split(",").map((e=>"'"+e+"'")).join(",")})\n\t)\n\tSELECT gene, SUM(total) AS count\n\tFROM filtered\n\tGROUP BY gene\n\tORDER BY count DESC\n\tLIMIT ${o}`,a=s.gene2mutcount.db.prepare(i).all(),l=[];for(const e of a){const t=n.genedb.getCoordByGene.get(e.gene);t&&(t.gene=e.gene,t.count=e.count,delete t.name,l.push(t))}t.send({genes:l})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.post(Jr+"/mds2",function(e){return async(t,n)=>{const s=t.query;try{const t=e[s.genome],r=await async function(e,t){if(!t)throw"invalid genome";if(e.dslabel){const n=t.datasets[e.dslabel];if(!n)throw"invalid dslabel";if(!n.track)throw"no mds2 track found for dataset";return n}const n={iscustom:1,track:{}};e.vcf&&(n.track.vcf=e.vcf,await R._H(n.track.vcf,t));e.ld;return n}(s,t);if(s.trigger_overlayld)return await async function(e,t,n){if(!e.ldtkname)throw".ldtkname missing";const s=t.track.ld.tracks.find((t=>t.name==e.ldtkname));if(!s)throw"ld tk not found by name: "+e.ldtkname;const r=e.m.ref+"."+e.m.alt,o=(s.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+e.m.pos+"-"+(e.m.pos+1),i=[];await R.UE({args:[s.file,o],dir:s.dir,callback:t=>{const n=t.split("\t"),s=Number.parseInt(n[1]),o=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);s==e.m.pos&&a==r?i.push({pos:o,alleles:l,r2:c}):o==e.m.pos&&l==r&&i.push({pos:s,alleles:a,r2:c})}}),n.send({lst:i})}(s,r,n);s.hidden_mclass&&(s.hidden_mclass=new Set(s.hidden_mclass));const o={mclass2count:{}};if(s.info_fields){o.info_fields={};for(const e of s.info_fields)if(e.iscategorical)o.info_fields[e.key]={value2count:{}};else if(e.isnumerical)o.info_fields[e.key]={filteredcount:0};else{if(!e.isflag)throw"unknown info type";o.info_fields[e.key]={count_yes:0,count_no:0}}}if(s.trigger_mafcovplot&&await async function(e,t,n,s){try{if(!n.track)throw"ds.track missing";const t=n.track.vcf;if(!t)throw"ds.track.vcf missing";if(n.iscustom)t.plot_mafcov={show_samplename:1};else if(!t.plot_mafcov)throw"maf-cov plot is not supported on this track";if(!e.m)throw".m{} missing";if(!t.AD)throw"vcf.AD{} missing";const r=(t.AD.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+(e.m.pos+1)+"-"+(e.m.pos+1),o=t.AD.chr2bcffile[e.m.chr];if(!o)throw"chr not in tk.AD.chr2bcffile";let i;if(await R.UE({isbcf:!0,args:["query","-r",r,"-f",ur,o],dir:t.AD.dir,callback:n=>{const[s,r,o]=$.S(n,t.AD);for(const t of r)if(t.pos==e.m.pos&&t.ref==e.m.ref&&t.alt==e.m.alt)return void(i=t)}}),!i)throw"variant not found";if(s.plotgroups=function(e,t,n){const s=[],r={name:"?",lst:[]};for(const s of e.sampledata){const o=s.AD[e.ref]||0,i=s.AD[e.alt]||0,a=o+i,l={mut:i,total:o+i,maf:0==a?0:i/a};t.plot_mafcov.show_samplename&&(l.sampleobj={name:n.cohort.termdb.q.id2sampleName(s.sampleobj.name)}),r.lst.push(l)}return s.push(r),s}(i,t,n),e.overlay_term){const t=await ys.g5({ds:n,term1_id:e.overlay_term,term1_q:e.overlay_term_q}),r=new Map;for(const e of t.lst)r.set(e.sample,e.key1);const o=(0,ar.Z)(lr),i=new Map;let a=0;for(const e of s.plotgroups)for(const t of e.lst){const e=r.get(t.sampleobj.name);if(e){const n=o(e);t.sampleobj.color=n,i.has(e)||i.set(e,{count:0,color:n,label:e}),i.get(e).count++}else a++,t.sampleobj.color=cr}if(s.categories=[],t.CTE1&&t.CTE1.name2bin)for(const e of t.CTE1.name2bin.keys()){const t=i.get(e);t&&s.categories.push(t)}else for(const[e,t]of i)s.categories.push(t);a&&s.categories.push({count:a,color:cr,label:"Unannotated"})}}catch(e){s.error=e.message||e,e.stack&&console.log(e.stack)}}(s,0,r,o),s.trigger_vcfbyrange&&(await nr(s,0,r,o),s.trigger_ld)){o.__mposset=new Set;for(const e of o.vcf.rglst)if(e.variants)for(const t of e.variants)o.__mposset.add(t.pos)}if(s.trigger_ld){o.ld={};for(const e of s.trigger_ld.tracks)await fr(e,s,0,r,o);delete o.__mposset}s.trigger_ssid_onevcfm&&await async function(e,t,n,s){if(n.iscustom)throw"custom ds not allowed";const r=n.track.vcf;if(!r)throw"ds.track.vcf missing";if(!e.m)throw"q.m missing";const o=(r.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+(e.m.pos+1)+"-"+(e.m.pos+1),i=r.chr2bcffile[e.m.chr];if(!i)throw"chr not in chr2bcffile";let a;if(await R.UE({isbcf:!0,args:["query",i,"-r",o,"-f",tr+"\t%FORMAT\n"],dir:r.dir,callback:t=>{const[n,s,o]=$.S(t,r);for(const t of s)if(t.pos==e.m.pos&&t.ref==e.m.ref&&t.alt==e.m.alt)return void(a=t)}}),!a)throw"variant not found";const l=[],c=[],u=[];for(const t of a.sampledata){if(!t.genotype)continue;const n=-1!=t.genotype.indexOf(e.m.ref),s=-1!=t.genotype.indexOf(e.m.alt);n?s?c.push(t.sampleobj.name):l.push(t.sampleobj.name):s&&u.push(t.sampleobj.name)}const f=Math.random().toString();s.ssid=f,s.groups={};const d=[];if(l.length){const e="Homozygous reference";s.groups[e]={size:l.length},d.push(e+"\t"+l.join(","))}if(c.length){const e="Heterozygous";s.groups[e]={size:c.length},d.push(e+"\t"+c.join(","))}if(u.length){const e="Homozygous alternative";s.groups[e]={size:u.length},d.push(e+"\t"+u.join(","))}await R.Sf(g().join(er.cachedir_ssid,f),d.join("\n"))}(s,0,r,o),s.trigger_getvcfcsq&&await async function(e,t,n,s){const r=n.track.vcf;if(!r)throw"ds.track.vcf missing";if(!e.m)throw"q.m missing";const o=(r.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+(e.m.pos+1)+"-"+(e.m.pos+1),i=r.chr2bcffile[e.m.chr];if(!i)throw"chr not in chr2bcffile";await R.UE({isbcf:!0,args:["query",i,"-r",o,"-f",tr+"\\n"],dir:r.dir,callback:t=>{const[n,o,i]=$.S(t,r);for(const t of o)if(t.pos==e.m.pos&&t.ref==e.m.ref&&t.alt==e.m.alt)return void(s.csq=t.csq)}})}(s,0,r,o),n.send(o)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Lr)),Br.post(Jr+"/mdsexpressionrank",(function(e,t){let n,s,o,i=new Set;Promise.resolve().then((()=>{if(!e.query.rglst)throw"rglst missing";if(e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>1e7)throw"Zoom in below 10 Mb to show expression rank";if(!e.query.sample)throw"sample missing";if(e.query.iscustom){if(n=Lr[e.query.genome],!n)throw"invalid genome";if(!e.query.file&&!e.query.url)throw"no file or url for expression data";s={},o={file:e.query.file,url:e.query.url,indexURL:e.query.indexURL}}else{const[t,r,i,a]=no(e.query);if(t)throw t;if(n=r,s=i,o=a,!o.samples)throw"total samples missing from server config";if(-1==o.samples.indexOf(e.query.sample))throw{nodata:1}}if(o.viewrangeupperlimit&&e.query.rglst.reduce(((e,t)=>e+t.stop-t.start),0)>o.viewrangeupperlimit)throw"zoom in under "+F.bplen(o.viewrangeupperlimit)+" to view data";if(e.query.levelkey){if(!e.query.levelvalue)throw"levelvalue is required when levelkey is used";if(!s.cohort||!s.cohort.annotation)throw".cohort.annotation missing from dataset"}if(!o.file){if(!o.url)throw"file or url missing";return R.d1(o.url,o.indexURL)}})).then((t=>{const n=[];for(const a of e.query.rglst)n.push(new Promise(((n,l)=>{const c=(0,q.spawn)(Pr,[o.file?g().join(r().tpmasterdir,o.file):o.url,a.chr+":"+a.start+"-"+a.stop],{cwd:t}),u=O().createInterface({input:c.stdout}),f=new Map;u.on("line",(t=>{const n=t.split("\t"),r=JSON.parse(n[3]);if(!r.gene)return;if(!r.sample)return;if(!Number.isFinite(r.value))return;const o=n[0],a=Number.parseInt(n[1]),l=Number.parseInt(n[2]);if(r.sample==e.query.sample)return f.has(r.gene)||f.set(r.gene,{chr:o,start:a,stop:l,allvalues:[]}),f.get(r.gene).thisvalue=r.value,void(r.ase&&(f.get(r.gene).ase=r.ase));if(e.query.attributes){const t=s.cohort.annotation[r.sample];if(!t)return;for(const n of e.query.attributes)if(n.k&&n.kvalue&&n.kvalue!=t[n.k])return}i.add(r.sample),f.has(r.gene)||f.set(r.gene,{chr:o,start:a,stop:l,allvalues:[]}),f.get(r.gene).allvalues.push({value:r.value})}));const d=[];c.stderr.on("data",(e=>d.push(e))),c.on("close",(e=>{const t=d.join("");t&&!$r(t)&&l({message:t}),n(f)}))})));return Promise.all(n)})).then((e=>{const n=[];for(const t of e)for(const[e,s]of t)null!=s.thisvalue&&(s.allvalues.sort(((e,t)=>e.value-t.value)),s.rank=bo(s.thisvalue,s.allvalues),delete s.allvalues,s.gene=e,n.push(s));t.send({result:n,samplecount:i.size})})).catch((e=>{e.stack&&console.log(e),e.nodata?t.send({nodata:1}):t.send({error:e.message?e.message:e})}))})),Br.post(Jr+"/mdsgeneboxplot",(e=>async(t,n)=>{try{const[s,o,i,a]=function(e,t){if(!t.query.gene)throw"gene name missing";if(!t.query.chr)throw"chr missing";if(!Number.isInteger(t.query.start))throw"start missing";if(!Number.isInteger(t.query.stop))throw"stop missing";const n=e[t.query.genome];if(!n)throw"invalid genome";let s,r,o;if(t.query.iscustom){if(!t.query.file&&!t.query.url)throw"no file or url for expression data";s={},r={file:t.query.file,url:t.query.url,indexURL:t.query.indexURL}}else{if(!n.datasets)throw"genome is not equipped with datasets";if(!t.query.dslabel)throw"dslabel missing";if(s=n.datasets[t.query.dslabel],!s)throw"invalid dslabel";if(!s.queries)throw"dataset is not equipped with queries";if(!t.query.querykey)throw"querykey missing";if(r=s.queries[t.query.querykey],!r)throw"invalid querykey"}if(t.query.svcnv)if(o={},t.query.iscustom)o.dsquery={file:t.query.svcnv.file,url:t.query.svcnv.url,indexURL:t.query.svcnv.indexURL};else{t.query.svcnv.genome=t.query.genome;const e=n.datasets[t.query.svcnv.dslabel];if(!e)throw"invalid dslabel";if(!e.queries)throw"dataset is not equipped with queries";if(!t.query.svcnv.querykey)throw"querykey missing";const s=e.queries[t.query.svcnv.querykey];if(!s)throw"invalid querykey";o.ds=e,o.dsquery=s}if(t.query.getgroup)if(t.query.sampleset);else{if(!s.cohort||!s.cohort.annotation)throw"no sample annotation for getting group";if(t.query.getgroup_unannotated){if(!r.boxplotbysamplegroup)throw"dsquery.boxplotbysamplegroup{} missing when getgroup_unannotated"}else{if(!Array.isArray(t.query.getgroup))throw"getgroup should be array";for(const e of t.query.getgroup){if(!e.k)throw"k missing from one of getgroup";if(!e.kvalue)throw"kvalue missing from one of getgroup"}}}return[n,s,r,o]}(e,t);t.query.getalllst,n.send(await async function(e,t,n,s,o){n.url&&(n.dir=await R.d1(n.url,n.indexURL));s&&s.dsquery.url&&(s.dsquery.dir=await R.d1(s.dsquery.url,s.dsquery.indexURL));const i=function(e){if(!e.query.sampleset)return;const t=new Map;for(const n of e.query.sampleset)for(const e of n.samples)t.set(e,n.name);return t}(o),a=new Map,l=[],c=[];if(await R.UE({args:[n.file?g().join(r().tpmasterdir,n.file):n.url,o.query.chr+":"+o.query.start+"-"+o.query.stop],dir:n.dir,callback:e=>{const s=e.split("\t"),r=JSON.parse(s[3]);if(r.gene&&r.gene==o.query.gene&&Number.isFinite(r.value))if(o.query.getalllst)l.push({sample:r.sample,value:r.value});else if(o.query.getgroup){if(!r.sample)return;if(i)return void(o.query.getgroup_unannotated?i.has(r.sample)||c.push(r):i.get(r.sample)==o.query.getgroup[0].full&&c.push(r));const e=t.cohort.annotation[r.sample];if(o.query.getgroup_unannotated){if(!e)return void c.push(r);for(const t of n.boxplotbysamplegroup.attributes)if(null==e[t.k])return void c.push(r);return}if(!e)return;for(const t of o.query.getgroup)if(t.kvalue!=e[t.k])return;c.push(r)}else if(n.boxplotbysamplegroup&&t.cohort&&t.cohort.annotation){if(!r.sample)return;let e;e=null==o.query.index_boxplotgroupers||0==o.query.index_boxplotgroupers?n.boxplotbysamplegroup.attributes:n.boxplotbysamplegroup.additionals[o.query.index_boxplotgroupers-1].attributes;const s=t.cohort.annotation[r.sample];if(!s)return void l.push({sample:r.sample,value:r.value});const i=s[e[0].k];if(null==i)return void l.push({sample:r.sample,value:r.value});const c=[];for(let t=1;t<e.length;t++){const n=s[e[t].k];if(null==n)break;c.push(n)}c.unshift(i);const u=c.join(", ");if(!a.has(u)){const t={samples:[],attributes:[]};for(const n of e){const e=s[n.k];if(null==e)break;const r={k:n.k,kvalue:e};n.full&&(r.full=n.full,r.fullvalue=s[n.full]),t.attributes.push(r)}a.set(u,t)}a.get(u).samples.push({sample:r.sample,value:r.value})}else if(i){if(!r.sample)return;const e=i.get(r.sample);if(!e)return void l.push({sample:r.sample,value:r.value});a.has(e)||a.set(e,{samples:[],attributes:[{full:e}]}),a.get(e).samples.push({sample:r.sample,value:r.value})}else l.push({sample:r.sample,value:r.value})}}),o.query.getgroup2boxplot){c.sort(((e,t)=>e.value-t.value));const{w1:e,w2:t,p25:n,p50:s,p75:r,out:o}=R.JC(c);return{n:c.length,min:c[0].value,max:c[c.length-1].value,w1:e,w2:t,p25:n,p50:s,p75:r,out:o}}const u=[];for(const[e,t]of a)u.push({name:e,values:t.samples,attributes:t.attributes});l.length&&u.push({name:"Unannotated",values:l});c.length&&u.push({values:c});if(o.query.getalllst)return{lst:u[0].values};if(o.query.iscustom&&!i||1==u.length){if(u[0]){const e=u[0].values;return e.sort(((e,t)=>t.value-e.value)),{lst:e,max:e[0].value,min:e[e.length-1].value}}return{nodata:1}}const f=await async function(e,t){if(!t||!e.query.svcnv.useloss&&!e.query.svcnv.usegain&&!e.query.svcnv.usesv)return;let n=e.query.start,s=e.query.stop;e.query.svcnv.usesv&&Number.isInteger(e.query.svcnv.svflank)&&(n=Math.max(0,n-e.query.svcnv.svflank),s+=e.query.svcnv.svflank);const o=new Map;return await R.UE({args:[t.dsquery.file?g().join(r().tpmasterdir,t.dsquery.file):t.dsquery.url,e.query.chr+":"+n+"-"+s],dir:t.dsquery.dir,callback:t=>{const n=t.split("\t"),s=JSON.parse(n[3]);if(s.sample)if(s.chrA||s.chrB){if(!e.query.svcnv.usesv)return;o.has(s.sample)||o.set(s.sample,{}),o.get(s.sample).sv=1}else{if(!e.query.svcnv.usegain&&!e.query.svcnv.useloss)return;if(e.query.svcnv.usesv&&e.query.svcnv.svflank){const t=Number.parseInt(n[1]),s=Number.parseInt(n[2]);if(Math.max(e.query.start,t)>Math.min(e.query.stop,s))return}if(!Number.isFinite(s.value))return;if(!e.query.svcnv.usegain&&s.value>0)return;if(!e.query.svcnv.useloss&&s.value<0)return;if(e.query.svcnv.valueCutoff&&Math.abs(s.value)<e.query.svcnv.valueCutoff)return;if(e.query.svcnv.bplengthUpperLimit&&Number.parseInt(n[2])-Number.parseInt(n[1])>e.query.svcnv.bplengthUpperLimit)return;o.has(s.sample)||o.set(s.sample,{}),s.value>0?o.get(s.sample).gain=1:s.value<0&&(o.get(s.sample).loss=1)}}}),o}(o,s);if(o.query.getgroup){if(u[0]){const e=u[0].values;if(e.sort(((e,t)=>t.value-e.value)),f)for(const t of e){const e=f.get(t.sample);if(e)for(const n in e)t[n]=e[n]}return{lst:e,max:e[0].value,min:e[e.length-1].value}}return{nodata:1}}const d=[];let p=null,m=null;for(const e of u){e.values.sort(((e,t)=>e.value-t.value));const t=e.values.length;null==p?(p=e.values[0].value,m=e.values[t-1].value):(p=Math.min(p,e.values[0].value),m=Math.max(m,e.values[t-1].value));const{w1:n,w2:s,p25:r,p50:i,p75:a,out:l}=R.JC(e.values),c=[{isall:1,w1:n,w2:s,p25:r,p50:i,p75:a,out:l}];if(f){if(o.query.svcnv.usegain){const t=e.values.filter((e=>f.has(e.sample)&&f.get(e.sample).gain));if(t.length){const{w1:e,w2:n,p25:s,p50:r,p75:o,out:i}=R.JC(t);c.push({iscnvgain:1,samplecount:t.length,w1:e,w2:n,p25:s,p50:r,p75:o,out:i})}}if(o.query.svcnv.useloss){const t=e.values.filter((e=>f.has(e.sample)&&f.get(e.sample).loss));if(t.length){const{w1:e,w2:n,p25:s,p50:r,p75:o,out:i}=R.JC(t);c.push({iscnvloss:1,samplecount:t.length,w1:e,w2:n,p25:s,p50:r,p75:o,out:i})}}if(o.query.svcnv.usesv){const t=e.values.filter((e=>f.has(e.sample)&&f.get(e.sample).sv));if(t.length){const{w1:e,w2:n,p25:s,p50:r,p75:o,out:i}=R.JC(t);c.push({issv:1,samplecount:t.length,w1:e,w2:n,p25:s,p50:r,p75:o,out:i})}}}d.push({name:e.name+" ("+e.values.length+")",boxplots:c,attributes:e.attributes})}return d.sort(((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)),{groups:d,min:p,max:m}}(0,o,i,a,t))}catch(e){e.stack&&console.log(e),n.send({error:e.message||e})}})(Lr)),Br.post(Jr+"/mdsgenevalueonesample",(async function(e,t){const n=e.query;try{if(!n.sample)throw".sample missing";if(!n.genes)throw".genes[] missing";let s,o,i;if(e.query.iscustom){if(s=Lr[n.genome],!s)throw"invalid genome";if(!n.file&&!n.url)throw"no file or url for expression data";o={},i={file:n.file,url:n.url,indexURL:n.indexURL}}else{const[e,t,r,a]=no(n);if(e)throw e;s=t,o=r,i=a}const a=i.file?null:await R.d1(i.url,i.indexURL),l={};let c=!0;for(const e of n.genes){let t;await R.UE({args:[i.file?g().join(r().tpmasterdir,i.file):i.url,e.chr+":"+e.start+"-"+e.stop],dir:a,callback:s=>{const r=s.split("\t");if(!r[3])return;const o=JSON.parse(r[3]);o.gene==e.gene&&o.sample==n.sample&&(t=o.value)}}),Number.isFinite(t)&&(l[e.gene]=t,c=!1)}c?t.send({nodata:1}):t.send({result:l})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/vcf",(async function(e,t){try{const[n,s,r]=R.ZX(e);if(n)throw n;const o=r?await R.d1(s,e.query.indexURL):null;if(!e.query.rglst)throw"rglst missing";const i=[];for(const t of e.query.rglst)await R.UE({args:[s,t.chr+":"+t.start+"-"+t.stop],dir:o,callback:e=>i.push(e)});t.send({linestr:i.join("\n")})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.get(Jr+"/vcfheader",(async function(e,t){try{if(!e.query.genome)throw"genome missing";const n=Lr[e.query.genome];if(!n)throw"invalid genome";const[s,r,o]=R.ZX(e);if(s)throw s;const i=o?await R.d1(r,e.query.indexURL):null;t.send({metastr:(await R.ZD(r,i)).join("\n"),nochr:await R.Jy(r,i,n)})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/translategm",(async function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"invalid genome";const s=e.query.gm;if(!s)throw"missing gm{}";if(!s.chr)throw"gm.chr missing";if(!s.start)throw"gm.start missing";if(!Number.isInteger(s.start))throw"gm.start not integer";if(!s.stop)throw"gm.stop missing";if(!Number.isInteger(s.stop))throw"gm.stop not integer";const r=await R.Kf(n,s.chr+":"+(s.start+1)+"-"+s.stop),o=F.fasta2gmframecheck(s,r);t.send({frame:o})}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.post(Jr+"/samplematrix",(function(e,t){Promise.resolve().then((()=>{const t=Lr[e.query.genome];if(!t)throw"invalid genome";let n,s;if(e.query.iscustom){if(!e.query.querykey2tracks)throw"querykey2tracks{} missing for custom dataset";n={queries:{}};for(const t in e.query.querykey2tracks){const s=e.query.querykey2tracks[t];if(!s.type)throw'missing "type" for a data track';if(s.type==F.tkt.mdsvcf){const s=e.query.querykey2tracks[t];s.type=F.mdsvcftype.vcf,n.queries[t]={type:F.tkt.mdsvcf,info:s.info,tracks:[s]}}else if(s.type==F.tkt.mdssvcnv)n.queries[t]=s;else{if(s.type!=F.tkt.mdsexpressionrank)throw"unknown type of data track: "+s.type;n.queries[t]=s}}}else{if(!t.datasets)throw"genome is not equipped with datasets";if(!e.query.dslabel)throw"dslabel missing";if(n=t.datasets[e.query.dslabel],!n)throw"invalid dslabel";if(!n.queries)throw"dataset is not equipped with queries"}if(e.query.sampleset)s=new Set(e.query.sampleset);else if(e.query.limitsamplebyeitherannotation){if(!n.cohort)throw"limitsamplebyeitherannotation but no cohort in ds";if(!n.cohort.annotation)throw"limitsamplebyeitherannotation but no cohort.annotation in ds";s=new Set;for(const t in n.cohort.annotation){const r=n.cohort.annotation[t];for(const n of e.query.limitsamplebyeitherannotation)if(r[n.key]==n.value){s.add(t);break}}}const r=[];for(const t of e.query.features){let e,o=[];if(t.querykey){if(!n.queries)throw"using querykey for a feature but no ds.queries";if(e=n.queries[t.querykey],!e)throw"unknown dsquery by key "+t.querykey}else if(t.querykeylst){if(!n.queries)throw"using querykeylst for a feature but no ds.queries";for(const e of t.querykeylst){const t=n.queries[e];if(!t)throw'unknown key "'+e+'" from querykeylst';o.push(t)}if(0==o.length)throw"no valid keys in querykeylst"}else if(!t.issampleattribute)throw"unknown way to query a feature";if(t.isgenevalue){const[o,i]=wo(t,n,e,s);if(o)throw"error with isgenevalue: "+o;r.push(i)}else if(t.iscnv){const[o,i]=_o(t,n,e,s);if(o)throw"error with iscnv: "+o;r.push(i)}else if(t.isloh){const[o,i]=ko(t,n,e,s);if(o)throw"error with isloh: "+o;r.push(i)}else if(t.isvcf){const[o,i]=Ao(t,n,e,s);if(o)throw"error with isvcf: "+o;r.push(i)}else if(t.isitd){const[o,i]=qo(t,n,e,s);if(o)throw"error with isitd: "+o;r.push(i)}else if(t.issvfusion){const[o,i]=xo(t,n,e,s);if(o)throw"error with issvfusion: "+o;r.push(i)}else if(t.issvcnv){const[o,i]=No(t,n,e,s);if(o)throw"error with issvcnv: "+o;r.push(i)}else if(t.ismutation){const[e,i]=So(t,n,o,s);if(e)throw"error with ismutation: "+e;r.push(i)}else{if(!t.issampleattribute)throw"unknown type of feature";{const[e,o]=vo(t,n,s);if(e)throw"error with issampleattribute: "+e;r.push(o)}}}return Promise.all(r)})).then((e=>{t.send({results:e})})).catch((e=>{t.send({error:"string"==typeof e?e:e.message}),e.stack&&console.error(e.stack)}))})),Br.get(Jr+"/mdssamplescatterplot",(async function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"invalid genome";const s=n.datasets[e.query.dslabel];if(!s)throw"invalid dataset";if(!s.cohort)throw"no cohort for dataset";if(!s.cohort.annotation)throw"cohort.annotation missing for dataset";const r=s.cohort.scatterplot;if(!r)throw"scatterplot not supported for this dataset";const o=[];for(const t in s.cohort.annotation){const n=s.cohort.annotation[t];if(e.query.subsetkey&&n[e.query.subsetkey]!=e.query.subsetvalue)continue;const i=n[r.x.attribute];if(!Number.isFinite(i))continue;const a=n[r.y.attribute];Number.isFinite(a)&&o.push({sample:t,x:i,y:a,s:n})}t.send({colorbyattributes:r.colorbyattributes,colorbygeneexpression:r.colorbygeneexpression,querykey:r.querykey,dots:o,tracks:r.tracks})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/mdssamplesignature",(function(e,t){try{const n=e.query;if(!n.sample)throw".sample missing";const s=Lr[n.genome];if(!s)throw"invalid genome";const r=s.datasets[n.dslabel];if(!r)throw"invalid dataset";if(!r.cohort)throw"no cohort for dataset";if(!r.cohort.mutation_signature)throw"no mutation_signature for cohort";const o=[];for(const e in r.cohort.mutation_signature.sets){const t=r.cohort.mutation_signature.sets[e];if(!t.samples)continue;const s=t.samples.map.get(n.sample);if(!s)continue;const i=[];for(const e in t.signatures)s[e]&&i.push({k:e,v:s[e]});i.length&&o.push({key:e,valuename:t.samples.valuename,annotation:i.sort(((e,t)=>t.v-e.v))})}t.send({lst:o})}catch(e){e.stack&&console.error(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/mdssurvivalplot",function(e){return async(t,n)=>{try{const s=t.query,r=e[s.genome];if(!r)throw"invalid genome";const o=r.datasets[s.dslabel];if(!o)throw"invalid dataset";if(!o.cohort)throw"no cohort for dataset";if(!o.cohort.annotation)throw"cohort.annotation missing for dataset";const i=o.cohort.survivalplot;if(!i)throw"survivalplot not supported for this dataset";if(!i.plots)throw".plots{} missing";if(t.query.init)return void n.send(i.init);if(!s.type)throw".type missing";const a=i.plots[s.type];if(!a)throw"unknown plot type: "+s.type;const l=function(e,t,n){if(!e.samplerule)throw".samplerule missing";if(!e.samplerule.full)throw".samplerule.full missing";const s=[];if(e.samplerule.full.byattr){const n=e.samplerule.full.key;if(!n)throw"key missing from samplerule.full{}";const r=e.samplerule.full.value;if(null==r)throw"value missing from samplerule.full{}";for(const e in t.cohort.annotation){const o=t.cohort.annotation[e];o[n]==r&&s.push({name:e,o})}}else if(e.samplerule.full.useall)for(const e in t.cohort.annotation){const n=t.cohort.annotation[e];s.push({name:e,o:n})}else{if(!e.samplerule.full.usesampleset)throw"unknown rule for samplerule.full";{const n=e.samplerule.full.sampleset;for(const e in n){const r=n[e],o=t.cohort.annotation[r];null!=o&&s.push({name:r,o})}}}const r=[];for(const e of s)Number.isFinite(e.o[n.serialtimekey])&&(e.serialtime=e.o[n.serialtimekey],e.censored=e.o[n.iscensoredkey],r.push(e));if(0==r.length)throw"no samples found for full set";return r}(s,o,a),c=await async function(e,t,n,s){if(t.samplerule.mutated_sets){const n=new Set(e.map((e=>e.name))),s=t.samplerule.mutated_sets.reduce(((t,s)=>{const r=new Set(s.samplenames);s.lst=e.filter((e=>r.has(e.name)));for(const e of s.samplenames)n.delete(e);return delete s.samplenames,t.push(s),t}),[]);return s.push({name:"No mutation (n="+n.size+")",lst:e.filter((e=>n.has(e.name))),is_notmutated:!0}),s}const r=t.samplerule.set;if(!r)return[{name:"All",lst:e}];if(r.geneexpression){if(!r.gene)throw".gene missing from samplerule.set";if(!r.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(r.start))throw".start not integer from samplerule.set";if(!Number.isInteger(r.stop))throw".start not integer from samplerule.set";if(r.bymedian)return await async function(e,t,n,s){const r=t.samplerule.set,[o,i]=await Ar(e,t,n),a=Math.ceil(i.length/2),l=i[a-1].genevalue;return[{name:r.gene+" "+o.datatype+" below median (n="+a+", value<"+l+")",lst:i.slice(0,a)},{name:r.gene+" "+o.datatype+" above median (n="+(i.length-a)+", value>="+l+")",lst:i.slice(a,i.length)}]}(e,t,n);if(r.byquartile)return await async function(e,t,n,s){const r=t.samplerule.set,[o,i]=await Ar(e,t,n),a=Math.ceil(.25*i.length),l=Math.ceil(.5*i.length),c=Math.ceil(.75*i.length),u=i[a-1].genevalue,f=i[l-1].genevalue,d=i[c-1].genevalue;return[{name:r.gene+" "+o.datatype+" from 1st quartile (n="+a+", value<"+u+")",lst:i.slice(0,a),isfirstquartile:!0},{name:r.gene+" "+o.datatype+" from 2nd quartile (n="+(l-a)+", "+u+"<=value<"+f+")",lst:i.slice(a,l)},{name:r.gene+" "+o.datatype+" from 3rd quartile (n="+(c-l)+", "+f+"<=value<"+d+")",lst:i.slice(l,c)},{name:r.gene+" "+o.datatype+" from 4th quartile (n="+(i.length-c)+", value>="+d+")",lst:i.slice(c,i.length),isfourthquartile:!0}]}(e,t,n)}if(r.mutation){if(!r.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(r.start))throw".start not integer from samplerule.set";if(!Number.isInteger(r.stop))throw".start not integer from samplerule.set";return await async function(e,t,n){const s=t.samplerule.set;if(s.samples_snvindel=new Set,s.samples_cnv=new Set,s.samples_loh=new Set,s.samples_sv=new Set,s.samples_fusion=new Set,s.samples_itd=new Set,s.cnv&&!s.snvindel&&!s.loh&&!s.sv&&!s.fusion&&!s.itd){const[s,r]=await xr(e,t,n,!0),o=[],i=[],a=[];for(const t of e)s.has(t.name)?o.push(t):r.has(t.name)?i.push(t):a.push(t);const l=[];return i.length&&l.push({name:"Copy number loss (n="+i.length+")",lst:i}),o.length&&l.push({name:"Copy number gain (n="+o.length+")",lst:o}),a.length&&l.push({name:"No copy number variation (n="+a.length+")",lst:a}),l}const r=await xr(e,t,n),o=[];for(const t of e)r.find((e=>e.name==t.name))||o.push(t);const i=[];r.length&&i.push({name:"With mutation (n="+r.length+")",lst:r});o.length&&i.push({name:"No mutation (n="+o.length+")",lst:o});return i}(e,t,n)}throw"unknown rule for samplerule.set{}"}(l,s,o);let u;c.length>1&&(u=await qr(c)),await async function(e,t){if(!e.samplerule.mutated_sets)return;const n=t.find((e=>e.is_notmutated));if(!n)return;for(const e of t){if(e.is_notmutated)continue;const t=await qr([e,n]);e.pvalue=t}}(s,c),await async function(e,t){if(!e.samplerule.set)return;if(!e.samplerule.set.geneexpression)return;if(!e.samplerule.set.byquartile)return;if(4!=t.length)return;if(e.samplerule.set.against1st){for(let e=1;e<4;e++)t[e].pvalue=await qr([t[0],t[e]]);return}if(e.samplerule.set.against4th){for(let e=0;e<3;e++)t[e].pvalue=await qr([t[e],t[3]]);return}}(s,c);for(const e of c)Cr(e),delete e.lst;const f={samplesets:c,pvalue:u};s.samplerule.set&&s.samplerule.set.mutation&&(f.count_snvindel=s.samplerule.set.samples_snvindel.size,f.count_cnv=s.samplerule.set.samples_cnv.size,f.count_loh=s.samplerule.set.samples_loh.size,f.count_sv=s.samplerule.set.samples_sv.size,f.count_fusion=s.samplerule.set.samples_fusion.size,f.count_itd=s.samplerule.set.samples_itd.size),n.send(f)}catch(e){e.stack&&console.error(e.stack),n.send({error:e.message||e})}}}(Lr)),Br.post(Jr+"/fimo",function(e){return async(t,n)=>{try{const s=t.query;if(!s.m)throw"no mutation";if(!s.m.chr)throw"mutation chr missing";if(!Number.isInteger(s.m.pos))throw"mutation position is not integer";if(!s.m.ref)throw"mutation ref allele missing";if(!s.m.alt)throw"mutation alt allele missing";const r=e[s.genome];if(!r)throw"invalid genome";if(!r.fimo_motif)throw"motif finding not supported on this genome";const o=await async function(e,t){const n=e.m.pos-e.flankspan,s=e.m.pos+e.flankspan,r=await R.Kf(t,e.m.chr+":"+n+"-"+s);!function(e,t,n){if(!e.m.ref)return;if("-"==e.m.ref)return;const s=n.split("\n").slice(1).join("").toUpperCase(),r=s.substring(e.m.pos-t,e.m.pos-t+e.m.ref.length);if(r==e.m.ref.toUpperCase())return;if(common.reversecompliment(r)==e.m.ref.toUpperCase())e.m.ref=r,"-"!=e.m.alt&&(e.m.alt=common.reversecompliment(e.m.alt))}(e,n,r);const o=await wr(e,t,r),i=new Map;for(const e of o)e.pvalue_ref=e.pvalue,delete e.pvalue,e.logpvalue_ref=e.logpvalue,delete e.logpvalue,i.has(e.name)||i.set(e.name,[]),i.get(e.name).push(e);const a=function(e,t,n,s){const r=s.split("\n"),o=r.slice(1).join("");return r[0]+"\n"+o.substr(0,e.pos-t)+("-"==e.alt?"":e.alt)+o.substr(e.pos-t+("-"==e.ref?0:e.ref.length))}(e.m,n,0,r),l=await wr(e,t,a);for(const e of l){e.pvalue_alt=e.pvalue,delete e.pvalue,e.logpvalue_alt=e.logpvalue,delete e.logpvalue,i.has(e.name)||i.set(e.name,[]);let t=!0;for(const n of i.get(e.name))if(null!=n.logpvalue_ref&&n.strand==e.strand&&Math.abs(e.start-n.start)<=2&&Math.abs(e.stop-n.stop)<=2){n.pvalue_alt=e.pvalue_alt,n.logpvalue_alt=e.logpvalue_alt,n.logpvaluediff=e.logpvalue_alt-n.logpvalue_ref,n.logpvaluediff>0?n.gain=!0:n.loss=!0,t=!1;break}t&&i.get(e.name).push(e)}let c=0,u=0;const f=[];for(const t of i.values())for(const n of t)null==n.logpvaluediff&&(null==n.pvalue_ref?(n.gain=!0,n.logpvaluediff=n.logpvalue_alt):null==n.pvalue_alt&&(n.loss=!0,n.logpvaluediff=-n.logpvalue_ref)),null!=e.minabslogp&&Math.abs(n.logpvaluediff)<e.minabslogp||(n.logpvaluediff>0?c=Math.max(c,n.logpvaluediff):u=Math.min(u,n.logpvaluediff),f.push(n));return{items:f,valuemin:u,valuemax:c,refstart:n,refstop:s,refseq:r.split("\n").slice(1).join("")}}(s,r);n.send(o)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}}(Lr)),Br.all(Jr+"/termdb",ve.TO(Lr)),Br.all(Jr+"/termdb-barsql",Se.TO(Lr)),Br.post(Jr+"/singlecell",function(e){return async(t,n)=>{try{const s=t.query,r=e[s.genome];if(!r)throw"invalid genome";if(s.getpcd)return void await async function(e,t){const n={},s=await async function(e,t){if(!e.textfile)throw".textfile missing";{const[t,n,s]=R.ZX({query:{file:e.textfile}});if(t)throw".textfile error: "+t;if(!s){if(await R.yE(n))throw"file not exist: "+e.textfile;if(await R.t7(n))throw"file not readable: "+e.textfile}e.textfile=n}let n,s,r,o,i;if(e.getpcd.category_autocolor){const t=e.getpcd.values_count&&e.getpcd.values_count<=10?lr:hr;n=ar.Z(t),r={},o={}}else if(e.getpcd.category_customcolor){const t=ar.Z(hr);a=e.getpcd.cat_values,l=t,n=e=>{let t=!1;for(const n of a)if(n.value==e)return t=!0,n.color;if(!t)return l(e)},r={},o={},i={}}else if(e.getpcd.gene_expression){const n=e.getpcd.gene_expression;if(!n.file)throw"gene_expression.file missing";{const[e,t,s]=R.ZX({query:{file:n.file}});if(e)throw e;n.file=t}if(!Number.isInteger(n.barcodecolumnidx))throw"gene_expression.barcodecolumnidx missing";if(!n.chr)throw"gene_expression.chr missing";if(!n.start)throw"gene_expression.start missing";if(!n.stop)throw"gene_expression.stop missing";if(!n.genename)throw"gene_expression.genename missing";if(!n.autoscale)throw"gene_expression: unknown scaling method";if(!n.color_min)throw"gene_expression.color_min missing at autoscale";if(!n.color_max)throw"gene_expression.color_max missing at autoscale";const r=(n.nochr?n.chr.replace("chr",""):n.chr)+":"+n.start+"-"+n.stop,o=new Map;s=new Map;let i=0,a=0;if(t.numbercellwithgeneexp=0,t.numbercelltotal=0,await R.UE({args:[n.file,r],callback:e=>{const s=JSON.parse(e.split("\t")[3]);s.gene==n.genename&&Number.isFinite(s.value)&&(t.numbercellwithgeneexp++,n.autoscale&&(i=Math.min(i,s.value),a=Math.max(a,s.value)),o.set(s.sample,s.value))}}),n.autoscale){t.minexpvalue=i,t.maxexpvalue=a;const e=Pe.ZP(n.color_min,n.color_max);for(const[t,n]of o){const r=_e.ZP(e((n-i)/(a-i)));s.set(t,Number.parseInt(yr(r.r,r.g,r.b),16))}}}var a,l;return new Promise(((i,a)=>{const l=[],c=O().createInterface({input:m().createReadStream(e.textfile)});let u=!0,f=0,d=0;c.on("line",(i=>{if(u)return void(u=!1);const a=i.split(e.delimiter),c=[];for(const t of e.getpcd.coord)c.push(a[t]),f=Math.max(f,a[t]),d=Math.min(d,a[t]);if(2==e.getpcd.coord.length&&c.push("0"),n){const t=a[e.getpcd.category_index],s=n(t);if(e.hidden_types.includes(t))if(e.background_color){const t=_e.ZP(e.background_color),n=Number.parseInt(yr(t.r,t.g,t.b),16);c.push(n)}else c.push(16777215);else c.push(Number.parseInt(s.slice(1),16));r&&(r[t]=s),o&&(o[t]=t in o?o[t]+1:1)}else if(s){t.numbercelltotal++;const n=a[e.getpcd.gene_expression.barcodecolumnidx];let r=s.get(n);if(void 0===r)if(e.getpcd.gene_expression.color_no_exp){const t=_e.ZP(e.getpcd.gene_expression.color_no_exp);r=Number.parseInt(yr(t.r,t.g,t.b),16)}else r="2894892";c.push(r)}l.push(c.join(" "))})),c.on("close",(()=>{r&&(e.getpcd.category_customorder&&(r=function(e,t){let n={};const s=Object.keys(e).length;for(var r=1;r<=s;r++){const s=t.find((e=>{if(e.order==r)return e.value}));s&&(n[s.value]=e[s.value])}for(const s of t)s.order||(n[s.value]=e[s.value]);for(const s in e){t.find((e=>{if(e.value==JSON.stringify(s))return!0}))||(n[s]=e[s])}return n}(r,e.getpcd.cat_values)),t.category2color=r,t.categorycount=o),t.data_sphere_r=Math.max(Math.abs(f),Math.abs(d)),i(l)}))}))}(e,n),r="# .PCD v.7 - Point Cloud Data file format\nVERSION .7\nFIELDS x y z rgb\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH 1200\nHEIGHT 800\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS 960000\nDATA ascii\n";n.pcddata=r+s.join("\n"),t.send(n)}(s,n);if(s.getgeneboxplot)return void await async function(e,t,n){const s=e.getgeneboxplot,r=e.getgeneboxplot.values_count&&e.getgeneboxplot.values_count<=10?ar.Z(lr):ar.Z(hr);if(!s.expfile)throw"getgeneboxplot.expfile missing";{const[e,t,n]=R.ZX({query:{file:s.expfile}});if(e)throw"getgeneboxplot.expfile error: "+e;s.expfile=t}if(!s.chr)throw"getgeneboxplot.chr missing";if(!s.start)throw"getgeneboxplot.start missing";if(!s.stop)throw"getgeneboxplot.stop missing";if(!s.genename)throw"getgeneboxplot.genename missing";const o=await br(s),i=(s.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop;let a=0,l=0;await R.UE({args:[s.expfile,i],callback:e=>{const t=JSON.parse(e.split("\t")[3]);if(t.gene!=s.genename)return;if(!t.sample)return;if(!Number.isFinite(t.value))return;const n=o.get(t.sample);n&&(n.expvalue=t.value,a=Math.min(a,t.value),l=Math.max(l,t.value))}});const c=new Map;for(const[e,t]of o)c.has(t.category)||c.set(t.category,[]),s.exclude_cells&&0==parseInt(t.expvalue)||c.get(t.category).push({value:t.expvalue});const u=[],f=(d=ss.Z().domain([a,l]).ticks(20),e=>{const t=[];for(let e=1;e<d.length;e++)t.push(0);for(const n of e)for(let e=1;e<d.length;e++)if(n.value<=d[e]){t[e-1]++;break}return t});var d;for(const[e,t]of c){t.sort(((e,t)=>e.value-t.value));const n=R.JC(t);delete n.out;const s=r(e);n.category=e,n.color=s,n.numberofcells=t.length,n.density=f(t),u.push(n)}let p=[];if(e.getgeneboxplot.cat_values){const t=Object.keys(e.getgeneboxplot.cat_values).length;for(var m=1;m<=t;m++){const t=e.getgeneboxplot.cat_values.find((e=>{if(e.order==m)return e.value}));t&&p.push(u.filter((e=>e.category==t.value))[0])}for(const t of e.getgeneboxplot.cat_values)t.order||p.push(u.filter((e=>e.category==t.value))[0]);for(const t of u){e.getgeneboxplot.cat_values.find((e=>{if(e.value==t.category)return!0}))||p.push(t)}for(const t of p){const n=e.getgeneboxplot.cat_values.find((e=>{if(e.value==t.category)return e}));n&&n.color&&(t.color=n.color)}}else p=u;n.send({boxplots:p,minexpvalue:a,maxexpvalue:l})}(s,0,n);if(s.getheatmap)return void await async function(e,t,n){const s=e.getheatmap,r=[];if(!s.expfile)throw"getgeneboxplot.expfile missing";{const[e,t,n]=R.ZX({query:{file:s.expfile}});if(e)throw"getgeneboxplot.expfile error: "+e;s.expfile=t}s.gene_list.forEach((e=>{if(!e.chr)throw"getgeneboxplot.chr missing";if(!e.start)throw"getgeneboxplot.start missing";if(!e.stop)throw"getgeneboxplot.stop missing";if(!e.gene)throw"getgeneboxplot.genename missing"}));const o=await br(s);for(const e of s.gene_list){const t=(e.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;let n=0,i=0;const a=e.gene;await R.UE({args:[s.expfile,t],callback:t=>{const s=JSON.parse(t.split("\t")[3]);if(s.gene.toUpperCase()!==e.gene.toUpperCase())return;if(!s.sample)return;if(!Number.isFinite(s.value))return;const r=o.get(s.sample);r&&(r.expvalue=s.value,n=Math.min(n,s.value),i=Math.max(i,s.value))}});const l=new Map;for(const[e,t]of o)l.has(t.category)||l.set(t.category,[]),l.get(t.category).push({value:t.expvalue});const c=[];for(const[e,t]of l){let n=0;for(const e of t)n+=e.value;const s=t.length,r=(n/s).toFixed(3);c.push({category:e,mean:r,numberofcells:s})}r.push({genename:a,heatmap:c})}n.send({gene_heatmap:r})}(s,0,n)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}(Lr)),Br.post(Jr+"/massSession",(async function(e,t){try{const n=e.body.__sessionFor__,{filename:s,route:o,dslabel:i,embedder:a}=n||{};let l;if(s){const t={headers:e.headers,query:n};if(l=pr.i.getPayloadFromHeaderAuth(t,o),!l.email)throw"invalid credentials: no jwt.email";if(l.dslabel!=i||l.route!=o||l.embedder!=a)throw"invalid credentials: mismatched payload";delete e.body.__sessionFor__}const c=s||function(){const e=[];for(;e.length<15;){const t=46+Math.floor(80*Math.random());(t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122)&&e.push(String.fromCharCode(t))}return e.join("")}(),u=JSON.stringify(e.body),f=s?mr(n,l):r().cachedir_massSession;await m().promises.access(f).then((()=>!0)).catch((()=>!1))||m().mkdirSync(f,{recursive:!0}),await R.Sf(g().join(f,c),u),t.send({id:c})}catch(e){t.send({error:e.message||e})}})),Br.get(Jr+"/massSession",(async function(e,t){try{const n=e.query.id;if(!n)throw"session id missing";const{route:s,dslabel:o,embedder:i}=e.query,a=e.query.route?pr.i.getPayloadFromHeaderAuth(e,e.query.route):null,l=e.query.route?mr(e.query,a):r().cachedir_massSession,c=g().join(l,n);let u;try{u=(await m().promises.stat(c)).birthtime}catch(e){throw"invalid session"}const f=await R.b5(c),d=JSON.parse(f);if(e.query.route)return void t.send({state:d});const p=new Date,h=new Date(u),y=r().features.massSessionDuration||30,b=y-Math.round((p.getTime()-h.getTime())/864e5);t.send({state:d,sessionDaysLeft:b,massSessionDuration:y})}catch(e){t.send({error:e.message||e})}})),Br.delete(Jr+"/massSession",(async function(e,t){try{const n=e.query.ids;if(!n)throw"session ids[] missing";const{route:s,dslabel:o,embedder:i}=e.query,a=e.query.route?pr.i.getPayloadFromHeaderAuth(e,e.query.route):null;if(!a)throw"missing credentials";const l=e.query.route?mr(e.query,a):r().cachedir_massSession,c=[];for(const e of n){const t=g().join(l,e);m().unlink(t,(e=>{if(e)throw c.push(e),e}))}c.length||t.send({status:"ok"})}catch(e){t.send({error:e.message||e})}})),Br.get(Jr+"/sessionIds",(async function(e,t){try{const{filename:n,route:s,dslabel:r,embedder:o}=e.query,i=pr.i.getPayloadFromHeaderAuth(e,s);if(!i.email)throw"invalid credentials: no jwt.email";if(i.dslabel!=r||i.route!=s||i.embedder!=o)throw"invalid credentials: mismatched payload";const a=mr(e.query,i);if(!await m().promises.access(a).then((()=>!0)).catch((()=>!1)))return void t.send({status:"ok",sessionIds:[]});const l=await m().promises.readdir(a);t.send({status:"ok",sessionIds:l})}catch(e){t.status(401),t.send({error:e.message||e})}})),Br.get(Jr+"/isoformbycoord",(async function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"invalid genome";if(!e.query.chr)throw"chr missing";const s=Number(e.query.pos);if(!Number.isInteger(s))throw"pos must be positive integer";const o=n.tracks.find((e=>e.__isgene));o||reject("no gene track");const i=[];await R.UE({args:[g().join(r().tpmasterdir,o.file),e.query.chr+":"+s+"-"+s],callback:e=>{const t=e.split("\t")[3];if(!t)return;const s=JSON.parse(t);if(!s.isoform)return;const r={isoform:s.isoform},o=n.genedb.getjsonbyisoform.get(s.isoform);o&&(r.name=JSON.parse(o.genemodel).name,r.isdefault=o.isdefault),i.push(r)}}),t.send({lst:i})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/ase",(async function(e,t){const n=e.query,s=3e6,o=5e5;try{const e=Lr[n.genome];if(!e)throw"invalid genome";if(!n.samplename)throw"samplename missing";if(!n.chr)throw"no chr";if(!n.start||!n.stop)throw"no start/stop";if(!n.rnabarheight)throw"no rnabarheight";if(!n.dnabarheight)throw"no dnabarheight";if(!Number.isInteger(n.barypad))throw"invalid barypad";if(n.rnamax&&!Number.isFinite(n.rnamax))throw"invalid value for rnamax";if(!n.checkrnabam)throw".checkrnabam{} missing";const i=uo(n.checkrnabam);if(i)throw i;if(n.refcolor||(n.refcolor="blue"),n.altcolor||(n.altcolor="red"),!e.tracks)throw"genome.tracks[] missing";const a=e.tracks.find((e=>e.__isgene));if(!a)throw"no gene track from this genome";await async function(e,t){if(e.rnabamfile)e.rnabamfile=g().join(r().tpmasterdir,e.rnabamfile);else{if(!e.rnabamurl)throw"no file or url for rna bam";e.rnabamurl_dir=await R.d1(e.rnabamurl,e.rnabamindexURL||e.rnabamurl+".bai")}if(e.rnabam_nochr=await R.Dp(e.rnabamfile||e.rnabamurl,t,e.rnabamurl_dir),e.vcffile)e.vcffile=g().join(r().tpmasterdir,e.vcffile);else{if(!e.vcfurl)throw"no file or url for vcf";e.vcfurl_dir=await R.d1(e.vcfurl,e.vcfindexURL)}e.vcf_nochr=await R.Jy(e.vcffile||e.vcfurl,e.vcfurl_dir,t)}(n,e);const l=await ho(e,a,n.chr,n.start,n.stop),c={};if(n.stop-n.start<s)for(const[e,t]of l){const e={file:n.rnabamfile,url:n.rnabamurl,dir:n.rnabamurl_dir,nochr:n.rnabam_nochr};let s;s=n.rnabamispairedend?await oo(e,n.chr,t):await ro(e,n.chr,t),t.fpkm=1e9*s/(n.rnabamtotalreads*t.exonlength)}else c.fpkmrangelimit=s;const[u,f,d,p]=function(e,t){let n=e.start,s=e.stop;for(const[e,r]of t)n=Math.min(n,r.start),s=Math.max(s,r.stop);const r=e.start,o=e.stop;return[n,s,r,o]}(n,l),h=await async function(e,t,n,s,r){const o=await yo(e.vcffile||e.vcfurl,e.vcfurl_dir),[i,a,l,c]=$.e(o);if(c)throw c;const u={info:i,format:a,samples:l},f=await go(e.vcffile||e.vcfurl,(e.vcf_nochr?e.chr.replace("chr",""):e.chr)+":"+s+"-"+r,e.vcfurl_dir),d=[];for(const t of f||[]){const[n,s,r]=$.S(t,u);for(const t of s){if(!F.basecolor[t.ref]||!F.basecolor[t.alt])continue;if(!t.sampledata)continue;const n=mo(t,e.samplename,e.checkrnabam);n&&d.push(n)}}const p=[];for(const e of d)for(const[t,s]of n)if(e.pos>=s.start&&e.pos<=s.stop){p.push(e);break}return p}(n,0,l,u,f);for(const e of h)e.rnacount={nocoverage:1};let y,b;p-d>=o?c.covplotrangelimit=o:(n.rnamax?y=n.rnamax:(y=await async function(e,t,n){let s=0;return await R.UE({isbam:!0,args:["depth","-r",(e.rnabam_nochr?e.chr.replace("chr",""):e.chr)+":"+(t+1)+"-"+(n+1),"-g","DUP",e.rnabamurl||e.rnabamfile],dir:e.rnabamurl_dir,callback:e=>{const t=e.split("\t");if(3!=t.length)return;const n=Number.parseInt(t[2]);Number.isInteger(n)&&(s=Math.max(s,n))}}),s}(n,d,p),c.rnamax=y),b=await async function(e,t,n,s,r){const o=new Map;for(const e of s)e.dnacount.ishet&&e.pos>=t&&e.pos<=n&&o.set(e.pos,e);const i=(0,N.createCanvas)(e.width*e.devicePixelRatio,(e.rnabarheight+e.barypad+e.dnabarheight)*e.devicePixelRatio),a=i.getContext("2d");e.devicePixelRatio>1&&a.scale(e.devicePixelRatio,e.devicePixelRatio);let l,c,u=!1;n-t<=e.width?(u=!0,l=1,c=e.width/(n-t),a.lineWidth=c):(c=1,l=(n-t)/e.width);return await R.UE({isbam:!0,args:["depth","-r",(e.rnabam_nochr?e.chr.replace("chr",""):e.chr)+":"+(t+1)+"-"+(n+1),"-g","DUP",e.rnabamurl||e.rnabamfile],dir:e.rnabamurl_dir,callback:n=>{const s=n.split("\t");if(3!=s.length)return;const i=Number.parseInt(s[1])-1;if(!Number.isInteger(i))return;const f=Number.parseInt(s[2]);if(!Number.isInteger(f))return;const d=e.rnabarheight*Math.min(f,r)/r,p=u?(i-t)*c:(i-t)/l;a.strokeStyle="#ccc",a.beginPath(),a.moveTo(p+c/2,e.rnabarheight),a.lineTo(p+c/2,e.rnabarheight-d),a.stroke(),a.closePath(),f>r&&(a.strokeStyle="blue",a.beginPath(),a.moveTo(p+c/2,0),a.lineTo(p+c/2,2),a.stroke(),a.closePath());const m=o.get(i);m&&(m.rnacount.h=d)}}),{canvas:i,ctx:a,isbp:u,binpxw:c,binbpsize:l}}(n,d,p,h,y)),c.coveragesrc=await function(e,t,n,s,r,o,i,a){const l=[];for(const n of t)n.dnacount.ishet&&l.push((e.rnabam_nochr?e.chr.replace("chr",""):e.chr)+":"+(n.pos+1)+"-"+(n.pos+1));return new Promise(((n,s)=>{const c=(0,q.spawn)(Ur,["mpileup","-q",e.checkrnabam.rnapileup_q,"-Q",e.checkrnabam.rnapileup_Q,"--no-reference","-a","INFO/AD","-d",999999,"-r",l.join(","),e.rnabamurl||e.rnabamfile],{cwd:e.rnabamurl_dir});O().createInterface({input:c.stdout}).on("line",(e=>{if("#"==e[0])return;const n=po(e);if(!n)return;let s;n.pos>=r&&n.pos<=o&&n.DP;const i=t.find((e=>e.pos==n.pos));if(i){i.__x=s;const e=n.allele2count[i.ref]||0,t=n.allele2count[i.alt]||0;e+t>0&&(delete i.rnacount.nocoverage,i.rnacount.ref=e,i.rnacount.alt=t,i.rnacount.f=t/(e+t))}})),c.on("close",(()=>{if(!i)return void n();const{canvas:s,ctx:l,binpxw:c}=i;l.lineWidth=Math.max(3,c);let u=0;for(const n of t)n.dnacount&&(n.pos<r||n.pos>o||(n.__x=e.width*(n.pos-r)/(o-r),u=Math.max(u,n.dnacount.ref+n.dnacount.alt)));for(const n of t){if(null==n.__x)continue;n.rnacount.nocoverage||(null==n.rnacount.h&&(n.rnacount.h=e.rnabarheight*(n.rnacount.ref+n.rnacount.alt)/a),l.strokeStyle=e.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight),l.lineTo(n.__x+c/2,e.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.stroke(),l.closePath(),l.strokeStyle=e.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.lineTo(n.__x+c/2,e.rnabarheight-n.rnacount.h),l.stroke(),l.closePath());const t=e.dnabarheight*(n.dnacount.ref+n.dnacount.alt)/u;n.dnacount.ishet&&(l.strokeStyle=e.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight+e.barypad),l.lineTo(n.__x+c/2,e.rnabarheight+e.barypad+(1-n.dnacount.f)*t),l.stroke(),l.closePath(),l.strokeStyle=e.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,e.rnabarheight+e.barypad+(1-n.dnacount.f)*t),l.lineTo(n.__x+c/2,e.rnabarheight+e.barypad+t),l.stroke(),l.closePath()),delete n.__x}n(s.toDataURL())}))}))}(n,h,0,0,d,p,b,y),await async function(e,t){if(0==e.length)return;const n=[];for(const s of e)s.rnacount.nocoverage||s.rnacount.ref+s.rnacount.alt<t.checkrnabam.rna_mintotalreads||n.push(s);if(0==n.length)return;const s=await function(e){const t=g().join(r().cachedir,Math.random().toString())+".snp",n=[];for(const t of e)t.rnacount.nocoverage||null!=t.rnacount.ref&&null!=t.rnacount.alt&&n.push(t.pos+"."+t.ref+"."+t.alt+"\t\t\t\t\t\t\t\t"+t.rnacount.ref+"\t"+t.rnacount.alt);return new Promise(((e,s)=>{m().writeFile(t,n.join("\n")+"\n",(n=>{n&&s("cannot write"),e(t)}))}))}(n),o=await fo(s);await function(e,t){return new Promise(((n,s)=>{m().readFile(t,"utf8",((t,r)=>{t&&s("cannot read binom pvalue"),r||n();for(const t of r.trim().split("\n")){const n=t.split("\t"),s=e.find((e=>n[0]==e.pos+"."+e.ref+"."+e.alt));s&&(s.rnacount.pvalue=Number.parseFloat(n[10]))}n()}))}))}(e,o),m().unlink(s,(()=>{})),m().unlink(o,(()=>{}))}(h,n),c.genes=function(e,t,n){const s=[];for(const[r,o]of t){s.push(o);const t=e.filter((e=>e.pos>=o.start&&e.pos<=o.stop));if(0==t.length){o.nosnp=1;continue}o.snps=t;const r=t.filter((e=>null!=e.rnacount.pvalue));if(0==r.length){o.nornasnp=1;continue}const i=r.reduce(((e,t)=>e+Math.abs(t.rnacount.f-.5)),0);let a=null,l=0;for(const e of r)null==a?a=e.rnacount.pvalue:a*=e.rnacount.pvalue,e.rnacount.pvalue<=n.checkrnabam.binompvaluecutoff&&l++;o.ase={markers:t.filter((e=>e.dnacount.ishet)).length,ase_markers:l,mean_delta:i/r.length,geometricmean:Math.pow(a,1/r.length)}}return s}(h,l,n);let v=0;for(const e of h)e.dnacount&&e.pos>=d&&e.pos<=p&&(v=Math.max(v,e.dnacount.ref+e.dnacount.alt));c.dnamax=v,t.send(c)}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.post(Jr+"/bamnochr",(async function(e,t){const n=e.query;try{const e=Lr[n.genome];if(!e)throw"invalid genome";if(n.file)n.file=g().join(r().tpmasterdir,n.file);else{if(!n.url)throw"no bam file or url";n.url_dir=await R.d1(n.url,n.indexURL||n.url+".bai")}const s=await R.Dp(n.file||n.url,e,n.url_dir);t.send({nochr:s})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}})),Br.get(Jr+"/gene2canonicalisoform",(function(e,t){try{if(!e.query.gene)throw".gene missing";const n=Lr[e.query.genome];if(!n)throw"unknown genome";if(!n.genedb.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const s=n.genedb.get_gene2canonicalisoform.get(e.query.gene);t.send(s)}catch(e){t.send({error:e.message||e}),e.stack&&console.log(e.stack)}})),Br.get(Jr+"/ideogram",(function(e,t){try{const n=Lr[e.query.genome];if(!n)throw"invalid genome";if(!n.genedb.hasIdeogram)throw"ideogram not supported on this genome";if(!e.query.chr)throw".chr missing";const s=n.genedb.getIdeogramByChr.all(e.query.chr);if(!s.length)throw"no ideogram data for this chr";t.send(s)}catch(e){t.send({error:e.message||e})}}));R.lY,R.ZX;function jo(e){const t=e.split(/\r?\n/);if(t.length<=1||!t[0])return[null,[]];const n=t[0].split("\t"),s=[];for(let e=1;e<t.length;e++){if("#"==t[e][0])continue;const r=t[e].split("\t"),o={};for(let e=0;e<n.length;e++){const t=r[e];t&&(o[n[e]]=t)}s.push(o)}return[null,s]}async function To(e){try{await m().promises.stat(e.tpmasterdir)}catch(t){const n="Error with "+e.tpmasterdir+": "+t.code;if("validate"==process.argv[2])throw n;return void console.log("\n!!! "+n+"\n")}if(function(){if(r().features.skip_checkDependenciesAndVersions)return void console.log("SKIPPED checkDependenciesAndVersions()");const e=["jsonlite","cmprsk","hwde","lmtest"];for(const t of e){const e=x().spawnSync(r().Rscript,["-e",`suppressPackageStartupMessages(library("${t}"))`],{encoding:"utf8"});if(e.stderr.trim())throw e.stderr}const t=10;{const e=x().execSync(r().samtools+" --version",{encoding:"utf8"}).trim().split("\n"),[n,s]=e[0].split(" ");if("samtools"!=n||!s)throw'cannot run "samtools version"';const[o,i]=s.split(".");if("1"!=o)throw"samtools not 1.*";if(Number(i)<t)throw`samtools not >= 1.${t}`}{const e=x().execSync(r().bcftools+" -v",{encoding:"utf8"}).trim().split("\n"),[n,s]=e[0].split(" ");if("bcftools"!=n||!s)throw'cannot run "bcftools version"';const[o,i]=s.split(".");if("1"!=o)throw"bcftools not 1.*";if(Number(i)<t)throw`bcftools not >= 1.${t}`}}(),null!=e.base_zindex){const t=Number.parseInt(e.base_zindex);if(Number.isNaN(t)||t<=0)throw"base_zindex must be positive integer";e.base_zindex=t}if(e.jwt){if(!e.jwt.secret)throw"jwt.secret missing";if(!e.jwt.permissioncheck)throw"jwt.permissioncheck missing"}if(!e.tpmasterdir)throw".tpmasterdir missing";if(!e.cachedir)throw".cachedir missing";if(e.cachedir_massSession=await Io("massSession"),e.cachedir_massSessionTrash=await Io("massSessionTrash"),e.cache_snpgt={dir:await Io("snpgt"),fileNameRegexp:/[^\w]/,sampleColumn:6},e.cachedir_bam=await Io("bam"),e.cachedir_genome=await Io("genome"),e.cachedir_ssid=await Io("ssid"),e.commonOverrides&&F.applyOverrides(e.commonOverrides),!e.genomes)throw".genomes[] missing";if(!Array.isArray(e.genomes))throw".genomes[] not array";for(const t of e.genomes){if(!t.name)throw".name missing from a genome: "+JSON.stringify(t);if(!t.file)throw".file missing from genome "+t.name;const n=g().join(process.cwd(),t.file),s=require(m().existsSync(n)?n:t.file),r=s.default||s;if(Lr[t.name]=r,!r.genomefile)throw".genomefile missing from .js file of genome "+t.name;if("NA"==r.genomefile||(r.genomefile=g().join(e.tpmasterdir,r.genomefile)),r.genomicNameRegexp||(r.genomicNameRegexp=/[^a-zA-Z0-9.:_-]/),r.tracks||(r.tracks=[]),t.tracks)for(const e of t.tracks)r.tracks.push(e);if(t.datasets&&(r.rawdslst=t.datasets),t.snp&&(r.snp=t.snp),t.blat){if(!t.blat.host)throw".blat.host missing for "+t.name;if(!t.blat.port)throw".blat.port missing for "+t.name;r.blat=t.blat}if(t.nosnp&&delete r.snp,t.nohicenzyme&&delete r.hicenzymefragment,t.nohicdomain&&delete r.hicdomain,r.genedb&&t.no_gene2canonicalisoform&&delete r.genedb.gene2canonicalisoform,t.updateAttr)for(const e of t.updateAttr){let t=r;for(const[n,s]of e.entries())if(t)if("object"==typeof s)for(const e in s)t[e]=s[e];else{if("string"==typeof t[s]){e[n+1]&&(t[s]=e[n+1]);break}t=t[s]}}}e.defaultgenome&&Lr[e.defaultgenome]&&(Lr[e.defaultgenome].isdefault=!0);for(const t in Lr){const n=Lr[t];if(!n.majorchr)throw t+": majorchr missing";if(!n.defaultcoord)throw t+": defaultcoord missing";if(await R.Kf(n,n.defaultcoord.chr+":"+n.defaultcoord.start+"-"+(n.defaultcoord.start+1)),n.tracks||(n.tracks=[]),"string"==typeof n.majorchr){const e=n.majorchr.trim().split(/[\s\t\n]+/),s={},r=[];for(let n=0;n<e.length;n+=2){const o=e[n],i=Number.parseInt(e[n+1]);if(Number.isNaN(i))throw t+" majorchr invalid chr size for "+o+" ("+e[n+1]+")";s[o]=i,r.push(o)}n.majorchr=s,n.majorchrorder=r}n.chrlookup={};for(const e in n.majorchr)n.chrlookup[e.toUpperCase()]={name:e,len:n.majorchr[e],major:!0};if(n.minorchr){if("string"==typeof n.minorchr){const e=n.minorchr.trim().split(/[\s\t\n]+/),s={};for(let n=0;n<e.length;n+=2){const r=Number.parseInt(e[n+1]);if(Number.isNaN(r))throw t+" minorchr invalid chr size for "+e[n]+" ("+e[n+1]+")";s[e[n]]=r}n.minorchr=s}for(const e in n.minorchr)n.chrlookup[e.toUpperCase()]={name:e,len:n.minorchr[e]}}if(n.genedb){if(!n.genedb.dbfile)throw t+": .genedb.dbfile missing";try{console.log("Connecting",n.genedb.dbfile),n.genedb.db=R.sE(n.genedb.dbfile)}catch(e){throw`Cannot connect genedb: ${n.genedb.dbfile}: ${e}`}n.genedb.getnamebynameorisoform=n.genedb.db.prepare("select name from genes where name=? or isoform=?"),n.genedb.getnamebyisoform=n.genedb.db.prepare("select distinct name from genes where isoform=?"),n.genedb.getjsonbyname=n.genedb.db.prepare("select isdefault,genemodel from genes where name=?"),n.genedb.getjsonbyisoform=n.genedb.db.prepare("select isdefault,genemodel from genes where isoform=?"),n.genedb.getnameslike=n.genedb.db.prepare("select distinct name from genes where name like ? limit 20");const e=(0,bs.jj)(n.genedb.db);e.has("genealias")&&(n.genedb.getNameByAlias=n.genedb.db.prepare("select name from genealias where alias=?"),n.genedb.getAliasByName=n.genedb.db.prepare("select alias from genealias where name=?")),e.has("gene2coord")&&(n.genedb.getCoordByGene=n.genedb.db.prepare("select * from gene2coord where name=?")),e.has("ideogram")?(n.genedb.hasIdeogram=!0,n.genedb.getIdeogramByChr=n.genedb.db.prepare("select * from ideogram where chromosome=?")):n.genedb.hasIdeogram=!1,e.has("gene2canonicalisoform")&&(n.genedb.get_gene2canonicalisoform=n.genedb.db.prepare("select isoform from gene2canonicalisoform where gene=?")),e.has("buildDate")&&(n.genedb.get_buildDate=n.genedb.db.prepare("select date from buildDate")),n.genedb.hasTable_refseq2ensembl=e.has("refseq2ensembl"),n.genedb.sqlTables=[...e],n.genedb.tableSize={};for(const t of e)"buildDate"!=t&&(n.genedb.tableSize[t]=n.genedb.db.prepare(`select count(*) as size from ${t}`).get().size)}if(n.termdbs)for(const e in n.termdbs)(0,bs.JV)(n.termdbs[e],Dr),console.log(`${e} initiated as ${t}-level termdb`);for(const t of n.tracks)if(t.__isgene){if(!t.file)throw"Tabix file missing for gene track: "+JSON.stringify(t);try{await R.LC(g().join(e.tpmasterdir,t.file))}catch(e){throw"Error with "+t.file+": "+e}}if(n.proteindomain){if(!n.proteindomain.dbfile)throw t+".proteindomain: missing dbfile for sqlite db";if(!n.proteindomain.statement)throw t+".proteindomain: missing statement for sqlite db";let e;try{console.log("Connecting",n.proteindomain.dbfile),e=R.sE(n.proteindomain.dbfile)}catch(e){throw"Error with "+n.proteindomain.dbfile+": "+e}n.proteindomain.getbyisoform=e.prepare(n.proteindomain.statement)}if(n.snp){if(!n.snp.bigbedfile)throw t+".snp: missing bigBed file";n.snp.bigbedfile=g().join(e.tpmasterdir,n.snp.bigbedfile),await R.Ic(n.snp.bigbedfile)}if(n.fimo_motif){if(!n.fimo_motif.db)throw t+".fimo_motif: db file missing";if(n.fimo_motif.db=g().join(e.tpmasterdir,n.fimo_motif.db),n.fimo_motif.annotationfile){const[t,s]=jo(m().readFileSync(g().join(e.tpmasterdir,n.fimo_motif.annotationfile),{encoding:"utf8"}).trim());n.fimo_motif.tf2attr={};for(const e of s)n.fimo_motif.tf2attr[e.Model.split("_")[0]]=e}}if(n.hicenzymefragment){if(!Array.isArray(n.hicenzymefragment))throw"hicenzymefragment should be an array";for(const t of n.hicenzymefragment){if(!t.enzyme)throw".enzyme missing for one element of hicenzymefragment[]";if(!t.file)throw".file missing for one element of hicenzymefragment[]";try{await R.LC(g().join(e.tpmasterdir,t.file))}catch(e){throw"Error with "+t.file+": "+e}}}if(n.hicdomain){if(!n.hicdomain.groups)throw".groups{} missing from hicdomain";for(const t in n.hicdomain.groups){const s=n.hicdomain.groups[t];if(!s.name)throw".name missing from hicdomain "+t;if(!s.sets)throw".set{} missing from hicdomain "+t;for(const n in s.sets){const r=s.sets[n];if(!r.name)throw".name missing from hicdomain "+t+" > "+n;if(!r.file)throw".file missing from hicdomain "+t+" > "+n;r.file=g().join(e.tpmasterdir,r.file);try{await R.LC(r.file)}catch(e){throw"Error with "+r.file+": "+e}}}}if(n.rawdslst){n.datasets={};for(const e of n.rawdslst){if(e.skip)continue;if(!e.name)throw"a nameless dataset from "+t;if(n.datasets[e.name])throw t+" has duplicating dataset name: "+e.name;if(!e.jsfile)throw"jsfile not available for dataset "+e.name+" of "+t;const s=g().join(process.cwd(),e.jsfile),r=require(m().existsSync(s)?s:e.jsfile),o="function"==typeof r?r(F):"function"==typeof r?.default?r.default(F):r.default||r;if(vs(o,e),o.noHandleOnClient=e.noHandleOnClient,o.label=e.name,o.genomename=t,n.datasets[o.label]=o,o.isMds3)try{await Ts(o,n,0,Br,Jr)}catch(e){throw e.stack&&console.log(e.stack),"Error with mds3 dataset "+o.label+": "+e}else if(o.isMds)try{await Ro(o,n,e)}catch(e){throw"Error with mds dataset "+o.label+": "+e}else Oo(o,n)}Mo(),delete n.rawdslst}}}async function Mo(){const e=await m().promises.readdir(r().cachedir_massSession);try{e.forEach((async e=>{const t=(await m().promises.stat(g().join(r().cachedir_massSession,e))).birthtime,n=new Date,s=new Date(t),o=r().features.massSessionDuration||30;Math.round((n.getTime()-s.getTime())/864e5)>o&&(await m().promises.copyFile(g().join(r().cachedir_massSession,e),g().join(r().cachedir_massSessionTrash,e)),await m().promises.unlink(g().join(r().cachedir_massSession,e)),console.log("File deleted: ",e,t))}))}catch(e){throw`Error: ${e}`}}function Oo(e,t){if(e.dbfile)try{console.log("Connecting",e.dbfile),e.newconn=R.sE(e.dbfile)}catch(t){throw"Error with "+e.dbfile+": "+t}if(e.snvindel_attributes)for(const t of e.snvindel_attributes)if(t.lst)for(const e of t.lst)e.get=e.get.toString();else t.get=t.get.toString();if(e.cohort){if(e.cohort.levels){if(!Array.isArray(e.cohort.levels))throw"cohort.levels must be array for "+e.genomename+"."+e.label;if(0==e.cohort.levels.length)throw"levels is blank array for cohort of "+e.genomename+"."+e.label;for(const t of e.cohort.levels)if(!t.k)throw".k key missing in one of the levels, .cohort, in "+e.genomename+"."+e.label}if(e.cohort.fromdb){if(!e.cohort.fromdb.sql)throw".sql missing from ds.cohort.fromdb in "+e.genomename+"."+e.label;const t=e.newconn.prepare(e.cohort.fromdb.sql).all();delete e.cohort.fromdb,e.cohort.raw=t,console.log(t.length+" rows retrieved for "+e.label+" sample annotation")}if(e.cohort.files){let t=[];for(const n of e.cohort.files){if(!n.file)throw".file missing from one of cohort.files[] for "+e.genomename+"."+e.label;const s=m().readFileSync(g().join(r().tpmasterdir,n.file),"utf8").trim();if(!s)throw n.file+" is empty for "+e.genomename+"."+e.label;t=[...t,...Q(s)]}delete e.cohort.files,e.cohort.raw?e.cohort.raw=[...e.cohort.raw,...t]:e.cohort.raw=t,console.log(t.length+" rows retrieved for "+e.label+" sample annotation")}if(e.cohort.tosampleannotation){if(!e.cohort.tosampleannotation.samplekey)throw".samplekey missing from .cohort.tosampleannotation for "+e.genomename+"."+e.label;if(!e.cohort.key4annotation)throw".cohort.key4annotation missing when .cohort.tosampleannotation is on for "+e.genomename+"."+e.label}}if(!e.queries)throw".queries missing from dataset "+e.label+", "+e.genomename;if(!Array.isArray(e.queries))throw e.label+".queries is not array";for(const n of e.queries){const s=Eo(n,e,t);if(s)throw'Error parsing a query in "'+e.label+'": '+s}if(e.vcfinfofilter){const t=F.validate_vcfinfofilter(e.vcfinfofilter);if(t)throw e.label+": vcfinfofilter error: "+t}if(e.url4variant)for(const t of e.url4variant){if(!t.makelabel)throw"makelabel() missing for one item of url4variant from "+e.label;if(!t.makeurl)throw"makeurl() missing for one item of url4variant from "+e.label;t.makelabel=t.makelabel.toString(),t.makeurl=t.makeurl.toString()}}async function Io(e){const t=g().join(r().cachedir,e);try{await m().promises.stat(t)}catch(e){if("ENOENT"!=e.code)throw"error stating dir";try{await m().promises.mkdir(t)}catch(e){throw"cannot make dir"}}return t}function Eo(e,t,n){if(!e.name)return".name missing";if(e.dsblocktracklst){if(!Array.isArray(e.dsblocktracklst))return"dsblocktracklst not an array in "+t.label;for(const n of e.dsblocktracklst){if(!n.type)return"missing type for a blocktrack of "+t.label;if(!n.file&&!n.url)return"neither file or url given for a blocktrack of "+t.label}}else if(e.vcffile){const t=x().execSync(Pr+" -H "+g().join(r().tpmasterdir,e.vcffile),{encoding:"utf8"}).trim();if(""==t)return"no meta lines in VCF file "+e.vcffile+" of query "+e.name;const[s,o,i,a]=$.e(t.split("\n"));if(a)return"error parsing VCF meta lines of "+e.vcffile+": "+a.join("; ");e.vcf={vcfid:Math.random().toString(),info:s,format:o,samples:i},e.hlinfo&&(e.vcf.hlinfo=e.hlinfo,delete e.hlinfo),e.infopipejoin&&(e.vcf.infopipejoin=e.infopipejoin,delete e.infopipejoin);const l=x().execSync(Pr+" -l "+g().join(r().tpmasterdir,e.vcffile),{encoding:"utf8"}).trim();if(""==l)return"tabix -l found no chromosomes/contigs in "+e.vcffile+" of query "+e.name;e.vcf.nochr=F.contigNameNoChr(n,l.split("\n"));let c=0;if(s)for(const e in s)c++;console.log("Parsed vcf meta from "+e.vcffile+": "+c+" INFO, "+i.length+" sample, "+(e.vcf.nochr?'no "chr"':'has "chr"'))}else{if(!e.makequery)return"do not know how to parse query: "+e.name;if(e.isgeneexpression){if(!e.config)return"config object missing for gene expression query of "+e.name;e.config.maf&&(e.config.maf.get=e.config.maf.get.toString())}}}async function Ro(e,t,n){if((e.isMds2||e.isMds3||e.isMds)&&vs(e,n),e.assayAvailability){if(!e.assayAvailability.file)throw".assayAvailability.file missing";if(!e.assayAvailability.assays)throw".assayAvailability.assays[] missing";Object.freeze(e.assayAvailability.assays),e.assayAvailability.samples=new Map;for(const t of m().readFileSync(g().join(r().tpmasterdir,e.assayAvailability.file),{encoding:"utf8"}).trim().split("\n")){const[n,s]=t.split("\t");e.assayAvailability.samples.set(n,JSON.parse(s))}console.log(e.assayAvailability.samples.size+" samples with assay availability ("+e.label+")")}if(e.gene2mutcount){if(!e.gene2mutcount.dbfile)throw".gene2mutcount.dbfile missing";try{console.log("Connecting",e.gene2mutcount.dbfile),e.gene2mutcount.db=R.sE(e.gene2mutcount.dbfile),console.log("DB connected for "+e.label+": "+e.gene2mutcount.dbfile)}catch(t){throw`Error connecting db at ${e.gene2mutcount.dbfile}`}}if(e.sampleAssayTrack){if(!e.sampleAssayTrack.file)throw".file missing from sampleAssayTrack";e.sampleAssayTrack.samples=new Map;let t=0,n=new Set;for(const s of m().readFileSync(g().join(r().tpmasterdir,e.sampleAssayTrack.file),{encoding:"utf8"}).trim().split("\n")){if(!s)continue;if("#"==s[0])continue;const[r,o,i]=s.split("\t");if(!o||!i)continue;if(!e.sampleAssayTrack.samples.has(r)){if(e.cohort&&e.cohort.annotation&&!e.cohort.annotation[r]){n.add(r);continue}e.sampleAssayTrack.samples.set(r,[])}const a=JSON.parse(i);if(!F.tkt[a.type])throw"invalid type from a sample track: "+i;a.name||(a.name=r+" "+o),a.assayName=o,e.sampleAssayTrack.samples.get(r).push(a),t++}console.log(t+" assay-tracks from "+e.sampleAssayTrack.samples.size+" samples ("+e.label+")"),n.size&&console.log("Error: "+n.size+" samples with assay tracks are unannotated: "+[...n].join(" "))}if(e.singlesamplemutationjson){const t=e.singlesamplemutationjson;if(!t.file)throw".file missing from singlesamplemutationjson";t.samples={};let n=0;for(const e of m().readFileSync(g().join(r().tpmasterdir,t.file),{encoding:"utf8"}).trim().split("\n")){if(!e)continue;if("#"==e[0])continue;const[s,r]=e.split("\t");s&&r&&(n++,t.samples[s]=r)}console.log(n+" samples for disco plot")}if(e.cohort&&e.cohort.db&&e.cohort.termdb&&await Ks(e,Br,Jr),e.cohort&&e.cohort.files){if(!Array.isArray(e.cohort.files))throw".cohort.files is not array";if(!e.cohort.tohash)throw".tohash() missing from cohort";if("function"!=typeof e.cohort.tohash)throw".cohort.tohash is not function";if(!e.cohort.samplenamekey)throw".samplenamekey missing";if(e.cohort.annotation={},e.cohort.mutation_signature){const t=e.cohort.mutation_signature;if(!t.sets)throw".mutation_signature.sets missing";for(const n in t.sets){const s=t.sets[n];if(s.name||(s.name=n),!s.signatures)throw".signatures{} missing from a signature set";if(s.samples){if(!s.samples.file)throw".samples.file missing from a signature set";const[t,n]=jo(m().readFileSync(g().join(r().tpmasterdir,s.samples.file),{encoding:"utf8"}).trim());s.samples.map=new Map;for(const t of n){const n=t[e.cohort.samplenamekey];if(!n)throw e.cohort.samplenamekey+" missing in file "+s.samples.file;s.samples.map.set(n,t);for(const e in s.signatures)if(t[e]){const r=Number.parseFloat(t[e]);if(Number.isNaN(r))throw"mutation signature value is not float: "+t[e]+" from sample "+n;s.samples.skipzero&&0==r?delete t[e]:t[e]=r}}}}}if(e.cohort.attributes){if(!e.cohort.attributes.lst)throw".lst[] missing for cohort.attributes";if(!Array.isArray(e.cohort.attributes.lst))return".cohort.attributes.lst is not array";for(const t of e.cohort.attributes.lst){if(!t.key)throw".key missing from one of the .cohort.attributes.lst[]";if(!t.label)throw".label missing from one of the .cohort.attributes.lst[]";if(!t.values)throw".values{} missing from "+t.label+" of .cohort.attributes.lst";for(const e in t.values)if(!t.values[e].label)throw".label missing from one value of "+t.label+" in .cohort.attributes.lst"}if(e.cohort.attributes.defaulthidden)for(const t in e.cohort.attributes.defaulthidden){const n=e.cohort.attributes.lst.find((e=>e.key==t));if(!n)throw"invalid defaulthidden key: "+t;for(const s in e.cohort.attributes.defaulthidden[t])if(!n.values[s])throw"invalid defaulthidden value "+s+" for "+t}}if(e.cohort.hierarchies){if(!e.cohort.hierarchies.lst)throw".lst[] missing from .cohort.hierarchies";if(!Array.isArray(e.cohort.hierarchies.lst))throw".cohort.hierarchies.lst is not array";for(const t of e.cohort.hierarchies.lst){if(!t.name)throw".name missing from one hierarchy";if(!t.levels)throw".levels[] missing from one hierarchy";if(!Array.isArray(t.levels))throw".levels is not array from one hierarchy";for(const e of t.levels)if(!e.k)throw".k missing from one level in hierarchy "+t.name}}if(e.cohort.sampleAttribute){if(!e.cohort.sampleAttribute.attributes)throw"attributes{} missing from cohort.sampleAttribute";for(const t in e.cohort.sampleAttribute.attributes){const n=e.cohort.sampleAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from cohort.sampleAttribute.attributes";if(n.values)for(const e in n.values){const t=n.values[e];if("object"!=typeof t)throw'value "'+e+'" not pointing to {} from sampleAttribute';t.name||(t.name=e)}if(n.showintrack&&!n.isinteger&&!n.isfloat)throw n.label+": .showintrack requires .isinteger or .isfloat"}}if(e.cohort.scatterplot){if(!e.cohort.sampleAttribute)throw".sampleAttribute missing but required for .cohort.scatterplot";const t=e.cohort.scatterplot;if(!t.querykey)throw".querykey missing from .cohort.scatterplot";{if(!e.queries)throw".cohort.scatterplot.querykey in use but ds.queries{} missing";const n=e.queries[t.querykey];if(!n)throw"unknown query by .cohort.scatterplot.querykey: "+t.querykey;if(n.type!=F.tkt.mdssvcnv)throw"type is not "+F.tkt.mdssvcnv+" of the track pointed to by .cohort.scatterplot.querykey"}if(t.colorbygeneexpression){if(!t.colorbygeneexpression.querykey)throw"querykey missing from .cohort.scatterplot.colorbygeneexpression";if(!e.queries)throw".cohort.scatterplot.colorbygeneexpression in use but ds.queries{} missing";const n=e.queries[t.colorbygeneexpression.querykey];if(!n)throw"unknown query by .cohort.scatterplot.colorbygeneexpression.querykey: "+t.colorbygeneexpression.querykey;if(!n.isgenenumeric)throw"isgenenumeric missing from the track pointed to by .cohort.scatterplot.colorbygeneexpression.querykey"}if(t.tracks,!t.x)throw".x missing from .cohort.scatterplot";if(!t.x.attribute)throw".attribute missing from .cohort.scatterplot.x";const n=e.cohort.sampleAttribute.attributes[t.x.attribute];if(!n)throw"scatterplot.x.attribute is not defined in sampleAttribute";if(!n.isfloat)throw'scatterplot.x is not "isfloat"';if(!t.y)throw".y missing from .cohort.scatterplot";if(!t.y.attribute)throw".attribute missing from .cohort.scatterplot.y";const s=e.cohort.sampleAttribute.attributes[t.y.attribute];if(!s)throw"scatterplot.y.attribute is not defined in sampleAttribute";if(!s.isfloat)throw'scatterplot.y is not "isfloat"';if(t.colorbyattributes)for(const n of t.colorbyattributes){if(!n.key)throw".key missing from one of scatterplot.colorbyattributes";const t=e.cohort.sampleAttribute.attributes[n.key];if(!t)throw"unknown attribute by key "+n.key+" from scatterplot.colorbyattributes";n.label=t.label,n.values=t.values}}for(const t of e.cohort.files){if(!t.file)throw".file missing from one of .cohort.files";const[n,s]=jo(m().readFileSync(g().join(r().tpmasterdir,t.file),{encoding:"utf8"}).trim());if(n)throw'cohort annotation file "'+t.file+'": '+n;console.log(e.label+": "+s.length+" samples loaded from annotation file "+t.file),s.forEach((t=>{for(const n in t){let s;e.cohort.sampleAttribute&&(s=e.cohort.sampleAttribute.attributes[n]),s||e.cohort.termdb&&e.cohort.termdb.termjson&&e.cohort.termdb.termjson.map&&(s=e.cohort.termdb.termjson.map.get(n)),s&&(s.isfloat?t[n]=Number.parseFloat(t[n]):s.isinteger&&(t[n]=Number.parseInt(t[n])))}e.cohort.tohash(t,e)}))}if(e.cohort.annorows=Object.values(e.cohort.annotation),console.log(e.label+": total samples from sample table: "+e.cohort.annorows.length),e.cohort.survivalplot){const t=e.cohort.survivalplot;if(!t.plots)throw".plots{} missing from survivalplot";t.init={plottypes:[]};for(const e in t.plots){const n=t.plots[e];if(!n.name)throw".name missing from survivalplot "+e;if(!n.serialtimekey)throw".serialtimekey missing from survivalplot "+e;if(!n.iscensoredkey)throw".iscensoredkey missing from survivalplot "+e;if(!n.timelabel)throw".timelabel missing from survivalplot "+e;n.key=e,t.init.plottypes.push({key:e,name:n.name,timelabel:n.timelabel})}if(t.samplegroupattrlst){t.init.samplegroupings=[];for(const n of t.samplegroupattrlst){if(!n.key)throw".key missing from an attr of samplegroupattrlst for survival";const s=e.cohort.sampleAttribute.attributes[n.key];if(!s)throw'unknown attribute key "'+n.key+'" from survival samplegroupattrlst';const r=new Map;for(const s in e.cohort.annotation){const o=e.cohort.annotation[s],i=o[n.key];if(null==i)continue;let a=!1;for(const e in t.plots)if(null!=o[t.plots[e].serialtimekey]){a=!0;break}a&&(r.has(i)?r.set(i,r.get(i)+1):r.set(i,1))}if(0==r.size)throw'no value found for "'+n.key+'" from survival samplegroupattrlst';const o=[];for(const[e,t]of r)o.push({value:e,count:t});t.init.samplegroupings.push({key:n.key,label:s.label,values:o})}}}}if(e.mutationAttribute){if(!e.mutationAttribute.attributes)throw"attributes{} missing from mutationAttribute";for(const t in e.mutationAttribute.attributes){const n=e.mutationAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from mutationAttribute.attributes";if(!n.appendto_link&&n.values)for(const e in n.values){if(!n.values[e].name)throw".name missing for value "+e+" of key "+t+" from mutationAttribute.attributes"}}}if(e.alleleAttribute){if(!e.alleleAttribute.attributes)throw"attributes{} missing from alleleAttribute";for(const t in e.alleleAttribute.attributes){const n=e.alleleAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from alleleAttribute.attributes";if(!n.isnumeric){if(!n.values)throw".values{} missing for non-numeric key "+t+" from alleleAttribute.attributes";for(const e in n.values){if(!n.values[e].name)throw".name missing for value "+e+" of key "+t+" from alleleAttribute.attributes"}}}}if(e.locusAttribute){if(!e.locusAttribute.attributes)throw"attributes{} missing from locusAttribute";for(const t in e.locusAttribute.attributes){const n=e.locusAttribute.attributes[t];if(!n.label)throw".label missing for key "+t+" from locusAttribute.attributes";if(!n.isnumeric&&!n.appendto_link){if(!n.values)throw".values{} missing for non-numeric key "+t+" from locusAttribute.attributes";for(const e in n.values){if(!n.values[e].name)throw".name missing for value "+e+" of key "+t+" from locusAttribute.attributes"}}}}if(e.queries)for(const s in e.queries){if(n.remove_queries&&-1!=n.remove_queries.indexOf(s)){delete e.queries[s];continue}const r=e.queries[s];if(n.hide_queries&&-1!=n.hide_queries.indexOf(s)&&(r.hideforthemoment=1),r.istrack){if(!r.type)throw".type missing for track query "+s;if(r.viewrangeupperlimit&&!Number.isInteger(r.viewrangeupperlimit))throw".viewrangeupperlimit should be integer for track query "+s;if(r.type==F.tkt.mdsjunction){const n=$o(r,e,t);if(n)throw s+" (mdsjunction) error: "+n}else if(r.type==F.tkt.mdscnv){const n=Po(r,e,t);if(n)throw s+" (mdscnv) error: "+n}else if(r.type==F.tkt.mdssvcnv){const n=Go(r,e,t);if(n)throw s+" (svcnv) error: "+n}else{if(r.type!=F.tkt.mdsvcf)throw"unknown track type for a query: "+r.type+" "+s;{const n=await zo(r,e,t);if(n)throw s+" (vcf) error: "+n}}Fo(r,e)}else{if(!r.isgenenumeric)throw"unknown type of query from "+s;{const n=Uo(r,e,t);if(n)throw s+" (genenumeric) error: "+n}}}if(e.track&&await Xs(e,t),e.annotationsampleset2matrix){if(!e.cohort)throw"ds.cohort misssing when annotationsampleset2matrix is in use";if(!e.cohort.annotation)throw"ds.cohort.annotation misssing when annotationsampleset2matrix is in use";if(!e.queries)throw"ds.queries misssing when annotationsampleset2matrix is in use";if(!e.annotationsampleset2matrix.key)throw".key STR missing in annotationsampleset2matrix";if(!e.annotationsampleset2matrix.groups)throw".groups{} missing in annotationsampleset2matrix";if("object"!=typeof e.annotationsampleset2matrix.groups)throw"ds.annotationsampleset2matrix.groups{} not an object";for(const t in e.annotationsampleset2matrix.groups){const n=e.annotationsampleset2matrix.groups[t];if(!n.groups||!Array.isArray(n.groups)||0==n.groups.length)throw".groups[] must be nonempty array in "+t;for(const s of n.groups){if(!s.name)throw".name missing from one of .groups[] in "+t;const n=s.matrixconfig;if(!n)throw".matrixconfig missing from one of .groups[] of "+t;if(!n.features)throw".features[] missing from group "+t;if(!Array.isArray(n.features))throw".features[] should be array from group "+t;if(0==n.features.length)throw".features[] zero length from group "+t;for(const s of n.features){if(e.annotationsampleset2matrix.commonfeatureattributes)for(const t in e.annotationsampleset2matrix.commonfeatureattributes)null==s[t]&&(s[t]=e.annotationsampleset2matrix.commonfeatureattributes[t]);if(!s.ismutation)return"unknown feature type from group "+t;if(!s.position)throw"position missing from feature "+JSON.stringify(s)+" from group "+t;if(!s.querykeylst)throw".querykeylst[] missing from ismutation feature from group "+t;if(!Array.isArray(s.querykeylst))throw".querykeylst[] not an array from ismutation feature from group "+t;if(0==s.querykeylst.length)throw".querykeylst[] zero length from ismutation feature from group "+t;for(const n of s.querykeylst)if(!e.queries[n])throw'unknown query key "'+n+'" from ismutation feature of group '+t}if(!n.limitsamplebyeitherannotation)throw".limitsamplebyeitherannotation[] missing from group "+t;if(!Array.isArray(n.limitsamplebyeitherannotation))throw".limitsamplebyeitherannotation[] should be array from group "+t;if(0==n.limitsamplebyeitherannotation.length)throw".limitsamplebyeitherannotation[] zero length from group "+t;for(const e of n.limitsamplebyeitherannotation){if(!e.key)throw"key missing from one of limitsamplebyeitherannotation from group "+t;if(!e.value)throw"value missing from one of limitsamplebyeitherannotation from group "+t}}}delete e.annotationsampleset2matrix.commonfeatureattributes}}function Fo(e,t){if(e.groupsamplebyattr){e.groupsamplebyattr.key2group=new Map;for(const n in t.cohort.annotation)co(n,[],e.groupsamplebyattr.key2group,[],t,e)}}function $o(e,t,n){if(e.readcountCutoff&&(!Number.isInteger(e.readcountCutoff)||e.readcountCutoff<1))return"readcountCutoff must be positive integer";let s;if(e.file){const[t,n]=Co(e.file);if(t)return"tabix file error: "+t;e.file=n,s=n}else{if(!e.url)return"no file or url given for mdsjunction "+e.name;s=e.url}const r={encoding:"utf8"};const o=x().execSync(Pr+" -H "+s,r).trim();if(o){const n=o.split("\n");if(1!=n.length)return"mdsjunction file has multiple header lines (begin with #), but should have just 1";const s=n[0].split("\t");if(s[5]){e.samples=s.slice(5),e.attributeSummary=Do(e.samples,t),e.hierarchySummary=Lo(e.samples,t);for(const t in e.hierarchySummary){let n=0;for(const s in e.hierarchySummary[t])n++;console.log(n+" "+t+" hierarchy levels for "+e.name)}}}{const t=x().execSync(Pr+" -l "+s,r).trim();if(!t)return"no chromosomes found";e.nochr=F.contigNameNoChr(n,t.split("\n"))}if(console.log("(mdsjunction) "+e.name+": "+(e.samples?e.samples.length:0)+" samples, "+(e.nochr?'no "chr"':'has "chr"')),!e.infoFilter)return".infoFilter{} missing";if(!e.infoFilter.lst)return".lst[] missing from .infoFilter";for(const t of e.infoFilter.lst){if(!t.key)return".key missing from one of infoFilter";if(!t.label)return".label missing from one of infoFilter";if(!t.categories)return".categories missing from one of infoFilter";for(const e in t.categories){if(!t.categories[e].label)return".label missing from one category of "+t.label;if(!t.categories[e].color)return".color missing from on category of "+t.label}if(t.hiddenCategories){for(const e in t.hiddenCategories)if(!t.categories[e])return"invalid hidden key "+e+" of "+t.label}else t.hiddenCategories={}}if(!e.singlejunctionsummary)return".singlejunctionsummary missing but is currently required from "+e.name;if(e.singlejunctionsummary.readcountboxplotpercohort){if(!e.singlejunctionsummary.readcountboxplotpercohort.groups)return".groups[] missing from query.singlejunctionsummary.readcountboxplotpercohort for "+e.name;for(const t of e.singlejunctionsummary.readcountboxplotpercohort.groups){if(!t.key)return".key missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups";if(!t.label)return".label missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups"}}}function Do(e,t){if(!(t.cohort&&t.cohort.annotation&&t.cohort.attributes&&e))return;const n={};for(const s of t.cohort.attributes.lst){const r={};for(const e in s.values)r[e]=0;for(const n of e){const e=t.cohort.annotation[n];if(!e)continue;const o=e[s.key];null!=o&&(o in r&&r[o]++)}n[s.key]=r}return n}function Lo(e,t){if(!t.cohort||!t.cohort.annotation||!t.cohort.hierarchies||0==e.length)return;const n=[];for(const s of e){const e=t.cohort.annotation[s];e&&n.push(e)}const s={};for(const e of t.cohort.hierarchies.lst){const t=(0,S.N)(n,e.levels),r=me()(t);r.sum((e=>e.value));const o={};r.eachBefore((e=>{o[e.id]=e.value})),s[e.name]=o}return s}function Po(e,t,n){let s;if(e.file){const[t,n]=Co(e.file);if(t)return"tabix file error: "+t;s=n}else{if(!e.url)return"no file or url given for (mdscnv) "+e.name;s=e.url}const r={encoding:"utf8"};const o=x().execSync(Pr+" -H "+s,r).trim();if(o){const n=o.split("\n");if(1!=n.length)return"mdscnv file has multiple header lines (begin with #), but should have just 1";const s=n[0].split("\t");e.samples=s.slice(5),e.attributeSummary=Do(e.samples,t),e.hierarchySummary=Lo(e.samples,t);for(const t in e.hierarchySummary){let n=0;for(const s in e.hierarchySummary[t])n++;console.log(n+" "+t+" hierarchy levels for "+e.name)}}{const t=x().execSync(Pr+" -l "+s,r).trim();if(!t)return"no chromosomes found";e.nochr=F.contigNameNoChr(n,t.split("\n"))}console.log("("+e.type+") "+e.name+": "+(e.samples?e.samples.length:"no")+" samples, "+(e.nochr?'no "chr"':'has "chr"'))}function Go(e,t,n){let s;if(e.file){const[t,n]=Co(e.file);if(t)return"tabix file error: "+t;s=n}else{if(!e.url)return"no file or url given for (svcnv) "+e.name;s=e.url}const r={encoding:"utf8"};const o=x().execSync(Pr+" -H "+s,r).trim();if(o){const n=new Set;for(const e of o.split("\n"))for(const t of e.split(" ").slice(1))n.add(t);if(0==n.size)return"no samples from the header line";if(e.samples=[...n],t.cohort&&t.cohort.annotation){const n=new Set;for(const s of e.samples)t.cohort.annotation[s]||n.add(s);n.size&&console.log("mdssvcnv unannotated samples: "+(e.noprintunannotatedsamples?n.size:[...n].join(" ")))}}{const t=x().execSync(Pr+" -l "+s,r).trim();if(!t)return"no chromosomes found";e.nochr=F.contigNameNoChr(n,t.split("\n"))}if(e.expressionrank_querykey){const n=t.queries[e.expressionrank_querykey];if(!n)return"invalid key by expressionrank_querykey";if(!n.isgenenumeric)return"query "+e.expressionrank_querykey+" not tagged as isgenenumeric"}if(e.vcf_querykey){const n=t.queries[e.vcf_querykey];if(!n)return"invalid key by vcf_querykey";if(n.type!=F.tkt.mdsvcf)return"query "+e.vcf_querykey+" not of mdsvcf type"}if(e.groupsamplebyattr){if(!e.groupsamplebyattr.attrlst)return".attrlst[] missing from groupsamplebyattr";if(0==e.groupsamplebyattr.attrlst.length)return"groupsamplebyattr.attrlst[] empty array";if(!t.cohort)return"groupsamplebyattr in use but ds.cohort missing";if(!t.cohort.annotation)return"groupsamplebyattr in use but ds.cohort.annotation missing";t.cohort.sampleAttribute||(t.cohort.sampleAttribute={}),t.cohort.sampleAttribute.attributes||(t.cohort.sampleAttribute.attributes={},console.log("cohort.sampleAttribute added when groupsamplebyattr is in use"));for(const n of e.groupsamplebyattr.attrlst){if(!n.k)return"k missing from one of groupsamplebyattr.attrlst[]";t.cohort.sampleAttribute.attributes[n.k]||(t.cohort.sampleAttribute.attributes[n.k]={label:n.label||n.k})}if(e.groupsamplebyattr.sortgroupby){if(!e.groupsamplebyattr.sortgroupby.key)return".key missing from .sortgroupby";if(!e.groupsamplebyattr.sortgroupby.order)return".order[] missing from .sortgroupby";if(!Array.isArray(e.groupsamplebyattr.sortgroupby.order))return".order must be an array"}e.groupsamplebyattr.attrnamespacer||(e.groupsamplebyattr.attrnamespacer=", ")}console.log("("+e.type+") "+e.name+": "+(e.samples?e.samples.length:"no")+" samples, "+(e.nochr?'no "chr"':'has "chr"'))}function Uo(e,t,n){if(!e.datatype)return"datatype missing";if(e.viewrangeupperlimit&&Number.isNaN(e.viewrangeupperlimit))return"invalid value for viewrangeupperlimit";let s;if(!e.file)return"file missing";{const[t,n]=Co(e.file);if(t)return"tabix file error: "+t;s=n}const r={cwd:null,encoding:"utf8"};{const t=x().execSync(Pr+" -H "+s,r).trim();if(!t)return"no header line (#sample <sample1> ...)";const n=new Set;for(const e of t.split("\n")){const t=e.split(" ");for(let e=1;e<t.length;e++)n.add(t[e])}if(0==n.size)return"no sample names from header line";e.samples=[...n],console.log("(genenumeric) "+e.name+": "+e.samples.length+" samples")}if(e.boxplotbysamplegroup){if(!e.boxplotbysamplegroup.attributes)return"boxplotbysamplegroup.attributes missing";if(!Array.isArray(e.boxplotbysamplegroup.attributes))return"boxplotbysamplegroup.attributes should be array";for(const t of e.boxplotbysamplegroup.attributes)if(!t.k)return"k missing from one of boxplotbysamplegroup.attributes[]"}}async function zo(e,t,n){if(!e.tracks)return"tracks[] missing";if(!Array.isArray(e.tracks))return"tracks should be array";e.info={};for(const s of e.tracks){if(!s.file)return"file missing from a track (url not supported yet)";const[r,o]=Co(s.file);if(r)return"tabix file error: "+r;if(s.type!=F.mdsvcftype.vcf)return"invalid track type: "+s.type;{s.cwd;const t=await R.ZD(o,s.cwd);if(0==t.length)return"no meta/header lines for "+o;const[n,r,i,a]=$.e(t);if(a)return"error parsing vcf meta for "+o+": "+a.join("\n");if(0==i.length)return"vcf file has no sample: "+o;for(const t in n)e.info[t]=n[t];if(s.format=r,s.samplenameconvert){if("function"!=typeof s.samplenameconvert)return".samplenameconvert must be function";for(const e of i)e.name=s.samplenameconvert(e.name)}s.samples=i}if(t.cohort&&t.cohort.annotation){const e=[];for(const n of s.samples)t.cohort.annotation[n.name]||e.push(n.name);e.length&&console.log(t.label+": VCF "+s.file+" has unannotated samples: "+e.join(","))}{const e=[];if(await R.UE({args:["-l",o],dir:s.cwd,callback:t=>{e.push(t)}}),0==e.length)return"no chr from "+o;s.nochr=F.contigNameNoChr(n,e)}console.log("("+e.type+") "+o+": "+s.samples.length+" samples, "+(s.nochr?"no chr":"has chr"))}if(e.singlesamples){if(!e.singlesamples.tablefile)return".singlesamples.tablefile missing for the VCF query";e.singlesamples.samples={};let t=0;for(const n of m().readFileSync(g().join(r().tpmasterdir,e.singlesamples.tablefile),{encoding:"utf8"}).trim().split("\n")){if(!n)continue;if("#"==n[0])continue;const s=n.split("\t");s[0]&&s[1]&&(e.singlesamples.samples[s[0]]=s[1],t++)}console.log(t+" single-sample VCF files")}}},6191:(e,t,n)=>{"use strict";n.d(t,{i:()=>y});var s=n(7147),r=n(1017),o=n.n(r),i=n(9344),a=n.n(i),l=n(8088);async function c(e,t){!function(e){for(const t in e){const n=e[t];if("login"==n.type){if(n.embedders)throw"unexpected 'embedders' property";n["*"]={"*":{type:"basic",password:n.password,secret:n.secret}},delete n.type,delete n.password}else if("jwt"==n.type){for(const e in n.embedders)n.termdb={[e]:Object.assign({type:n.type},n.embedders[e])},n.headerKey&&(n.termdb[e].headerKey=n.headerKey);delete n.type,delete n.embedders,delete n.headerKey}else if(n.type)throw`unknown legacy credentials type='${n.type}'`}}(e);const n="secrets";if("string"==typeof e[n]){const t=await s.promises.readFile(e[n],"utf8");e[n]=JSON.parse(t)}for(const t in e){const n=e[t];n["*"]&&(n["/**"]=n["*"],delete n["*"]);const s=n.headerKey||"x-ds-access-token";delete n.headerKey;for(const r in n){const o=n[r];for(const n in o){o[n]=JSON.parse(JSON.stringify(o[n]));const i=o[n],a="string"==typeof i?e.secrets[i]:i;if("basic"==a.type)a.secret||(a.secret=a.password),a.authRoute="/dslogin";else if("jwt"==a.type)a.authRoute="/jwt-status",a.headerKey||(a.headerKey=s);else if("forbidden"!=a.type&&"open"!=a.type)throw`unknown cred.type='${a.type}' for dsCredentials[${t}][${n}][${r}]`;a.dslabel=t,a.route=r,a.cookieId="termdb"==r&&a.headerKey||`${t}-${r}-${n}-Id`}}}}const u={termdb:["matrix"],samples:["singleSampleData","getAllSamples","scatter","convertSampleId","getAllSamplesByName"]};function f(e,t){return e.cookies?.[`${t?.cookieId}`]||e.cookies?.[`${e.query.dslabel}SessionId`]||e.headers?.["x-sjppds-sessionid"]||e.query?.["x-sjppds-sessionid"]}async function d(e,t,n,r,o,i,l=""){if(r.secret)try{const c=Date.now(),u=Math.floor(c/1e3),f={dslabel:t.dslabel,id:n,iat:u,time:c,ip:e.ip,embedder:t.embedder,route:r.route,exp:u+Math.floor(o/1e3),email:l};r.dsnames&&(f.datasets=r.dsnames.map((e=>e.id)));const d=a().sign(f,r.secret);return await s.promises.appendFile(i,`${t.dslabel}\t${n}\t${c}\t${l}\t${e.ip}\t${t.embedder}\t${r.route}\n`),d}catch(e){throw e}}function p(e,t,n,s,r){if(!s.headers.authorization||n&&e[t]?.[n])return;if(!r.secret)throw{status:"error",error:`no credentials set up for this embedder='${s.query.embedder}'`,code:403};const[o,i]=s.headers.authorization.split(" ");if("bearer"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Bearer'`;const c=Buffer.from(i,"base64").toString();try{const o=a().verify(c,r.secret);if(n&&o.id!=n&&s.headers?.["x-sjppds-sessionid"]!=o.id)return;e[t]||(e[t]={});const i="/"!=s.path[0]||r.route.startsWith("/")?s.path:s.path.slice(1);if((0,l.isMatch)(i,r.route)||"authorizedActions"==i)return e[t][o.id]=o,o.id}catch(e){return}}async function m(e,t,n,r,o,i,a){const l=Date.now(),c=Math.random().toString()+"."+l.toString().slice(4),u=i.ip;return n[e.dslabel]||(n[e.dslabel]={}),n[e.dslabel][c]={id:c,time:l,email:o,ip:u},await s.promises.appendFile(r,`${e.dslabel}\t${c}\t${l}\t${o}\t${u}\t${e.embedder}\t${a.route}\n`),a.cookieMode&&"set-cookie"!=a.cookieMode||t.header("Set-Cookie",`${a.cookieId}=${c}; HttpOnly; SameSite=None; Secure`),c}function h(e,t,n,s,r=null){if(!n)return;if(!e.embedder)throw"missing q.embedder";const o=n.secret;if(!o)throw{status:"error",error:"no credentials set up for this embedder",code:403};const i=Math.floor((s||Date.now())/1e3),l=t[n.headerKey];if(!l)throw`missing header['${n.headerKey}']`;const c=n.processor?require(n.processor):{},u=c.handleToken?.(l)||l,f=a().verify(u,o);if(r)return{iat:f.iat,email:f.email,ip:f.ip};if(c.handlePayload)try{c.handlePayload(n,f,i)}catch(e){if("bad decrypt"==e.reason)throw`Please login again to access this feature. (${e.reason})`;throw e}if(i>f.exp)throw"Please login again to access this feature. (expired token)";const d=(n.dsnames||[e.dslabel]).filter((e=>!f.datasets?.includes(e.id))).map((e=>e.id));if(d.length)throw{error:"Missing access",linkKey:d.join(",")};return{iat:f.iat,email:f.email,ip:f.ip}}function g(e,t,n){if(!n.looseIpCheck||!e.ip?.includes(":")&&t){if(!t)throw"Server error: missing ip address in saved session";if(e.ip!=t&&e.ips?.[0]!=t&&e.connection?.remoteAddress!=t)throw"Your connection has changed, please refresh your page or sign in again."}}const y={maySetAuthRoutes:async function(e,t="",r=null){const i=r||n(334),b=i.features?.sessionTracking||"",v=o().join(i.cachedir,"dsSessions"),w=o().join(i.cachedir,"authorizedActions"),_=i.dsCredentials||{};delete i.dsCredentials;const k=i.maxSessionAge||576e5;let q;if(!_||!Object.keys(_).length)return y.getDsAuth=()=>[],y.getForbiddenRoutesForDsEmbedder=()=>[],y.userCanAccess=()=>!0,y.getRequiredCredForDsEmbedder=()=>{},void(y.getPayloadFromHeaderAuth=()=>({}));try{c(_)}catch(e){throw e}function x(e,t,n){if(!e.dslabel)return;const s=_[e.dslabel]||_["*"];if(s){if("/jwt-status"==t){const t=s[e.route]||s.termdb||s["/**"];return t&&(t[e.embedder]||t["*"])}if("/dslogin"==t){const t=s[e.route]||s["/**"];return t&&(t[e.embedder]||t["*"])}if(t.startsWith("/termdb")&&s.termdb){const t=s.termdb;return(n||u.termdb).includes(e.for)&&(t[e.embedder]||t["*"])}if(t.startsWith("/burden")&&s.burden)return s.burden[e.embedder]||s.burden["*"]}for(const n in _){if(n!=e.dslabel&&"*"!=n)continue;const s=_[n];for(const n in s){const r=s[n].routePattern||n;if(!(0,l.isMatch)(t,r))continue;const o=s[n];for(const t in o)if(t==e.embedder||"*"==t)return o[t]}}}e.use(((e,t,n)=>{if("/dslogin"==e.path||"/jwt-status"==e.path||"/dslogout"==e.path)return void n();const s=e.query,r=x(s,e.path);if(!r)return void n();let o;"jwt-only"==b&&(q={});try{const i=f(e,r);let a;if(!i){if("OPTIONS"==e.method.toUpperCase())return t.status(204),void t.send();if(a=p(q,s.dslabel,i,e,r),!a)throw o=401,"missing session cookie"}a||(a=p(q,s.dslabel,i,e,r));const l=q[s.dslabel]?.[i]||q[s.dslabel]?.[a];if(!l)throw o=401,"unestablished or expired browser session";g(e,l.ip,r);const c=Date.now();if(c-l.time>k){const{iat:t}=h(s,e.headers,r,l),n=c-t;if(n>k)throw delete q[s.dslabel][i],"Please login again to access this feature. (expired session)";if(n<3e5)return void(l.time=c)}l.time-c<900&&(l.time=c),n()}catch(e){console.log(e);const n=e.code||o;n&&t.status(n),t.send("object"==typeof e?e:{error:e})}}));try{q=await async function(e,t,n){const r={};for(const t in e)r[t]||(r[t]={});try{const e=await s.promises.readFile(t,"utf8"),o=+new Date;for(const t of e.split("\n")){if(!t)continue;const[e,s,i,a,l]=t.split("\t"),c=Number(i);r[e]||(r[e]={}),o-c<n&&(r[e][s]={id:s,time:c,email:a,ip:l})}return r}catch(e){return(0,s.existsSync)(t)&&console.log(e),r}}(_,v,k);const e=[];for(const t in q)for(const n in q[t]){const s=q[t][n];e.push(`${s.dslabel}\t${s.id}\t${s.time}\t${s.email}\t${s.ip}\t${s.embedder}\t${s.route}`)}await s.promises.writeFile(v,e.join("\n"))}catch(e){throw e}var N;await(N=0,new Promise((e=>setTimeout(e,N)))),e.post(t+"/dslogin",(async(e,t)=>{let n=401;try{const s=e.query,r=x(s,e.path);if(!r)throw n=400,`No login required for dataset='${s.dslabel}'`;if("/dslogin"!=r.authRoute)throw n=400,`Incorrect authorization route, use '${r.authRoute}'`;if(!e.headers.authorization)throw"missing authorization header";const[o,i]=e.headers.authorization.split(" ");if("basic"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Basic'`;if(Buffer.from(i,"base64").toString()!=r.password)throw"invalid password";const a=await m(s,t,q,v,"",e,r);n=401;const l=await d(e,s,a,r,k,v);t.send({status:"ok",jwt:l,route:r.route})}catch(e){t.status(n),t.send({error:e})}})),e.post(t+"/dslogout",(async(e,t)=>{try{const n=e.query,r=f(e,x(n,e.path));if(!r)throw"missing session cookie";const o=q[n.dslabel]?.[r];if(!o)return void t.send({status:"ok"});delete q[n.dslabel][r];e.ip;await s.promises.appendFile(v,`${n.dslabel}\t${r}\t0\t\t${o.ip}\t${o.embedder}\t${o.route}\n`),t.send({status:"ok"})}catch(e){t.status(401),t.send({error:e})}})),e.post(t+"/jwt-status",(async(e,t)=>{let n=401;try{const s=e.query,r=x(s,e.path);if(!r)return void t.send({status:"ok"});if("/jwt-status"!=r.authRoute)throw n=400,`Incorrect authorization route, use ${r.authRoute}'`;const{email:o,ip:i}=await h(s,e.headers,r);g(e,i,r);const a=await m(s,t,q,v,o,e,r);n=401;const l=await d(e,s,a,r,k,v,o);t.send({status:"ok",jwt:l,route:r.route,[r.cookieId]:a})}catch(e){console.log(e),t.status(n),t.send(e instanceof Error||"object"!=typeof e?{error:e}:e)}})),e.post(t+"/authorizedActions",(async(e,t)=>{const n=e.query;try{const r=x(n,"termdb");if(!r)return void t.send({status:"ok"});const o=f(e),i=p(q,n.dslabel,o,e,r),a=q[n.dslabel]?.[o]||q[n.dslabel]?.[i],{email:l}=a.email,c=new Date;await s.promises.appendFile(w,`${n.dslabel}\t${l}\t${c}\t${n.action}\t${JSON.stringify(n.details)}\n`),t.send({status:"ok"})}catch(e){t.status(401),t.send("object"==typeof e?e:{error:e})}})),y.getDsAuth=function(e){const t=[],n=e.query.embedder||e.get("host").split(":")[0];for(const s in _){if(s.startsWith("__"))continue;const r=_[s];for(const o in r){const i=r[o];for(const r in i){if(!(0,l.isMatch)(n,r))continue;const a=i[r],c=f({query:Object.assign({},e.query,{dslabel:s}),headers:e.headers,cookies:e.cookies},a),u=q[s]?.[c],d=u?.time||0;t.push({dslabel:s,route:o,type:a.type||"basic",insession:("basic"!=a.type||!e.path.startsWith("/genomes"))&&(("jwt"!=a.type||c)&&Date.now()-d<k)})}}}return t},y.getForbiddenRoutesForDsEmbedder=function(e,t){const n=[],s=_[e]||_["*"];if(!s)return n;for(const e in s){const r=s[e][t]||s[e]["*"];"forbidden"==r?.type&&n.push(e)}return n},y.getRequiredCredForDsEmbedder=function(e,t){const n=[];for(const s in _)if((0,l.isMatch)(e,s))for(const e in _[s])for(const r in _[s][e]){if(!(0,l.isMatch)(t,r))continue;const o=_[s][e][r];n.push({route:e,type:o.type,headerKey:o.headerKey})}return n},y.userCanAccess=function(e,t){const n=x(e.query,e.path,u.samples);if(!n)return!0;if("basic"==n.type&&e.path.startsWith("/genomes"))return!1;const s=f(e,n),r=p(q,t.label,s,e,n),o=q[t.label]?.[s]||q[t.label]?.[r],i=o?.time||0;return Date.now()-i<k},y.getPayloadFromHeaderAuth=function(e,t){if(!e.headers?.authorization)return{};const n=x(e.query,t);if(!n)return{};const[s,r]=e.headers.authorization.split(" ");if("bearer"!=s.toLowerCase())throw`unsupported authorization type='${s}', allowed: 'Bearer'`;const o=Buffer.from(r,"base64").toString();return a().verify(o,n.secret)||{}}},getJwtPayload:h,canDisplaySampleIds:(e,t)=>!!t.cohort.termdb.displaySampleIds&&y.userCanAccess(e,t),getDsAuth:()=>[],getForbiddenRoutesForDsEmbedder:()=>[],userCanAccess:()=>!0,getRequiredCredForDsEmbedder:()=>{},getPayloadFromHeaderAuth:()=>({})}},7833:(e,t,n)=>{"use strict";n.r(t);var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=(n(3345),n(334)),l=n.n(a),c=n(8907),u=n(8064),f=n(5494),d=n(6733),p=n(5558),m=n(3602),h=n(6279);const g={snvindel:f,sv:h,fusion:h,svjson:n(8423),cnv:d,itd:m,deletion:p,truncation:n(8235)};function y(e,t,n,s,r,o){for(const i of t.yesSamples){if(o&&!o.includes(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:parseInt(e),class:"WT",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:parseInt(e),class:"WT",_SAMPLEID_:i})}for(const i of t.noSamples){if(o&&!o.includes(i))continue;n.has(i)||n.set(i,{sample:i});const t=n.get(i);s in t||(t[s]={key:s,values:[],label:s}),r?t[s].values.some((t=>t.dt==e&&t.origin==r))||t[s].values.push({dt:parseInt(e),class:"Blank",_SAMPLEID_:i,origin:r}):t[s].values.some((t=>t.dt==e))||t[s].values.push({dt:parseInt(e),class:"Blank",_SAMPLEID_:i})}}async function b(e,t){const n=e.cohort;try{if(n.mutationFlagSet)return n.mutationFlagSet;if(!n.mutationset)return;const s={},r=e.sampleName2Id;for(const[e,o]of n.mutationset.entries()){const n=await v(e,o,t);s[Math.random()]=n;for(const e in n.data)for(const t of n.data[e])t._SAMPLENAME_=t.sample.split(";")[0].trim(),t._SAMPLEID_=r.get(t._SAMPLENAME_)||t._SAMPLENAME_}return n.mutationFlagSet=s,s}catch(e){throw e}}async function v(e,t,n){const s=u.Dz(n);if(!s)throw"init_bulk_flag() failed";s.tpsetname=t.name?t.name:"set"+e;for(const e in t){if(!(e in g))throw`unknown mutationset: ${e}`;const n=t[e].startsWith("/")?t[e]:i().join(l().tpmasterdir,t[e]);try{const t=(await r().promises.readFile(n,"utf8")).trim().split(/\r?\n/);if(g[e].parseheader(t[0],s))throw`${e} header line error: herr`;for(let n=1;n<t.length;n++)g[e].parseline(n,t[n],s)}catch(e){throw e}}return s}exports.mayGetGeneVariantData=async function(e,t){const n=this,s=e.term.name,r=await b(n,t.genome),o=new Map;if(!r)return o;let i;t?.filter?.lst.length>0&&(i=[...new Set((await(0,c.cf)(t.filter,n)).map((e=>e.id)))]);for(const e in r){const t=r[e];if(s in t.data){for(const e of t.data[s]){const t=e._SAMPLEID_;if(i&&!i.includes(t))continue;o.has(t)||o.set(t,{sample:t});const n=o.get(t);s in n||(n[s]={key:s,values:[],label:s}),n[s].values.push(e)}if(n.assayAvailability?.byDt)for(const e in n.assayAvailability.byDt){const t=n.assayAvailability.byDt[e];if(t.byOrigin)for(const n in t.byOrigin){y(e,t.byOrigin[n],o,s,n,i)}else y(e,t,o,s,!1,i)}}}return o},exports.getTermTypes=async function(e){const t=this;try{const n="string"==typeof e.ids?JSON.parse(e.ids):e.ids,s=n.map((()=>"?")).join(","),r=`SELECT id, name, type, jsondata, parent_id FROM terms WHERE id IN (${s}) OR name IN (${s})`,o=t.cohort.db.connection.prepare(r).all([...n,...n]),i={};for(const e of o)e.jsondata&&Object.assign(e,JSON.parse(e.jsondata)),i[e.id]=e;const a=n.filter((e=>!i[e])),l=await b(t,e.genome);if(l)for(const e in l){const t=l[e];if(t.data)for(const e of a)e in t.data&&!(e in i)&&(i[e]={name:e,type:"geneVariant"})}return i}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}},exports.mayGetMatchingGeneNames=async function(e,t,n,s=25){const r=await b(this,n.genome);if(r)for(const n in r){const o=r[n];for(const n in o.data){if(n.length>s)continue;if(!o.data[n]?.length)continue;const r={name:n,type:"geneVariant",isleaf:!0};n===t?e.equals.push(r):n.startsWith(t)?e.startsWith.push(r):n.includes(" "+t)?e.startsWord.push(r):n.includes(t)?e.includes.push(r):"TP53"==n&&0}}},exports.get_flagset=b},4065:(e,t,n)=>{"use strict";function s(e,t){if(e.genomicNameRegexp.test(t.input))throw"invalid character in gene name";if(t.deep){const n={};let s;{const n=e.genedb.getnamebynameorisoform.get(t.input,t.input);n&&(s=n.name)}if(!s&&e.genedb.getNameByAlias){const n=e.genedb.getNameByAlias.get(t.input);n&&(s=n.name)}if(!s&&e.genedb.get_gene2canonicalisoform&&t.input.toUpperCase().startsWith("ENSG")){const r=e.genedb.get_gene2canonicalisoform.get(t.input);if(r&&r.isoform){const t=r.isoform;n.found_isoform=t;const o=e.genedb.getnamebynameorisoform.get(t,t);if(!o)throw"cannot map enst isoform to symbol";s=o.name}}s||(s=t.input);const r=e.genedb.getjsonbyname.all(s);return n.gmlst=r.map((e=>{const t=JSON.parse(e.genemodel);return e.isdefault&&(t.isdefault=!0),t})),n}const n=t.input.toUpperCase(),s=(n.substr(0,2),e.genedb.getnameslike.all(n+"%"));if(s.length)return s.sort(),{hits:s.map((e=>e.name))};if(e.genedb.getNameByAlias){const t=e.genedb.getNameByAlias.all(n);if(t.length)return{hits:t.map((e=>e.name))}}{const n=e.genedb.getnamebynameorisoform.get(t.input,t.input);if(n)return{hits:[n.name]}}return{hits:[]}}n.d(t,{S:()=>s})},2062:(e,t,n)=>{"use strict";n.d(t,{W:()=>a,A:()=>l});var s=n(334),r=n.n(s),o=n(7147),i=n.n(o);async function a(e){l.deps||async function(){const e=`${process.cwd()}/package.json`;try{if(!i().existsSync(e))return;{const t=i().readFileSync(e,{encoding:"utf8"}),n=JSON.parse(t),s=n?.dependencies["@sjcrh/proteinpaint-server"];s&&(l.deps["@sjcrh/proteinpaint-server"].entry=s);const r=n?.dependencies["@sjcrh/proteinpaint-client"];r&&(l.deps.entry["@sjcrh/proteinpaint-client"]||(l.deps["@sjcrh/proteinpaint-client"]={}),l.deps["@sjcrh/proteinpaint-client"]=r)}}catch(e){console.log(e)}}();const t={status:"ok",genomes:{},versionInfo:l};for(const n in e){const s=e[n],r={};if(s.genedb&&(r.genedb={buildDate:s.genedb.get_buildDate?.get().date||"unknown",tables:s.genedb.tableSize}),s.termdbs){r.termdbs={};for(const e in s.termdbs){const t=s.termdbs[e];r.termdbs[e]={buildDate:t.cohort.termdb.q.get_buildDate?.get().date||"unknown"}}}Object.keys(r).length&&t.genomes&&(t.genomes[n]=r)}return t}const l={pkgver:"2.43.2",codedate:function(){const e=i().existsSync(r().binpath+"/server.js")&&i().statSync(r().binpath+"/server.js").mtime||new Date(0),t=i().existsSync("public/bin/proteinpaint.js")&&i().statSync("public/bin/proteinpaint.js").mtime||new Date(0);return(e>t?e:t).toDateString()}(),launchdate:new Date(Date.now()).toString().split(" ").slice(0,5).join(" "),deps:{}},c=`${r().binpath}/package.json`;if(i().existsSync(c)){const e=JSON.parse(i().readFileSync(c,{encoding:"utf8"}));l.deps["@sjcrh/proteinpaint-server"]={installed:e.version}}const u=c.replace("server","client");if(i().existsSync(u)){const e=JSON.parse(i().readFileSync(u,{encoding:"utf8"}));l.deps["@sjcrh/proteinpaint-client"]={installed:e.version}}},9157:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>c});var s=n(7147),r=n.n(s),o=(n(1017),n(334)),i=n.n(o),a=n(2081),l=n(2781);async function c(e,t,n=[]){try{await r().promises.stat(e)}catch(t){throw`${e} does not exist`}const s=[],o=[];return new Promise(((r,c)=>{const u=(0,a.spawn)(i().Rscript,[e,...n]);if(t&&t.length>0)try{const e=t.join("\n")+"\n";l.Readable.from(e).pipe(u.stdin)}catch(e){u.kill();let t=e;o.length>0&&(t+=`\nR stderr: ${o.join("").trim()}`),c(t)}u.stdout.on("data",(e=>s.push(e))),u.stderr.on("data",(e=>o.push(e))),u.on("error",(e=>c(e))),u.on("close",(e=>{if(0!==e){let t=`R process exited with non-zero status code=${e}`;s.length>0&&(t+=`\nR stdout: ${s.join("").trim()}`),o.length>0&&(t+=`\nR stderr: ${o.join("").trim()}`),c(t)}if(o.length>0){const e=o.join("").trim();c(`R process emitted standard error\nR stderr: ${e}`)}const t=s.join("").trim().split("\n");r(t)}))}))}},901:(e,t,n)=>{"use strict";n.d(t,{T:()=>r,w:()=>o});var s=n(8907);async function r(e,t,n){if(!t)return;const r=function(e,t){{const t=e.filter||e.filterObj;if(t){if(!Array.isArray(t.lst))throw"filterObj.lst is not array";return 0==t.lst.length?null:t}}if(e.tid2value){if("object"!=typeof e.tid2value)throw"q.tid2value{} not object";return o(e.tid2value,t)}}(e,n);if(!r)return;const i=[...new Set((await(0,s.cf)(r,n)).map((e=>e.id)))];let a;a=Number.isInteger(t[0])?new Set(t):new Set(t.map((e=>e.name)));const l=new Set;for(const e of i)a.has(e)&&l.add(e);return l}function o(e,t){const n={type:"tvslst",in:!0,join:"and",lst:[]};for(const s in e){const r=t.cohort.termdb.q.termjsonByOneid(s);if(!r)continue;const o=e[s];n.lst.push({type:"tvs",tvs:{term:r,values:[{key:o}]}})}return n}},4555:(e,t,n)=>{"use strict";n.d(t,{Ak:()=>$,Z5:()=>G,sV:()=>ne,eG:()=>P,r8:()=>oe,z7:()=>re,ws:()=>ee,nD:()=>X,wm:()=>te,IK:()=>J,CN:()=>U,xq:()=>L,vK:()=>D});var s=n(2273),r=n(4048);class o extends Error{constructor(e,t,n){const s=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=n}}class i extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const a=e=>null!==e&&"object"==typeof e,l=(...e)=>{for(const t of e)if((!a(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return u({},...e)},c=(e={},t={})=>{const n=new globalThis.Headers(e),s=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[e,t]of r.entries())s&&"undefined"===t||void 0===t?n.delete(e):n.set(e,t);return n},u=(...e)=>{let t={},n={};for(const s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(a(s)){for(let[e,n]of Object.entries(s))a(n)&&e in t&&(n=u(t[e],n)),t={...t,[e]:n};a(s.headers)&&(n=c(n,s.headers),t.headers=n)}return t},f=(()=>{let e=!1,t=!1;const n="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return n&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),d="function"==typeof globalThis.AbortController,p="function"==typeof globalThis.ReadableStream,m="function"==typeof globalThis.FormData,h=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},y=2147483647,b=Symbol("stop"),v={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},w={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},_=e=>h.includes(e)?e.toUpperCase():e,k=[413,429,503],x={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:k,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},N=(e={})=>{if("number"==typeof e)return{...x,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...x,...e,afterStatusCodes:k}};class S{static create(e,t){const n=new S(e,t),s=async()=>{if("number"==typeof n._options.timeout&&n._options.timeout>y)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await n._fetch();for(const t of n._options.hooks.afterResponse){const s=await t(n.request,n._options,n._decorateResponse(e.clone()));s instanceof globalThis.Response&&(e=s)}if(n._decorateResponse(e),!e.ok&&n._options.throwHttpErrors){let t=new o(e,n.request,n._options);for(const e of n._options.hooks.beforeError)t=await e(t);throw t}if(n._options.onDownloadProgress){if("function"!=typeof n._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!p)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(e.clone(),n._options.onDownloadProgress)}return e},r=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(s):s();for(const[e,s]of Object.entries(g))r[e]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||s);const o=(await r).clone();if("json"===e){if(204===o.status)return"";if(0===(await o.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await o.text())}return o[e]()};return r}constructor(e,t={}){Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e;const n="credentials"in Request.prototype;if(this._options={credentials:n?this._input.credentials:void 0,...t,headers:c(this._input.headers,t.headers),hooks:u({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:_(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:N(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(d){if(this.abortController=new globalThis.AbortController,this._options.signal){const e=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(e.reason)}))}this._options.signal=this.abortController.signal}if(f&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(m&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(t,{...this.request}),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<=this._options.retry.limit&&!(e instanceof i)){if(e instanceof o){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const t=e.response.headers.get("Retry-After");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t);return Number.isNaN(e)?e=Date.parse(t)-Date.now():e*=1e3,void 0!==this._options.retry.maxRetryAfter&&e>this._options.retry.maxRetryAfter?0:e}if(413===e.response.status)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const n=Math.min(this._calculateRetryDelay(t),y);if(0!==n&&this._retryCount>0){await async function(e,{signal:t}){return new Promise(((n,s)=>{function r(){clearTimeout(o),s(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",r,{once:!0}));const o=setTimeout((()=>{t?.removeEventListener("abort",r),n()}),e)}))}(n,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===b)return}return this._retry(e)}throw t}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const n={};for(const s in t)s in w||s in v||s in e||(n[s]=t[s]);return n})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),e):async function(e,t,n,s){return new Promise(((r,o)=>{const a=setTimeout((()=>{n&&n.abort(),o(new i(e))}),s.timeout);s.fetch(e,t).then(r).catch(o).then((()=>{clearTimeout(a)}))}))}(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const n=Number(e.headers.get("content-length"))||0;let s=0;return 204===e.status?(t&&t({percent:1,totalBytes:n,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(r){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array),await async function e(){const{done:i,value:a}=await o.read();if(i)r.close();else{if(t){s+=a.byteLength;t({percent:0===n?0:s/n,transferredBytes:s,totalBytes:n},a)}r.enqueue(a),await e()}}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}const A=e=>{const t=(t,n)=>S.create(t,l(e,n));for(const n of h)t[n]=(t,s)=>S.create(t,l(e,s,{method:n}));return t.create=e=>A(l(e)),t.extend=t=>A(l(e,t)),t.stop=b,t},C=A();var j=n(1017),T=n.n(j),M=n(4973);function O(e){const t={op:e.in?"and":"not",content:[]};if(!Array.isArray(e.lst))throw"filter.lst[] not array";for(const n of e.lst){if("tvs"!=n.type)throw'filter.lst[] item.type!="tvs"';if(!n.tvs)throw"item.tvs missing";if(!n.tvs.term)throw"item.tvs.term missing";if(n.tvs.values){const e={op:n.tvs.isnot?"!=":"in",content:{field:I(n.tvs.term.id),value:n.tvs.values.map((e=>e.key))}};t.content.push(e)}else{if(!n.tvs.ranges)throw"unknown tvs structure when converting to gdc filter";for(const e of n.tvs.ranges)e.startunbounded?t.content.push({op:e.stopinclusive?n.tvs.isnot?">":"<=":n.tvs.isnot?">=":"<",content:{field:I(n.tvs.term.id),value:e.stop}}):e.stopunbounded?t.content.push({op:e.startinclusive?n.tvs.isnot?"<":">=":n.tvs.isnot?"<=":">",content:{field:I(n.tvs.term.id),value:e.start}}):n.tvs.isnot?t.content.push({op:"or",content:[{op:"and",content:[{op:e.startinclusive?"<":"<=",content:{field:I(n.tvs.term.id),value:e.start}}]},{op:"and",content:[{op:e.stopinclusive?">":">=",content:{field:I(n.tvs.term.id),value:e.stop}}]}]}):t.content.push({op:"and",content:[{op:e.startinclusive?">=":">",content:{field:I(n.tvs.term.id),value:e.start}},{op:e.stopinclusive?"<=":"<",content:{field:I(n.tvs.term.id),value:e.stop}}]})}}return t}function I(e){const t=e.split(".");return"case"==t[0]&&(t[0]="cases"),t.join(".")}n(3345);var E=n(334),R=n.n(E);function F(...e){R().debugmode&&console.log(e.join(" "))}function $(e,t){e.convertSampleId.get=e=>{const n={};for(const s of e)n[s]=t.__gdc.map2caseid.get(s)||s;return n}}async function D(e,t){e.get=async e=>{if(!e.ssm_id)throw".ssm_id missing";const{host:n,headers:s}=t(e),r=await C(T().join(n.rest,"ssms",e.ssm_id+"?fields=consequence.transcript.is_canonical,consequence.transcript.transcript_id"),{headers:s}).json();if(!Array.isArray(r?.data?.consequence))throw".data.consequence not array";const o=r.data.consequence.find((e=>e.transcript.is_canonical));return o?o.transcript.transcript_id:r.data.consequence[0].transcript.transcript_id}}function L(e){e.queries.snvindel.byrange.get=async t=>await e.queries.snvindel.byisoform.get(t)}function P(e,t){e.queries.geneExpression.get=async n=>{if(!Array.isArray(n.genes))throw"q.genes[] not array";const s=new Map,r=new Date,o=await G(n,e);if(0==o.length)return{gene2sample2value:s,byTermId:{}};const i=new Date;F(o.length,"cases with exp data:",i-r,"ms");const[a,l]=await async function(e,t,n,s,r){const o=[],i=new Map;for(const n of e){const e=n.gene||n.name;if("string"!=typeof e)continue;if(e.startsWith("ENSG")&&15==e.length){o.push(e),i.set(e,e);continue}const s=t.genedb.getAliasByName.all(e);if(Array.isArray(s))for(const t of s)if(t.alias.startsWith("ENSG")){o.push(t.alias),i.set(t.alias,e);break}if(o.length>100)break}try{const{host:e,headers:t}=s.getHostHeaders(r),a=await C.post(`${e.geneExp}/gene_expression/gene_selection`,{headers:t,json:{case_ids:n,gene_ids:o,selection_size:o.length}}).json();if(!Array.isArray(a.gene_selection))throw"re.gene_selection[] not array";const l=[];for(const e of a.gene_selection){if("string"!=typeof e.gene_id)throw".gene_id missing from one of re.gene_selection[]";l.push(e.gene_id)}return[l,i]}catch(e){throw e}}(n.genes,t,o,e,n);if(0==a.length)return{gene2sample2value:s,byTermId:{}};const c=new Date;F(a.length,"out of",n.genes.length,"genes selected for exp:",c-i,"ms");const u={};for(const e of a){const t=l.get(e);u[t]={gencodeId:e},s.set(t,new Map)}const f=await async function(e,t,n,s,r,o){const{host:i,headers:a}=o.getHostHeaders(e),l=(await C.post(`${i.geneExp}/gene_expression/values`,{headers:a,json:{case_ids:n,gene_ids:t,format:"tsv",tsv_units:"uqfpkm"}}).text()).trim().split("\n");if(l.length<=1)throw"less than 1 line from tsv response.body";const c=l[0].split("\t").slice(1);if(c.length!=n.length)throw"sample column length != case_ids.length";const u={};for(const e of c){const t=o.__gdc.caseid2submitter.get(e);if(!t)throw"case submitter id unknown for a uuid";u[e]={label:t}}for(let e=1;e<l.length;e++){const t=l[e].split("\t");if(t.length!=c.length+1)throw"number of fields in gene line does not equal header";const n=t[0];if(!n)throw"ensg l[0] missing from a line";const o=s.get(n);if(!o)throw"symbol missing for "+n;for(const[e,n]of c.entries()){const s=Number(t[e+1]);if(!Number.isFinite(s))throw"non-numeric exp value from gdc";r.get(o)[n]=s}}return u}(n,a,o,l,s,e);return F("gene-case matrix built:",new Date-c,"ms"),{gene2sample2value:s,byTermId:u,bySampleId:f}}}async function G(e,t){const n={op:"and",content:[]};e.filter0&&n.content.push(e.filter0),e.filterObj&&n.content.push(O(e.filterObj)),e.filter&&n.content.push(O(e.filter));const s={size:1e4,fields:"case_id"};n.content.length&&(s.case_filters=n);try{const{host:n,headers:r}=t.getHostHeaders(e),o=await C.post(T().join(n.rest,"cases"),{headers:r,json:s}).json();if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";const i=[];for(const e of o.data.hits)if(e.id&&t.__gdc.casesWithExpData.has(e.id)&&(i.push(e.id),1e3==i.length))break;return i}catch(e){throw e.stack&&console.log(e.stack),e}}function U(e){e.queries.snvindel.byisoform.get=async t=>{const n=z(t,e),r=await async function(e,t){const n=ie,s=le,{host:r,headers:o}=t.getHostHeaders(e),i=C.post(T().join(r.rest,n.endpoint),{headers:o,json:Object.assign({size:n.size,fields:n.fields.join(",")},n.filters(e))}).json(),a=C.post(T().join(r.rest,s.endpoint),{headers:o,json:Object.assign({size:s.size,fields:s.fields.join(",")},s.filters(e,t))}).json(),[l,c]=await Promise.all([i,a]);if(!Array.isArray(l?.data?.hits)||!Array.isArray(c?.data?.hits))throw"ssm tandem query not returning data.hits[]";const u=new Map;for(const t of l.data.hits){if(!t.ssm_id)throw"ssm_id missing from a ssms hit";if(!t.consequence)throw".consequence[] missing from a ssm";if(!Number.isInteger(t.start_position))throw"hit.start_position is not integer";let n;t.csqcount=t.consequence.length,n=e.isoform?t.consequence.find((t=>t.transcript.transcript_id==e.isoform)):t.consequence.find((e=>e.transcript.is_canonical)),t.consequence=n||t.consequence[0],t.cases=[],u.set(t.ssm_id,t)}for(const e of c.data.hits){if(!e.ssm)throw".ssm{} missing from a case";if(!e.ssm.ssm_id)throw".ssm.ssm_id missing from a case";const t=u.get(e.ssm.ssm_id);if(!t)throw"ssm_id not found in ssms query";if(!e.case)throw".case{} missing from a case";t.cases.push(e.case)}return[...u.values()]}(t,e),o=[];for(const e of r){const n={ssm_id:e.ssm_id,dt:s.dtsnvindel,chr:e.chromosome,pos:e.start_position-1,ref:e.reference_allele,alt:e.tumor_allele,isoform:t.isoform,csqcount:e.csqcount};if(B(n,e.consequence),!t.hiddenmclass||!t.hiddenmclass.has(n.class)){n.samples=[];for(const s of e.cases){const e={};if(t.gdcUseCaseuuid){if(e.sample_id=s.case_id,!e.sample_id)throw"gdcUseCaseuuid=true but c.case_id undefined"}else if(e.sample_id=s.observation?.[0]?.sample?.tumor_sample_uuid,!e.sample_id)throw"gdcUseCaseuuid=false but c.observation?.[0]?.sample?.tumor_sample_uuid undefined";n.samples.push(e)}o.push(n)}}if(n){t.isoform=n;for(const e of o)e.isoform=n}return o}}function z(e,t){if(!e.isoform)return;let n;if("N"==e.isoform[0]&&t.refseq2ensembl_query){const s=t.refseq2ensembl_query.get(e.isoform);s&&(n=e.isoform,e.isoform=s.ensembl)}return n}function B(e,t){if(t&&t.transcript.consequence_type){const[n,r,o]=s.vepinfo(t.transcript.consequence_type);e.class=r,e.mname=t.transcript.aa_change}e.mname||(e.mname=e.ref+">"+e.alt),e.class||(s.basecolor[e.ref]&&s.basecolor[e.alt]?e.class=s.mclasssnv:"-"==e.ref?e.class=s.mclassinsertion:"-"==e.alt?e.class=s.mclassdeletion:e.class=s.mclassmnv)}function J(e){const t=["cnv.cnv_change","cnv.gene_level_cn","cnv.consequence.gene.symbol","case.submitter_id","case.case_id"];function n(e){const n=t.slice();if(e.twLst)for(const t of e.twLst){let e=t.term.id;e.startsWith("case.")&&(e="occurrence."+e),n.push(e)}return n.join(",")}function r(e){if(!e.gene&&"string"!=typeof e.gene)throw"p.gene does not provide non-empty string";const t={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};return e.gene&&t.filters.content.push({op:"=",content:{field:"cnv.consequence.gene.symbol",value:e.gene.split(",")}}),e.filter0&&t.case_filters.content.push(e.filter0),e.filterObj&&t.case_filters.content.push(O("string"==typeof e.filterObj?JSON.parse(e.filterObj):e.filterObj)),t}e.queries.geneCnv.bygene.get=async t=>{const{host:o,headers:i}=e.getHostHeaders(t),a=await C.post(T().join(o.rest,"cnv_occurrences"),{headers:i,json:Object.assign({size:1e5,fields:n(t)},r(t))}).json();if(!Array.isArray(a?.data?.hits))throw"geneCnv response body is not {data:hits[]}";const l={ssm_id:"geneCnvGain",dt:s.dtcnv,class:s.mclasscnvgain,samples:[]},c={ssm_id:"geneCnvLoss",dt:s.dtcnv,class:s.mclasscnvloss,samples:[]};for(const e of a.data.hits){if("object"!=typeof e.cnv)throw"hit.cnv{} not obj";if("object"!=typeof e.case)throw"hit.case{} not obj";if(!e.cnv.gene_level_cn)throw"hit.cnv.gene_level_cn is not true";let n;if("Gain"==e.cnv.cnv_change)n=l;else{if("Loss"!=e.cnv.cnv_change)throw"hit.cnv.cnv_change is not Gain/Loss";n=c}const s={sample_id:e.case.case_id};if(t.twLst)for(const n of t.twLst)W(s,e.case,n);n.samples.push(s)}const u=[];return l.samples.length&&u.push(l),c.samples.length&&u.push(c),u}}function H(e,t){if(!t)return;const n=t.split(",");for(const t of n){const n=t.split("--");if(2==n.length)return e.geneA=n[0].split("(")[0],void(e.geneB=n[1].split("(")[0])}}function W(e,t,n){const s=n.term.id.split(".");if(function t(r,o){const i=s[o];if(o==s.length-1)return void(e[n.term.id]?e[n.term.id].add(r[i]):e[n.term.id]=r[i]);const a=r[i];if(null==a)return;if(Array.isArray(a)){e[n.term.id]=new Set;for(const e of a)t(e,o+1);return}t(a,o+1)}(t,1),e[n.term.id]instanceof Set&&(e[n.term.id]=[...e[n.term.id]][0]),n.term.id in e&&"categorical"==n.term.type){const t=function(e,t){if("custom-groupset"==t.q?.type&&Array.isArray(t.q?.groupsetting?.customset?.groups))for(const n of t.q.groupsetting.customset.groups){if(!Array.isArray(n.values))throw"group.values[] not array from tw.q.groupsetting.customset.groups";if(-1!=n.values.findIndex((t=>t.key==e)))return n.name}if("predefined-groupset"==t.q?.type&&Number.isInteger(t.q.groupsetting?.predefined_groupset_idx)&&t.term.groupsetting?.lst[t.q.groupsetting.predefined_groupset_idx])for(const n of t.term.groupsetting.lst[t.q.groupsetting.predefined_groupset_idx]){if(!Array.isArray(n.values))throw"group.values[] not array from tw.term.groupsetting.lst[]";if(-1!=n.values.findIndex((t=>t.key==e)))return n.name}}(e[n.term.id],n);t&&(e[n.term.id]=t)}}function V(e,t){const n={};for(const s of t)if(("integer"==s.term.type||"float"==s.term.type)&&s.q?.mode)if("discrete"==s.q.mode||"binary"==s.q.mode){const t={};for(const n of e){const e=n[s.term.id];Number.isFinite(e)&&("min"in t?(t.min=Math.min(e,t.min),t.max=Math.max(e,t.max)):(t.min=e,t.max=e))}const o=(0,r.gp)(s.q,(e=>t),s.term.valueConversion);for(const e of o)e.name=e.label;n[s.term.id]={bins:o};for(const t of e){const e=t[s.term.id];Number.isFinite(e)&&(t[s.term.id]=Z(o,e))}}else if("continuous"!=s.q.mode)throw"mayApplyBinning: unknown numeric q.mode";return n}function Z(e,t){for(const n of e)if(n.startunbounded){if(t<n.stop)return n.label;if(n.stopinclusive&&t==n.stop)return n.label}else if(n.stopunbounded){if(t>n.start)return n.label;if(n.startinclusive&&t==n.start)return n.label}else if((t>n.start||t===n.start&&n.startinclusive)&&(t<n.stop||t===n.stop&&n.stopinclusive))return n.label}function K(e){for(const t of e)if(null==t.id||""==t.id){if(!t?.term?.id)throw"tw.id and tw.term are both missing";t.id=t.term.id}else t.term||(t.term={id:t.id})}async function X(e,t,n,s){if(e.isHierCluster)return await async function(e,t,n){const s={op:"and",content:[]};e.filter0&&s.content.push(e.filter0);e.filterObj&&s.content.push(O(e.filterObj));const r=[];for(const e of t){const t=n.cohort.termdb.q.termjsonByOneid(e.term.id);t&&r.push({term:t,q:e.q})}const o=["case_id"],i=new Map;for(const e of r){const t=e.term.id.replace(/^case\./,"");o.push(t),i.set(t,e.term.id)}const{host:a,headers:l}=n.getHostHeaders(e),c=await C.post(T().join(a.rest,"cases"),{headers:l,json:{size:n.__gdc.casesWithExpData.size,fields:o.join(","),case_filters:s.content.length?s:void 0}}).json();if(!Array.isArray(c?.data?.hits))throw"re.data.hits[] not array";const u=[];for(const e of c.data.hits){if("string"!=typeof e.case_id)throw"h.case_id missing";if(!n.__gdc.casesWithExpData.has(e.case_id))continue;const t={sample_id:e.case_id};for(const n of r)W(t,e,n);u.push(t)}const f=V(u,r);return{byTermId:f,samples:u}}(e,t,n);if(K(t),s){if(!Array.isArray(s))throw"geneTwLst not array";e.isoforms=[];for(const t of s){if(!t?.term?.name)throw"gene tw missing .term.name";if(t.term.isoform)e.isoforms.push(t.term.isoform);else{if("object"!=typeof e.genome)throw"serverside genome obj missing, needed to map gene name to canonical isoform";if(!e.genome?.genedb?.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const n=e.genome.genedb.get_gene2canonicalisoform.get(t.term.name);if(!n?.isoform)continue;e.isoforms.push(n.isoform)}}}t.some((e=>"case.observation.sample.tumor_sample_uuid"==e.id))||t.push({term:{id:"case.observation.sample.tumor_sample_uuid"}}),t.some((e=>"case.case_id"==e.id))||t.push({term:{id:"case.case_id"}}),"samples"==e.get&&(e.ssm_id_lst||e.isoform)&&(t.some((e=>"ssm.ssm_id"==e.id))||t.push({term:{id:"ssm.ssm_id"}}),t.some((e=>"case.observation.read_depth.t_alt_count"==e.id))||t.push({term:{id:"case.observation.read_depth.t_alt_count"}}),t.some((e=>"case.observation.read_depth.t_depth"==e.id))||t.push({term:{id:"case.observation.read_depth.t_depth"}}),t.some((e=>"case.observation.read_depth.n_depth"==e.id))||t.push({term:{id:"case.observation.read_depth.n_depth"}}));const r=[];for(const e of t){const t=n.cohort.termdb.q.termjsonByOneid(e.term.id);t&&r.push({term:t,q:e.q})}const o=t.map((e=>e.term.id));e.hiddenmclass&&(o.push("ssm.consequence.transcript.consequence_type"),o.push("ssm.consequence.transcript.transcript_id"),o.push("ssm.consequence.transcript.is_canonical")),e.rglst&&(o.push("ssm.chromosome"),o.push("ssm.start_position"));const i={size:1e4,fields:o.join(",")};z(e,n),Object.assign(i,le.filters(e,n));const{host:a,headers:l}=n.getHostHeaders(e),c=await C.post(T().join(a.rest,le.endpoint),{headers:l,json:i}).json();if(delete e.isoforms,!Array.isArray(c?.data?.hits))throw"variant2samples re.data.hits is not array for query";const u=[];for(const t of c.data.hits){if(!t.case)throw"variant2samples .case{} missing from a hit";const s={};if(t.ssm&&(s.ssm_id=t.ssm.ssm_id),e.hiddenmclass){if(!Array.isArray(t.ssm?.consequence))continue;let n;n=e.isoform?t.ssm.consequence.find((t=>t.transcript.transcript_id==e.isoform)):t.ssm.consequence.find((e=>e.transcript.is_canonical));const s={};if(B(s,n||t.ssm.consequence[0]),e.hiddenmclass.has(s.class))continue}if(e.gdcUseCaseuuid){if(s.sample_id=t.case.case_id,!s.sample_id)throw"querySamples_gdcapi: case.case_id missing"}else{const e=t.case?.observation?.[0]?.sample?.tumor_sample_uuid;if(!e)throw"querySamples_gdcapi: aliquot_id missing";s.sample_id=await n.__gdc.aliquot2submitter.get(e),s.sample_URLid=t.case.case_id+"?bioId="+e}for(const e of r)W(s,t.case,e);Y(t.case,s),Q(s,n),u.push(s)}const f=V(u,r);if(s){const e={gene:s.map((e=>e.term.name)).join(","),twLst:r},t=await n.queries.geneCnv.bygene.get(e);for(const e of t)for(const t of e.samples)u.push(t)}const d=new Map;for(const e of u)(0,M.z9)([e],d,e.ssm_id);return{byTermId:f,samples:[...d.values()]}}function Y(e,t){if(!e.observation)return;const n=e.observation[0];n&&n.read_depth&&(t.formatK2v={TumorAC:n.read_depth.t_depth-n.read_depth.t_alt_count+","+n.read_depth.t_alt_count,NormalDepth:n.read_depth.n_depth})}function Q(e,t){const n=e["case.project.project_id"];n&&(e.caseIsOpenAccess=t.__gdc.gdcOpenProjects?.has(n))}async function ee(e,t,n,s){K(e);const r=[];for(const t of e)t.term&&"categorical"==t.term.type&&r.push({id:t.id,path:t.id.replace("case.","").replace(/\./g,"__"),type:t.term.type});const o=function(e){const t=[];for(const n of e)if(n.id)if(n.type="categorical")t.push(n.path+" {buckets { doc_count, key }}");else{if("integer"!=n.type&&"float"!=n.type)throw"unknown term type";t.push(n.path+" {stats { count }}")}const n=`query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (case_filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\t${t.join("\n")}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`;return n}(r),i=function(e,t){const n={filters:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}}]}};ce(e?.tid2value,n.filters.content,t),e&&e.ssm_id_lst&&n.filters.content.push({op:"=",content:{field:"cases.gene.ssm.ssm_id",value:e.ssm_id_lst.split(",")}});e.filter0&&n.filters.content.push(e.filter0);e.filterObj&&n.filters.content.push(O(e.filterObj));return n}(t,s),{host:a,headers:l}=s.getHostHeaders(t),c=["data","explore","cases","aggregations"];let u=(await C.post(a.graphql,{headers:l,json:{query:o,variables:i}}).json())[c[0]];for(let e=1;e<c.length;e++)if(u=u[c[e]],!u)throw`.${c[e]} missing from data structure of termid2totalsize2 for query :${o} and filter: ${filter}`;for(const e of r){if("categorical"==e.type&&!Array.isArray(u[e.path].buckets))throw c.join(".")+" not array for query :"+o+" and filter: "+filter;if(("integer"==e.type||"float"==e.type)&&"object"!=typeof u[e.path].stats)throw c.join(".")+" not object for query :"+o+" and filter: "+filter}const f=new Map;for(const e of r)if("categorical"==e.type){const t=u[e.path].buckets,n=[];for(const e of t)n.push([e.key.replace(".","__"),e.doc_count]);f.set(e.id,n)}else if("integer"==e.type||"float"==e.type){const t=u[e.path].stats.count;f.set(e.id,{total:t})}return n?[f,n]:f}function te(e){const t=["consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change"];e.queries.snvindel.m2csq.get=async n=>{const{host:s,headers:r}=e.getHostHeaders(n),o=await C(s.rest+"/ssms/"+n.ssm_id+"?fields="+t.join(","),{headers:r}).json();if(!o.data||!o.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(o.data.consequence))throw".data.consequence not array";return o.data.consequence.map((e=>e.transcript))}}function ne(e,t){e.queries.singleSampleMutation.get=async t=>{if(t.sample.startsWith("___")){const e=t.sample.substring(3);if(!e)throw"expecting uuid after prefix but got blank";t.case_id=e}else e.__gdc.caseid2submitter.has(t.sample)?t.case_id=t.sample:(t.case_id=e.__gdc.map2caseid.get(t.sample),t.case_id||(t.case_id=await se(t.sample,e)));return await async function(e,t,n){const r={mlst:[],dt2total:[]};{const{host:n,headers:o}=t.getHostHeaders(e),i=await C.post(T().join(n.rest,ie.endpoint),{headers:o,json:{size:1e4,fields:ie.fields.join(","),filters:ie.filters(e).filters}}).json();if(!Number.isInteger(i.data?.pagination?.total))throw"re.data.pagination.total not integer";if(!Array.isArray(i.data?.hits))throw"re.data.hits[] not array";i.data.hits.length<i.data.pagination.total&&r.dt2total.push({dt:1,total:i.data.pagination.total});for(const e of i.data.hits){let t=e.consequence.find((e=>1==e.transcript.is_canonical));t||(t=e.consequence[0]);const n=t.transcript.aa_change||t.transcript.consequence_type,[o,i,a]=s.vepinfo(t.transcript.consequence_type);r.mlst.push({dt:s.dtsnvindel,mname:n,class:i,gene:t.transcript.gene.symbol,chr:e.chromosome,pos:e.start_position,ref:e.reference_allele,alt:e.tumor_allele})}}{const n=await async function(e,t){const{host:n,headers:r}=t.getHostHeaders(e),o=await C.post(T().join(n.rest,"files"),{headers:r,json:{size:1e4,fields:["cases.samples.sample_type","data_type","file_id","data_format","experimental_strategy","analysis.workflow_type"].join(","),filters:function(e){if(!e.case_id)throw".case_id missing";return{op:"and",content:[{op:"in",content:{field:"cases.case_id",value:[e.case_id]}},{op:"in",content:{field:"data_type",value:["Masked Copy Number Segment","Copy Number Segment","Transcript Fusion"]}}]}}(e)}}).json();if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";let i,a,l;for(const e of o.data.hits)if("BEDPE"!=e.data_format){if("TXT"==e.data_format){if("Genotyping Array"==e.experimental_strategy){const t=e.cases?.[0].samples?.[0]?.sample_type;if(!t)continue;if(t.includes("Normal"))continue;if("Masked Copy Number Segment"!=e.data_type)continue;i=e.file_id;continue}if("WGS"==e.experimental_strategy){if(!e.file_id)continue;if("Copy Number Segment"!=e.data_type)continue;a=e.file_id;continue}}}else{if("RNA-Seq"!=e.experimental_strategy)continue;if("Arriba"!=e.analysis?.workflow_type)continue;if("Transcript Fusion"!=e.data_type)continue;l=e.file_id}const c=[];if(a){const e=(await C(T().join(n.rest,"data",a),{headers:r}).text()).split("\n");for(let t=1;t<e.length;t++){const n=e[t].split("\t");if(7!=n.length)continue;const r=Number(n[4]),o=Number(n[5]),i=Number(n[6]);if(Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(i))continue;const a={dt:s.dtcnv,chr:n[1],start:Number(n[2]),stop:Number(n[3]),value:r};!a.chr||Number.isNaN(a.start)||Number.isNaN(a.stop)||(c.push(a),r>0&&0==i&&o>0&&c.push({dt:s.dtloh,chr:a.chr,start:a.start,stop:a.stop,segmean:.5}))}}else if(i){const e=(await C(T().join(n.rest,"data",i),{headers:r}).text()).split("\n");for(let t=1;t<e.length;t++){const n=e[t].split("\t");if(6!=n.length)continue;if(!n[1])continue;const r={dt:s.dtcnv,chr:"chr"+n[1],start:Number(n[2]),stop:Number(n[3]),value:Number(n[5])};Number.isNaN(r.start)||Number.isNaN(r.stop)||Number.isNaN(r.value)||c.push(r)}}if(l)try{const e=(await C(T().join(n.rest,"data",l),{headers:r}).text()).split("\n");for(let t=1;t<e.length;t++){const n=e[t].split("\t"),r={dt:s.dtfusionrna,chrA:n[0],posA:Number(n[1]),chrB:n[3],posB:Number(n[4])};r.chrA&&r.chrB&&!Number.isNaN(r.posA)&&!Number.isNaN(r.posB)&&(H(r,n[6]),c.push(r))}}catch(e){}return c}(e,t);r.mlst.push(...n)}return r}(t,e)}}async function se(e,t){const{host:n,headers:s}=t.getHostHeaders(q),r=await C.post(T().join(n.rest,"cases"),{headers:s,json:{size:1,fields:"case_id,submitter_id",filters:{op:"or",content:[{op:"=",content:{field:"samples.portions.analytes.aliquots.aliquot_id",value:[e]}},{op:"=",content:{field:"submitter_id",value:[e]}},{op:"=",content:{field:"samples.submitter_id",value:[e]}}]}}}).json();console.log(r);for(const e of r.data.hits)if(e.case_id)return e.case_id;throw"cannot convert to case_id (uuid)"}function re(e,t){e.queries.singleCell.samples.get=async t=>{const n={op:"and",content:[]};t.filter0&&n.content.push(t.filter0);const s={filters:{op:"and",content:[{op:"=",content:{field:"data_format",value:"tsv"}},{op:"=",content:{field:"data_type",value:"Single Cell Analysis"}},{op:"=",content:{field:"experimental_strategy",value:"scRNA-Seq"}}]},case_filters:n,size:100,fields:["cases.submitter_id","cases.project.project_id","cases.samples.sample_type","cases.samples.submitter_id","cases.primary_site","cases.disease_type"].join(",")},{host:r,headers:o}=e.getHostHeaders(t),i=await C.post(T().join(r.rest,"files"),{headers:o,json:s}).json();if(!Number.isInteger(i.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(i.data?.hits))throw"re.data.hits[] not array";const a=new Map;for(const e of i.data.hits){if(!e.id)throw"h.id (fileId) missing";const t=e.id,n=e.cases?.[0];if(!n)throw"h.cases[0] missing";const s=n.submitter_id;if(a.has(s)||a.set(s,{sample:s,"case.primary_site":n.primary_site,"case.disease_type":n.disease_type,"case.project.project_id":n.project?.project_id,experiments:[]}),!n.samples?.[0])throw"h.cases[0].samples[0] missing";a.get(s).experiments.push({experimentID:t,sampleName:n.samples[0].submitter_id,sampleType:n.samples[0].sample_type})}return{samples:[...a.values()]}}}function oe(e,t){e.queries.singleCell.data.get=async t=>{const{host:n,headers:s}=e.getHostHeaders(t),r=(await C(T().join(n.rest,"data",t.sample),{headers:s}).text()).trim().split("\n"),o={name:"UMAP",cells:[],colorBy:"Cluster"},i={name:"TSNE",cells:[],colorBy:"Cluster"},a={name:"PCA",cells:[],colorBy:"Cluster"},l={id:"cluster",name:"Seurat cluster",type:"categorical",values:{}},c={[l.id]:{}};for(let e=1;e<r.length;e++){const t=r[e],n=t.split("\t"),s=n[0];if(!s)throw"cellId missing from a line: "+t;const u=n[3];if(!u)throw"seuratCluster missing from a line";l.values[u]={label:"Cluster "+u},c[l.id][s]=`Cluster ${u}`;const f=Number(n[4]),d=Number(n[5]),p=Number(n[9]),m=Number(n[10]),h=Number(n[14]),g=Number(n[15]);if(Number.isNaN(f))throw"umap1 is nan";if(Number.isNaN(d))throw"umap2 is nan";if(Number.isNaN(p))throw"tsne1 is nan";if(Number.isNaN(m))throw"tsne2 is nan";if(Number.isNaN(h))throw"pc1 is nan";if(Number.isNaN(g))throw"pc2 is nan";const y=`Cluster ${u}`;o.cells.push({cellId:s,x:f,y:d,category:y}),i.cells.push({cellId:s,x:p,y:m,category:y}),a.cells.push({cellId:s,x:h,y:g,category:y})}return{plots:[i,o,a],terms:[l],tid2cellvalue:c}}}const ie={endpoint:"/ssms",size:1e5,fields:["ssm_id","chromosome","start_position","reference_allele","tumor_allele","consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change","consequence.transcript.gene.symbol","consequence.transcript.is_canonical"],filters:e=>{const t={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};let n;if(e.rglst&&(n=e.rglst[0],ae(n)),e.isoform){if("string"!=typeof e.isoform)throw".isoform value not string";t.filters.content.push({op:"=",content:{field:"consequence.transcript.transcript_id",value:[e.isoform]}}),n&&(t.filters.content.push({op:">=",content:{field:"start_position",value:n.start}}),t.filters.content.push({op:"<=",content:{field:"start_position",value:n.stop}}))}else if(n)t.filters.content.push({op:"=",content:{field:"chromosome",value:n.chr}}),t.filters.content.push({op:">=",content:{field:"start_position",value:n.start}}),t.filters.content.push({op:"<=",content:{field:"start_position",value:n.stop}});else{if(!e.case_id)throw".isoform, .rglst, and .case_id are all missing";if("string"!=typeof e.case_id)throw".case_id value not string";t.filters.content.push({op:"=",content:{field:"cases.case_id",value:[e.case_id]}})}if(e.set_id){if("string"!=typeof e.set_id)throw".set_id value not string";t.case_filters.content.push({op:"in",content:{field:"cases.case_id",value:[e.set_id]}})}return e.filter0&&t.case_filters.content.push(e.filter0),e.filterObj&&t.case_filters.content.push(O(e.filterObj)),t}};function ae(e){if("object"!=typeof e)throw"p.rglst[0] not object";if("string"!=typeof e.chr||!e.chr||!Number.isInteger(e.start)||!Number.isInteger(e.stop))throw"p.rglst[0] not valid {chr,start,stop}"}const le={endpoint:"/ssm_occurrences",size:1e5,fields:["ssm.ssm_id","case.case_id","case.submitter_id","case.observation.sample.tumor_sample_uuid"],filters:(e,t)=>{const n={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};let s=!1;if(e.ssm_id_lst){if("string"!=typeof e.ssm_id_lst)throw"ssm_id_lst not string";n.filters.content.push({op:"=",content:{field:"ssm.ssm_id",value:e.ssm_id_lst.split(",")}}),s=!0}else if(e.isoform)n.filters.content.push({op:"=",content:{field:"ssms.consequence.transcript.transcript_id",value:[e.isoform]}}),s=!0;else if(e.isoforms){if(!Array.isArray(e.isoforms))throw".isoforms[] not array";n.filters.content.push({op:"in",content:{field:"ssms.consequence.transcript.transcript_id",value:e.isoforms}}),s=!0}{let t;if(e.rglst&&(t=e.rglst[0],ae(t)),s)t&&(n.filters.content.push({op:">=",content:{field:"ssms.start_position",value:t.start}}),n.filters.content.push({op:"<=",content:{field:"ssms.start_position",value:t.stop}}));else{if(!t)throw".ssm_id_lst, .isoform, .isoforms, .rglst[] are all missing";n.filters.content.push({op:"=",content:{field:"ssms.chromosome",value:t.chr}}),n.filters.content.push({op:">=",content:{field:"ssms.start_position",value:t.start}}),n.filters.content.push({op:"<=",content:{field:"ssms.start_position",value:t.stop}})}}if(e.set_id){if("string"!=typeof e.set_id)throw".set_id value not string";n.case_filters.content.push({op:"in",content:{field:"cases.case_id",value:[e.set_id]}})}return e.filter0&&n.case_filters.content.push(e.filter0),e.filterObj&&n.case_filters.content.push(O(e.filterObj)),ce(e.tid2value,n.case_filters.content,t),n}};function ce(e,t,n){if(e)for(const s in e){const r=n.cohort.termdb.q.termjsonByOneid(s);if(!r)continue;const o=s.replace(/^case\./,"cases.");if("categorical"==r.type)t.push({op:"in",content:{field:o,value:[e[s]]}});else if("integer"==r.type)for(const n of e[s])t.push({op:n.op,content:{field:o,value:n.range}})}}},4973:(e,t,n)=>{"use strict";n.d(t,{z9:()=>p,dq:()=>f,uK:()=>d});var s=n(1881),r=n(4555),o=n(8877),i=n(7011);async function a(e,t){const n=[];let s=null,r=null;for(const o of t.map((t=>t[e.id]))){if(e.values?.[o]?.uncomputable)continue;const t=Number(o);Number.isFinite(t)&&(n.push(t),null===s?s=r=t:(s=Math.min(s,t),r=Math.max(r,t)))}const a=(0,o.Z)().domain([s,r]).range([10,510]),l=(0,i.q)(a,{values:n},!0,20);if(!Array.isArray(l.bins))throw"getBinsDensity does not return []";if(0==l.bins.length)throw"getBinsDensity returns an empty array";return{minvalue:s,maxvalue:r,densityMax:l.densityMax,density:l.bins,samplecount:n.length,unit:e.unit,ticks:20}}n(3345);var l=n(2273),c=n(4065),u=n(2974);const f=".";function d(e){const t=e.variant2samples;if(t){if(t.type_samples="samples",t.type_sunburst="sunburst",t.type_summary="summary",!t.variantkey)throw".variantkey missing from variant2samples";if(-1==["ssm_id"].indexOf(t.variantkey))throw"invalid value of variantkey";if(t.twLst){if(!Array.isArray(t.twLst))throw"variant2samples.twLst[] is not array";if(0==t.twLst.length)throw"variant2samples.twLst[] empty array";if(!e.cohort||!e.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.twLst is in use";for(const n of t.twLst){if(!n.id)throw"tw.id missing from one of variant2samples.twLst[]";const t=e.cohort.termdb.q.termjsonByOneid(n.id);if(!t)throw"term not found for one of variant2samples.twLst: "+n.id;if(n.term=t,!n.q)throw"tw.q{} missing for one of variant2samples.twLst: "+n.id}}if(t.sunburst_twLst){if(!Array.isArray(t.sunburst_twLst))throw".sunburst_twLst[] not array from variant2samples";if(0==t.sunburst_twLst.length)throw".sunburst_twLst[] empty array from variant2samples";if(!e.cohort||!e.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.sunburst_twLst is in use";for(const n of t.sunburst_twLst){if(!n.id)throw"tw.id missing from one of variant2samples.sunburst_twLst[]";const t=e.cohort.termdb.q.termjsonByOneid(n.id);if(!t)throw"term not found for one of variant2samples.sunburst_twLst: "+n.id;if(n.term=t,!n.q)throw"tw.q{} missing for one of variant2samples.sunburst_twLst: "+n.id}}if(t.gdcapi);else{let t=!1;if(e.queries?.snvindel?.byrange?._tk?.samples&&(t=!0),e.queries?.svfusion?.byrange?.samples&&(t=!0),!t)throw"cannot find a sample source from ds.queries{}"}t.get=async t=>await async function(e,t){!function(e,t){if("samples"==e.get){const n=t.queries?.snvindel?.byrange;n&&(n.bcffile||n.chr2bcffile)&&n._tk.format&&(e.addFormatValues=!0)}}(e,t);const n=await async function(e,t){const n=e.twLst?e.twLst.slice():[];if(t.variant2samples.gdcapi)return await(0,r.nD)(e,n,t,e.geneTwLst);if(e.ssm_id_lst)return await async function(e,t,n){const s=new Map;for(const t of e.ssm_id_lst.split(",")){const r=t.split(f);if(4!=r.length){if(6!=r.length)throw"unknown format of ssm id";{if(!n.queries.svfusion||!n.queries.svfusion.byrange)throw"queries.svfusion.byrange missing when id has 6 fields";const[t,o,i,a,c,u]=r,f=decodeURIComponent(u),d=Number(t);if(d!=l.dtsv&&d!=l.dtfusionrna)throw"dt not sv/fusion";const m=Number(i);if(Number.isNaN(m))throw"position not integer";const h=Number(c);if(Number.isNaN(h))throw"pairlstIdx not integer";const g=Object.assign({},e,{rglst:[{chr:o,start:m,stop:m+1}]}),y=await n.queries.svfusion.byrange.get(g);for(const e of y)e.dt==d&&e.pos==m&&e.strand==a&&e.pairlstIdx==h&&e.mname==f&&p(e.samples,s,e.ssm_id)}}else{if(!n.queries.snvindel||!n.queries.snvindel.byrange)throw"queries.snvindel.byrange missing when id has 4 fields";const[t,o,i,a]=r,l=Number(o);if(Number.isNaN(l))throw"no integer position for snvindel from ssm id";const c=Object.assign({},e,{rglst:[{chr:t,start:l,stop:l}]}),u=await n.queries.snvindel.byrange.get(c);for(const e of u)e.pos==l&&e.ref==i&&e.alt==a&&p(e.samples,s,e.ssm_id)}}return m(s,t,n),{samples:[...s.values()]}}(e,n,t);if(e.rglst)return await h(e,n,t);if(e.geneTwLst){if("object"!=typeof e.genome)throw"serverside genome obj needed";e.rglst=[];for(const t of e.geneTwLst)if(t.term.chr&&t.term.start&&t.term.stop)e.rglst.push({chr:t.term.chr,start:t.term.start,stop:t.term.stop});else{const n=c.S(e.genome,{deep:1,input:t.term.name});if(n.gmlst){const t=n.gmlst[0];e.rglst.push({chr:t.chr,start:t.start,stop:t.stop})}}const s=await h(e,n,t);return delete e.rglst,{samples:s}}if(!t?.cohort?.termdb)throw"unable to do sql query: .cohort.termdb missing for ds";const s={ds:t,filter:e.filter||e.filterObj},o=await(0,u.gh)(s,e.twLst),i=[];for(const t in o.samples){const n=o.samples[t];n.sample_id=n.sample,delete n.sample;for(const t of e.twLst)n[t.term.id]&&(n[t.term.id]=n[t.term.id].key);i.push(n)}return{samples:i}}(e,t);if(e.get==t.variant2samples.type_samples)return!e.useIntegerSampleId&&t?.cohort?.termdb?.q?.id2sampleName&&n.samples.forEach((e=>e.sample_id=t.cohort.termdb.q.id2sampleName(e.sample_id))),n;if(e.get==t.variant2samples.type_sunburst)return n.nodes=await async function(e,t,n){const r=(0,s.N)(e,n.twLst.map((e=>({k:e.id}))));for(const e of r)delete e.lst;if(t?.cohort?.termdb?.termid2totalsize2){const e=await async function(e,t,n,s){if(0==e.length)throw"zero terms for crosstab";if(e.length>3)throw"crosstab will not work with more than 3 levels";const r=[],o=new Map;for(const t of e)o.set(t.id,new Set);const i=!s;if(s)for(const n of s){if(n.id0){if(!n.v0)continue;o.get(n.id0).add(t.cohort.termdb.useLower?n.v0.toLowerCase():n.v0)}if(n.id1&&e[1]){if(!n.v1)continue;o.get(n.id1).add(t.cohort.termdb.useLower?n.v1.toLowerCase():n.v1)}if(n.id2&&e[2]){if(!n.v2)continue;o.get(n.id2).add(t.cohort.termdb.useLower?n.v2.toLowerCase():n.v2)}}const a=e[0].id;{const s={};n.filterObj&&(s.filterObj=n.filterObj),n.filter0&&(s.filter0=n.filter0);const l=await t.cohort.termdb.termid2totalsize2.get([e[0]],s);for(const[e,n]of l.get(a)){const s=t.cohort.termdb.useLower?e.toLowerCase():e;i?(o.get(a).add(s),r.push({count:n,id0:a,v0:s})):o.get(a).has(s)&&r.push({count:n,id0:a,v0:s})}}const l=e?.[1]?.id;if(l){const s=[];for(const r of o.get(a)){const o={tid2value:{[a]:r}};n.filterObj&&(o.filterObj=n.filterObj),n.filter0&&(o.filter0=n.filter0),s.push(t.cohort.termdb.termid2totalsize2.get([e[1]],o,r))}const c=await Promise.all(s);for(const[e,n]of c)for(const[s,c]of e.get(l)){const e=t.cohort.termdb.useLower?s.toLowerCase():s;i?(o.get(l).add(e),r.push({count:c,id0:a,v0:n,id1:l,v1:e})):o.get(l).has(e)&&r.push({count:c,id0:a,v0:n,id1:l,v1:e})}}const c=e?.[2]?.id;if(c){const s=[];for(const r of o.get(a))for(const i of o.get(l)){const o={tid2value:{[a]:r,[l]:i}};n.filterObj&&(o.filterObj=n.filterObj),n.filter0&&(o.filter0=n.filter0),s.push(t.cohort.termdb.termid2totalsize2.get([e[2]],o,{v0:r,v1:i}))}const u=await Promise.all(s);for(const[e,n]of u)for(const[e,s]of v2counts.get(c)){const u=t.cohort.termdb.useLower?e.toLowerCase():e;i?(o.get(c).add(u),r.push({count:s,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:u})):o.get(c).has(u)&&r.push({count:s,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:u})}}return r}(n.twLst,t,n,r);await async function(e,t,n){for(const s of e){if(!s.id0)continue;if(!s.v0)continue;const e=n.cohort.termdb.useLower?s.v0.toLowerCase():s.v0;if(!s.id1){const n=t.find((t=>null==t.id1&&t.v0==e));n&&(s.cohortsize=n.count);continue}if(!s.v1)continue;const r=n.cohort.termdb.useLower?s.v1.toLowerCase():s.v1;if(!s.id2){const n=t.find((t=>null==t.id2&&t.v0==e&&t.v1==r));n&&(s.cohortsize=n.count);continue}if(!s.v2)continue;const o=n.cohort.termdb.useLower?s.v2.toLowerCase():s.v2;if(!s.id3){const t=crosstabL2.find((t=>t.v0==e&&t.v1==r&&t.v2==o));t&&(s.cohortsize=t.count)}}}(r,e,t)}return r}(n.samples,t,e),delete n.samples,n;if(e.get==t.variant2samples.type_summary)return n.summary=await async function(e,t,n){if(!n.twLst)throw"q.twLst[] missing for make_summary()";const s=[];for(const t of n.twLst)if(t.term)if("categorical"==t.term.type){const n=g(e,t.id);s.push({termid:t.id,numbycategory:[...n].sort(((e,t)=>t[1]-e[1]))})}else{if("integer"!=t.term.type&&"float"!=t.term.type)throw"unknown term type";{const n=await a(t.term,e);s.push({termid:t.id,density_data:n})}}if(t.cohort.termdb.termid2totalsize2){const e=await t.cohort.termdb.termid2totalsize2.get(n.twLst,n);for(const{termid:t,numbycategory:n}of s){if(!n)continue;const s=e.get(t);if(s)for(const e of n){const t=s.find((t=>t[0].toLowerCase()==e[0].toLowerCase()));t&&e.push(t[1])}}}return s}(n.samples,t,e),delete n.samples,n;throw"unknown get type"}(t,e)}}function p(e,t,n){for(const s of e){t.has(s.sample_id)||(s.ssm_id_lst=[],s.formatK2v&&(s.ssmid2format={}),t.set(s.sample_id,s));const e=t.get(s.sample_id);e.ssm_id_lst.push(n),e.ssmid2format&&(e.ssmid2format[n]=s.formatK2v)}}function m(e,t,n){if(t)for(const s of e.values())for(const e of t){const t=n.cohort.termdb.q.getSample2value(e.id,s.sample_id);t[0]&&(s[e.id]=t[0].value)}}async function h(e,t,n){const s=new Map;if(n.queries.snvindel){const t=await n.queries.snvindel.byrange.get(e);for(const e of t)p(e.samples,s,e.ssm_id)}if(n.queries.svfusion){const t=await n.queries.svfusion.byrange.get(e);for(const e of t)p(e.samples,s,e.ssm_id)}if(n.queries.cnv){const t=await n.queries.cnv.byrange.get(e);for(const e of t)p(e.samples,s,e.ssm_id)}return m(s,t,n),{samples:[...s.values()]}}function g(e,t){const n=new Map;if("sample_id"in e[0]){for(const s of e){const e=s[t];e&&(n.has(e)||n.set(e,new Set),n.get(e).add(s.sample_id))}const s=new Map;for(const[e,t]of n)s.set(e,t.size);return s}if("case_uuid"in e[0]){for(const s of e){const e=s[t];e&&(n.has(e)||n.set(e,new Set),n.get(e).add(s.case_uuid))}const s=new Map;for(const[e,t]of n)s.set(e,t.size);return s}for(const t of e){const e=t[term.id];e&&n.set(e,1+(n.get(e)||0))}return n}},334:(e,t,n)=>{const s=n(7147),r=n(1017),o=process.cwd()?process.cwd()+"/serverconfig.json":"",i=r.join(__dirname,"../serverconfig.json"),a=r.join(__dirname,"../../serverconfig.json"),l=o&&s.existsSync(o)?o:s.existsSync(i)?i:s.existsSync(a)?a:"";let c;if(!l)throw"missing serverconfig.json";try{const e=s.readFileSync(l,{encoding:"utf8"});c=JSON.parse(e)}catch(e){throw`Error reading or parsing ${l}:`+e}if(c.port||(c.port=process.env.PP_PORT||3e3),c.tabix||(c.tabix="tabix"),c.samtools||(c.samtools="samtools"),c.bcftools||(c.bcftools="bcftools"),c.hicstraw||(c.hicstraw="straw"),c.bigwigsummary||(c.bigwigsummary="bigWigSummary"),c.bigBedToBed||(c.bigBedToBed="bigBedToBed"),c.bigBedInfo||(c.bigBedInfo="bigBedInfo"),c.bigBedNamedItems||(c.bigBedNamedItems="bigBedNamedItems"),c.clustalo||(c.clustalo="clustalo"),c.Rscript||(c.Rscript="Rscript"),c.gfServer||(c.gfServer="gfServer"),c.gfClient||(c.gfClient="gfClient"),!("allow_env_overrides"in c)&&c.debugmode&&(c.allow_env_overrides=!0),!c.binpath){const e=process.argv.find((e=>e.includes("/build")));if(e)c.binpath=e.split("/build")[0]+"/server";else{if(process.argv.find((e=>e.includes(".spec.js"))))c.binpath=r.dirname(__dirname);else{const e=process.argv.find((e=>e.endsWith("/bin.js")||e.endsWith("/server.js")||e.endsWith("/proteinpaint")||e.endsWith("/proteinpaint-server")));if(e)try{const t=s.realpathSync(e);c.binpath=r.dirname(t)}catch(e){throw e}else if(s.existsSync("./server"))c.binpath=s.realpathSync("./server");else if(s.existsSync("./src"))c.binpath=s.realpathSync("./src/..");else if(__dirname.includes("/server/"))c.binpath=__dirname.split("/server/")[0]+"/server";else{if(!__dirname.includes("/proteinpaint"))throw"unable to determine the serverconfig.binpath";c.binpath=__dirname}}}}if(c.debugmode){const e=[],t=r.join(c.binpath,"src/test/routes"),n=["gdc.js","specs.js","readme.js"];if(c.routeSetters)for(const o of c.routeSetters)if(!n.includes(o))if(s.existsSync(o))e.push(o);else if(s.existsSync(`${t}/${o}`))e.push(`${t}/${o}`);else{const t=r.join(c.binpath,o);s.existsSync(t)&&e.push(t)}for(const r of n){const n=`${t}/${r}`;!e.includes(n)&&s.existsSync(n)&&e.push(n)}c.routeSetters=e}if(c.allow_env_overrides){if(process.env.PP_URL&&(c.URL=process.env.URL),"PP_BASEPATH"in process.env&&(c.basepath=process.env.PP_BASEPATH),s.existsSync("./.ssl")&&!c.ssl){c.ssl={};const e=s.readdirSync("./.ssl");for(const t of e)t.endsWith(".key")&&(c.ssl.key=process.cwd()+"/.ssl/"+t),t.endsWith(".crt")&&(c.ssl.cert=process.cwd()+"/.ssl/"+t)}"PP_BACKEND_ONLY"in process.env&&(c.backend_only=1==+process.env.PP_BACKEND_ONLY||"true"===process.env.PP_BACKEND_ONLY)}if(process.env.PP_MODE?.startsWith("container")&&Object.assign(c,{port:3e3,tpmasterdir:"/home/root/pp/tp",cachedir:"/home/root/pp/cache",hicstraw:"/home/root/pp/tools/straw",bigwigsummary:"/home/root/pp/tools/bigWigSummary",bigBedToBed:"/home/root/pp/tools/bigBedToBed",bigBedNamedItems:"/home/root/pp/tools/bigBedNamedItems",bigBedInfo:"/home/root/pp/tools/bigBedInfo"}),c.features||(c.features={}),process.argv.find((e=>"validate"==e))&&(c.features.stopGdcCacheAliquot=!0),!c.backend_only&&s.existsSync(r.join(process.cwd(),"./public"))){const e=r.join(c.binpath,"cards");c.cards||(c.cards={target:e,path:"cards"})}if(s.existsSync("./public/rev.txt")){const e=s.readFileSync("./public/rev.txt",{encoding:"utf8"}).trim().split(" ")[1];e&&(c.commitHash=e)}if(s.existsSync("./package.json")){const e=s.readFileSync("./package.json",{encoding:"utf8"});c.version=JSON.parse(e).version}e.exports=c},938:(e,t,n)=>{"use strict";n.d(t,{e8:()=>f,Tt:()=>m,TO:()=>u});n(1017);var s=n(3345);const r=require("partjson");var o=n.n(r),i=n(670),a=n(1271),l=n(2974),c=n(2273);(0,i.WU)(".3r");function u(e){return async(t,n)=>{const s=t.query;for(const e of[0,1,2]){const t="term"+e,n=t+"_id";"string"==typeof s[n]?s[n]=decodeURIComponent(s[n]):"string"==typeof s[t]&&(s[t]=JSON.parse(decodeURIComponent(s[t])));const r=t+"_q";"string"==typeof s[r]&&(s[r]=JSON.parse(decodeURIComponent(s[r])))}try{const t=e[s.genome];if(!t)throw"invalid genome";const r=t.datasets[s.dslabel];if(!r)throw"invalid dslabel";if(!r.cohort)throw"ds.cohort missing";const o=r.cohort.termdb;if(!o)throw"no termdb for this dataset";const i=await f(s,r,o);s.term2_q&&await async function(e,t,n){const s=[];for(const t of e.charts){const e={};e.chartId=t.chartId,e.serieses=[];const r=t.serieses.filter((e=>!n.term1.includes(e.seriesId)));for(const t of r){const s={};s.seriesId=t.seriesId,s.data=t.data.filter((e=>!n.term2.includes(e.dataId))),s.total=s.data.reduce(((e,t)=>e+t.total),0),e.serieses.push(s)}e.total=e.serieses.reduce(((e,t)=>e+t.total),0),e.maxSeriesTotal=e.serieses.reduce(((e,t)=>e<t.total?t.total:e),0),s.push(e)}e.tests={};for(const n of s){const s={};for(const e of n.serieses)for(const t of e.data)s[t.dataId]=void 0===s[t.dataId]?t.total:s[t.dataId]+t.total;const r=[];let o=0;const i=new Map;for(const e of n.serieses)for(const t of e.data){const a=t.total,l=s[t.dataId]-t.total,c=e.total-t.total,u=n.total-s[t.dataId]-(e.total-t.total),f=e.seriesId,d=t.dataId;r.push({index:o,n1:a,n2:l,n3:c,n4:u}),i.set(o,{seriesId:f,dataId:d}),o++}const l={input:r},c=t.cohort.termdb.multipleTestingCorrection;c&&(l.mtc=c.method,c.skipLowSampleSize&&(l.skipLowSampleSize=c.skipLowSampleSize));const u=await(0,a.run_rust)("fisher",JSON.stringify(l)),f=[];for(const e of JSON.parse(u)){const t=i.get(e.index).seriesId,n=i.get(e.index).dataId,s=e.n1,r=e.n2,o=e.n3,a=e.n4,l=e.p_value,c="chisq"===e.fisher_chisq,u=null===l,d=e.adjusted_p_value,p=f.find((e=>e.term1comparison===t));p?p.term2tests.push({term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:s,R2C1:r,R1C2:o,R2C2:a},isChi:c,skipped:u}):f.push({term1comparison:t,term2tests:[{term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:s,R2C1:r,R1C2:o,R2C2:a},isChi:c,skipped:u}]})}e.tests[n.chartId]=f}}(i.data,r,s.hiddenValues),n.send(i)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}async function f(e,t,n){if(e.ds=t,e.ssid){const[t,n]=await s.L0(e.ssid);e.sample2gt=t,e.genotype2sample=n}const r=+new Date;e.results={};const i=new Map;for(let t=0;t<=2;t++){let n=null;if(e[`term${t}_id`]){const s=e[`term${t}_id`];n={id:s,q:e[`term${t}_q`],term:{id:s}}}else e[`term${t}`]&&(n={term:e[`term${t}`],q:e[`term${t}_q`]});n&&i.set(t,n)}const a=[...i.values()],u=await(0,l.Yu)({filter:e.filter,terms:a},e.ds,e.genome),f=new Map,d=[];if(u.samples)if("geneVariant"==i.get(1)?.term?.type||"geneVariant"==i.get(2)?.term?.type)!function(e,t,n,s,r){t.push([]);let o=1;const i=e.get(1)?e.get(1).term:null,a=i?.id?i.id:i?.name;a&&n.refs.byTermId[a]?.bins?t.push(n.refs.byTermId[a]?.bins):t.push([]);const l=e.get(2)?e.get(2).term:null,u=l?.id?l.id:l?.name;u&&n.refs.byTermId[u]?.bins?t.push(n.refs.byTermId[u]?.bins):t.push([]);for(const[t,i]of Object.entries(n.samples)){const n=parseInt(t);if("geneVariant"==e.get(1)?.term?.type){const e=[],t=i[a];for(const s of t.values)if(e.some((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))){const t=e.filter((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))[0];if("object"!=typeof t.item.key1){const e=t.item.key1;t.item.key1={},t.item.key1[e]=1}t.item.key1[c.mclass[s.class].label]=t.item.key1[c.mclass[s.class].label]?t.item.key1[c.mclass[s.class].label]+1:1}else{const t={sample:o,name:r.sampleId2Name.get(n)};t.key1=c.mclass[s.class].label,t.val1=c.mclass[s.class].label;const a=r.assayAvailability?.byDt?.[s.dt]?.byOrigin;t.key0=t.val0=a?(a[s.origin]?.label||s.origin)+" "+c.dt2label[s.dt]:c.dt2label[s.dt],t.key2=i[u]?i[u].key:"",t.val2=i[u]?i[u].value:"",e.push({value:s,item:t})}for(const t of e){if("object"==typeof t.item.key1){let e="";for(const[n,s]of Object.entries(t.item.key1))e+=`${n}(${s})+`;t.item.key1=e.slice(0,-1),t.item.val1=e.slice(0,-1)}s.set(o.toString(),t.item),o++}}else if("geneVariant"==e.get(2)?.term?.type){const e=[],t=i[u],l=i[a];for(const s of t.values)if(e.some((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))){const t=e.filter((e=>e.value.dt==s.dt&&(!s.origin||s.origin==e.value.origin)))[0];if("object"!=typeof t.item.key2){const e=t.item.key2;t.item.key2={},t.item.key2[e]=1}t.item.key2[c.mclass[s.class].label]=t.item.key2[c.mclass[s.class].label]?t.item.key2[c.mclass[s.class].label]+1:1}else{const t={sample:o,name:r.sampleId2Name.get(n)};t.key1=l.key,t.val1=l.value;const i=r.assayAvailability?.byDt?.[s.dt]?.byOrigin;t.key0=t.val0=i?(i[s.origin]?.label||s.origin)+" "+c.dt2label[s.dt]:c.dt2label[s.dt],t.key2=c.mclass[s.class].label,t.val2=c.mclass[s.class].label,e.push({value:s,item:t})}for(const t of e){if("object"==typeof t.item.key2){let e="";for(const[n,s]of Object.entries(t.item.key2))e+=`${n}(${s})+`;t.item.key2=e.slice(0,-1),t.item.val2=e.slice(0,-1)}s.set(o.toString(),t.item),o++}}}}(i,d,u,f,t);else for(let e=0;e<=2;e++){const t=i.get(e)?.q,n=i.get(e)?i.get(e).term:null,s=n?.id?n.id:n?.name;if(s&&u.refs.byTermId[s]?.bins?d.push(u.refs.byTermId[s]?.bins):d.push([]),t?.binColored)for(const n of d[e]){const e=t.binColored;n.start==e.start&&n.stop==e.stop&&(n.color=e.color)}for(const[t,n]of Object.entries(u.samples)){let r;if(f.get(t))r=f.get(t);else if(!f.has(t)){r={sample:parseInt(t)},f.set(t,r)}if(r)if(s){const o=n[s];o?(r[`key${e}`]=1!=e?o.key:o.values?.map((e=>e.key))||[o.key],r[`val${e}`]=o.value,1===e&&(r.dedupkey1=o.values?[`${o.values.length}-value samples`]:[o.key])):f.set(t,null)}else r[`key${e}`]="",r[`val${e}`]=""}}e.results.lst=[...f.values()].filter((e=>null!==e)),e.results.bins=d;const h=+new Date,g=function(e,t,n,r){const i=[0,1,2].map((t=>{const s=function(e,t,n){const s=e["term"+n+"_id"];let r={};e[s]||s?r=t.q.termjsonByOneid(s):e[`term${n}`]&&(r=e[`term${n}`]);const o="integer"==r.type||"float"==r.type,i=r.values?Object.keys(r.values).filter((e=>r.values[e].uncomputable)).map((e=>+e)):[],a=e=>o&&!i.includes(e),l=e["term"+n+"_q"]?e["term"+n+"_q"]:{};return{term:r,isComputableVal:a,q:l}}(e,n,t);s.q.index=t;const r=e.results.bins[t];return Object.assign(s,{key:"key"+t,val:"val"+t,nval:"nval"+t,bins:r,q:s.q,orderedLabels:m(s.term,r,void 0,s.q)})}));return new(o())({data:t,seed:'{"results": {"charts": [], "refs":{}}}',template:p,"=":{prep(e){for(const t of i)if("key1"!=t.key||Array.isArray(e[t.key])||(e[t.key]=[e[t.key]]),"condition"==t.term.type){if(t.q.bar_by_grade)if(Array.isArray(e[t.key])){for(const[n,s]of e[t.key].entries())s in t.term.values&&(e[t.key][n]=t.term.values[s].label);if("key1"==t.key&&e.dedupkey1)for(const[n,s]of e.dedupkey1.entries())s in t.term.values&&(e.dedupkey1[n]=t.term.values[s].label)}else e[t.key]in t.term.values&&(e[t.key]=t.term.values[e[t.key]].label)}else"float"!=t.term.type&&"integer"!=t.term.type||t.isComputableVal(e[t.val])&&(e[t.nval]=e[t.val]);return!0},sampleCount:(e,t)=>t.self.samples?t.self.samples.size:void 0,maxSeriesTotal(e,t){let n=0;for(const e of t.self.serieses)e&&e.total>n&&(n=e.total);return n},maxAcrossCharts(e,t){let n=0;for(const e of t.self.charts)e.maxSeriesTotal>n&&(n=e.maxSeriesTotal);return n},boxplot(e,t){const n=t.self.values;if(!n||!n.length)return;n.sort(((e,t)=>e-t));const r=s.JC(n.map((e=>({value:+e}))));r.mean=t.self.sum/n.length;let o=0;for(const e of n)o+=Math.pow(e-r.mean,2);return r.sd=Math.sqrt(o/(n.length-1)),r.min=t.self.min,r.max=t.self.max,r},getAF(t,n){if(r.track&&r.track.vcf&&r.track.vcf.termdb_bygenotype&&r.track.vcf.termdb_bygenotype.getAF&&e.term2_is_genotype){if(!e.chr)throw"chr missing for getting AF";if(!e.pos)throw"pos missing for getting AF";return function(e,t,n,r,o){const i=o.track.vcf.termdb_bygenotype,a=r.has(s.EO.href)?r.get(s.EO.href):new Set,l=r.has(s.EO.halt)?r.get(s.EO.halt):new Set,c=r.has(s.EO.het)?r.get(s.EO.het):new Set;let u=0,f=0;for(const s of e){let e=!1;if(i.sex_chrs.has(t))if(i.male_samples.has(s)){if(i.chr2par&&i.chr2par[t])for(const s of i.chr2par[t])if(n>=s.start&&n<=s.stop){e=!0;break}}else e=!0;else e=!0;e?(f+=2,l.has(s)?u+=2:c.has(s)&&u++):(f++,a.has(s)||u++)}return 0==f||0==u?0:(u/f).toFixed(3)}(n.self.samples?[...n.self.samples]:[],e.chr,Number(e.pos),e.genotype2sample,r)}},filterEmptySeries(e){const t=e.serieses.filter((e=>e.total));e.serieses.splice(0,e.serieses.length,...t)},bins:()=>i.map((e=>e.bins)),q:()=>i.map(((e,t)=>{const n={};for(const t in e.q)"index"!=t&&(n[t]=e.q[t]);return n})),useColOrder:()=>i[1].orderedLabels.length>0,useRowOrder:()=>i[2].orderedLabels.length>0,sortColsRows(e){if(i[1].orderedLabels.length){const t=i[1].orderedLabels;e.cols.sort(((e,n)=>t.indexOf(e)-t.indexOf(n))),e.dedupCols&&e.dedupCols.sort(((e,n)=>t.indexOf(e)-t.indexOf(n)))}if(i[2].orderedLabels.length){const t=i[2].orderedLabels;e.rows.sort(((e,n)=>t.indexOf(e)-t.indexOf(n)))}if(e.dedupCols){const t=i[1].orderedLabels;e.dedupCols.sort(((e,n)=>{const s=`${e}`.includes("-value samples"),r=`${n}`.includes("-value samples");return s||r?s&&r?e<n?-1:1:s?1:r?-1:0:t.indexOf(e)-t.indexOf(n)}))}},sortCharts(e){if(i[0].orderedLabels.length){const t=i[0].orderedLabels;e.charts.sort(((e,n)=>t.indexOf(e.chartId)-t.indexOf(n.chartId)))}}}})}(e,e.results.lst,n,t);g.tree.results&&(g.tree.results.times={sql:h-r,pj:g.times});return{data:g.tree.results,bins:d}}const d={seriesId:"@key",data:[{dataId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()"},"$key2"],"_:_max":"<$nval2","~values":["$nval2",0],"~sum":"+$nval2","~samples":["$sample","set"],"__:total":"=sampleCount()","__:boxplot":"=boxplot()","__:AF":"=getAF()"},p=JSON.stringify({"@errmode":["","","",""],"@before()":"=prep()",results:{"_2:maxAcrossCharts":"=maxAcrossCharts()","_:_min":">$nval1","_:_max":"<$nval1",charts:[{chartId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()","_1:maxSeriesTotal":"=maxSeriesTotal()","@done()":"=filterEmptySeries()",serieses:[d,"$key1[]"],dedupedSerieses:[d,"$dedupkey1[]"]},"$key0"],"~sum":"+$nval1","~values":["$nval1",0],"__:boxplot":"=boxplot()","_:_refs":{cols:["$key1[]"],dedupCols:["$dedupkey1[]"],colgrps:["-"],rows:["$key2"],rowgrps:["-"],col2name:{"$key1[]":{name:"@branch",grp:"-"}},row2name:{$key2:{name:"@branch",grp:"-"}},"__:useColOrder":"=useColOrder()","__:useRowOrder":"=useRowOrder()","__:bins":"=bins()","__:q":"=q()","@done()":"=sortColsRows()"},"@done()":"=sortCharts()"}});function m(e,t,n,s){if(n)return n.map((e=>e.label));if("condition"==e.type){if(s?.groups?.length)return s.groups.map((e=>e.name));if(e.values)return Object.keys(e.values).map(Number).sort(((e,t)=>e-t)).map((t=>e.values[t].label))}const r=Object.values(e.values||{})[0];return r&&"order"in r?Object.keys(e.values).sort(((t,n)=>"order"in e.values[t]&&"order"in e.values[n]?e.values[t].order-e.values[n].order:"order"in e.values[t]?e.values[t].order:"order"in e.values[n]?e.values[n].order:0)).map((t=>e.values[t].key)):t?.map((e=>e.name?e.name:e.label))}},4453:(e,t,n)=>{"use strict";n.d(t,{g:()=>d,y:()=>p});var s=n(1017),r=n.n(s),o=n(8907),i=n(3345),a=n(7147),l=n.n(a),c=n(9157),u=n(334),f=n.n(u);async function d(e,t){try{if(!t.cohort)throw"cohort missing from ds";const n=t.cohort.termdb.minTimeSinceDx,s=Number(e.minSampleSize);if(!Number.isFinite(n))throw"invalid minTimeSinceDx";if(!Number.isFinite(s))throw"invalid minSampleSize";e.ds=t;const r={data:{}},i=await(0,o.g5)(e);if(!i.lst.length)return r;const a={};for(const e of i.lst){const t=e.key0,n=e.val1,s=e.key1,r=e.key2;t in a||(a[t]=[]),a[t].push({time:n,event:s,series:r})}const l=e.term2_id&&i.CTE2.bins?i.CTE2.bins:[];r.refs={bins:l};const c={data:{},startTime:n};r.noEvents={},r.lowSampleSize={};for(const e in a){const t=a[e],n=new Set(t.map((e=>e.series)));for(const o of n){const n=t.filter((e=>e.series==o));n.find((e=>1===e.event))?n.length<s?r.lowSampleSize[e]=(r.lowSampleSize[e]||[]).concat([o]):c.data[e]=(c.data[e]||[]).concat(n):r.noEvents[e]=(r.noEvents[e]||[]).concat([o])}e in c.data||(r.data[e]={})}if(!Object.keys(c.data).length)return{data:{}};const u=await p(c);return Object.assign(r.data,u),r}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}async function p(e){for(let t in e.data)""===t&&(t="*",e.data[t]=e.data[""],delete e.data[""]),e.data[t]=e.data[t].map((e=>({time:e.time,event:e.event,series:""===e.series?"*":e.series})));const t=r().join(f().cachedir,Math.random().toString()+".json");await(0,i.Sf)(t,JSON.stringify(e));const n=await(0,c.default)(r().join(f().binpath,"utils/cuminc.R"),[],[t]),s=JSON.parse(n[0]);for(const e in s)"*"===e&&(s[""]=s[e],delete s[e]);for(const e in s)for(const t in s[e].estimates)"*"===t&&(s[e].estimates[""]=s[e].estimates[t],delete s[e].estimates[t]);return l().unlink(t,(()=>{})),s}},5257:(e,t,n)=>{"use strict";async function s(e,t,n="f"){if(!e)return;if("tvslst"!=e.type)throw'filter.type is not "tvslst" but: '+e.type;if(!Array.isArray(e.lst))throw"filter.lst must be an array";if(0==e.lst.length)return console.error("filter.lst[] is zero length, see if is an error");if(1==e.lst.length){if("tvslst"==e.lst[0].type)throw'only one element at a level: type should not be "tvslst"'}else if("or"!=e.join&&"and"!=e.join)throw'multiple elements at a level: filter.join must equal either "or" or "and"';"in"in e||(e.in=!0);const u=[],f=[],d=[];for(const[p,m]of e.lst.entries()){const e=n+"_"+p;let h;if("tvslst"==m.type)h=await s(m,t,e);else{if(!m.tvs)throw"filter item should have a 'tvs' or 'lst' property";if(m.tvs.term.id&&!t.cohort.termdb.q.termjsonByOneid(m.tvs.term.id))throw"invalid term id in tvs";if("categorical"==m.tvs.term.type)h=r(m.tvs,e);else if("survival"==m.tvs.term.type)h=o(m.tvs,e);else if("samplelst"==m.tvs.term.type)h=i(m.tvs,e);else if("integer"==m.tvs.term.type||"float"==m.tvs.term.type)h=l(m.tvs,e,t);else if("condition"==m.tvs.term.type)h=c(m.tvs,e);else{if("geneVariant"!=m.tvs.term.type)throw"unknown term type";h=await a(m.tvs,e,t)}}u.push(h.CTEname),f.push(...h.CTEs),d.push(...h.values)}const p="and"==e.join?"INTERSECT":"UNION",m=u.map((e=>"SELECT * FROM "+e)).join("\n"+p+"\n");return e.in?f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\t${m}\n\t\t\t\t)\n\t\t\t`):f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\tSELECT id as sample\n\t\t\t\t\tFROM sampleidmap\n\t\t\t\t\tWHERE sample NOT IN (\n\t\t\t\t\t\t${m}\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t`),{filters:f.join(",\n"),CTEs:f,values:d,CTEname:n}}function r(e,t){return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = ?\n\t\t\t\tAND value ${e.isnot?"NOT":""} IN (${e.values.map((e=>"?")).join(", ")})\n\t\t\t)`],values:[e.term.id,...e.values.map((e=>e.key))],CTEname:t}}function o(e,t){return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM survival\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${e.q?.cutoff?"AND tte >= "+e.q?.cutoff:""}\n\t\t\t\tAND exit_code ${e.isnot?"NOT":""} IN (${e.values.map((e=>"?")).join(", ")})\n\t\t\t)`],values:[e.term.id,...e.values.map((e=>e.key))],CTEname:t}}function i(e,t){const n=[];for(const t in e.term.values){const s=e.term.values[t].list;n.push(...s)}return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id ${e.isnot?"NOT IN":"IN"} (${Array(n.length).fill("?").join(", ")})\n\t\t\t)`],values:[...n.map((e=>e.sampleId))],CTEname:t}}async function a(e,t,n){const s={term:e.term,q:{}},r=await n.mayGetGeneVariantData(s,{genome:n.genomename}),o=[];for(const[t,n]of r){const s=n[e.term.name].values;let r=!0;for(const t of e.values){const e=s.filter((e=>e.dt==t.dt&&(!t.origin||t.origin==e.origin)));for(const n of e)if(t.mclassExcludeLst.includes(n?.class)){r=!1;break}}r&&o.push(t)}return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${o.map((e=>"?")).join(", ")})\n\t\t\t)`],values:[...o],CTEname:t}}function l(e,t,n){if(!e.ranges)throw".ranges{} missing";const s=[e.term.id],r=n.cohort.termdb.q.termjsonByOneid(e.term.id),o=[];let i,a=!1;for(const t of e.ranges)if("value"in t){const n=e.isnot?"!":"";o.push(`value ${n}= ?`),s.push(""+t.value)}else{a=!0;const n=[];t.startunbounded||(t.startinclusive?n.push("value >= ?"):n.push("value > ? "),s.push(t.start)),t.stopunbounded||(t.stopinclusive?n.push("value <= ?"):n.push("value < ? "),s.push(t.stop));const r=e.isnot?"NOT ":"";n.length&&o.push(r+"("+n.join(" AND ")+")")}a&&r.values&&(i=Object.keys(r.values).filter((e=>r.values[e].uncomputable)).map(Number).filter((t=>e.isnot||!e.ranges.find((e=>"value"in e&&Number(e.value)==t)))),i.length&&s.push(...i));const l=o.join(" OR ");return{CTEs:[`\n\t\t ${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_${r.type}\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${l?"AND ("+l+")":""}\n\t\t\t\t${i&&i.length?`AND value NOT IN (${i.map((e=>"?")).join(",")})`:""}\n\t\t\t)`],values:s,CTEname:t}}function c(e,t){let n,s;if(e.bar_by_children)n="child";else{if(!e.bar_by_grade)throw"must set the bar_by_grade or bar_by_children query parameter";n="grade"}if(e.value_by_max_grade)s="max_grade";else if(e.value_by_most_recent)s="most_recent";else{if(!e.value_by_computable_grade)throw"unknown setting of value_by_?";s="computable_grade"}const r=[],o=[];if(!e.values)throw e.grade_and_child?"-- Todo: tvs.grade_and_child":'unknown condition term filter type: expecting term-value "values" or "grade_and_child" key';return o.push(e.term.id,...e.values.map((e=>""+e.key))),r.push(`\n\t\t\t${t} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM ${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\tWHERE term_id = ? \n\t\t\t\tAND ${s} = 1\n\t\t\t\tAND value ${e.isnot?"NOT":""} IN (${e.values.map((e=>"?")).join(", ")})\n\t\t\t)`),{CTEs:r,values:o,CTEname:t}}n.d(t,{w:()=>s})},2826:(e,t,n)=>{"use strict";n.d(t,{iK:()=>G,pq:()=>P,TO:()=>L});var s=n(334),r=n.n(s),o=n(394),i=(n(8088),n(6191));function a(e,t,n,s){const o=n.cohort.termdb,a={selectCohort:o.selectCohort,supportedChartTypes:o.q.getSupportedChartTypes(e.embedder),hiddenChartTypes:n.cohort.hiddenChartTypes,renamedChartTypes:n.cohort.renamedChartTypes,allowedTermTypes:l(n),termMatch2geneSet:o.termMatch2geneSet,massSessionDuration:r().features.massSessionDuration||30,dataDownloadCatch:o.dataDownloadCatch,matrix:o.matrix,hierCluster:o.hierCluster,mclass:o.mclass,alwaysRefillCategoricalTermValues:o.alwaysRefillCategoricalTermValues,isGeneSetTermdb:o.isGeneSetTermdb,lollipop:o.lollipop,urlTemplates:o.urlTemplates};o.chartConfigByType&&(a.chartConfigByType=o.chartConfigByType),o.multipleTestingCorrection&&(a.multipleTestingCorrection=o.multipleTestingCorrection),o.helpPages&&(a.helpPages=o.helpPages),o.minTimeSinceDx&&(a.minTimeSinceDx=o.minTimeSinceDx),o.timeUnit&&(a.timeUnit=o.timeUnit),o.cohortStartTimeMsg&&(a.cohortStartTimeMsg=o.cohortStartTimeMsg),o.displaySampleIds&&(a.displaySampleIds=o.displaySampleIds),o.logscaleBase2&&(a.logscaleBase2=o.logscaleBase2),n.assayAvailability&&(a.assayAvailability=n.assayAvailability),n.customTwQByType&&(a.customTwQByType=n.customTwQByType),a.requiredAuth=i.i.getRequiredCredForDsEmbedder(e.dslabel,e.embedder),function(e,t){if(!t.restrictAncestries)return;e.restrictAncestries=t.restrictAncestries.map((e=>({name:e.name,tvs:e.tvs,PCcount:e.PCcount})))}(a,o),function(e,t){if(!t.cohort.scatterplots)return;e.scatterplots=t.cohort.scatterplots.plots.map((e=>({name:e.name,dimensions:e.dimensions,colorTW:e.colorTW,shapeTW:e.shapeTW})))}(a,n),function(e,t){if(!t.cohort.matrixplots)return;e.matrixplots=t.cohort.matrixplots.plots.map((e=>({name:e.name})))}(a,n),function(e,t,n){const s=t.queries;if(!s)return;e.queries={defaultCoord:s.defaultCoord||n.defaultcoord};const r=e.queries;s.defaultBlock2GeneMode&&(r.defaultBlock2GeneMode=s.defaultBlock2GeneMode);s.snvindel&&(r.snvindel={allowSNPs:s.snvindel.allowSNPs});if(s.cnv){r.cnv={};for(const e of["cnvMaxLength","cnvGainCutoff","cnvLossCutoff","absoluteValueRenderMax","gainColor","lossColor"])e in s.cnv&&(r.cnv[e]=s.cnv[e])}s.topMutatedGenes&&(r.topMutatedGenes=s.topMutatedGenes);s.topVariablyExpressedGenes&&(r.topVariablyExpressedGenes=s.topVariablyExpressedGenes);s.singleSampleMutation&&(r.singleSampleMutation={sample_id_key:s.singleSampleMutation.sample_id_key,discoSkipChrM:s.singleSampleMutation.discoSkipChrM});if(s.singleSampleGenomeQuantification){r.singleSampleGenomeQuantification={};for(const e in s.singleSampleGenomeQuantification)r.singleSampleGenomeQuantification[e]=JSON.parse(JSON.stringify(s.singleSampleGenomeQuantification[e])),delete r.singleSampleGenomeQuantification[e].folder}if(s.singleSampleGbtk){r.singleSampleGbtk={};for(const e in s.singleSampleGbtk)r.singleSampleGbtk[e]=JSON.parse(JSON.stringify(s.singleSampleGbtk[e])),delete r.singleSampleGbtk[e].folder}s.rnaseqGeneCount&&(r.rnaseqGeneCount=!0);s.singleCell&&(r.singleCell={samples:{firstColumnName:s.singleCell.samples.firstColumnName,sampleColumns:s.singleCell.samples.sampleColumns,experimentColumns:s.singleCell.samples.experimentColumns},data:{sameLegend:s.singleCell.data.sameLegend,refName:s.singleCell.data.refName}})}(a,n,s),t.send({termdbConfig:a})}function l(e){(0,o.qN)(e);const t=new Set;for(const n of e.cohort.termdb.termtypeByCohort)n.type&&t.add(n.type);if(e.cohort.termdb.allowedTermTypes)for(const n of e.cohort.termdb.allowedTermTypes)t.add(n);return e?.queries?.defaultBlock2GeneMode&&t.add("geneVariant"),[...t]}var c=n(8907),u=n(5708),f=n(4453),d=n(1017),p=n.n(d),m=n(2974),h=n(3345),g=n(7147),y=n.n(g),b=n(9157);async function v(e,t){try{if(!t.cohort)throw"cohort missing from ds";e.ds=t;const n=[];for(const t of[0,1,2]){const s="term"+t,r=s+"_id";"string"==typeof e[r]?(e[r]=decodeURIComponent(e[r]),e[s]=e.ds.cohort.termdb.q.termjsonByOneid(e[r])):"string"==typeof e[s]&&(e[s]=JSON.parse(decodeURIComponent(e[s])));const o=s+"_q";e[s]&&n.push({term:e[s],q:e[o]})}if(e.term2){if("survival"==e.term2.type&&"survival"==e.term1.type)throw"term and overlay are both survival terms - only one could be a survival term";if("survival"!=e.term2.type&&"survival"!=e.term1.type)throw"no survival terms, either the main term OR the overlay term must be a survival term"}else if("survival"!=e.term1.type)throw"non-survival term";if(e.term0&&"survival"==e.term0.type)throw"term0 must not be a survival term";const s=function(e){if(e.term1&&"survival"==e.term1.type)return 1;if(!e.term2)throw"term1.type is not survival and term2 is missing";if("survival"!=e.term2.type)throw"both term1 and term2 are not survival type";return 2}(e),o=e[`term${s}`],i=e["term"+(1==s?2:1)],a=await(0,m.Yu)({terms:n,filter:e.filter},t,e.genome);if(a.error)throw a.error;const l=function(e,t){const n=Object.values(e.samples).filter((e=>e[t.id]));return n.sort(((e,n)=>e[t.id].value<n[t.id].value?-1:1))}(a,o),c={},u={chart:new Set,series:new Set};for(const t of l){const n=t[o.id],s=n.value;if(s<0)continue;const r=n.key;let a;if(i)if("id"in i){if(!(i.id in t))continue;a=t[i.id].key}else if("samplelst"==i.type){if(!(i.name in t))continue;a=t[i.name].key}else a=w(i,t);else a="*";u.series.add(a);const l=e.term0&&t[e.term0.id||e.term0.name]||{key:""};l.key in c||(c[l.key]=[],u.chart.add(l.key)),c[l.key].push({time:s,status:r,series:a})}const f=e.term2_id&&a.refs[e.term2.id]?.bins||[],d={keys:["chartId","seriesId","time","survival","lower","upper","nevent","ncensor","nrisk"],case:[],refs:{bins:f}};for(const e in c){const t=c[e],n=p().join(r().cachedir,Math.random().toString()+".json");await(0,h.Sf)(n,JSON.stringify(t));const s=await(0,b.default)(p().join(r().binpath,"utils/survival.R"),[],[n]),o=JSON.parse(s);for(const t of o.estimates){for(const e in t)t[e]="series"==e?"*"==t[e]?"":t[e]:Number(t[e]);d.case.push([e,t.series,t.time,t.surv,t.lower,t.upper,t.nevent,t.ncensor,t.nrisk])}o.tests&&(d.tests||(d.tests={}),d.tests[e]=o.tests),y().unlink(n,(()=>{}))}d.case.sort(((e,t)=>e[2]-t[2]));const g=function(e,t=[]){if(e){if("condition"==e.type&&e.values)return Object.keys(e.values).map(Number).sort(((e,t)=>e-t)).map((t=>e.values[t].label));if(e.values)return Object.keys(e.values).sort(((t,n)=>"order"in e.values[t]&&"order"in e.values[n]?e.values[t].order-e.values[n].order:0)).map((t=>e.values[t].label))}return t.map((e=>e.name?e.name:e.label))}(e.term2,f?f.map((e=>e.name?e.name:e.label)):[]);return d.refs.orderedKeys={chart:[...u.chart].sort(),series:[...u.series].sort(g?(e,t)=>g.indexOf(e)-g.indexOf(t):void 0)},d}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}function w(e,t){const n=e.name;if("geneVariant"==e.type){if(!t[n]||!t[n].values)return"Wildtype";const e=t[n].values.filter((e=>"Blank"!=e.class));return e.find((e=>"WT"!=e.class))?`${n} Variant`:e.find((e=>"WT"==e.class))?`${n} Wildtype`:t[n].values.length>e.length?"Not tested":"Not sure"}throw`cannot get series key for term='${n}'`}var _=n(8599),k=n(3795),q=n(1575),x=n(2188);var N=n(478),S=n(1271);async function A(e,t,n,s){!function(e,t){if(!e.chr)throw"q.chr missing";if(e.start=Number(e.start),e.stop=Number(e.stop),!Number.isInteger(e.start)||!Number.isInteger(e.stop))throw"q.start/stop is not integer";if("object"!=typeof e.details)throw"q.details{} not object";if(!Array.isArray(e.details.groups))throw"q.details.groups[] not array";if(!e.details.groups[0])throw"q.details.groups[0] missing";if(e.details.groups.length>2)throw"q.details.groups[] has more than 2";for(const n of e.details.groups)if("filter"==n.type){if("object"!=typeof n.filter)throw".filter not an object for group type=filter"}else if("population"==n.type){if(!n.key)throw".key missing from group type=population";if(!t.queries.snvindel?.populations)throw"group type=population but this ds does not have populations";if(!t.queries.snvindel.populations.find((e=>e.key==n.key)))throw"invalid key of group type=population"}else{if("info"!=n.type)throw"unknown group type from details.groups[]";if(!n.infoKey)throw".infoKey missing from group type=info"}if(e.details.groupTestMethods){if(!Array.isArray(e.details.groupTestMethods))throw"details.groupTestMethods[] not array";if(!Number.isInteger(e.details.groupTestMethodsIdx))throw"details.groupTestMethodsIdx not integer";if(!e.details.groupTestMethods[e.details.groupTestMethodsIdx])throw"invalid array index of details.groupTestMethodsIdx"}}(e,n);const r=await async function(e,t){const n={rglst:[{chr:e.chr,start:e.start,stop:e.stop}],addFormatValues:!0,variantFilter:e.variantFilter},[s,r]=e.details.groups;if("filter"==s.type&&"filter"==r?.type){n.filterObj=T(e,s.filter);const o=j(await t.queries.snvindel.byrange.get(n));n.filterObj=T(e,r.filter);const i=j(await t.queries.snvindel.byrange.get(n)),a=function(e,t,n){const[s,r]=n.details.groups,o=[];for(const n of e){n.groupData=[{refCount:n._refCount,altCount:n._altCount}];const e=t.find((e=>e.chr==n.chr&&e.pos==n.pos&&e.ref==n.ref&&e.alt==n.alt));e?n.groupData.push({refCount:e._refCount,altCount:e._altCount}):n.groupData.push({refCount:0,altCount:0}),o.push(n)}for(const n of t){e.find((e=>e.chr==n.chr&&e.pos==n.pos&&e.ref==n.ref&&e.alt==n.alt))||(n.groupData=[{refCount:0,altCount:0},{refCount:n._refCount,altCount:n._altCount}],o.push(n))}return o}(o.mlst,i.mlst,e);return{mlst:a,totalSampleCount_group1:C(o.mlst),totalSampleCount_group2:C(i.mlst)}}n.filterObj=T(e);const o=await t.queries.snvindel.byrange.get(n),i=j(o);"filter"==s.type?i.totalSampleCount_group1=C(o):"filter"==r?.type&&(i.totalSampleCount_group2=C(o));return i}(e,n);if(1==e.details.groups.length)M(n,r.mlst,e.details.groups[0]);else{if(2!=e.details.groups.length)throw"q.details.groups.length not 1 or 2";await async function(e,t,n){const[s,r]=t.groups;if("filter"==s.type&&"filter"==r.type)return void await async function(e,t,n){const s=t.groupTestMethods[t.groupTestMethodsIdx];if(!s)throw"details.groupTestMethodsIdx out of bound";switch(s.name){case"Allele frequency difference":return void I(e,t,n);case"Fisher's exact test":return void await F(n);default:throw"unknown value from groupTestMethods[]"}}(e,t,n.mlst);if("population"==s.type&&"filter"==r.type||"population"==r.type&&"filter"==s.type)return void await async function(e,t,n){const s=await async function(e,t,n){const s=t.groups.find((e=>"population"==e.type));if(!s)return;if(!s.adjust_race)return;const r=e.queries.snvindel.populations.find((e=>e.key==s.key));if(!r)throw"invalid group.key for population";const o=new Set;for(const e of n.mlst)for(const t of e.samples)o.add(t.sample_id);const i=new Map;let a=0;for(const t of r.sets){const n={infokey_AC:t.infokey_AC,infokey_AN:t.infokey_AN,average:0},s=await(0,c.J4)({ds:e,key:t.key});for(const e of s){if(!o.has(e.sample))continue;const t=Number(e.value);Number.isFinite(t)&&(n.average+=t,a+=t)}i.set(t.key,n)}for(const[e,t]of i)t.average/=a;n.pop2average={};for(const[e,t]of i)n.pop2average[e]=t.average;return i}(e,t,n);for(const r of n.mlst)r.groupData=E(e,t,r,s);const r=t.groupTestMethods[t.groupTestMethodsIdx];if(!r)throw"details.groupTestMethodsIdx out of bound";switch(r.name){case"Allele frequency difference":return void I(e,t,n.mlst);case"Fisher's exact test":return void await F(n.mlst);default:throw"unknown value from groupTestMethods[]"}}(e,t,n);I(e,t,n.mlst)}(n,e.details,r)}for(const e of r.mlst)delete e.samples,delete e._altCount,delete e._refCount;t.send(r)}function C(e){const t=new Set;for(const n of e)if(n.samples)for(const e of n.samples)t.add(e.sample_id);return t.size}function j(e){const t={mlst:[],skipMcountWithoutAlt:0};for(const n of e){const[e,s]=O(n);0!=e?(n._altCount=e,n._refCount=s-e,t.mlst.push(n)):t.skipMcountWithoutAlt++}return t}function T(e,t){const n=[e.filter];if(t)n.push(t);else for(const t of e.details.groups)"filter"==t.type&&n.push(t.filter);return(0,N.xH)(n)}function M(e,t,n){if("filter"!=n.type)if("info"!=n.type){if("population"!=n.type)throw"unknown type of single group";{const s=e.queries.snvindel.populations.find((e=>e.key==n.key));if(!s)throw"unknown population";for(const e of t){let t=0,n=0;for(const r of s.sets)t+=Number(e.info[r.infokey_AC]||0),n+=Number(e.info[r.infokey_AN]||0);e.nm_axis_value=t/n}}}else{if(!n.infoKey)throw"infoKey missing on single group.type=info";for(const e of t){const t=e.info[n.infoKey];if(null==t);else{const n=Number(t);Number.isNaN(n)||(e.nm_axis_value=n)}}}else for(const e of t)e.nm_axis_value=Number((e._altCount/(e._altCount+e._refCount)).toPrecision(2))}function O(e){let t=0,n=0;for(const s of e.samples){if(!s?.formatK2v?.GT)continue;const r=s.formatK2v.GT.split("/").map(Number);n+=r.length;for(const n of r)n==e.altAlleleIdx&&t++}return[t,n]}function I(e,t,n){const[s,r]=t.groups;M(e,n,s);const o=n.map((e=>e.nm_axis_value));M(e,n,r);for(const[e,t]of n.entries())t.nm_axis_value=o[e]-t.nm_axis_value}function E(e,t,n,s){const r=[];for(const o of t.groups)if("info"!=o.type)if("filter"!=o.type){if("population"!=o.type)throw"unknown group.type";{if(!o.key)throw"group.key missing for type=population";const t=e.queries.snvindel.populations.find((e=>e.key==o.key));if(!t)throw"invalid group.key for population";const i=new Map;for(const e of t.sets)i.set(e.key,{ACraw:Number(n.info[e.infokey_AC]||0),ANraw:Number(n.info[e.infokey_AN]||0)});let a=0,l=0;if(o.adjust_race)[a,l]=R(i,s);else for(const e of i.values())l+=e.ACraw,a+=e.ANraw-e.ACraw;r.push({altCount:l,refCount:a})}}else r.push({altCount:n._altCount,refCount:n._refCount});else{if(!o.key)throw"group.key missing for type=info";r.push({value:n.info[o.key]})}return r}function R(e,t){let n=0;for(const t of e.values())n+=t.ANraw;let s=0,r=0;for(const[o,i]of e)i.ANadj=n*t.get(o).average,i.ACadj=0==i.ANadj?0:i.ACraw*i.ANadj/i.ANraw,s+=i.ACadj,r+=i.ANadj;return[r-s,s]}async function F(e){for(let t=0;t<Math.ceil(e.length/200);t++){const n=[];for(let s=200*t;s<200*(t+1);s++){const t=e[s];if(!t)break;const r=t.groupData;r&&r[0]&&r[1]&&Number.isFinite(r[0].altCount)&&Number.isFinite(r[0].refCount)&&Number.isFinite(r[1].altCount)&&Number.isFinite(r[1].refCount)?(n.push({index:s,n1:Math.floor(r[0].altCount),n2:Math.floor(r[0].refCount),n3:Math.floor(r[1].altCount),n4:Math.floor(r[1].refCount)}),t.htmlSections=[{key:"Contigency table",html:`<table style="font-size:.9em">\n\t\t\t\t<tr style="opacity:.5">\n\t\t\t\t <td></td>\n\t\t\t\t <td>Group1</td>\n\t\t\t\t <td>Group 2</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">ALT allele count</td>\n\t\t\t\t <td>${r[0].altCount}</td>\n\t\t\t\t <td>${Math.floor(r[1].altCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">REF allele count</td>\n\t\t\t\t <td>${r[0].refCount}</td>\n\t\t\t\t <td>${Math.floor(r[1].refCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">Allele frequency</td>\n\t\t\t\t <td>${(r[0].altCount/(r[0].altCount+r[0].refCount)).toFixed(3)}</td>\n\t\t\t\t <td>${(r[1].altCount/(r[1].altCount+r[1].refCount)).toFixed(3)}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>`}]):console.log(`${t.chr}.${t.pos}.${t.ref}.${t.alt}\t${JSON.stringify(r)}`)}const s=await(0,S.run_rust)("fisher",JSON.stringify({input:n}));for(const t of JSON.parse(s)){const n=e[t.index];n&&(n.p_value=t.p_value.toPrecision(2),t.p_value>0&&(n.nm_axis_value=Number((-Math.log10(t.p_value)).toPrecision(2))))}}let t=0;for(const n of e)n.p_value>0&&(t=Math.max(t,n.nm_axis_value));for(const n of e)0==n.p_value&&(n.nm_axis_value=Math.max(50,t))}var $=n(4065),D=n(4013);function L(e){return async(t,n)=>{const s=t.query;(0,h.Y5)(s,t.cookies);try{const r=e[s.genome];if(!r)throw"invalid genome";const[o,l]=P(r,s);if(s.findterm)return await async function(e,t,n,s,r){const o={equals:[],startsWith:[],startsWord:[],includes:[]},i=decodeURIComponent(e.findterm).toUpperCase(),a=[];try{if("snp"==e.targetType){if(!s.queries?.snvindel?.allowSNPs)throw"this dataset does not support snp search";const e=await(0,D.SC)({byName:!0,lst:[i.toLowerCase()]},r);for(const t of e)a.push({type:"geneVariant",name:t.name,subtype:"snp",chr:t.chrom,start:t.chromStart,stop:t.chromEnd,alleles:t.alleles})}else{const t=(0,q.CG)({type:"geneVariant"},e.usecase).has("plot");if(s.mayGetMatchingGeneNames&&t&&await s.mayGetMatchingGeneNames(o,i,e),s.queries?.defaultBlock2GeneMode&&t)try{const e=(0,$.S)(r,{input:i});if(Array.isArray(e.hits))for(let t=0;t<7&&e.hits[t];t++)a.push({name:e.hits[t],type:"geneVariant"})}catch(e){}}const l=await n.q.findTermByName(i,e.cohortStr,e.treeFilter,e.usecase);a.push(...l.map(G));a.forEach((e=>{"geneVariant"!=e.type&&(e.__ancestors=n.q.getAncestorIDs(e.id),e.__ancestorNames=n.q.getAncestorNames(e.id))})),t.send({lst:a})}catch(e){e.stack&&console.log(e.stack),t.send({error:e.message||e})}}(s,n,l,o,r);if(s.getterminfo)return function(e,t,n){if(!e.tid)throw"no term id";t.send({terminfo:n.q.getTermInfo(e.tid)})}(s,n,l);if(s.phewas)return s.update?await u.update_image(s,n):s.getgroup?await u.getgroup(s,n):await u.trigger(s,n,o);if(s.gettermdbconfig)return a(s,n,o,r);if(s.getcohortsamplecount)return n.send({count:o.cohort.termdb.q.getcohortsamplecount(s.cohort)});if(s.getsamplecount)return n.send(await async function(e,t,n){const s=i.i.canDisplaySampleIds(e,n);if("list"==t.getsamplecount){return await c.cf(t.filter,n,s)}return await c.B9(t,n)}(t,s,o));if(s.getsamples)return await async function(e,t,n){const s=await c.cf(e.filter,n),r=s.map((e=>n.cohort.termdb.q.id2sampleName(e)));t.send({samples:r})}(s,n,o);if(s.getcuminc)return await async function(e,t,n){const s=await(0,f.g)(e,n);t.send(s)}(s,n,o);if(s.getsurvival)return await async function(e,t,n){const s=await v(e,n);t.send(s)}(s,n,o);if(s.getregression)return await async function(e,t,n){const s=await(0,_.j)(e,n);t.send(s)}(s,n,o);if(s.validateSnps)return n.send(await(0,k.G)(s,l,o,r));if(s.getvariantfilter)return function(e,t){if(t.track)return void e.send(t.track.variant_filter);e.send(t?.queries?.snvindel?.variant_filter||{})}(n,o);if(s.getLDdata)return await async function(e,t,n){if(!e.ldtkname)throw".ldtkname missing";if(!t.queries?.ld?.tracks)throw"no ld tk";const s=t.queries.ld.tracks.find((t=>t.name==e.ldtkname));if(!s)throw"unknown ld tk";if("object"!=typeof e.m)throw"q.m{} not object";if(!e.m.chr)throw"q.m.chr missing";if(!Number.isInteger(e.m.pos))throw"q.m.pos not integer";if(!e.m.ref||!e.m.alt)throw"q.m{} invalid alleles";const r=e.m.ref+"."+e.m.alt,o=(s.nochr?e.m.chr.replace("chr",""):e.m.chr)+":"+e.m.pos+"-"+(e.m.pos+1),i=[];await(0,h.UE)({args:[s.file,o],dir:s.dir,callback:t=>{const n=t.split("\t"),s=Number.parseInt(n[1]),o=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);s==e.m.pos&&a==r?i.push({pos:o,alleles:l,r2:c}):o==e.m.pos&&l==r&&i.push({pos:s,alleles:a,r2:c})}}),n.send({lst:i})}(s,o,n);if(s.genesetByTermId)return function(e,t,n){if(!n.termMatch2geneSet)throw"this feature is not enabled";if("string"!=typeof e.genesetByTermId||0==e.genesetByTermId.length)throw"invalid query term id";const s=n.q.getGenesetByTermId(e.genesetByTermId);t.send(s)}(s,n,l);if(s.getSampleScatter&&(s.for="scatter"),"scatter"==s.for)return await(0,x.uR)(t,s,n,o,r);if(s.getLowessCurve)return await(0,x.v8)(t,s,n);if(s.getCohortsData)return await async function(e,t,n){const s=function(e){const t=e.cohort.db.connection.prepare("select * from features").all();return{cohorts:e.cohort.db.connection.prepare("select * from cohorts where cohort in (select distinct(cohort) from cohort_features)\n\t\t order by sample_count desc").all(),features:t,cfeatures:e.cohort.db.connection.prepare("select * from cohort_features").all()}}(n);t.send(s)}(0,n,o);if("mds3queryDetails"==s.for)return function(e,t){const n={},s=t.queries||{};s.snvindel&&(n.snvindel={},s.snvindel.details&&(n.snvindel.details=s.snvindel.details),s.snvindel.populations&&(n.snvindel.populations=s.snvindel.populations));s.trackLst&&(n.trackLst=s.trackLst);if(s.ld){n.ld=JSON.parse(JSON.stringify(s.ld));for(const e of n.ld.tracks)delete e.file}e.send(n)}(n,o);if("termTypes"==s.for)return n.send(await o.getTermTypes(s));if("matrix"==s.for)return await async function(e,t,n,s,r){if(e.getPlotDataByName){if(!s.cohort?.matrixplots?.plots)throw"ds.cohort.matrixplots.plots missing for the dataset";const t=s.cohort.matrixplots.plots.find((t=>t.name===e.getPlotDataByName));if(!t)throw"invalid name of premade matrix plot";return void n.send(t.matrixConfig)}const o=await(0,m.Yu)(e,s,r);if(i.i.canDisplaySampleIds(t,s))for(const e of Object.values(o.samples))e.sampleName=s.sampleId2Name.get(e.sample);n.send(o)}(s,t,n,o,r);if("getSamplesPerFilter"==s.for)return await(0,m.fZ)(s,o,n);if("mds3variantData"==s.for)return await A(s,n,o);if(s.for,"convertSampleId"==s.for)return function(e,t,n){if(!n.convertSampleId)throw"not supported on this ds";if(!Array.isArray(e.inputs))throw"q.inputs[] not array";t.send({mapping:n.convertSampleId.get(e.inputs)})}(s,n,l);if("singleSampleData"==s.for)return async function(e,t,n,s,r){const o=i.i.canDisplaySampleIds(t,s);let a=[];if(o)try{a=r.q.getSingleSampleData(e.sampleId,e.term_ids),n.send(a)}catch(e){n.send({error:e.message||e})}else n.send({error:"Requires sign in to access the sample data"})}(s,t,n,o,l);if("getProfileFacilities"==s.for)return async function(e,t,n,s,r){const o=i.i.canDisplaySampleIds(t,s);let a=[];if(o)try{a=r.q.getProfileFacilities(),n.send(a)}catch(e){n.send({error:e.message||e})}else n.send({error:"Requires sign in to access the sample data"})}(0,t,n,o,l);if("getAllSamples"==s.for)return async function(e,t,n,s){const r=i.i.canDisplaySampleIds(t,s);let o=[];r&&(o=Object.fromEntries(s.sampleId2Name));n.send(o)}(0,t,n,o);if("getAllSamplesByName"==s.for)return async function(e,t,n,s){if(!i.i.canDisplaySampleIds(t,s))return n.send({});if(s.queries?.singleCell?.samples?.get){const e=await s.queries.singleCell.samples.get(),t={};for(const n of e.samples)t[n.sample]=s.cohort.termdb.q.sampleName2id(n.sample);return void n.send(t)}{let t=s.sampleName2Id;if(e.filter){e.ds=s;const n=await(0,c.cf)(e.filter,e.ds,!0);t=new Map;for(const e of n)t.set(e.name,e.id)}n.send(Object.fromEntries(t))}}(s,t,n,o);if("DEanalysis"==s.for)return await async function(e,t,n){if(!n.queries?.rnaseqGeneCount)throw"not enabled by this dataset";const s=await n.queries.rnaseqGeneCount.get(e);t.send(s)}(s,n,o);throw"termdb: doesn't know what to do"}catch(e){n.send({error:e.message||e}),e.stack?console.log(e.stack):console.log(e)}}}function P(e,t){{const n=e.datasets[t.dslabel];if(n){if(n?.cohort?.termdb)return[n,n.cohort.termdb];throw".cohort.termdb not found on this dataset"}}if(!e.termdbs)throw"invalid dslabel";const n=e.termdbs[t.dslabel];if(!n)throw"invalid dslabel";if(!n.cohort)throw"ds.cohort missing for genome-level termdb";if(!n.cohort.termdb)throw"ds.cohort.termdb{} missing for a genome-level termdb";return[n,n.cohort.termdb]}function G(e){return JSON.parse(JSON.stringify(e))}},2974:(e,t,n)=>{"use strict";n.d(t,{Yu:()=>f,fZ:()=>d,gh:()=>p,te:()=>m});var s=n(1017),r=n.n(s),o=n(8907),i=n(5257),a=(n(9157),n(7147),n(7219),n(334)),l=n.n(a),c=n(3345),u=n(8599);async function f(e,t,n){try{return function(e,t,n){if(!t.cohort)throw"cohort missing from ds";if(!e.terms)throw"missing 'terms' parameter";e.ds=t,e.genome=n;for(const t of e.terms)t.term.name||(t.term=e.ds.cohort.termdb.q.termjsonByOneid(t.term.id)),t.q||console.log("do something??");if(e.currentGeneNames&&!Array.isArray(e.currentGeneNames))throw"currentGeneNames[] is not array";e.filter0&&"string"==typeof e.filter0&&(e.filter0=JSON.parse(e.filter0))}(e,t,n),await async function(e){const[t,n]=function(e){const t=[],n=[];for(const s of e){const e=s.term.type;"snplst"==e||"snplocus"==e||"geneVariant"==e?n.push(s):t.push(s)}return[t,n]}(e.terms),[s,r]=await async function(e,t){if(!t.length)return[{},{}];if(e.ds?.cohort?.db)return await p(e,t);if(e.ds?.variant2samples?.get)return await async function(e,t){const n={filter0:e.filter0,filterObj:e.filter,genome:e.genome,get:"samples",twLst:t,gdcUseCaseuuid:!0,isHierCluster:e.isHierCluster};e.rglst&&(n.rglst=e.rglst);if(e.currentGeneNames){n.geneTwLst=[];for(const t of e.currentGeneNames)n.geneTwLst.push({term:{name:t,type:"geneVariant"}})}const s=await e.ds.variant2samples.get(n),r={};for(const e of s.samples){const n={sample:e.sample_id};for(const s of t){const t=e[s.term.id];Array.isArray(t)&&null!=t[0]&&null!=t[0]?n[s.term.id]={key:t[0],value:t[0]}:null!=t&&null!=t&&(n[s.term.id]={key:t,value:t})}r[e.sample_id]=n}return[r,s.byTermId||{}]}(e,t);throw"unknown method for dictionary terms"}(e,t);if(t.length&&!Object.keys(s).length)return{samples:s,refs:{byTermId:r,bySampleId:{}}};const i=await async function(e,t){if(!t.find((e=>"snplst"==e.term.type||"snplocus"==e.term.type)))return;if(!e.filter)return;return new Set((await(0,o.cf)(e.filter,e.ds)).map((e=>e.id)))}(e,n);for(const o of n)if("geneVariant"==o.term.type){e.ds.cohort?.termdb?.getGeneAlias&&(r[o.term.name]=e.ds.cohort?.termdb?.getGeneAlias(e,o));const n=await e.ds.mayGetGeneVariantData(o,e);for(const[e,r]of n.entries())o.term.name in r&&(t.length||e in s||(s[e]={sample:e}),s[e]&&(s[e][o.term.name]=r[o.term.name]))}else{if("snplst"!=o.term.type&&"snplocus"!=o.term.type)throw"unknown type of non-dictionary term";{o.type=o.term.type;const e=new Map;await(0,u._)(o,e,!0);for(const[t,n]of e){if(i&&!i.has(t))continue;t in s||(s[t]={sample:t});const e={};for(const[t,s]of n.id2value)e[t]=s.value;s[t][o.term.id]=e}}}const a={};for(const t in s)e.ds.cohort?.termdb?.q?.id2sampleName?a[t]={label:e.ds.cohort.termdb.q.id2sampleName(Number(t))}:e.ds.__gdc?.caseid2submitter&&(a[t]={label:e.ds.__gdc.caseid2submitter.get(t)});return{samples:s,refs:{byTermId:r,bySampleId:a}}}(e)}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}async function d(e,t,n){e.ds=t;const s={};for(const t in e.filters){const n=e.filters[t],r=(await(0,o.cf)(n,e.ds)).map((e=>e.id));s[t]=Array.from(new Set(r))}n.send(s)}async function p(e,t){const n={},s={},r={},a=await(0,i.w)(e.filter,e.ds),l=a?a.values.slice():[],c=await Promise.all(t.map((async(t,n)=>{const i=await(0,o.Bi)(e,l,n,a,t);if(i.bins&&(s[t.term.id]={bins:i.bins}),i.events&&(s[t.term.id]={events:i.events}),t.term.values){const e=Object.values(t.term.values);e.find((e=>"order"in e))&&(s[t.term.id]={keyOrder:e.sort(((e,t)=>e.order-t.order)).map((e=>e.key))})}return"id"in t.term&&(r[t.term.id]=t),i}))).catch(console.error);l.push(...t.map((e=>e.term.id||e.term.name)));const u=`WITH\n\t\t${a?a.filters+",":""}\n\t\t${c.map((e=>e.sql)).join(",\n")}\n\t\t${c.map((e=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${e.tablename}\n\t\t\t${a?`WHERE sample IN ${a.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,f=e.ds.cohort.db.connection.prepare(u).all(l),d=await async function(e){if(!e.currentGeneNames)return;const t=new Set;for(const n of e.currentGeneNames){const s={term:{name:n,type:"geneVariant"}},r=await e.ds.mayGetGeneVariantData(s,e);for(const e of r.keys())t.add(e)}return t}(e);for(const{sample:e,term_id:t,key:s,value:o}of f){if(d&&!d.has(e))continue;n[e]||(n[e]={sample:e});r[t];if(n[e][t]){if(!n[e][t].values){const s=n[e][t];n[e][t]={values:[s]}}n[e][t].values.push({key:s,value:o})}else n[e][t]={key:s,value:o}}return[n,s]}async function m(e){if(e.cohort.matrixplots){if(!Array.isArray(e.cohort.matrixplots.plots))throw"cohort.matrixplots.plots is not array";for(const t of e.cohort.matrixplots.plots){if(!t.name)throw".name missing from one of matrixplots.plots[]";if(!t.file)throw"unknown data source of one of matrixplots.plots[]";{const e=await c.b5(r().join(l().tpmasterdir,t.file));t.matrixConfig=JSON.parse(e),t.getConfig&&(t.matrixConfig=t.getConfig(t.matrixConfig))}}}}},5708:(e,t,n)=>{"use strict";n.r(t),n.d(t,{do_precompute:()=>y,getgroup:()=>N,trigger:()=>g,update_image:()=>k});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(8907),c=n(6718),u=n(2826),f=n(4521),d=n.n(f),p=n(334),m=n.n(p),h=n(9157);async function g(e,t,n){if(!n.cohort)throw"ds.cohort missing";if(!n.cohort.termdb)throw"cohort.termdb missing";if(!n.cohort.termdb.phewas)throw"not allowed on this dataset";if(!e.ssid)throw"ssid missing";const s={};let r;e.filter&&(r=new Set(await l.cf(e.filter,n)));const[o,c]=await a.L0(e.ssid,r);s.numberofsamples=o.size;const f=c.has(a.EO.het)?c.get(a.EO.het).size:0,d=c.has(a.EO.href)?c.get(a.EO.href).size:0,p=c.has(a.EO.halt)?c.get(a.EO.halt).size:0,g=function(e,t,n,s,r,o){const i=[];let a;if(t.cohort.termdb.selectCohort&&e){const t=e.lst.find((e=>"cohortFilter"==e.tag));t&&(a=t.tvs.values.map((e=>e.key)).sort().join(","))}for(const e of t.cohort.termdb.q.getcategory2vcfsample()){if(a&&e.subcohort!=a)continue;const l=u.iK(t.cohort.termdb.q.termjsonByOneid(e.term_id));for(const t of e.categories){const[a,c,u]=x(n,t.group1lst);let f,d,p;t.group2lst?[f,d,p]=x(n,t.group2lst):(f=s-a,d=o-c,p=r-u),a+f+c+d+u+p!=0&&i.push({term:l,group_name:e.group_name,parent_name:e.parent_name,group1label:t.group1label,group2label:t.group2label,table:[u,p,a,f,c,d]})}}return i}(e.filter,n,o,f,d,p);s.testcount=g.length;{const e=[];for(let t=0;t<g.length;t++)e.push(t+"\t"+g[t].table.join("\t"));const t=await(0,h.default)(i().join(m().binpath,"utils/fisher.2x3.R"),e);let n=0;for(const e of t)g[n++].pvalue=Number(e.split("\t")[7])}s.maxlogp=function(e){let t=0;for(const n of e)0==n.pvalue?n.logp=100:n.logp=-Math.log10(n.pvalue),t=Math.max(t,n.logp);return t}(g);const y=function(e){const t=new Map;for(const n of e)t.has(n.group_name)||t.set(n.group_name,[]),t.get(n.group_name).push(n);const n=[];for(const[e,s]of t)n.push({group_name:e,categories:s});return n}(g);s.tmpfile=await function(e){const t=[];for(const n of e)for(const e of n.categories)t.push(n.group_name+"\t"+e.logp+"\t"+e.pvalue+"\t"+JSON.stringify(e));return a.tG(t.join("\n"))}(y),q(y,s,e);{const e=.05;s.hoverdots=g.filter((t=>t.pvalue<=e))}t.send(s)}async function y(e){if(!e.cohort)throw"ds.cohort missing";if(!e.cohort.termdb)throw"cohort.termdb missing";if(!e.cohort.termdb.phewas)throw"not allowed on this dataset";e.cohort.termdb.selectCohort?await async function(e){const t=await async function(e){if(!e.cohort.termdb.phewas.precompute_subcohort2totalsamples)return;for(const t in e.cohort.termdb.phewas.precompute_subcohort2totalsamples){const n=e.cohort.termdb.phewas.precompute_subcohort2totalsamples[t];if(n.termtype)for(const t in n.termtype)n.termtype[t].samples=await l.cf(n.termtype[t].filter,e)}return e.cohort.termdb.phewas.precompute_subcohort2totalsamples}(e),n=function(e){const t=new Map,n=e.cohort.db.connection.prepare("SELECT * FROM subcohort_terms");for(const{term_id:e,cohort:s}of n.all())t.has(e)||t.set(e,new Set),t.get(e).add(s);return t}(e),s=r().createWriteStream("category2vcfsample"),o=[];for(const{group_name:r,term:i}of e.cohort.termdb.q.getAlltermsbyorder()){if(!i.type)continue;if(!n.has(i.id)){o.push(i.id);continue}let a="";{const t=e.cohort.termdb.q.getTermParent(i.id);t&&(a=t.name)}const c=v(i,e,n);for(const n of c){const o=await l.g5(n);let c;if("categorical"==i.type||"integer"==i.type||"float"==i.type)c=w(o.lst,i,e);else{if("condition"!=i.type)throw"unknown term type";c=e.cohort.termdb.phewas.comparison_groups?_(o.lst,e):w(o.lst,i,e)}c=b({categories:c,q:n,subcohortTermtype2samples:t,term:i});for(const e of c)console.log(e.group1lst.length+(e.group2lst?"/"+e.group2lst.length:"")+"\t"+e.group1label+"\t"+i.name+"\t"+n.cohortname);s.write(n.cohortname+"\t"+r+"\t"+i.id+"\t"+a+"\t"+(n.term1_q?JSON.stringify(n.term1_q):"{}")+"\t"+JSON.stringify(c)+"\n")}}s.end((()=>{console.log('Phewas precompute result written to file "category2vcfsample".'),o.length&&(console.log(o.length+" empty terms:"),console.log(o.join("\n")))}))}(e):await async function(e){const[t]=await async function(e){let t=null;if(e.cohort.termdb.phewas.samplefilter4termtype&&e.cohort.termdb.phewas.samplefilter4termtype.condition){const n=await l.cf(e.cohort.termdb.phewas.samplefilter4termtype.condition.filter,e);if(e.track&&e.track.vcf&&e.track.vcf.sample2arrayidx){t=[];for(const s of n)e.track.vcf.sample2arrayidx.has(s)&&t.push(s)}else t=n}return[t]}(e),n=[];for(const{group_name:s,term:r}of e.cohort.termdb.q.getAlltermsbyorder()){if(!r.type)continue;let o="";{const t=e.cohort.termdb.q.getTermParent(r.id);t&&(o=t.name)}const i=v(r,e);for(const a of i){const i=await l.g5(a);let c;if("categorical"==r.type||"integer"==r.type||"float"==r.type)c=w(i.lst,r,e);else{if("condition"!=r.type)throw"unknown term type";c=e.cohort.termdb.phewas.comparison_groups?_(i.lst,e):w(i.lst,r,e)}c=b({categories:c,q:a,term:r,condition_samplelst:t});for(const e of c)console.log(e.group1lst.length+(e.group2lst?"/"+e.group2lst.length:"")+"\t"+e.group1label+"\t"+r.name);n.push(s+"\t"+r.id+"\t"+o+"\t"+(a.term1_q?JSON.stringify(a.term1_q):"{}")+"\t"+JSON.stringify(c))}}r().writeFileSync("category2vcfsample",n.join("\n")),console.log('Phewas precompute result written to file "category2vcfsample".')}(e)}function b(e){const{categories:t,q:n,term:s,subcohortTermtype2samples:r,condition_samplelst:o}=e;if(r&&r[n.cohortname]&&r[n.cohortname].termtype&&r[n.cohortname].termtype[s.type]){const e=r[n.cohortname].termtype[s.type].samples;for(const n of t)if(n.group2lst)n.group2lst=n.group2lst.filter((t=>-1!=e.indexOf(t)));else if(n.copycontrolfrom1stgroup){n.group2lst=[];for(const e of t[0].group2lst)n.group2lst.push(e)}else{const t=new Set(n.group1lst);n.group2lst=e.filter((e=>!t.has(e)))}return t}if(o&&"condition"==s.type){for(const e of t)if(e.group2lst)e.group2lst=e.group2lst.filter((e=>-1!=o.indexOf(e)));else if(e.copycontrolfrom1stgroup){e.group2lst=[];for(const n of t[0].group2lst)e.group2lst.push(n)}else{const t=new Set(e.group1lst);e.group2lst=o.filter((e=>!t.has(e)))}return t}if(!s.values)return t;const i=new Set;for(const e in s.values)s.values[e].uncomputable&&i.add(s.values[e].label);if(0==i.size)return t;const a=[];for(const e of t)i.has(e.group1label)?console.log("skip "+e.group1label+", "+s.id):a.push(e);for(let e=0;e<a.length;e++){const t=a[e];t.group2lst=[];for(let n=0;n<a.length;n++)n!=e&&t.group2lst.push(...a[n].group1lst)}return a}function v(e,t,n){const s=[];if(t.cohort.termdb.selectCohort){if(!n)throw"term2cohort is required when cohort selection is enabled";for(const r of t.cohort.termdb.selectCohort.values){const o=r.keys.sort().join(",");if(!n.get(e.id).has(o))continue;const i={type:"tvslst",in:!0,join:"",lst:[{type:"tvs",tvs:{term:t.cohort.termdb.selectCohort.term,values:r.keys.map((e=>({key:e})))}}]};if("categorical"==e.type)s.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:t,term1_id:e.id});else if("float"==e.type||"integer"==e.type)s.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:t,term1_id:e.id,term1_q:e.bins.default});else{if("condition"!=e.type)throw"unknown term type";s.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:t,term1_id:e.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}}}else if("categorical"==e.type)s.push({ds:t,term1_id:e.id});else if("float"==e.type||"integer"==e.type)s.push({ds:t,term1_id:e.id,term1_q:e.bins.default});else{if("condition"!=e.type)throw"unknown term type";s.push({ds:t,term1_id:e.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}return s}function w(e,t,n){const s=new Map;for(const r of e){if(n.track&&n.track.vcf&&n.track.vcf.sample2arrayidx&&!n.track.vcf.sample2arrayidx.has(r.sample))continue;const e=r.key1;if(!s.has(e)){let n=e;t.values&&(n=t.values[e]?t.values[e].label:e),s.set(e,{group1label:n,group2label:"All others",group1lst:[]})}s.get(e).group1lst.push(r.sample)}return[...s.values()]}function _(e,t){const n=[];for(const s of t.cohort.termdb.phewas.comparison_groups){const r=[],o=[];for(const n of e){if(t.track&&t.track.vcf&&t.track.vcf.sample2arrayidx&&!t.track.vcf.sample2arrayidx.has(n.sample))continue;const e=Number(n.key1);s.group1grades.has(e)?r.push(n.sample):s.group2grades&&s.group2grades.has(e)&&o.push(n.sample)}0!=r.length?n.push({group1label:s.group1label,group2label:s.group2label,group1lst:r,group2lst:o.length?o:void 0,copycontrolfrom1stgroup:s.copycontrolfrom1stgroup}):console.log("Empty group1: "+s.group1label)}return n}async function k(e,t){const n=await a.b5(i().join(m().cachedir,e.file)),s=[];for(const e of n.trim().split("\n")){const[t,n]=e.split("\t",2),r=Number(n);0!=s.length&&s[s.length-1].group_name==t||s.push({group_name:t,categories:[]}),s[s.length-1].categories.push({logp:r})}const r={maxlogp:Number(e.max)};q(s,r,e),t.send(r)}function q(e,t,n){const s=Number(n.intendwidth),r=Number(n.axisheight),o=Number(n.groupnamefontsize),i=Number(n.dotradius),a=Number(n.groupxspace),l=Number(n.leftpad),u=Number(n.rightpad),f=Number(n.toppad),d=Number(n.bottompad),p=Number(n.devicePixelRatio),m=s/e.reduce(((e,t)=>e+t.categories.length),0),h=(0,c.createCanvas)(10,10),g=h.getContext("2d");let y=0;for(const t of e){const e=t.categories.length*m;t.width=Math.max(e,o)+2*a,t.dotshiftx=e>o?m:o/t.categories.length,y+=t.width}const b=l+y+u;h.width=b*p;const v=f+r+d;h.height=v*p,p>1&&g.scale(p,p),y=0,g.fillStyle="#FDFEE2";for(const[t,n]of e.entries())t%2==0&&g.fillRect(y,f,n.width,r),y+=n.width;y=0,g.fillStyle="black",t.grouplabels=[];for(const n of e){t.grouplabels.push({name:n.group_name,x:y+n.width/2,y:f+r+2*i});let e=0;for(const s of n.categories){const o=0==t.maxlogp?0:s.logp>=t.maxlogp?r:r*s.logp/t.maxlogp;g.beginPath(),g.arc(y+a+e,f+r-o,i,0,2*Math.PI),g.fill(),s.x=y+a+e,e+=n.dotshiftx}y+=n.width}t.canvaswidth=b,t.canvasheight=v,t.toppad=f,t.bottompad=d,t.axisheight=r,t.dotradius=i,t.groupnamefontsize=o,t.src=h.toDataURL()}function x(e,t){const n=new Map;for(const s of t){const t=e.get(s);t&&n.set(t,1+(n.get(t)||0))}return[n.get(a.EO.het)||0,n.get(a.EO.halt)||0,n.get(a.EO.href)||0]}async function N(e,t){if(!e.file)throw"file missing";return new Promise(((n,s)=>{const o=[],a=d().createInterface({input:r().createReadStream(i().join(m().cachedir,e.file))});a.on("line",(t=>{if(!t.startsWith(e.getgroup+"\t"))return;const n=t.split("\t"),s=JSON.parse(n[3]);s.pvalue=Number(n[2]),o.push(s)})),a.on("close",(()=>{t.send({categories:o}),n()}))}))}},8599:(e,t,n)=>{"use strict";n.d(t,{_:()=>M,j:()=>k});var s=n(1017),r=n.n(s),o=n(8907),i=n(5257),a=n(9157),l=n(7147),c=n.n(l),u=n(7219),f=n.n(u),d=n(334),p=n.n(d),m=n(3345),h=n(1271),g=n(4453);const y=["linear","logistic","cox"],b=1;let v,w;const _={NodeJS:{},"regression.R":{}};async function k(e,t){try{!function(e,t){if(!t.cohort)throw"cohort missing from ds";if(e.ds=t,!e.regressionType)throw"regressionType missing";if(!y.includes(e.regressionType))throw"unknown regressionType";if(!e.outcome)throw"missing 'outcome' parameter";if(!("id"in e.outcome))throw"outcome.id missing";if(!e.outcome.q)throw"outcome.q missing";if(e.outcome.q.computableValuesOnly=!0,e.outcome.term=t.cohort.termdb.q.termjsonByOneid(e.outcome.id),!e.outcome.term)throw"invalid outcome term: "+e.outcome.id;if(!e.independent)throw"independent[] missing";if(!Array.isArray(e.independent)||0==e.independent.length)throw"q.independent is not non-empty array";for(const n of e.independent){if(!n.q)throw`missing q for independent term '${n.id}'`;if(q(n,e,t),"snplst"!=n.type&&"snplocus"!=n.type){if(n.q.computableValuesOnly=!0,!n.id)throw".id missing for an independent term";if(n.term=t.cohort.termdb.q.termjsonByOneid(n.id),!n.term)throw`invalid independent term='${n.id}'`}else{if(!n.q.cacheid)throw"q.cacheid missing";if(p().cache_snpgt.fileNameRegexp.test(n.q.cacheid))throw"invalid cacheid";if("object"!=typeof n.q.snp2effAle)throw"q.snp2effAle{} is not object";if(!Number.isInteger(n.q.alleleType))throw"q.alleleType is not integer";if(!Number.isInteger(n.q.geneticModel))throw"q.geneticModel is not integer";if(3==n.q.geneticModel&&"object"!=typeof n.q.snp2refGrp)throw"q.snp2refGrp{} is not object when geneticMode=3";if("snplst"==n.type&&!Number.isInteger(n.q.missingGenotype))throw"q.missingGenotype is not integer for snplst"}}for(const t of e.independent){t.interactions||(t.interactions=[]);for(const n of t.interactions)if(!e.independent.find((e=>e.id==n)))throw"interacting term id missing from independent[]: "+n}}(e,t),v=(new Date).getTime();const n=await async function(e,t,n){const[s,r]=function(e){const t=[],n=[];for(const s of e)"snplst"==s.type||"snplocus"==s.type?n.push(s):t.push(s);return[t,n]}(t),a=await async function(e,t){const n=new Map,s=await(0,i.w)(e.filter,e.ds),r=s?s.values.slice():[],a=await Promise.all(t.map((async(t,n)=>await(0,o.Bi)(e,r,n,s,t)))).catch(console.error);r.push(...t.map((e=>e.id)));const l=`WITH\n\t\t${s?s.filters+",":""}\n\t\t${a.map((e=>e.sql)).join(",\n")}\n\t\t${a.map((e=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${e.tablename}\n\t\t\t${s?`WHERE sample IN ${s.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,c=e.ds.cohort.db.connection.prepare(l).all(r),u=[],f=e.ds.cohort.termdb.ageEndOffset;if(!f)throw"missing age end offset";for(const t of c)if("cox"==e.regressionType&&t.term_id==e.outcome.id){const n=t.key,{age_start:s,age_end:r}=JSON.parse(t.value);if(-1==n)continue;const o={age_start:s,age_end:"age"==e.outcome.q.timeScale?r+f:r};u.push({sample:t.sample,key:n,value:o,term_id:t.term_id})}else u.push(t);for(const{sample:e,term_id:s,key:r,value:o}of u){const i=t.find((e=>e.id==s));if(n.has(e)||n.set(e,{sample:e,id2value:new Map}),n.get(e).id2value.has(s))throw`duplicate '${s}' entry for sample='${e}'`;n.get(e).id2value.set(s,{key:i.q.scale?r/i.q.scale:r,value:i.q.scale?o/i.q.scale:o})}const d=new Set;for(const e of n.values())for(const n of t)if(!e.id2value.has(n.id)){d.add(e.sample);break}for(const e of d)n.delete(e);return n}(e,s);for(const e of r){if(T(e,a,n),"snplst"!=e.type&&"snplocus"!=e.type)throw"unknown type of independent non-dictionary term";await M(e,a)}return[...a.values()]}(e,[e.outcome,...e.independent],t);w=(new Date).getTime(),_.NodeJS.getSampleData=(w-v)/1e3+" sec",v=(new Date).getTime();const s=function(e,t){const n={id:e.outcome.id,name:e.outcome.term.name,rtype:"numeric"};"logistic"==e.regressionType&&(n.categories={ref:e.outcome.refGrp,nonref:S(e.outcome)});"cox"==e.regressionType&&(n.timeToEvent={timeId:e.outcome.id+"_time",eventId:e.outcome.id+"_event",timeScale:e.outcome.q.timeScale},"age"==n.timeToEvent.timeScale&&(n.timeToEvent.agestartId=e.outcome.id+"_agestart",n.timeToEvent.ageendId=e.outcome.id+"_ageend"));const s=[];for(const t of e.independent)"snplst"==t.type||"snplocus"==t.type?N(t,s,e):x(t,s,e);const r=[];for(const o of t){const{sample:t,id2value:i}=o;if(!i.has(e.outcome.id)){o.noOutcome=!0;continue}const a=i.get(e.outcome.id);let l=!1;for(const t of e.independent)if("snplocus"!=t.type)if("snplst"==t.type){for(const e of t.highAFsnps.keys())if(!i.get(e)){l=!0;break}}else{if(!i.get(t.id)){l=!0;break}}if(l)continue;const c={};if("linear"==e.regressionType&&(c[n.id]=a.value),"logistic"==e.regressionType&&(c[n.id]=a.key===e.outcome.refGrp?0:1),"cox"==e.regressionType){c[n.timeToEvent.eventId]=a.key;const{age_start:t,age_end:s}=a.value;c[n.timeToEvent.timeId]=s-t,"age"==e.outcome.q.timeScale&&(c[n.timeToEvent.agestartId]=t,c[n.timeToEvent.ageendId]=s)}for(const e of s){const t=i.get(e.id);c[e.id]=t?"numeric"===e.rtype?t.value:t.key:null}r.push(c)}const o={regressionType:e.regressionType,binpath:p().binpath,data:r,outcome:n,independent:s};return o}(e,n);w=(new Date).getTime(),_.NodeJS.makeRinput=(w-v)/1e3+" sec",function(e){const t=e.regressionType,n=e.outcome;if(e.data.length<b)throw"too few samples to fit model";let s=e.independent.length;if("cox"==t)if("time"==n.timeToEvent.timeScale)s+=2;else{if("age"!=n.timeToEvent.timeScale)throw"unknown cox regression time scale";s+=4}else s+=1;if(e.data.find((e=>Object.keys(e).length!=s)))throw"unequal number of variables in data entries";if("logistic"==t){if([...new Set(e.data.map((e=>e[n.id])))].find((e=>![0,1].includes(e))))throw"non-0/1 outcome values found"}if("cox"==t){if([...new Set(e.data.map((e=>e[n.timeToEvent.eventId])))].find((e=>![0,1].includes(e))))throw"non-0/1 outcome event values found"}for(const t of e.independent)if("numeric"==t.rtype){if(t.refGrp)throw`reference group given for '${t.id}'`}else{if("factor"!=t.rtype)throw`variable rtype='${t.rtype}' not recognized`;{if(!t.refGrp)throw`reference group not given for '${t.id}'`;if("snplst"==t.type||"snplocus"==t.type)continue;const n=new Set(e.data.map((e=>e[t.id])));if(n.size<2)throw`fewer than 2 categories in data of variable='${t.id}'`;if(!n.has(t.refGrp))throw`reference group missing in data of variable='${t.id}'`}}}(s);const[r,a]=function(e){const t={},n={};if(t.outcome=e.outcome.id,n[e.outcome.id]="outcome",e.outcome.timeToEvent){const s=e.outcome.timeToEvent;t.outcome_time=s.timeId,n[s.timeId]="outcome_time",t.outcome_event=s.eventId,n[s.eventId]="outcome_event","age"==s.timeScale&&(t.outcome_agestart=s.agestartId,t.outcome_ageend=s.ageendId,n[s.agestartId]="outcome_agestart",n[s.ageendId]="outcome_ageend")}for(const[s,r]of e.independent.entries())t["id"+s+"_"]=r.id,n[r.id]="id"+s+"_";if(e.outcome.id=n[e.outcome.id],e.outcome.timeToEvent){const t=e.outcome.timeToEvent;t.timeId=n[t.timeId],t.eventId=n[t.eventId],"age"==t.timeScale&&(t.agestartId=n[t.agestartId],t.ageendId=n[t.ageendId])}for(const t of e.independent)if(t.id=n[t.id],t.interactions&&t.interactions.length>0)for(const[e,s]of t.interactions.entries())t.interactions[e]=n[s];for(const t of e.data)for(const e in t)t[n[e]]=t[e],delete t[e];return[t,n]}(s),l={resultLst:[]};return await Promise.all([A(s,r,e,l),C(e,n,s,l)]),console.log("benchmark:",_),l}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}function q(e,t,n){if(!e.q.restrictAncestry)return;if(!("name"in e.q.restrictAncestry))throw".name missing from tw.q.restrictAncestry";if(!n.cohort.termdb.restrictAncestries)throw"ds.cohort.termdb.restrictAncestries missing";const s=n.cohort.termdb.restrictAncestries.find((t=>t.name==e.q.restrictAncestry.name));if(!s)throw"unknown ancestry for restriction: "+e.q.restrictAncestry.name;if(s.pcs)e.q.restrictAncestry.pcs=s.pcs;else{if(!s.PCBySubcohort)throw"unknown way of accessing pcs from ds.cohort.termdb.restrictAncestries: "+e.q.restrictAncestry.name;{if(!t.filter)throw"q.filter missing while trying to access subcohort for PCBySubcohort";const n=I(t.filter,"cohortFilter");if(!n)throw"tvs by tag=cohortFilter missing from q.filter.lst[] while trying to access subcohort for PCBySubcohort";const r=n.tvs.values.map((e=>e.key)).sort().join(","),o=s.PCBySubcohort[r];if(!o)throw"unknown key for PCBySubcohort: "+r;if(!o.pcs)throw"pcs Map() missing from PCBySubcohort[]: "+r;e.q.restrictAncestry.pcs=o.pcs}}}function x(e,t,n){const s={id:e.id,name:e.term.name,type:"spline"==e.q.mode?"spline":"other",rtype:"continuous"==e.q.mode||"spline"==e.q.mode?"numeric":"factor"};if(e.interactions.length>0){s.interactions=[];for(const t of e.interactions){const e=n.independent.find((e=>e.id==t));if("snplst"==e.type)for(const t of e.highAFsnps.keys())s.interactions.push(t);else{if("snplocus"==e.type)continue;s.interactions.push(t)}}}"factor"===s.rtype&&(s.refGrp=e.refGrp),"spline"==e.q.mode&&(s.spline={knots:e.q.knots.map((e=>Number(e.value)))},n.independent.find((e=>"snplocus"==e.type))||(s.spline.plotfile=r().join(p().cachedir,Math.random().toString()+".png"))),t.push(s)}function N(e,t,n){for(const s of e.highAFsnps.keys()){const r={id:s,name:s,type:e.type};3==e.q.geneticModel?(r.rtype="factor",r.refGrp=e.q.snp2refGrp[s]):r.rtype="numeric";for(const t of n.independent)t.interactions.includes(e.id)&&(r.interactions||(r.interactions=[]),r.interactions.push(t.id));t.push(r)}if(e.q.restrictAncestry)for(const n of e.q.restrictAncestry.pcs.keys())t.push({id:n,name:n,type:"float",rtype:"numeric"})}function S(e){if("condition"==e.term.type){for(const t of e.q.groups)if(t.name!=e.refGrp)return t;throw"nonref group not found for logistic outcome"}if("predefined-groupset"==e.q.type){if(!e.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!Number.isInteger(e.q.groupsetting.predefined_groupset_idx))throw'outcome.q.predefined_groupset_idx not integer when q.type is "predefined-groupset"';if(!e.term.groupsetting)throw"outcome.term.groupsetting missing";const t=e.term.groupsetting.lst[e.q.groupsetting.predefined_groupset_idx];if(!t)throw"groupset not found by outcome.q.predefined_groupset_idx";const n=t.groups.find((t=>t.name!=e.refGrp));if(!n)throw"non-ref group not found for predefined-groupset";return n.name}if("custom-groupset"==e.q.type){if(!e.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!e.q.groupsetting.customset)throw"outcome.q.customset missing";const t=e.q.groupsetting.customset.groups.find((t=>t.name!=e.refGrp));if(!t)throw"non-ref group not found for custom-groupset";return t.name}if("values"==e.q.type){if(!e.term.values)throw"outcome.term.values{} missing";for(const t in e.term.values){const n=e.term.values[t];if(n.label!=e.refGrp)return n.label}throw"unknown nonref group from outcome.term.values"}if("custom-bin"==e.q.type){const t=e.q.lst.find((t=>t.label!=e.refGrp));if(!t)throw"non-ref bin is not found for custom-bin";return t.label}if("regular-bin"==e.q.type)throw"do not know a way to find computed bin list for type=regular-bin";throw"unknown outcome.q.type"}async function A(e,t,n,s){v=(new Date).getTime();const o=r().join(p().cachedir,Math.random().toString()+".json");await m.Sf(o,JSON.stringify(e));const i=await(0,a.default)(r().join(p().binpath,"utils","regression.R"),[],[o]);c().unlink(o,(()=>{})),await async function(e,t,n,s,r){if(1!=t.length)throw"expected 1 json line in R output";const o=JSON.parse(t[0]),i=o.data;_["regression.R"]=o.benchmark;for(const t of i){const o={data:{sampleSize:t.data.sampleSize,eventCnt:t.data.eventCnt?t.data.eventCnt:null}};if(t.id){const e=n[t.id];o.id=e;const r=s.independent.find((e=>"snplocus"==e.type));if(!r)throw"snplocus term missing";o.AFstr=r.snpid2AFstr.get(e),o.data.headerRow=j(e,r)}const i=t.data;if(i.residuals&&(o.data.residuals=i.residuals,o.data.residuals.label="linear"==e.regressionType?"Residuals":"Deviance residuals"),"cox"==e.regressionType){if(i.coefficients.rows.length<1)throw"fewer than 1 row in coefficients table"}else if(i.coefficients.rows.length<2)throw"fewer than 2 rows in coefficients table";o.data.coefficients={header:i.coefficients.header,intercept:"cox"==e.regressionType?null:i.coefficients.rows.shift(),terms:{},interactions:[]};for(const e of i.coefficients.rows)if(-1!=e[0].indexOf(":")){const t={},[s,r]=e.shift().split(":"),[i,a]=e.shift().split(":");t.term1=n[s],t.category1=i,t.term2=n[r],t.category2=a,t.lst=e,o.data.coefficients.interactions.push(t)}else{const t=e.shift(),s=e.shift(),r=n[t];o.data.coefficients.terms[r]||(o.data.coefficients.terms[r]={}),s?(o.data.coefficients.terms[r].categories||(o.data.coefficients.terms[r].categories={}),o.data.coefficients.terms[r].categories[s]=e):o.data.coefficients.terms[r].fields=e}o.data.coefficients.label="Coefficients",o.data.type3={header:i.type3.header,terms:{},interactions:[]},"cox"!=e.regressionType&&(o.data.type3.intercept=i.type3.rows.shift());for(const e of i.type3.rows)if(-1!=e[0].indexOf(":")){const t={},[s,r]=e.shift().split(":");t.term1=n[s],t.term2=n[r],t.lst=e,o.data.type3.interactions.push(t)}else{const t=n[e.shift()];o.data.type3.terms[t]||(o.data.type3.terms[t]=e)}if(o.data.type3.label="Type III statistics",i.totalSnpEffect){if(1!=i.totalSnpEffect.rows.length)throw"total SNP effect table should have 1 row";o.data.totalSnpEffect={header:i.totalSnpEffect.header.slice(0,4)};const e=i.totalSnpEffect.rows[0].slice(0,4),t=i.totalSnpEffect.rows[0][4].split(";"),s=t.findIndex((e=>!e.includes(":"))),r=t.splice(s,1)[0];o.data.totalSnpEffect.snp=n[r];const a=[];for(const e of t){if(!e.includes(":"))throw"expected interaction";const[t,s]=e.split(":");a.push({term1:n[t],term2:n[s]})}o.data.totalSnpEffect.interactions=a,o.data.totalSnpEffect.lst=e,o.data.totalSnpEffect.label="Total SNP effect"}i.tests&&(o.data.tests=i.tests,o.data.tests.label="Statistical tests"),o.data.other=i.other,o.data.other.label="Other summary statistics";for(const t of e.independent)if(t.spline&&t.spline.plotfile){o.data.splinePlots||(o.data.splinePlots=[]);const e=t.spline.plotfile,n=await c().promises.readFile(e);o.data.splinePlots.push({src:"data:image/png;base64,"+new Buffer.from(n).toString("base64"),size:f()(e)}),c().unlink(e,(e=>{if(e)throw e}))}i.warnings&&(o.data.warnings=i.warnings);const a=s.independent.find((e=>"snplst"==e.type));if(a){if(a.lowAFsnps&&a.lowAFsnps.size){o.data.warnings||(o.data.warnings=[]);for(const e of a.lowAFsnps.keys())o.data.warnings.push(`${e}: effect allele frequency below cutoff, excluded from analysis`)}if(a.monomorphicLst&&a.monomorphicLst.length){o.data.warnings||(o.data.warnings=[]);for(const e of a.monomorphicLst)o.data.warnings.push(`${e}: monomorphic, excluded from analysis`)}}r.resultLst.push(o)}}(e,i,t,n,s),w=(new Date).getTime(),_.NodeJS.runRegression=(w-v)/1e3+" sec"}async function C(e,t,n,s){const o=e.independent.find((e=>"snplocus"==e.type));if(o){if(v=(new Date).getTime(),function(e,t){for(const n of e.monomorphicLst){const s=e.snpgt2count.get(n),r=[];for(const[e,t]of s)r.push(e+"="+t);const o={id:n,data:{headerRow:j(n,e)}};t.resultLst.push(o)}}(o,s),o.lowAFsnps.size)if("linear"==e.regressionType)await async function(e,t,n,s){const o=[],i=new Map;for(const[s,r]of e.lowAFsnps){let e=0,a=null,l=null;const c=[],u=[];for(const{sample:s,noOutcome:o}of t){if(o)continue;const t=n.data[e++].outcome;if(!Number.isFinite(t))continue;const i=r.samples.get(s);if(!i)continue;null==a?a=l=t:(a=Math.min(a,t),l=Math.max(l,t));const[f,d]=i.split("/");f==r.effAle||d==r.effAle?c.push(t):u.push(t)}o.push({group1_id:s+"_hasEffAllele",group1_values:c,group2_id:s+"_noEffAllele",group2_values:u}),i.set(s,{minv:a,maxv:l})}const l=r().join(p().cachedir,Math.random().toString()+".json");await m.Sf(l,JSON.stringify(o));const u=await(0,a.default)(r().join(p().binpath,"utils/wilcoxon.R"),[],[l]);c().unlink(l,(()=>{}));const f=JSON.parse(u);for(const t of f){const n=t.group1_id.replace("_hasEffAllele",""),r=t.group1_values,o=t.group2_values;let a;a=null==t.pvalue||"null"==t.pvalue?"NA":t.pvalue.toPrecision(4);const{minv:l,maxv:c}=i.get(n),u=m.JC(r.sort(((e,t)=>e-t)).map((e=>({value:e}))));u.label=`Carry ${0==e.q.alleleType?"minor":"alternative"} allele, n=${r.length}`;const f=m.JC(o.sort(((e,t)=>e-t)).map((e=>({value:e}))));f.label=`No ${0==e.q.alleleType?"minor":"alternative"} allele, n=${o.length}`;const d={id:n,AFstr:e.snpid2AFstr.get(n),data:{headerRow:j(n,e),wilcoxon:{pvalue:a,boxplots:{minv:l,maxv:c,hasEff:u,noEff:f}}}};s.resultLst.push(d)}}(o,t,n,s);else if("logistic"==e.regressionType)await async function(e,t,n,s){const r=[];let o=0;const i=new Map;for(const[s,a]of e.lowAFsnps){let e=0,l=0,c=0,u=0,f=0;for(const{sample:s,noOutcome:r}of t){if(r)continue;const t=n.data[f++],o="outcome"in t?t.outcome:t.outcome_event;if(0!=o&&1!=o)throw"outcome is not 0 or 1";const i=a.samples.get(s);if(!i)continue;const[d,p]=i.split("/"),m=a.effAle==d||a.effAle==p;0==o?m?l++:e++:m?u++:c++}i.set(o,s);const d={index:o,n1:u,n2:l,n3:c,n4:e};r.push(d),o++}const a=await(0,h.run_rust)("fisher",JSON.stringify({input:r}));for(const t of JSON.parse(a)){const n=i.get(t.index),{effAle:r}=e.lowAFsnps.get(n),o=t.p_value,a="chisq"===t.fisher_chisq,l={id:n,AFstr:e.snpid2AFstr.get(n),data:{headerRow:j(n,e),fisher:{isChi:a,pvalue:Number(o.toFixed(4)),rows:[["","Carry "+r+" allele","No "+r+" allele"],["Have event",t.n1,t.n3],["No event",t.n2,t.n4]]}}};s.resultLst.push(l)}}(o,t,n,s);else{if("cox"!=e.regressionType)throw"unknown regression type";await async function(e,t,n,s){const r={data:{}},o=new Set;for(const[s,i]of e.lowAFsnps){const e=[];let a=0;for(const{sample:s,noOutcome:r}of t){if(r)continue;const t=n.data[a++];if(0!==t.outcome_event&&1!==t.outcome_event)throw"d.outcome_event is not 0/1";if(!Number.isFinite(t.outcome_time))throw"d.outcome_time is not numeric";const o={time:t.outcome_time,event:t.outcome_event},l=i.samples.get(s);if(!l)continue;const[c,u]=l.split("/");o.series=i.effAle==c||i.effAle==u?"1":"2",e.push(o)}new Set(e.map((e=>e.series))).size<2?o.add(s):r.data[s]=e}const i=await(0,g.y)(r);let a;for(const[t,n]of e.lowAFsnps){if(o.has(t)){a={pvalue:"NA",msg:"Cannot perform cumulative incidence test on this snp - at least one allele is not found in any sample"}}else{if(1==!i[t].tests?.length)throw"must have a single test";const e=Number(i[t].tests[0].pvalue);if(!Number.isFinite(e))throw"invalid pvalue";a={pvalue:Number(e.toFixed(4)),ci_data:{[t]:i[t]}}}const n={id:t,AFstr:e.snpid2AFstr.get(t),data:{headerRow:j(t,e),cuminc:a}};s.resultLst.push(n)}}(o,t,n,s)}w=(new Date).getTime(),_.NodeJS.snplocusPostprocess=(w-v)/1e3+" sec"}}function j(e,t){const n=t.snpgt2count.get(e);if(!n)return{k:"Error",v:"Variant not found"};const s=[];for(const[e,t]of n)s.push(e+"="+t);const r={snpid:e,gtcounts:s};return t.monomorphicLst.includes(e)?r.monomorphic=!0:(r.effAle=t.highAFsnps.has(e)?t.highAFsnps.get(e).effAle:t.lowAFsnps.get(e).effAle,r.af=t.snpid2AFstr.get(e)),{k:"Variant:",v:r}}function T(e,t,n){if(e.q.restrictAncestry)for(const[n,s]of e.q.restrictAncestry.pcs)for(const[e,r]of s)t.has(e)&&t.get(e).id2value.set(n,{key:r,value:r})}async function M(e,t,n){const s=(await m.b5(r().join(p().cache_snpgt.dir,e.q.cacheid))).split("\n"),o=s[0].split("\t").slice(p().cache_snpgt.sampleColumn).map(Number);if(n)for(const e of o)t.set(e,{id2value:new Map});const i=o.map((e=>t.has(e))),a=new Map;for(let t=1;t<s.length;t++){const n=s[t].split("\t"),r=n[0],l={refAle:n[3],altAles:n[4].split(","),samples:new Map};e.q.snp2effAle?l.effAle=e.q.snp2effAle[r]:l.effAle=l.altAles[0],a.set(r,l);for(const[e,t]of o.entries()){if(!i[e])continue;const s=n[e+p().cache_snpgt.sampleColumn];s&&a.get(r).samples.set(t,s)}}"snplst"!=e.type||n||function(e,t,n,s){if(0==t.q.missingGenotype){for(const t of e.values()){let e;if(t.refAle!=t.effAle)e=t.refAle;else for(const n of t.altAles)if(n!=t.effAle){e=n;break}if(!e)throw"not finding a non-effect allele";for(const[r,o]of n.entries())s[r]&&(t.samples.has(o)||t.samples.set(o,e+"/"+e))}return}if(1==t.q.missingGenotype){const t=new Set;for(const{samples:r}of e.values())for(const[e,o]of n.entries())s[e]&&(r.has(o)||t.add(o));for(const{samples:n}of e.values())for(const e of t)n.delete(e);return}throw"invalid missingGenotype value"}(a,e,o,i),e.snpgt2count=new Map;for(const[t,n]of a){const s=new Map;for(const[e,t]of n.samples)s.set(t,1+(s.get(t)||0));e.snpgt2count.set(t,s)}!function(e,t){e.lowAFsnps=new Map,e.highAFsnps=new Map,e.monomorphicLst=[],e.snpid2AFstr=new Map;for(const[n,s]of t){if(1==e.snpgt2count.get(n).size){e.monomorphicLst.push(n);continue}const t=s.samples.size;let r=0;for(const[e,t]of s.samples){const[e,n]=t.split("/");r+=(e==s.effAle?1:0)+(n==s.effAle?1:0)}const o=r/(2*t);e.snpid2AFstr.set(n,(100*o).toFixed(1)+"%"),o<e.q.AFcutoff/100?e.lowAFsnps.set(n,s):e.highAFsnps.set(n,s)}}(e,a);for(const[n,s]of e.highAFsnps)for(const[r,o]of s.samples){const[i,a]=o.split("/"),l=O(e,s.effAle,i,a);t.get(r).id2value.set(n,{key:l,value:l})}}function O(e,t,n,s){switch(e.q.geneticModel){case 0:return(n==t?1:0)+(s==t?1:0);case 1:return n==t||s==t?1:0;case 2:return n==t&&s==t?1:0;case 3:return n+"/"+s;default:throw"unknown geneticModel option"}}function I(e,t){if(e.tag===t)return e;if("tvslst"===e.type)for(const n of e.lst){const e=I(n,t);if(e)return e}}},2188:(e,t,n)=>{"use strict";n.d(t,{uR:()=>g,v8:()=>q,wz:()=>h});var s=n(2974),r=n(1017),o=n.n(r),i=n(3345),a=n(334),l=n.n(a),c=n(2273),u=n(8907),f=n(5257),d=n(6191),p=n(9157);const m="#F5F5DC";async function h(e){if(e.cohort.scatterplots){if(!Array.isArray(e.cohort.scatterplots.plots))throw"cohort.scatterplots.plots is not array";for(const t of e.cohort.scatterplots.plots){if(!t.name)throw".name missing from one of scatterplots.plots[]";if(!t.file)throw"unknown data source of one of scatterplots.plots[]";{const n=(await(0,i.b5)(o().join(l().tpmasterdir,t.file))).trim().split("\n"),s=n[0].split("\t");t.filterableSamples=[];const r=[];let a=0,c=0;for(let o=1;o<n.length;o++){const i=n[o].split("\t"),l=Number(i[1]),u=Number(i[2]);if(Number.isNaN(l)||Number.isNaN(u)){a++;continue}const f={sample:i[0],x:l,y:u},d=e.cohort.termdb.q.sampleName2id(i[0]);if(null==d){if(s[3]){f.info={};for(let e=3;e<s.length;e++)f.info[s[e]]=i[e]}r.push(f)}else c++,f.sampleId=d,t.filterableSamples.push(f)}r.length&&(t.referenceSamples=r),console.log(t.filterableSamples.length,`scatterplot lines from ${t.name} of ${e.label},`,t.referenceSamples?t.referenceSamples.length+" reference cases":"",a?a+" lines with invalid X/Y values":"")}}}}async function g(e,t,n,r,o){try{let i,a;if(2==t.coordTWs.length)i=[],a=await async function(e,t,n){t.ds=n;const s=[];if(2!=t.coordTWs.length)return s;const r=await(0,f.w)(t.filter,t.ds);let o="";r&&(o+=(0,u.ig)(`WITH ${r.filters}`,r.values.slice()));const i=t.coordTWs[0].term,a=t.coordTWs[1].term;let l;t.divideByTW&&"continuous"==t.divideByTW.q.mode&&(l=t.divideByTW.term);o+=`SELECT ax.sample AS sampleId, ax.value as x, ay.value AS y , ${l?"az.value AS z":"0 as z"}\n\t\t\tFROM anno_${i.type} ax \n\t\t\tJOIN anno_${a.type} ay on ax.sample = ay.sample \n\t\t\t${l?`JOIN anno_${l.type} az on ax.sample = az.sample and az.term_id = '${l.id}' `:""}\n\t\t\tWHERE ax.term_id = '${i.id}' and ay.term_id = '${a.id}'`,r&&(o+=` AND ax.sample IN ${r.CTEname}`);const c=t.ds.cohort.db.connection.prepare(o).all(),p=d.i.canDisplaySampleIds(e,n);for(const{sampleId:e,x:r,y:o,z:i}of c){const a={sampleId:e,x:r,y:o,z:i};p&&(a.sample=n.sampleId2Name.get(e));const l=k(t.coordTWs[0].term,r)&&k(t.coordTWs[1].term,o)&&k(t.divideByTW?.term,i);a&&l&&s.push(a)}return s}(e,t,r);else{if(!t.plotName)throw"Neither plot name or coordinates where provided";if(!r.cohort.scatterplots||!r.cohort.scatterplots.plots)throw"not supported";const e=r.cohort.scatterplots.plots.find((e=>e.name==t.plotName));if(!e)throw`plot not found with plotName ${t.plotName}`;const n=await async function(e,t,n){if(n.filterableSamples){let e=[],t=[];return n.referenceSamples&&(t=s(n.referenceSamples)),n.filterableSamples&&(e=s(n.filterableSamples)),[t,e]}if(n.gdcapi)throw"gdcapi not implemented yet";throw"do not know how to load data from this plot";function s(e){const t=[];for(const n of JSON.parse(JSON.stringify(e)))t.push(n);return t}}(0,0,e);i=n[0],a=n[1]}const l=[];t.coordTWs&&l.push(...t.coordTWs),t.colorTW&&l.push(t.colorTW),t.shapeTW&&l.push(t.shapeTW),t.divideByTW&&l.push(t.divideByTW),t.scaleDotTW&&l.push(t.scaleDotTW);const p=await(0,s.Yu)({filter:t.filter,terms:l},r,o);if(p.error)throw p.error;const h=await async function(e,t,n,s){const r={};for(const o of t){const t=n.samples[o.sampleId.toString()];if(!t)continue;let i=!1;if(s.colorTW&&!y(t,s.colorTW)||s.shapeTW&&!y(t,s.shapeTW))continue;let a="Default";if(s.divideByTW&&"continuous"!=s.divideByTW.q.mode)if(o.z=0,"geneVariant"==s.divideByTW.term.type)a=v(!0,t,s.divideByTW),null==a&&(a=v(!1,t,s.divideByTW),i=!0);else{const e=s.divideByTW.term.id||s.divideByTW.term.name,n=t[e]?.key;if(null==n)continue;a=s.divideByTW.term.values?.[n]?.label||n}if(!r[a]){const t=e.map((e=>({...e,category:"Ref",shape:"Ref",z:0})));r[a]={samples:t,colorMap:{},shapeMap:{},isLast:i}}if(s.divideByTW||(o.z=0),s.scaleDotTW){const e=t?.[s.scaleDotTW.id]?.key;if(!e||!k(s.scaleDotTW.term,e))continue;o.scale=e}else o.scale=1;o.cat_info={},o.hidden={},s.colorTW?"continuous"===s.colorTW?.q?.mode?t&&(o.category=t[s.colorTW.term.id||s.colorTW.term.name].value):b(t,o,s.colorTW,r[a].colorMap,"category"):o.category="Default",s.shapeTW?b(t,o,s.shapeTW,r[a].shapeMap,"shape"):o.shape="Ref",r[a].samples.push(o)}let o=0;for(const[e,t]of Object.entries(r))o=Math.max(o,Object.keys(t.colorMap).length);const i=(0,c.getColors)(o);for(const[o,a]of Object.entries(r)){if(s.colorTW&&"continuous"!==s.colorTW.q.mode){let e=20;const t=c.schemeCategory20,r=Object.entries(a.colorMap);for(const[o,a]of r){let r;if(s.colorTW.term.values?.[o])r=s.colorTW.term.values?.[o];else for(const e in s.colorTW.term.values)s.colorTW.term.values?.[e].label==o&&(r=s.colorTW.term.values?.[e]);if(r&&"color"in r)a.color=r.color;else if(n.refs?.byTermId[s.colorTW.term.id]?.bins){const r=n.refs.byTermId[s.colorTW.term.id].bins.find((e=>e.name===o));r?a.color=r.color:(a.color=t[e],e--)}else"geneVariant"!=s.colorTW.term.type&&(a.color=i(o))}}let r=1;for(const[e,t]of Object.entries(a.shapeMap))"shape"in t||(t.shape=r),r++;a.colorLegend=s.colorTW?_(a.colorMap,s.colorTW,n.refs):[["Default",{sampleCount:t.length,color:"blue"}]],a.colorLegend.push(["Ref",{sampleCount:e.length,color:s.colorTW?.term.values?.Ref?s.colorTW.term.values?.Ref.color:m}]),a.shapeLegend=_(a.shapeMap,s.shapeTW,n.refs),a.shapeLegend.push(["Ref",{sampleCount:e.length,shape:0}])}return r}(i,a,p,t);n.send(h)}catch(e){e.stack&&console.log(e.stack),n.send({error:e.message||e})}}function y(e,t){const n=e?.[t?.term?.id||t?.term?.name]?.key,s=void 0!==n;return s||console.log(JSON.stringify(e)+" missing value for the term "+JSON.stringify(t)),s}function b(e,t,n,s,r){let o=null;"geneVariant"==n.term.type?function(e,t,n,s,r){if("geneVariant"==n.term.type){const o=e?.[n.term.name]?.values;t.cat_info[r]=[];for(const e of o){const n=c.mclass[e.class],o=w(e);let i;t.cat_info[r].push(e),null==s[o]?(i={color:n.color,sampleCount:1,hasOrigin:"origin"in e},s[o]=i):(i=s[o],i.sampleCount=i.sampleCount+1,i.hasOrigin=i.hasOrigin||"origin"in e)}t[r]=v(!0,e,n)||v(!1,e,n),t[r]||(t[r]=w(o[0])),t.hidden[r]=!!n.q.hiddenValues&&t[r]in n.q.hiddenValues}}(e,t,n,s,r):(o=e?.[n.id||n.term.name]?.key,n.term.values?.[o]?.label?(o=n.term.values?.[o]?.label,t.hidden[r]=!!n.q.hiddenValues&&o in n.q.hiddenValues):t.hidden[r]=!!n.q.hiddenValues&&e?.[n.id]?.key in n.q.hiddenValues,o&&(t[r]=o.toString(),null==s[o]?s[o]={sampleCount:1}:s[o].sampleCount++))}function v(e,t,n){const s=t?.[n.term.name]?.values;for(const[t,r]of Object.entries(c.dt2label)){const r=s.find((e=>{const s=w(e),r=!(n.q.hiddenValues&&s in n.q.hiddenValues);return e.dt==t&&r}));if(!r)continue;const o="WT"==r.class||"Blank"==r.class;if(e&&o)continue;return w(r)}}function w(e){const t=e.dt,n=c.mclass[e.class],s=c.morigin[e.origin]?.label,r=s?`${s[0]} ${c.dt2label[t]}`:c.dt2label[t];return`${n.label}, ${r}`}function _(e,t,n){let s=[];if(!t||0==e.size)return s;if("geneVariant"==t.term.type)s=Object.entries(e),s.sort(((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0));else if(n?.byTermId[t.term.id]?.bins){const r=n.byTermId[t.term.id].bins;for(const t of r)e[t.name]&&s.push([t.name,e[t.name]]);for(const[t,n]of Object.entries(e))s.some((e=>e[0]===t))||s.push([t,n])}else s=Object.entries(e),s.sort(((e,n)=>{let s,r;for(const o in t.term.values){const i=t.term.values[o];(i.label&&e[0]==i.label||o==e[0])&&(s=i),(i.label&&n[0]==i.label||o==n[0])&&(r=i)}return s&&"order"in s?s?.order<r?.order?-1:1:e[1].sampleCount>n[1].sampleCount?-1:1}));return s}function k(e,t){if(!e)return!0;return!e.values?.[t]?.uncomputable}async function q(e,t,n){const s=t.coords,r=o().join(l().cachedir,Math.random().toString()+".json");await(0,i.Sf)(r,JSON.stringify(s));let a=await(0,p.default)(o().join(l().binpath,"utils/lowess.R"),[],[r]);a=JSON.parse(a);const c=[];for(const[e,t]of Object.entries(a.x))c.push([t,a.y[e]]);return n.send(c)}},394:(e,t,n)=>{"use strict";n.d(t,{JV:()=>l,jj:()=>c,qN:()=>u});var s=n(334),r=n.n(s),o=n(3345),i=n(1575),a=n(6191);function l(e){if(!e.cohort)throw"ds.cohort missing";if(!e.cohort.db)throw"ds.cohort.db missing";if(!e.cohort.termdb)throw"ds.cohort.termdb missing";const t=e.cohort.db.file_fullpath||e.cohort.db.file;if(!t)throw"both file and file_fullpath missing";let n;try{console.log("Connecting",t),n=(0,o.sE)(t),console.log(`DB connected for ${e.label}: ${t}`)}catch(e){throw`Cannot connect db ${t}: ${e.message||e}`}e.cohort.db.connection=n;const s=c(n),l=["cohorts","sampleidmap","terms","ancestry","alltermsbyorder","termhtmldef","category2vcfsample","chronicevents","precomputed_chc_grade","precomputed_chc_child","precomputed_cuminc","precomputed_cox","subcohort_terms","subcohort_samples","survival","features","cohort_features","anno_integer","anno_float","anno_categorical","buildDate"];for(const e of l)s.has(e)||console.log(`${e} table missing!!!!!!!!!!!!!!!!!!!!`);if(!s.has("terms"))throw"terms table missing";if(!s.has("ancestry"))throw"ancestry table missing";if(e.cohort.termdb.selectCohort&&!s.has("subcohort_terms"))throw"subcohort_terms table is missing while termdb.selectCohort is enabled";e.cohort.termdb.q={};const f=e.cohort.termdb.q;if(s.has("buildDate")&&(f.get_buildDate=n.prepare("select date from buildDate")),s.has("term2genes")){e.cohort.termdb.termMatch2geneSet=!0;const t=n.prepare("SELECT genes FROM term2genes WHERE id=?"),s=new Map;f.getGenesetByTermId=e=>{if(s.has(e))return s.get(e);const n=t.get(e);if(n&&n.genes){const t=JSON.parse(n.genes);return s.set(e,t),t}}}if(s.has("sampleidmap")){const t=new Map,s=new Map,r=n.prepare("SELECT * FROM sampleidmap");let o=0;for(const{id:e,name:n}of r.all())t.set(e,n),s.set(n,e),o++;if(f.id2sampleName=e=>t.get(e),f.sampleName2id=e=>s.get(e),e.cohort.termdb.selectCohort){const e=n.prepare("SELECT cohort,sample_count from cohorts").all(),t={};for(const n of e)t[n.cohort]=n.sample_count;f.getcohortsamplecount=e=>e?t[e]||0:o}else f.getcohortsamplecount=()=>o}if(s.has("category2vcfsample")){const e=n.prepare("SELECT * FROM category2vcfsample");let t;f.getcategory2vcfsample=()=>{if(t)return t;t=e.all();for(const e of t)e.q=JSON.parse(e.q),e.categories=JSON.parse(e.categories);return t}}if(s.has("alltermsbyorder")){const e=n.prepare("SELECT * FROM alltermsbyorder");let t;f.getAlltermsbyorder=()=>{if(t)return t;const n=e.all();t=[];for(const e of n){const n=f.termjsonByOneid(e.id);n&&t.push({group_name:e.group_name,term:n})}return t}}{const e=n.prepare("SELECT name, jsondata FROM terms WHERE id=?"),t=new Map;f.termjsonByOneid=n=>{if(t.has(n))return t.get(n);const s=e.get(n);if(s){const e=JSON.parse(s.jsondata);return e.id=n,e.name=s.name||e.name,t.set(n,e),e}}}{const e=n.prepare("select id from terms where parent_id=?"),t=new Map;f.termIsLeaf=n=>{if(t.has(n))return t.get(n);let s=!0;const r=e.get(n);return r&&r.id&&(s=!1),t.set(n,s),s}}{const e=n.prepare("SELECT id, name, jsondata, s.included_types, s.child_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE parent_id is null\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),t=new Map;f.getRootTerms=(n="")=>{const s=n;if(t.has(s))return t.get(s);const r=e.all(n).map((e=>{const t=JSON.parse(e.jsondata);return t.id=e.id,t.name=e.name||t.name,t.included_types=e.included_types?e.included_types.split(","):["TO-DO-PLACEHOLDER"],t.child_types=e.child_types?e.child_types.split(","):[],t}));return t.set(s,r),r}}{const e=n.prepare("SELECT parent_id FROM terms WHERE id=?");{const t=new Map;f.termHasParent=n=>{if(t.has(n))return t.get(n);let s=!1;const r=e.get(n);return r&&r.parent_id&&(s=!0),t.set(n,s),s}}{const t=new Map;f.getTermParentId=n=>{if(t.has(n))return t.get(n);let s;const r=e.get(n);return r&&r.parent_id&&(s=r.parent_id),t.set(n,s),s}}{const e=new Map;f.getTermParent=t=>{if(e.has(t))return e.get(t);const n=f.getTermParentId(t);let s;return n&&(s=f.termjsonByOneid(n)),e.set(t,s),s}}}{const e=n.prepare("SELECT id, name, type, jsondata, s.included_types, s.child_types \n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=? \n\t\t\tWHERE id IN (SELECT id FROM terms WHERE parent_id=?)\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),t=new Map;f.getTermChildren=(n,s="")=>{const r=n+";;"+s;if(t.has(r))return t.get(r);const o=e.all([s,n]);let i;return o&&(i=o.map((e=>{const t=JSON.parse(e.jsondata);return t.id=e.id,t.name=e.name||t.name,t.included_types=e.included_types?e.included_types.split(","):[],t.child_types=e.child_types?e.child_types.split(","):[],t}))),t.set(r,i),i}}{const e=n.prepare("SELECT id, name, jsondata, s.included_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE name LIKE ?");f.findTermByName=(t,n="",s=null,r=null)=>{const o=e.all([n,"%"+t+"%"]);if(o){const e=[];for(const t of o){if(!t.jsondata)continue;const n=JSON.parse(t.jsondata);n.id=t.id,n.name=t.name||n.name,n.included_types=t.included_types?t.included_types.split(","):[],r&&!(0,i.CG)(n,r).has("plot")||e.push(n)}return e}}}{const e=n.prepare("SELECT MAX(value) AS v FROM anno_integer WHERE term_id=?"),t=n.prepare("SELECT MAX(value) AS v FROM anno_float WHERE term_id=?"),s=new Map;f.findTermMaxvalue=(n,r)=>{if(s.has(n))return s.get(n);const o=(r?e:t).get(n);return o?(s.set(n,o.v),o.v):void 0}}{const e={float:n.prepare("SELECT sample,value FROM anno_float WHERE term_id=?"),integer:n.prepare("SELECT sample,value FROM anno_integer WHERE term_id=?"),categorical:n.prepare("SELECT sample,value FROM anno_categorical WHERE term_id=?")};f.getAllValues4term=t=>{const n=f.termjsonByOneid(t);if(!n)return;const s=e[n.type];if(!s)return;const r=s.all(t);if(!r||0==r.length)return;const o=new Map;for(const e of r)o.set(e.sample,e.value);return o}}{const e=n.prepare("SELECT ancestor_id FROM ancestry WHERE term_id=?"),t=new Map;f.getAncestorIDs=n=>{if(t.has(n))return t.get(n);const s=e.all(n).map((e=>e.ancestor_id));return t.set(n,s),s}}{const e=n.prepare("SELECT t.name FROM ancestry as a, terms as t WHERE a.term_id=? AND t.id=a.ancestor_id"),t=new Map;f.getAncestorNames=n=>{if(t.has(n))return t.get(n);const s=e.all(n).map((e=>e.name));return t.set(n,s),s}}{const e={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=?")},t={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=? AND sample=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=? AND sample=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=? AND sample=?")},s={categorical:n.prepare("SELECT value FROM anno_categorical a,sampleidmap s WHERE term_id=? AND s.name=?"),integer:n.prepare("SELECT value FROM anno_integer a,sampleidmap s WHERE term_id=? AND s.name=?"),float:n.prepare("SELECT value FROM anno_float a, sampleidmap s WHERE term_id=? AND s.name=?")};f.getSample2value=(n,r=null)=>{const o=f.termjsonByOneid(n);return r?"string"==typeof r?s[o.type].all(n,r):t[o.type].all(n,r):e[o.type].all(n)}}if(s.has("termhtmldef")){const e=n.prepare("SELECT jsonhtml FROM termhtmldef WHERE id=?"),t=new Map;f.getTermInfo=n=>{if(t.has(n))return t.get(n);const s=e.get(n);if(s){const e=JSON.parse(s.jsonhtml);return e.id=n,t.set(n,e),e}}}f.getSupportedChartTypes=t=>{u(e);r().dsCredentials?.[e.label];const n={},s={};for(const o of e.cohort.termdb.termtypeByCohort)if(o.type){if(!(o.cohort in n)){n[o.cohort]=new Set(["regression","summary"]),e.cohort.scatterplots&&n[o.cohort].add("sampleScatter"),s[o.cohort]=0,e.cohort.allowedChartTypes?.includes("matrix")&&n[o.cohort].add("matrix");const r=a.i.getForbiddenRoutesForDsEmbedder(e.label,t);r.includes("termdb")||r.includes("*")||(n[o.cohort].add("dataDownload"),n[o.cohort].add("sampleView"),e.queries?.singleCell&&n[o.cohort].add("singleCellPlot"))}r().features?.draftChartTypes&&n[o.cohort].add(...r().features.draftChartTypes),"survival"!=o.type||n[o.cohort].has("survival")||n[o.cohort].add("survival"),"condition"!=o.type||n[o.cohort].has("cuminc")||n[o.cohort].add("cuminc"),"float"!=o.type&&"integer"!=o.type||(s[o.cohort]+=o.samplecount)}for(const e in s)s[e]>1&&n[e].add("sampleScatter");for(const e in n)n[e]=[...n[e]];if(e.cohort.allowedChartTypes)for(const t in n)n[t]=n[t].filter((t=>e.cohort.allowedChartTypes.includes(t)));if(e.queries){if(e.queries.snvindel||e.queries.trackLst)for(const e in n)n[e].push("genomeBrowser");if(e.queries.geneExpression)for(const e in n)n[e].push("hierCluster");if(e.queries.rnaseqGeneCount)for(const e in n)n[e].push("DEanalysis");if(e.queries.singleCell)for(const e in n)n[e].push("singleCellPlot")}return n},f.getSingleSampleData=function(e,t=[]){const s=t.length?`and term_id in (${t.map((e=>"?")).join(",")})`:"",r=`select term_id, value, jsondata from ( select term_id, value \n\t\tfrom anno_categorical \n\t\twhere sample=? ${s}\n\t\tunion all \n\t\tselect term_id, \n\t\tvalue from anno_float \n\t\twhere sample=? ${s}\n\t\tunion all \n\t\tselect term_id, value \n\t\tfrom anno_integer \n\t\twhere sample=? ${s}\n\t\tunion all \n\t\tselect term_id, (min_years_to_event || ' ' || value) as value \n\t\tfrom precomputed_chc_grade \n\t\twhere max_grade=1 and sample=? ${s}\n\t\tunion all \n\t\tselect term_id, (tte || ' ' || exit_code) as value \n\t\tfrom survival \n\t\twhere sample=? ${s}) join terms on terms.id = term_id`;return n.prepare(r).all([e,...t,e,...t,e,...t,e,...t,e,...t])},f.getProfileFacilities=function(){return n.prepare("select name from sampleidmap join \n\t\tanno_categorical on sampleidmap.id = anno_categorical.sample\n\t\twhere term_id = 'sampleType' and value = 'Facility'").all()}}function c(e){const t=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();return new Set(t.map((e=>e.name)))}function u(e){if(e.cohort.termdb.termtypeByCohort){if(!Array.isArray(e.cohort.termdb.termtypeByCohort))throw"termtypeByCohort is not array"}else{if(!e.cohort?.db?.connection)throw"termtypeByCohort[] not set but cohort.db.connection missing";e.cohort.termdb.termtypeByCohort=e.cohort.db.connection.prepare("WITH c AS (\n\t\t\tSELECT cohort, term_id\n\t\t\tFROM subcohort_terms s\n\t\t\tGROUP BY cohort, term_id\n\t\t) \n\t\tSELECT cohort, type, count(*) as samplecount\n\t\tFROM terms t\n\t\tJOIN c ON c.term_id = t.id\n\t\tGROUP BY cohort, type").all()}}},3795:(e,t,n)=>{"use strict";n.d(t,{G:()=>g,u:()=>y});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(3345),l=n(8907),c=(n(2826),n(4521),n(334)),u=n.n(c),f=n(3625);const d="%CHROM\t%POS\t%REF\t%ALT[\t%TGT]\n",p="%POS\t%ID\t%REF\t%ALT\t%INFO[\t%TGT]\n",m="./.",h=1e3;async function g(e,t,n,s){try{if(e.sumSamples)return await async function(e,t,n,s){if(!e.cacheid)throw"cacheid missing";if(u().cache_snpgt.fileNameRegexp.test(e.cacheid))throw"invalid cacheid";let r,o;if(n.track){if(r=n.track.vcf,!r)throw"ds.track.vcf missing"}else r=n.queries.snvindel.byrange._tk;if(e.filter){const t=new Set((await l.cf(e.filter,n)).map((e=>e.id)));if(0==t.size)throw"no samples from filter";o=r.samples.map((e=>t.has(e.name)))}else o=r.samples.map((e=>!0));const c=(await a.b5(i().join(u().cache_snpgt.dir,e.cacheid))).split("\n"),f=new Set,d=[];for(let e=1;e<c.length;e++){const t=c[e].split("\t"),n=t[0],s=t[3],i={},a={};for(let e=u().cache_snpgt.sampleColumn;e<t.length;e++){const n=t[e];if(!n)continue;if(!o[e-u().cache_snpgt.sampleColumn])continue;f.add(r.samples[e-u().cache_snpgt.sampleColumn].name),a[n]=1+(a[n]||0);const s=n.split("/");for(const e of s)i[e]=1+(i[e]||0)}const l=[];for(const e in i)l.push({allele:e,count:i[e],isRef:e==s});d.push({snpid:n,alleles:l,gt2count:a})}return{numOfSampleWithAnyValidGT:f.size,snps:d}}(e,0,n);if(e.snptext)return await async function(e,t,n){if(!n.snp)throw"snp not supported by genome";if(!e.snptext)throw".snptext missing";const s=function(e){const t=[];for(const n of e.trim().split("\n")){const[e,s]=n.trim().split(/[\s\t]/);if(e&&e.startsWith("rs")){if(t.find((t=>t.rsid==e)))continue;const n={rsid:e,snpid:e};s&&(n.effectAllele=s),t.push(n)}else t.push({rsid:e,snpid:e,invalid:"INVALID RSID"})}return t}(e.snptext);if(!s.length)throw"no snps";await async function(e,t){for(const n of e)if(!n.invalid)if(n.chr&&"string"==typeof n.chr){const e=t.chrlookup[n.chr.toUpperCase()];if(!e){n.invalid=!0;continue}if(!Number.isInteger(n.pos)){n.invalid=!0;continue}if(n.pos<=0||n.pos>=e.len){n.invalid=!0;continue}}else if(n.rsid){const e=await a.mr(t.snp.bigbedfile,n.rsid),s=[];for(const n of e){const e=n.split("\t"),r=t.chrlookup[e[0].toUpperCase()];r&&r.major&&s.push(e)}if(0==s.length){n.invalid=!0;continue}const r=s[0];n.chr=r[0],n.pos=Number.parseInt(r[1]),n.dbsnpRef=r[4],n.dbsnpAlts=r[6].split(",").filter(Boolean)}else n.invalid=!0;if(!e.find((e=>!e.invalid)))throw"no valid variants"}(s,n);const o=await async function(e,t,n){let s;if(n.track){if(s=n.track.vcf,!s)throw"ds.track.vcf missing"}else s=n.queries.snvindel.byrange._tk;const o=new Set,l=[];for(const e of t){if(e.invalid)continue;let t;if(s.chr2files){if(t=s.chr2files?.[e.chr].file,!t)throw"chr not in chr2files"}else if(s.chr2bcffile){if(t=s.chr2bcffile[e.chr],!t)throw"chr not in chr2bcffile"}else t=s.file||s.url;o.add(t);const n=(s.nochr?e.chr.replace("chr",""):e.chr)+"\t"+(e.pos+1);l.push(n)}const c=i().join(u().cachedir,await a.tG(l.join("\n"))),f=i().join(u().cachedir,await a.tG([...o].join("\n")));await a.UE({isbcf:!0,args:["query","-R",c,"-f",d,"-v",f],dir:s.dir,callback:e=>{const n=e.split("\t"),r=(s.nochr?"chr":"")+n[0],o=n[1],i=n[2],a=n[3].split(","),l=t.find((e=>{if(e.chr==r&&e.pos===o-1&&e.dbsnpRef==i&&e.dbsnpAlts.some((e=>a.includes(e))))return e}));if(l){l.referenceAllele=i,l.altAlleles=a,l.gtlst=[];for(let e=4;e<n.length;e++)l.gtlst.push(n[e]==m?"":n[e])}}}),r().unlink(c,(()=>{})),r().unlink(f,(()=>{}));const p=["snpid\tchr\tpos\tref\talt\teff\t"+s.samples.map((e=>e.name)).join("\t")];for(const e of t)e.invalid||e.gtlst&&(p.push(e.snpid+"\t"+e.chr+"\t"+e.pos+"\t"+e.referenceAllele+"\t"+e.altAlleles.join(",")+"\t"+(e.effectAllele||"")+"\t"+e.gtlst.join("\t")),delete e.gtlst);const h=e.genome+"_"+e.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random());return await a.Sf(i().join(u().cache_snpgt.dir,h),p.join("\n")),h}(e,s,t);return{snps:s,cacheid:o}}(e,n,s);if(e.chr)return await async function(e,t,n){const s=Number(e.start),r=Number(e.stop);if(!Number.isInteger(s)||!Number.isInteger(r))throw"start/stop are not integers";if(s>r||s<0)throw"invalid start/stop coordinate";let o,l;if(t.track){if(o=t.track.vcf,!o)throw"ds.track.vcf missing";if(l=o.chr2bcffile[e.chr],!l)throw"chr not in chr2bcffile"}else if(o=t.queries.snvindel.byrange._tk,l=o.chr2files?o.chr2files?.[e.chr].file:o.file||o.url,!l)throw"no bcf file";const c=(o.nochr?e.chr.replace("chr",""):e.chr)+":"+s+"-"+r,d=["query",l,"-r",c,"-f",p];e.variant_filter&&y(e.variant_filter,d);const g={snps:[]},b=["snpid\tchr\tpos\tref\talt\teff\t"+o.samples.map((e=>e.name)).join("\t")];return await a.UE({isbcf:!0,args:d,dir:o.dir,callback:(t,n)=>{if(g.snps.length>=h)return n.kill(),void(g.reachedVariantLimit=!0);const s=t.split("\t"),r=Number(s[0])-1,i=s[1],a=s[2],l=s[3].split(","),c=i&&"."!=i?i:r+"."+a+"."+l.join(","),u={snpid:c,chr:e.chr,pos:r};(0,f.H)(o,a,l,u,s[4],s[1]);for(const e of u.mlst)e.vcf_id&&(e.mname=e.vcf_id);g.snps.push(u);const d=[c,e.chr,r,a,l.join(","),""];for(let e=5;e<s.length;e++)d.push(s[e]==m?"":s[e]);b.push(d.join("\t"))}}),g.cacheid=e.genome+"_"+e.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random()),await a.Sf(i().join(u().cache_snpgt.dir,g.cacheid),b.join("\n")),g}(e,n);throw"unknown how to validate"}catch(e){return e.stack&&console.log(e.stack),{error:e.message||e}}}function y(e,t){const n=[];for(const t of e.lst)if(t.tvs.values){const e=t.tvs.isnot?"!=":"=";for(const s of t.tvs.values){const r=isNaN(s.key)?`"${s.key}"`:Number(s.key);n.push(`INFO/${t.tvs.term.id}${e}${r}`)}}else{if(!t.tvs.ranges)throw`unknown tvs spec for info_field: type=${t.type}, term.id=${t.tvs.term.id}`;for(const e of t.tvs.ranges)"start"in e&&n.push(`INFO/${t.tvs.term.id} ${e.startinclusive?">=":">"} ${e.start}`),"stop"in e&&n.push(`INFO/${t.tvs.term.id} ${e.stopinclusive?"<=":"<"} ${e.stop}`)}0!=n.length&&t.push("-i",n.join(" && "))}},8907:(e,t,n)=>{"use strict";n.d(t,{yT:()=>C,YG:()=>T,g5:()=>S,J4:()=>N,B9:()=>q,cf:()=>k,tt:()=>x,Bi:()=>A,ig:()=>M});var s={};n.r(s),n.d(s,{binary:()=>f,continuous:()=>l,cubicSpline:()=>c,discrete:()=>u});var r={};n.r(r),n.d(r,{groupset:()=>m,values:()=>d});var o={};n.r(o),n.d(o,{binary:()=>g,cox:()=>b,cuminc:()=>y,discrete:()=>h});var i=n(4048),a=n(5257);const l={getCTE(e,t,n,s,r,o,i){r.push(t.id);const a=C(t,s);return r.push(...a.values),{sql:`${e} AS (\n\t\t\t\tSELECT \n\t\t\t\t\tsample,\n\t\t\t\t\tvalue as key, \n\t\t\t\t\tvalue\n\t\t\t\tFROM anno_${t.type}\n\t\t\t\tWHERE term_id=? ${a.clause}\n\t\t\t)`,tablename:e}}},c=l,u={getCTE(e,t,n,s,r,o,i){r.push(t.id);const a=T(s,t,n,o,i),l=[],c=new Map;s.bin_size;for(const e of a)!("name"in e)&&e.label&&(e.name=e.label),c.set(e.name,e),l.push(`SELECT '${e.name}' AS name,\n\t\t\t\t${null==e.start?0:e.start} AS start,\n\t\t\t\t${null==e.stop?0:e.stop} AS stop,\n\t\t\t\t0 AS unannotated,\n\t\t\t\t${e.startunbounded?1:0} AS startunbounded,\n\t\t\t\t${e.stopunbounded?1:0} AS stopunbounded,\n\t\t\t\t${e.startinclusive?1:0} AS startinclusive,\n\t\t\t\t${e.stopinclusive?1:0} AS stopinclusive`);const u=[];if(t.values)for(const e in t.values){const n=t.values[e].uncomputable;if(s.computableValuesOnly&&n)continue;if(!s.computableValuesOnly&&!n)continue;u.push(e);const r=t.values[e];l.push(`SELECT '${r.label}' AS name,\n\t ${e} AS start,\n\t 0 AS stop,\n\t 1 AS unannotated,\n\t 0 AS startunbounded,\n\t 0 AS stopunbounded,\n\t 0 AS startinclusive,\n\t 0 AS stopinclusive`),c.set(r.label,{is_unannotated:!0,value:e,label:r.label})}const f="bin_defs_"+o,d=C(t,s,"a");r.push(...d.values);return{sql:`${f} AS (\n\t\t\t\t${l.join("\nUNION ALL\n")}\n\t\t\t),\n\t\t\t${e} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tb.name AS key,\n\t\t\t\t\tvalue\n\t\t\t\tFROM\n\t\t\t\t\tanno_${t.type} a\n\t\t\t\tJOIN ${f} b ON\n\t\t\t\t\t( b.unannotated=1 AND value=b.start )\n\t\t\t\t\tOR\n\t\t\t\t\t(\n\t\t\t\t\t\tb.unannotated=0 AND\n\t\t\t\t\t\t${u.length?"value NOT IN ("+u.join(",")+") AND":""}\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.startunbounded = 1\n\t\t\t\t\t\t\tOR value > b.start\n\t\t\t\t\t\t\tOR (b.startinclusive=1 AND value = b.start)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.stopunbounded\n\t\t\t\t\t\t\tOR value < b.stop\n\t\t\t\t\t\t\tOR (b.stopinclusive=1 AND value = b.stop)\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\tWHERE\n\t\t\t\tterm_id=? ${d.clause}\n\t\t\t)`,tablename:e,name2bin:c,bins:a}}},f=u,d={getCTE(e,t,n,s,r){r.push(t.id);const o=C(t,s);return r.push(...o.values),{sql:`${e} AS (\n\t\t\t\tSELECT sample,value as key, value as value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id=? ${o.clause}\n\t\t\t)`,tablename:e}}};let p=0;const m={async getCTE(e,t,n,s,r,o){if(!o.groups)throw`.groups[] missing from a group-set, term.id='${t.id}'`;const i=[],a=[];for(const e of o.groups)if("values"==e.type)i.push(`SELECT sample, ? as key, value\n\t\t\t\t\tFROM anno_categorical a\n\t\t\t\t\tWHERE term_id=?\n\t\t\t\t\t\tAND value IN (${e.values.map((e=>"?")).join(",")})\n\t\t\t\t`),r.push(e.name,t.id,...e.values.map((e=>e.key.toString())));else{if("filter"!=e.type)throw`unsupported groupset type='${e.type}'`;if(!("activeCohort"in s.groupsetting)||!e.filter4activeCohort)throw`activeCohort error: cannot construct filter statement for group name='${e.name}', term.id=${t.id}`;{const o=e.filter4activeCohort[s.groupsetting.activeCohort],l=await getFilterCTEs(o,n,"xf"+p++);if(!l)throw`unable to construct a group='${e.name}' filter for term.id='${t.id}'`;a.push(l.filters),r.push(...l.values.slice(),e.name,e.name),i.push(`SELECT sample, ? AS key, ? AS value\n\t\t\t\t\t\tFROM ${l.CTEname}`)}}return{sql:`${a.length?a.join("\n,")+",":""}\n\t\t\t${e} AS (\n\t\t\t\t${i.join("\nUNION ALL\n")}\n\t\t\t)`,tablename:e}}},h={getCTE(e,t,n,s,r){if(s.breaks&&s.breaks.length>0)return w(e,t,s,r);{const[n,o]=v(s);r.push(t.id);const i=C(t,s);return r.push(...i.values),{sql:`${e} AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tsample,\n\t\t\t\t\t\tvalue as key,\n\t\t\t\t\t\tvalue\n\t\t\t\t\tFROM\n\t\t\t\t\t\t${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tterm_id = ?\n\t\t\t\t\t\tAND ${o} = 1\n\t\t\t\t\t\t${i.clause}\n\t\t\t\t)`,tablename:e}}}},g={getCTE(e,t,n,s,r){if(1!=s.breaks?.length)throw"binary mode requires one break";return w(e,t,s,r)}},y={getCTE(e,t,n,s,r){if(1!=s.breaks?.length)throw"cuminc mode requires one break";return r.push(t.id,s.breaks[0]),{sql:`${e} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\ttime AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cuminc\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:e}}},b={getCTE(e,t,n,s,r){if(1!=s.breaks?.length)throw"cox mode requires one break";r.push(t.id,s.breaks[0]);const o=Object.keys(t.values).map(Number),i=Math.max(...o);return{sql:`${e} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\tjson_object('age_start', age_start, 'age_end', age_end) AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cox\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:e,events:[{event:1,label:`Event (grade ${s.breaks[0]===i?s.breaks[0]:`${s.breaks[0]}-${i}`})`},{event:0,label:"Censored/death"},{event:-1,label:"Event before entry into the cohort"}]}}};function v(e){const t=e.bar_by_children?"child":e.bar_by_grade?"grade":"";if(!t)throw"must set the bar_by_grade or bar_by_children query parameter";const n=e.value_by_max_grade?"max_grade":e.value_by_most_recent?"most_recent":e.value_by_computable_grade?"computable_grade":"";if(!n)throw"must set a valid value_by_*";return[t,n]}function w(e,t,n,s){const[r,o]=v(n);if("grade"!=r)throw"breaks must be used on grade values";const i=[];for(const e of n.groups)i.push(`SELECT sample, ? as key, value\n\t\t\tFROM precomputed_chc_grade\n\t\t\tWHERE\n\t\t\t\tterm_id=?\n\t\t\t\tAND ${o}=1\n\t\t\t\tAND value IN (${e.values.map((e=>"?")).join(",")})\n\t\t`),s.push(e.name,t.id,...e.values.map((e=>e.toString())));return{sql:`${e} AS (\n\t\t\t${i.join("\nUNION ALL\n")}\n\t\t)`,tablename:e}}const _={getCTE(e,t,n){let s,r,o="";for(const[e,i]of t.q.groups.entries())"in"in i||(i.in=!0),s=i.values.map((e=>e.sampleId)),r=s.map((()=>"?")).join(","),o+=`SELECT id as sample, ? as key, ? as value\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE sample ${i.in?"":"NOT"} IN (${r})\n\t\t\t`,e!=t.q.groups.length-1&&(o+="UNION ALL "),n.push(i.name,i.name,...s);return{sql:`${e} AS (${o})`,tablename:e}}};n(334),n(3345);async function k(e,t,n=!1){const s=await(0,a.w)(e,t),r=t.cohort.db.connection.prepare(s?`WITH ${s.filters} SELECT sample as id, name FROM ${s.CTEname} join sampleidmap on sample = sampleidmap.id`:"SELECT id, name FROM sampleidmap");let o;if(o=s?r.all(s.values):r.all(),n)return o;for(const e of o)delete e.name;return o}async function q(e,t){if(!e.filter)throw"filter missing";let n;if("object"==typeof e.filter)n=e.filter;else{if("string"!=typeof e.filter)throw"q.filter not obj or str";n=JSON.parse(e.filter)}const s=await(0,a.w)(n,t),r=`WITH ${s.filters}\n\t\tSELECT 'FILTERED_COHORT' as subcohort, count(distinct sample) as samplecount \n\t\tFROM ${s.CTEname}`;return t.cohort.db.connection.prepare(r).all(s.values)}async function x(e){const t=e.ds.cohort.termdb.q.termjsonByOneid(e.term_id);if("integer"!=t.type&&"float"!=t.type)throw"term is not numeric";if(!t.values)return[];const n=await(0,a.w)(e.filter,e.ds),s=n?n.values.slice():[];s.push(e.term_id);const r=[];for(const e in t.values)r.push("?"),s.push(Number(e));const o=`\n\t\t${n?"WITH "+n.filters:""}\n\t\tSELECT count(sample) AS samplecount,value\n\t\tFROM anno_${t.type}\n\t\tWHERE term_id=?\n\t\t${n?"AND sample IN "+n.CTEname:""}\n\t\tAND value IN (${r.join(",")})\n\t\tGROUP BY value`;return e.ds.cohort.db.connection.prepare(o).all(s)}async function N(e){if(!e.key)throw".key missing";if(!e.ds)throw".ds{} missing";const t=await(0,a.w)(e.filter,e.ds),n=t?t.values.slice():[],s=e.ds.cohort.termdb.q.termjsonByOneid(e.key);n.push(e.key);const r=`\n\t\t${t?"WITH "+t.filters:""}\n\t\tSELECT sample, value\n\t\tFROM anno_${s.type}\n\t\tWHERE term_id=?\n\t\t${t?" AND sample IN "+t.CTEname:""}`;return e.ds.cohort.db.connection.prepare(r).all(n)}async function S(e,t={}){"string"==typeof e.filter&&(e.filter=JSON.parse(decodeURIComponent(e.filter)));const n=Object.assign({withCTEs:!0,columnas:"t1.sample AS sample",groupby:""},t),s=await(0,a.w)(e.filter,e.ds),r=s?s.values.slice():[],o=await A(e,r,0,s),i=await A(e,r,1,s),l=await A(e,r,2,s),c=[o,i,l].map(((e,t)=>`\n\t\tSELECT sample, key, value, ${t} as termNum\n\t\tFROM ${e.tablename}\n\t\t${s?"WHERE sample IN "+s.CTEname:""}\n\t`)).join("\nUNION ALL\n"),u=`WITH\n\t\t${s?s.filters+",":""}\n\t\t${o.sql},\n\t\t${i.sql},\n\t\t${l.sql}\n\t\t${c}`;try{const t=e.ds.cohort.db.connection.prepare(u).all(r),a=new Map;for(const e of t){a.has(e.sample)||a.set(e.sample,{sample:e.sample});const t=a.get(e.sample),n=`key${e.termNum}`;n in t||(t[n]=[]),t[n].push(e)}const c=[],f=new Map;for(const t of a.values())if("key1"in t){if(e.term0_q&&e.term0_id){if(!("key0"in t))continue}else t.key0=[{key:"",value:""}];if(e.term2_q&&(e.term2_id||"samplelst"===e.term2.type)){if(!("key2"in t))continue}else t.key2=[{key:"",value:""}];t.rows=[];for(const e of t.key0)for(const n of t.key1)for(const s of t.key2)t.rows.push({sample:t.sample,key0:e.key,val0:e.value,key1:n.key,val1:n.value,key2:s.key,val2:s.value});for(const e of t.rows)if(n.groupby){if(!f.has(e[n.groupby])){const t=Object.assign({samplecount:0},e);c.push(t),f.set(e[n.groupby],t)}f.get(e[n.groupby]).samplecount++}else c.push(e)}return n.withCTEs?{lst:c,CTE0:o,CTE1:i,CTE2:l,filter:s}:c}catch(e){throw console.log("error in sql:\n",M(u,r)),e}}async function A(e,t,n,i,a=null){const l=a&&a.term||e[`term${n}`],c=l?l.id:e["term"+n+"_id"];if("samplelst"!=l?.type)if(a||1!=n){if(!c){const e="samplekey_"+n;return{tablename:e,sql:`${e} AS (\nSELECT null AS sample, '' as key, '' as value\n)`}}}else if(!c)throw"missing term1 id";const u=l&&l.type?l:e.ds.cohort.termdb.q.termjsonByOneid(c);if(!u)throw`no term found by id='${c}'`;let f=a&&a.q||e["term"+n+"_q"]||{};"string"==typeof f&&(f=JSON.parse(decodeURIComponent(f)));const d="samplekey_"+n;let p;if("categorical"==u.type){const n=j(u,f);p=await r[n?"groupset":"values"].getCTE(d,u,e.ds,f,t,n)}else if("integer"==u.type||"float"==u.type){const r="spline"==f.mode?"cubicSpline":f.mode||"discrete";p=await s[r].getCTE(d,u,e.ds,f,t,n,i)}else if("condition"==u.type){const n=f.mode||"discrete";p=await o[n].getCTE(d,u,e.ds,f,t)}else if("survival"==u.type)p=function(e,t,n,s,r){return s.push(t.id),{sql:`${e} AS (\n\t\t\tSELECT sample, exit_code as key, tte AS value\n\t\t\tFROM survival s\n\t\t\tWHERE s.term_id=?\n\t\t\t${r?"AND s.sample IN "+r.CTEname:""}\n\t\t)`,tablename:e}}(d,u,0,t,i);else{if("samplelst"!=u.type)throw"unknown term type";p=await _.getCTE(d,a||{term:u,q:f},t)}return p}function C(e,t,n=""){if(!e.values||!t.computableValuesOnly)return{values:[],clause:""};const s=Object.keys(e.values).filter((t=>e.values[t].uncomputable)),r=n?`${n}.value`:"value";return{values:s,clause:s.length?`AND ${r} NOT IN (${s.map((()=>"?")).join(",")})`:""}}function j(e,t){if(t.groupsetting&&!t.groupsetting.disabled&&t.groupsetting.inuse){if(Number.isInteger(t.groupsetting.predefined_groupset_idx)){if(t.groupsetting.predefined_groupset_idx<0)throw"q.predefined_groupset_idx out of bound";if(!e.groupsetting)throw"term.groupsetting missing when q.predefined_groupset_idx in use";if(!e.groupsetting.lst)throw"term.groupsetting.lst missing when q.predefined_groupset_idx in use";const n=e.groupsetting.lst[t.groupsetting.predefined_groupset_idx];if(!n)throw"q.predefined_groupset_idx out of bound";return n}if(t.groupsetting.customset)return t.groupsetting.customset;throw"do not know how to get groupset"}}function T(e,t,n,s,r){if("continuous"!=e.mode&&"spline"!=e.mode)return i.gp(e,(e=>function(e,t,n,s=[]){const r=[];n&&r.push(...n.values);r.push(t.id);const o=t.values?Object.keys(t.values).filter((e=>t.values[e].uncomputable)):[],i=[],a=[],l=[];let c;for(const e of s)c="pct_"+e,i.push(`\n\t\t${c} AS (\n\t\t SELECT value\n\t\t FROM vals\n\t\t LIMIT 1\n\t\t OFFSET (\n\t\t SELECT cast ( x as int ) - ( x < cast ( x as int ))\n\t\t FROM (\n\t\t SELECT cast(?*pct as int) as x \n\t\t FROM p\n\t\t )\n\t\t )\n\t\t)`),r.push(e),a.push(c),l.push(`${c}.value AS ${"p"+e}`);const u=`WITH\n\t\t${n?n.filters+", ":""} \n\t\tvals AS (\n\t\t\tSELECT value\n\t\t\tFROM anno_${t.type}\n\t\t\tWHERE\n\t\t\t${n?"sample IN "+n.CTEname+" AND ":""}\n\t\t\tterm_id=?\n\t\t\t${o.length?"AND value NOT IN ("+o.join(",")+")":""}\n\t\t\tORDER BY value ASC\n\t\t),\n\t\tp AS (\n\t\t\tSELECT count(value)/100 as pct\n\t\t\tFROM vals\n\t\t)\n\t\t${i.length?",\n"+i.join(","):""}\n\t\tSELECT \n\t\t\tmin(vals.value) as vmin,\n\t\t\tmax(vals.value) as vmax\n\t\t\t${l.length?",\n"+l.join(",\n"):""} \n\t\tFROM vals ${a.length?","+a.join(","):""}`,f=e.cohort.db.connection.prepare(u).all(r),d=f.length?f[0]:{};return d.max=f[0].vmax,d.min=f[0].vmin,d}(n,t,r,e)))}function M(e,t){const n=t.slice();let s;return e.split("").map((e=>{if("?"==e){s=e;const t=n.shift();return"string"==typeof t?`'${t}'`:t}return"\t"==e?"":"\n"!=e&&" "!=e||s!==e?(s=e,e):""})).join("")}},3345:(e,t,n)=>{"use strict";n.d(t,{Dp:()=>Q,JC:()=>oe,d1:()=>M,fk:()=>le,sE:()=>V,Ic:()=>F,yE:()=>P,t7:()=>G,ZX:()=>O,EO:()=>K,Kf:()=>W,ZD:()=>U,UE:()=>z,lY:()=>E,_H:()=>$,L0:()=>X,Y5:()=>re,z5:()=>ee,mr:()=>te,b5:()=>H,cl:()=>Y,Jy:()=>L,sI:()=>ne,aS:()=>se,LC:()=>D,Sf:()=>B,tG:()=>J});var s=n(7147),r=n.n(s),o=n(1017),i=n.n(o),a=n(2081),l=n(4521),c=n.n(l),u=n(2273),f=n(6819);const d=require("node-fetch");var p=n.n(d);const m=require("better-sqlite3");var h=n.n(m),g=n(334),y=n.n(g);n(2781);const b=require("minimatch");var v=n.n(b),w=n(6113),_=n.n(w),k=n(6452),q=n.n(k);const x=y(),{tabix:N,samtools:S,bcftools:A,bigBedToBed:C,bigBedNamedItems:j,bigBedInfo:T}=x;async function M(e,t){if(!e)throw".gz file URL missing";if("string"!=typeof e)throw".gz file URL not string";if(t&&"string"!=typeof t)throw"index URL not string";const[n,s,o]=R(e);if(n)throw".gz file URL error: "+n;const a=i().join(x.cachedir,s,o);try{await r().promises.stat(a)}catch(n){if("ENOENT"!=n.code)throw"stating gz url dir: "+n.code;try{await r().promises.mkdir(a,{recursive:!0})}catch(n){throw"url dir: cannot mkdir"}}if(!t)return a;{const[e,s,o]=R(t);if(e)throw"indexl url error: "+e;const l=i().join(a,i().basename(o));try{return await r().promises.stat(l),a}catch(n){if("ENOENT"==n.code)return await async function(e,t){try{const o=await p()(e);if(200!=o.status)throw"index file not accessible from url with status code "+o.status;await(n=o.body,s=t,new Promise(((e,t)=>{const o=r().createWriteStream(s);n.pipe(o),n.on("end",(()=>e()))})))}catch(e){throw"cannot download from url"}var n,s}(t,l),a;throw"stating indexl url file: "+n.code}}}function O(e,t=!0){let n=null,s=!1;if(e.query.file){if(n=e.query.file,E(n,t,!1))return["illegal file path"];n=i().join(x.tpmasterdir,n)}else if(e.query.url){if(n=e.query.url,n.includes(" "))return["url must not contain whitespace"];if(n.includes('"')||n.includes("'"))return["url must not contain single or double quotes"];s=!0}return n?[null,n,s]:["file unspecified"]}const I=Object.freeze([".bam",".bai",".gz",".tbi",".csi",".bw",".bb"]);function E(e,t=!1,n=!0){if("/"==e[0])return!0;if(e.includes('"')||e.includes("'"))return!0;if(e.includes("|")||e.includes("&"))return!0;if(e.includes(" "))return!0;if(-1!=e.indexOf(".."))return!0;if(e.match(/(\<script|script\>)/i))return!0;if(t&&x.whiteListPaths){let t=!0;for(const n of x.whiteListPaths){if(e.startsWith(n)||"!"!=n[0]&&v()(e,n)){t=!1;break}if("!"==n[0]&&!v()(e,n)){t=!0;break}}if(t)return!0}if(n)for(const t of I)if(t===i().extname(e).toLowerCase())return!0;return!1}function R(e){const t=e.split("://");return 2!=t.length?["improper url"]:t[0].length<3?["protocol string length too short"]:t[1].length<5?["body string length too short"]:[null,t[0],t[1]]}async function F(e){try{await r().promises.stat(e)}catch(t){const n=x.debugmode?`file='${e}'`:"";if("EACCES"==t.code)throw`Permission denied ${n}`;if("ENOENT"==t.code)throw`No such file or directory ${n}`;if("EPERM"==t.code)throw`Operation not permitted ${n}`;throw`cannot access file (' + e.code + ') ${n}`}}async function $(e,t,n){let s;if(e.file)e.file.startsWith(x.tpmasterdir)||(e.file=i().join(x.tpmasterdir,e.file)),s=e.file,await D(e.file);else{if(!e.url)throw"no file or url given for vcf file";s=e.url,e.dir=await utils.cache_index(e.url,e.indexURL)}const[r,o,l,c]=n?await(u=s,d=e.dir,new Promise(((e,t)=>{const n=(0,a.spawn)(A,["view","-h",u],{cwd:d}),s=[];n.stdout.on("data",(e=>s.push(e))),n.on("close",(()=>{e(f.e(s.join("").trim().split("\n")))}))}))):await async function(e,t){return f.e(await U(e,t))}(s,e.dir);var u,d;if(c)throw console.log(c.join("\n")),"got above errors parsing vcf";e.info=r,e.format=o,e.samples=l,await L(s,e.dir,t)&&(e.nochr=!0)}async function D(e){if(!e.endsWith(".gz"))throw"tabix file not ending with .gz";if(await P(e))throw e+" file not exist";if(await G(e))throw".gz file not readable";const t=e+".tbi";if(await P(t)){const t=e+".csi";if(await P(t))throw"neither .tbi .csi index file exist for "+e;if(await G(t))throw".csi index file not readable"}else if(await G(t))throw".tbi index file not readable"}async function L(e,t,n){const s=[];return await z({args:["-l",e],dir:t,callback:e=>{s.push(e)}}),u.contigNameNoChr(n,s)}function P(e){return new Promise(((t,n)=>{r().access(e,r().constants.F_OK,(e=>{e&&t(!0),t(!1)}))}))}function G(e){return new Promise(((t,n)=>{r().access(e,r().constants.R_OK,(e=>{e&&t(!0),t(!1)}))}))}async function U(e,t){const n=[];return await z({args:["-H",e],dir:t,callback:e=>{n.push(e)}}),n}function z({args:e,dir:t,callback:n,isbcf:s,isbam:r}){if(!e)throw"args is missing";if(!Array.isArray(e))throw"args[] is not array";if(0==e.length)throw"args[] empty array";if(!n)throw"callback is missing";if("function"!=typeof n)throw"callback() not a function";return new Promise(((o,i)=>{const l=(0,a.spawn)(s?A:r?S:N,e,{cwd:t}),u=c().createInterface({input:l.stdout}),f=[];u.on("line",(e=>n(e,l))),l.stderr.on("data",(e=>f.push(e))),l.on("close",(()=>{const e=f.join("").trim();e&&!ne(e)&&i(e),o()}))}))}function B(e,t){return new Promise(((n,s)=>{r().writeFile(e,t,(e=>{e&&s("cannot write"),n()}))}))}async function J(e){const t=Math.random().toString();return await B(i().join(x.cachedir,t),e),t}function H(e){return new Promise(((t,n)=>{r().readFile(e,{encoding:"utf8"},((s,r)=>{s&&n("cannot read file: "+e),t(r)}))}))}async function W(e,t){if("NA"==e.genomefile){const e=t.split(/[:-]/),n=[];for(let t=Number(e[1]);t<=Number(e[2]);t++)n.push("N");return`>${t}\n${n.join("")}`}const n=[];return await z({isbam:!0,args:["faidx",e.genomefile,t],callback:e=>n.push(e)}),n.join("\n")}function V(e,t={}){const n="/"==e[0]?e:i().join(x.tpmasterdir,e);try{return new(h())(n,Object.assign({readonly:!0,fileMustExist:!0},t))}catch(e){throw`error connecting to ${n}: ${e}`}}const Z=new Set(["Homozygous reference","Homozygous alternative","Heterozygous"]),K={href:"Homozygous reference",halt:"Homozygous alternative",het:"Heterozygous"};async function X(e,t){const n=await H(i().join(x.cachedir_ssid,e)),s=new Map,r=new Map;for(const e of n.trim().split("\n")){if(!e)continue;const[n,o]=e.split("\t");if(!o)continue;if(!Z.has(n))throw"unknown hardcoded genotype label: "+n;const i=o.split(",").map((e=>Number(e))),a=t?i.filter((e=>t.has(e))):i;for(const e of a)s.set(e,n);r.set(n,new Set(a))}return[s,r]}function Y(e){return e.replace(/\<script|\bon[\w]{1,38}\b[\ \t\n]*\=/gi," _")}async function Q(e,t,n){const s=[];if(await z({isbam:!0,args:["view","-H",e],dir:n,callback:e=>s.push(e)}),0==s.length)throw"cannot list bam header lines";const r=[];for(const e of s){if(!e.startsWith("@SQ"))continue;const t=e.split("\t")[1];t||reject("2nd field missing from @SQ line");const n=t.split(":");"SN"!=n[0]&&reject('@SQ line 2nd field is not "SN" but '+n[0]),n[1]||reject("@SQ line no value for SN"),r.push(n[1])}return u.contigNameNoChr(t,r)}function ee(e,t,n,s){return new Promise(((r,o)=>{const i=(0,a.spawn)(C,[`-chrom=${t}`,`-start=${n}`,`-end=${s}`,e,"stdout"]),l=[],c=[];i.stdout.on("data",(e=>l.push(e))),i.stderr.on("data",(e=>c.push(e))),i.on("close",(e=>{0!==e&&o(`bigBed query exited with non-zero status and this standard error:\n${c.join("")}`),c.length>0&&o(c.join(""));const t=l.join("").trim();r(t?t.split("\n"):[])}))}))}function te(e,t){return new Promise(((n,s)=>{const r=(0,a.spawn)(j,[e,t,"stdout"]),o=[],i=[];r.stdout.on("data",(e=>o.push(e))),r.stderr.on("data",(e=>i.push(e))),r.on("close",(e=>{0!==e&&s(`bigBed query exited with non-zero status and this standard error:\n${i.join("")}`),i.length>0&&s(i.join(""));const t=o.join("").trim();n(t?t.split("\n"):[])}))}))}function ne(e){return e.startsWith("[E::idx_test_and_fetch]")}async function se(e){return new Promise(((t,n)=>{const s=(0,a.spawn)(T,[e]),r=[],o=[];s.stdout.on("data",(e=>r.push(e))),s.stderr.on("data",(e=>o.push(e))),s.on("close",(e=>{const n=o.join("");n&&(n.includes("is not a big bed file")||n.includes("Couldn't open"),t(!1));r.join("").trim().startsWith("version")&&t(!0)}))}))}function re(e,t){if(t.sessionid){if("sessionid"in e)throw"q.sessionid already exists so cannot copy from cookies.sessionid";e.sessionid=t.sessionid}}function oe(e){const t=e.length;if(t<5)return{out:e};const n=e[Math.floor(t/2)].value,s=e[Math.floor(t/4)].value,r=e[Math.floor(3*t/4)].value,o=e[Math.floor(.05*t)].value,i=e[Math.floor(.95*t)].value,a=(e[Math.floor(.01*t)].value,r-s);let l,c;if(0==a)l=0,c=0;else{const n=e.findIndex((e=>e.value>s-1.5*a));l=e[-1==n?0:n].value;const o=e.findIndex((e=>e.value>r+1.5*a));c=e[-1==o?t-1:o-1].value}const u=e.filter((e=>e.value<s-1.5*a||e.value>r+1.5*a));return{w1:l,w2:c,p05:o,p25:s,p50:n,p75:r,p95:i,iqr:a,out:u}}const ie=x.features?.extApiCache||{},ae=i().join(x.cachedir,"extApiResponse");if(x.features?.extApiCache){r().existsSync(ae)||r().mkdirSync(ae,{recursive:!0});for(const e in ie){const t=i().join(ae,ie[e]);r().existsSync(t)||r().mkdirSync(t,{recursive:!0})}}async function le(e,t={},n={}){let s;for(const t in ie)e.includes(t)&&(s=i().join(ae,ie[t]));if(!e.includes(":/"))throw`cannot use cachedFetch wuth a relative URL: ${e}`;const o=s&&_().createHash("sha1").update(`${e} ${JSON.stringify(t.body)}`).digest("hex"),a=s&&i().join(s,o);let l;if(a&&r().existsSync(a))try{const e=r().readFileSync(a)?.toString("utf-8").trim();l=JSON.parse(e)}catch(e){throw console.log(e),e}else try{const s={"content-type":"application/json",accept:"application/json"};if(t.headers)for(const e in t.headers)s[e.toLowerCase()]=t.headers[e].toLowerCase();const o=t.method?.toLowerCase()||"get",i=n.client||q(),c=await i[o](e,{headers:s,body:"get"==o?void 0:s["content-type"].includes("json")?JSON.stringify(t.body||{}):t.body});if(a){const e="string"==typeof c.body?c.body:s.accept.includes("json")?JSON.stringify(c.body):t.response;r().writeFileSync(a,e,{encoding:"utf8"})}l="string"==typeof c.body&&s.accept.includes("json")?JSON.parse(c.body):c.body}catch(e){throw e}return n.metaKey&&(l[n.metaKey]={id:o,cacheFile:a}),{body:l}}},3625:(e,t,n)=>{"use strict";n.d(t,{H:()=>a});var s=n(9380),r=n(4298),o=n(736),i=n(2273);function a(e,t,n,a,l,c,u){const f=(0,s.w)(l);for(const t in e.info){if("A"==e.info[t].Number&&t in f&&(f[t]=f[t].split(",")),e.info[t].separator&&t in f){const n=f[t].split(e.info[t].separator);n.length>1&&(f[t]=n)}if("Float"==e.info[t].Type||"Integer"==e.info[t].Type)if(Array.isArray(f[t])){const e=f[t].map(Number);f[t]=e}else f[t]=Number(f[t])}a.mlst=n.map((e=>{const[n,s,r]=function(e,t,n){for(;t.length>1&&n.length>1&&t[t.length-1]==n[n.length-1];)t=t.substring(0,t.length-1),n=n.substring(0,n.length-1);for(;t.length>1&&n.length>1&&t[0]==n[0];)t=t.substring(1),n=n.substring(1),e++;return[e,t,n]}(a.pos,t,e),i={allele_original:e,ref:s,alt:r,pos:n,type:(0,o.P)(s,r)};return c&&"."!=c&&(i.vcf_id=c),i})),e.info?.CSQ&&f.CSQ&&(0,r.A)(f.CSQ,e.info.CSQ.csqheader,a);const d={};u&&(d.usegm={isoform:u});for(const[n,s]of a.mlst.entries()){(0,i.vcfcopymclass)(s,d),delete s.csq,s.mname||(s.mname="."!=c?c:a.pos+":"+t+">"+s.allele_original),s.altAlleleIdx=n+1,s.info={};for(const t in f)"A"==e.info?.[t]?.Number?s.info[t]=f[t][n]:s.info[t]=f[t]}}},126:(e,t,n)=>{var s={"./burden":5037,"./burden.ts":5037,"./gdc.maf":2538,"./gdc.maf.ts":2538,"./gdc.mafBuild":86,"./gdc.mafBuild.ts":86,"./gdc.topMutatedGenes":889,"./gdc.topMutatedGenes.ts":889,"./genelookup":3202,"./genelookup.ts":3202,"./healthcheck":1746,"./healthcheck.ts":1746,"./hicdata":3932,"./hicdata.ts":3932,"./hicstat":6310,"./hicstat.ts":6310,"./termdb.categories":5852,"./termdb.categories.ts":5852,"./termdb.cluster":4924,"./termdb.cluster.ts":4924,"./termdb.getdescrstats":2262,"./termdb.getdescrstats.ts":2262,"./termdb.getnumericcategories":5961,"./termdb.getnumericcategories.ts":5961,"./termdb.getpercentile":2630,"./termdb.getpercentile.ts":2630,"./termdb.getrootterm":7095,"./termdb.getrootterm.ts":7095,"./termdb.gettermchildren":3967,"./termdb.gettermchildren.ts":3967,"./termdb.singleSampleMutation":3677,"./termdb.singleSampleMutation.ts":3677,"./termdb.singlecellData":5707,"./termdb.singlecellData.ts":5707,"./termdb.singlecellSamples":7934,"./termdb.singlecellSamples.ts":7934,"./termdb.termsbyids":605,"./termdb.termsbyids.ts":605,"./termdb.topVariablyExpressedGenes":5057,"./termdb.topVariablyExpressedGenes.ts":5057,"./termdb.violin":2386,"./termdb.violin.ts":2386};function r(e){var t=o(e);return n(t)}function o(e){if(!n.o(s,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return s[e]}r.keys=function(){return Object.keys(s)},r.resolve=o,e.exports=r,r.id=126},1271:e=>{"use strict";e.exports=require("@sjcrh/proteinpaint-rust")},6718:e=>{"use strict";e.exports=require("canvas")},6452:e=>{"use strict";e.exports=require("got")},7219:e=>{"use strict";e.exports=require("image-size")},9344:e=>{"use strict";e.exports=require("jsonwebtoken")},8088:e=>{"use strict";e.exports=require("micromatch")},6464:e=>{"use strict";e.exports=require("util")},2081:e=>{"use strict";e.exports=require("child_process")},6113:e=>{"use strict";e.exports=require("crypto")},7147:e=>{"use strict";e.exports=require("fs")},1017:e=>{"use strict";e.exports=require("path")},4521:e=>{"use strict";e.exports=require("readline")},2781:e=>{"use strict";e.exports=require("stream")},9263:(e,t,n)=>{"use strict";function s(e,t){return null==e||null==t?NaN:e<t?-1:e>t?1:e>=t?0:NaN}n.d(t,{Z:()=>s})},5519:(e,t,n)=>{"use strict";n.d(t,{Nw:()=>l,ZP:()=>u,ZR:()=>c,ml:()=>a});var s=n(9263),r=n(3292),o=n(3745);const i=(0,r.Z)(s.Z),a=i.right,l=i.left,c=(0,r.Z)(o.Z).center,u=a},3292:(e,t,n)=>{"use strict";n.d(t,{Z:()=>o});var s=n(9263),r=n(788);function o(e){let t,n,o;function a(e,s,r=0,o=e.length){if(r<o){if(0!==t(s,s))return o;do{const t=r+o>>>1;n(e[t],s)<0?r=t+1:o=t}while(r<o)}return r}return 2!==e.length?(t=s.Z,n=(t,n)=>(0,s.Z)(e(t),n),o=(t,n)=>e(t)-n):(t=e===s.Z||e===r.Z?e:i,n=e,o=e),{left:a,center:function(e,t,n=0,s=e.length){const r=a(e,t,n,s-1);return r>n&&o(e[r-1],t)>-o(e[r],t)?r-1:r},right:function(e,s,r=0,o=e.length){if(r<o){if(0!==t(s,s))return o;do{const t=r+o>>>1;n(e[t],s)<=0?r=t+1:o=t}while(r<o)}return r}}}function i(){return 0}},788:(e,t,n)=>{"use strict";function s(e,t){return null==e||null==t?NaN:t<e?-1:t>e?1:t>=e?0:NaN}n.d(t,{Z:()=>s})},9724:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Adder:()=>q,InternMap:()=>S.L,InternSet:()=>S.H,ascending:()=>r.Z,bin:()=>K,bisect:()=>s.ZP,bisectCenter:()=>s.ZR,bisectLeft:()=>s.Nw,bisectRight:()=>s.ml,bisector:()=>o.Z,blur:()=>i,blur2:()=>a,blurImage:()=>l,count:()=>p,cross:()=>y,cumsum:()=>b,descending:()=>v.Z,deviation:()=>_,difference:()=>Re,disjoint:()=>Fe,every:()=>je,extent:()=>k,fcumsum:()=>N,filter:()=>Me,flatGroup:()=>M,flatRollup:()=>O,fsum:()=>x,greatest:()=>re,greatestIndex:()=>_e,group:()=>C,groupSort:()=>z,groups:()=>j,histogram:()=>K,index:()=>R,indexes:()=>F,intersection:()=>$e,least:()=>ve,leastIndex:()=>we,map:()=>Oe,max:()=>X,maxIndex:()=>Y,mean:()=>ue,median:()=>fe,medianIndex:()=>de,merge:()=>pe,min:()=>Q,minIndex:()=>ee,mode:()=>me,nice:()=>V,pairs:()=>he,permute:()=>L,quantile:()=>oe,quantileIndex:()=>ae,quantileSorted:()=>ie,quickselect:()=>te,range:()=>ye,rank:()=>be,reduce:()=>Ie,reverse:()=>Ee,rollup:()=>I,rollups:()=>E,scan:()=>ke,shuffle:()=>qe,shuffler:()=>xe,some:()=>Te,sort:()=>P,subset:()=>Ge,sum:()=>Ne,superset:()=>Le,thresholdFreedmanDiaconis:()=>le,thresholdScott:()=>ce,thresholdSturges:()=>Z,tickIncrement:()=>W.G9,tickStep:()=>W.ly,ticks:()=>W.ZP,transpose:()=>Se,union:()=>Ue,variance:()=>w,zip:()=>Ce});var s=n(5519),r=n(9263),o=n(3292);function i(e,t){if(!((t=+t)>=0))throw new RangeError("invalid r");let n=e.length;if(!((n=Math.floor(n))>=0))throw new RangeError("invalid length");if(!n||!t)return e;const s=d(t),r=e.slice();return s(e,r,0,n,1),s(r,e,0,n,1),s(e,r,0,n,1),e}const a=c(d),l=c((function(e){const t=d(e);return(e,n,s,r,o)=>{t(e,n,(s<<=2)+0,(r<<=2)+0,o<<=2),t(e,n,s+1,r+1,o),t(e,n,s+2,r+2,o),t(e,n,s+3,r+3,o)}}));function c(e){return function(t,n,s=n){if(!((n=+n)>=0))throw new RangeError("invalid rx");if(!((s=+s)>=0))throw new RangeError("invalid ry");let{data:r,width:o,height:i}=t;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((i=Math.floor(void 0!==i?i:r.length/o))>=0))throw new RangeError("invalid height");if(!o||!i||!n&&!s)return t;const a=n&&e(n),l=s&&e(s),c=r.slice();return a&&l?(u(a,c,r,o,i),u(a,r,c,o,i),u(a,c,r,o,i),f(l,r,c,o,i),f(l,c,r,o,i),f(l,r,c,o,i)):a?(u(a,r,c,o,i),u(a,c,r,o,i),u(a,r,c,o,i)):l&&(f(l,r,c,o,i),f(l,c,r,o,i),f(l,r,c,o,i)),t}}function u(e,t,n,s,r){for(let o=0,i=s*r;o<i;)e(t,n,o,o+=s,1)}function f(e,t,n,s,r){for(let o=0,i=s*r;o<s;++o)e(t,n,o,o+i,s)}function d(e){const t=Math.floor(e);if(t===e)return function(e){const t=2*e+1;return(n,s,r,o,i)=>{if(!((o-=i)>=r))return;let a=e*s[r];const l=i*e;for(let e=r,t=r+l;e<t;e+=i)a+=s[Math.min(o,e)];for(let e=r,c=o;e<=c;e+=i)a+=s[Math.min(o,e+l)],n[e]=a/t,a-=s[Math.max(r,e-l)]}}(e);const n=e-t,s=2*e+1;return(e,r,o,i,a)=>{if(!((i-=a)>=o))return;let l=t*r[o];const c=a*t,u=c+a;for(let e=o,t=o+c;e<t;e+=a)l+=r[Math.min(i,e)];for(let t=o,f=i;t<=f;t+=a)l+=r[Math.min(i,t+c)],e[t]=(l+n*(r[Math.max(o,t-u)]+r[Math.min(i,t+u)]))/s,l-=r[Math.max(o,t-c)]}}function p(e,t){let n=0;if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&++n;else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&(r=+r)>=r&&++n}return n}function m(e){return 0|e.length}function h(e){return!(e>0)}function g(e){return"object"!=typeof e||"length"in e?e:Array.from(e)}function y(...e){const t="function"==typeof e[e.length-1]&&function(e){return t=>e(...t)}(e.pop()),n=(e=e.map(g)).map(m),s=e.length-1,r=new Array(s+1).fill(0),o=[];if(s<0||n.some(h))return o;for(;;){o.push(r.map(((t,n)=>e[n][t])));let i=s;for(;++r[i]===n[i];){if(0===i)return t?o.map(t):o;r[i--]=0}}}function b(e,t){var n=0,s=0;return Float64Array.from(e,void 0===t?e=>n+=+e||0:r=>n+=+t(r,s++,e)||0)}var v=n(788);function w(e,t){let n,s=0,r=0,o=0;if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&(n=t-r,r+=n/++s,o+=n*(t-r));else{let i=-1;for(let a of e)null!=(a=t(a,++i,e))&&(a=+a)>=a&&(n=a-r,r+=n/++s,o+=n*(a-r))}if(s>1)return o/(s-1)}function _(e,t){const n=w(e,t);return n?Math.sqrt(n):n}function k(e,t){let n,s;if(void 0===t)for(const t of e)null!=t&&(void 0===n?t>=t&&(n=s=t):(n>t&&(n=t),s<t&&(s=t)));else{let r=-1;for(let o of e)null!=(o=t(o,++r,e))&&(void 0===n?o>=o&&(n=s=o):(n>o&&(n=o),s<o&&(s=o)))}return[n,s]}class q{constructor(){this._partials=new Float64Array(32),this._n=0}add(e){const t=this._partials;let n=0;for(let s=0;s<this._n&&s<32;s++){const r=t[s],o=e+r,i=Math.abs(e)<Math.abs(r)?e-(o-r):r-(o-e);i&&(t[n++]=i),e=o}return t[n]=e,this._n=n+1,this}valueOf(){const e=this._partials;let t,n,s,r=this._n,o=0;if(r>0){for(o=e[--r];r>0&&(t=o,n=e[--r],o=t+n,s=n-(o-t),!s););r>0&&(s<0&&e[r-1]<0||s>0&&e[r-1]>0)&&(n=2*s,t=o+n,n==t-o&&(o=t))}return o}}function x(e,t){const n=new q;if(void 0===t)for(let t of e)(t=+t)&&n.add(t);else{let s=-1;for(let r of e)(r=+t(r,++s,e))&&n.add(r)}return+n}function N(e,t){const n=new q;let s=-1;return Float64Array.from(e,void 0===t?e=>n.add(+e||0):r=>n.add(+t(r,++s,e)||0))}var S=n(8828);function A(e){return e}function C(e,...t){return D(e,A,A,t)}function j(e,...t){return D(e,Array.from,A,t)}function T(e,t){for(let n=1,s=t.length;n<s;++n)e=e.flatMap((e=>e.pop().map((([t,n])=>[...e,t,n]))));return e}function M(e,...t){return T(j(e,...t),t)}function O(e,t,...n){return T(E(e,t,...n),n)}function I(e,t,...n){return D(e,A,t,n)}function E(e,t,...n){return D(e,Array.from,t,n)}function R(e,...t){return D(e,A,$,t)}function F(e,...t){return D(e,Array.from,$,t)}function $(e){if(1!==e.length)throw new Error("duplicate key");return e[0]}function D(e,t,n,s){return function e(r,o){if(o>=s.length)return n(r);const i=new S.L,a=s[o++];let l=-1;for(const e of r){const t=a(e,++l,r),n=i.get(t);n?n.push(e):i.set(t,[e])}for(const[t,n]of i)i.set(t,e(n,o));return t(i)}(e,0)}function L(e,t){return Array.from(t,(t=>e[t]))}function P(e,...t){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");e=Array.from(e);let[n]=t;if(n&&2!==n.length||t.length>1){const s=Uint32Array.from(e,((e,t)=>t));return t.length>1?(t=t.map((t=>e.map(t))),s.sort(((e,n)=>{for(const s of t){const t=U(s[e],s[n]);if(t)return t}}))):(n=e.map(n),s.sort(((e,t)=>U(n[e],n[t])))),L(e,s)}return e.sort(G(n))}function G(e=r.Z){if(e===r.Z)return U;if("function"!=typeof e)throw new TypeError("compare is not a function");return(t,n)=>{const s=e(t,n);return s||0===s?s:(0===e(n,n))-(0===e(t,t))}}function U(e,t){return(null==e||!(e>=e))-(null==t||!(t>=t))||(e<t?-1:e>t?1:0)}function z(e,t,n){return(2!==t.length?P(I(e,t,n),(([e,t],[n,s])=>(0,r.Z)(t,s)||(0,r.Z)(e,n))):P(C(e,n),(([e,n],[s,o])=>t(n,o)||(0,r.Z)(e,s)))).map((([e])=>e))}var B=Array.prototype,J=B.slice;B.map;function H(e){return()=>e}var W=n(6106);function V(e,t,n){let s;for(;;){const r=(0,W.G9)(e,t,n);if(r===s||0===r||!isFinite(r))return[e,t];r>0?(e=Math.floor(e/r)*r,t=Math.ceil(t/r)*r):r<0&&(e=Math.ceil(e*r)/r,t=Math.floor(t*r)/r),s=r}}function Z(e){return Math.ceil(Math.log(p(e))/Math.LN2)+1}function K(){var e=A,t=k,n=Z;function r(r){Array.isArray(r)||(r=Array.from(r));var o,i,a,l=r.length,c=new Array(l);for(o=0;o<l;++o)c[o]=e(r[o],o,r);var u=t(c),f=u[0],d=u[1],p=n(c,f,d);if(!Array.isArray(p)){const e=d,n=+p;if(t===k&&([f,d]=V(f,d,n)),(p=(0,W.ZP)(f,d,n))[0]<=f&&(a=(0,W.G9)(f,d,n)),p[p.length-1]>=d)if(e>=d&&t===k){const e=(0,W.G9)(f,d,n);isFinite(e)&&(e>0?d=(Math.floor(d/e)+1)*e:e<0&&(d=(Math.ceil(d*-e)+1)/-e))}else p.pop()}for(var m=p.length;p[0]<=f;)p.shift(),--m;for(;p[m-1]>d;)p.pop(),--m;var h,g=new Array(m+1);for(o=0;o<=m;++o)(h=g[o]=[]).x0=o>0?p[o-1]:f,h.x1=o<m?p[o]:d;if(isFinite(a)){if(a>0)for(o=0;o<l;++o)null!=(i=c[o])&&f<=i&&i<=d&&g[Math.min(m,Math.floor((i-f)/a))].push(r[o]);else if(a<0)for(o=0;o<l;++o)if(null!=(i=c[o])&&f<=i&&i<=d){const e=Math.floor((f-i)*a);g[Math.min(m,e+(p[e]<=i))].push(r[o])}}else for(o=0;o<l;++o)null!=(i=c[o])&&f<=i&&i<=d&&g[(0,s.ZP)(p,i,0,m)].push(r[o]);return g}return r.value=function(t){return arguments.length?(e="function"==typeof t?t:H(t),r):e},r.domain=function(e){return arguments.length?(t="function"==typeof e?e:H([e[0],e[1]]),r):t},r.thresholds=function(e){return arguments.length?(n="function"==typeof e?e:Array.isArray(e)?H(J.call(e)):H(e),r):n},r}function X(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n<t||void 0===n&&t>=t)&&(n=t);else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&(n<r||void 0===n&&r>=r)&&(n=r)}return n}function Y(e,t){let n,s=-1,r=-1;if(void 0===t)for(const t of e)++r,null!=t&&(n<t||void 0===n&&t>=t)&&(n=t,s=r);else for(let o of e)null!=(o=t(o,++r,e))&&(n<o||void 0===n&&o>=o)&&(n=o,s=r);return s}function Q(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function ee(e,t){let n,s=-1,r=-1;if(void 0===t)for(const t of e)++r,null!=t&&(n>t||void 0===n&&t>=t)&&(n=t,s=r);else for(let o of e)null!=(o=t(o,++r,e))&&(n>o||void 0===n&&o>=o)&&(n=o,s=r);return s}function te(e,t,n=0,s=e.length-1,r){for(r=void 0===r?U:G(r);s>n;){if(s-n>600){const o=s-n+1,i=t-n+1,a=Math.log(o),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(o-l)/o)*(i-o/2<0?-1:1);te(e,t,Math.max(n,Math.floor(t-i*l/o+c)),Math.min(s,Math.floor(t+(o-i)*l/o+c)),r)}const o=e[t];let i=n,a=s;for(ne(e,n,t),r(e[s],o)>0&&ne(e,n,s);i<a;){for(ne(e,i,a),++i,--a;r(e[i],o)<0;)++i;for(;r(e[a],o)>0;)--a}0===r(e[n],o)?ne(e,n,a):(++a,ne(e,a,s)),a<=t&&(n=a+1),t<=a&&(s=a-1)}return e}function ne(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}var se=n(3745);function re(e,t=r.Z){let n,s=!1;if(1===t.length){let o;for(const i of e){const e=t(i);(s?(0,r.Z)(e,o)>0:0===(0,r.Z)(e,e))&&(n=i,o=e,s=!0)}}else for(const r of e)(s?t(r,n)>0:0===t(r,r))&&(n=r,s=!0);return n}function oe(e,t,n){if(s=(e=Float64Array.from((0,se.K)(e,n))).length){if((t=+t)<=0||s<2)return Q(e);if(t>=1)return X(e);var s,r=(s-1)*t,o=Math.floor(r),i=X(te(e,o).subarray(0,o+1));return i+(Q(e.subarray(o+1))-i)*(r-o)}}function ie(e,t,n=se.Z){if(s=e.length){if((t=+t)<=0||s<2)return+n(e[0],0,e);if(t>=1)return+n(e[s-1],s-1,e);var s,r=(s-1)*t,o=Math.floor(r),i=+n(e[o],o,e);return i+(+n(e[o+1],o+1,e)-i)*(r-o)}}function ae(e,t,n){if(s=(e=Float64Array.from((0,se.K)(e,n))).length){if((t=+t)<=0||s<2)return ee(e);if(t>=1)return Y(e);var s,r=Math.floor((s-1)*t),o=te(Uint32Array.from(e,((e,t)=>t)),r,0,s-1,((t,n)=>U(e[t],e[n])));return re(o.subarray(0,r+1),(t=>e[t]))}}function le(e,t,n){return Math.ceil((n-t)/(2*(oe(e,.75)-oe(e,.25))*Math.pow(p(e),-1/3)))}function ce(e,t,n){return Math.ceil((n-t)*Math.cbrt(p(e))/(3.49*_(e)))}function ue(e,t){let n=0,s=0;if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&(++n,s+=t);else{let r=-1;for(let o of e)null!=(o=t(o,++r,e))&&(o=+o)>=o&&(++n,s+=o)}if(n)return s/n}function fe(e,t){return oe(e,.5,t)}function de(e,t){return ae(e,.5,t)}function pe(e){return Array.from(function*(e){for(const t of e)yield*t}(e))}function me(e,t){const n=new S.L;if(void 0===t)for(let t of e)null!=t&&t>=t&&n.set(t,(n.get(t)||0)+1);else{let s=-1;for(let r of e)null!=(r=t(r,++s,e))&&r>=r&&n.set(r,(n.get(r)||0)+1)}let s,r=0;for(const[e,t]of n)t>r&&(r=t,s=e);return s}function he(e,t=ge){const n=[];let s,r=!1;for(const o of e)r&&n.push(t(s,o)),s=o,r=!0;return n}function ge(e,t){return[e,t]}function ye(e,t,n){e=+e,t=+t,n=(r=arguments.length)<2?(t=e,e=0,1):r<3?1:+n;for(var s=-1,r=0|Math.max(0,Math.ceil((t-e)/n)),o=new Array(r);++s<r;)o[s]=e+s*n;return o}function be(e,t=r.Z){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");let n=Array.from(e);const s=new Float64Array(n.length);2!==t.length&&(n=n.map(t),t=r.Z);const o=(e,s)=>t(n[e],n[s]);let i,a;return Uint32Array.from(n,((e,t)=>t)).sort(t===r.Z?(e,t)=>U(n[e],n[t]):G(o)).forEach(((e,t)=>{const n=o(e,void 0===i?e:i);n>=0?((void 0===i||n>0)&&(i=e,a=t),s[e]=a):s[e]=NaN})),s}function ve(e,t=r.Z){let n,s=!1;if(1===t.length){let o;for(const i of e){const e=t(i);(s?(0,r.Z)(e,o)<0:0===(0,r.Z)(e,e))&&(n=i,o=e,s=!0)}}else for(const r of e)(s?t(r,n)<0:0===t(r,r))&&(n=r,s=!0);return n}function we(e,t=r.Z){if(1===t.length)return ee(e,t);let n,s=-1,o=-1;for(const r of e)++o,(s<0?0===t(r,r):t(r,n)<0)&&(n=r,s=o);return s}function _e(e,t=r.Z){if(1===t.length)return Y(e,t);let n,s=-1,o=-1;for(const r of e)++o,(s<0?0===t(r,r):t(r,n)>0)&&(n=r,s=o);return s}function ke(e,t){const n=we(e,t);return n<0?void 0:n}const qe=xe(Math.random);function xe(e){return function(t,n=0,s=t.length){let r=s-(n=+n);for(;r;){const s=e()*r--|0,o=t[r+n];t[r+n]=t[s+n],t[s+n]=o}return t}}function Ne(e,t){let n=0;if(void 0===t)for(let t of e)(t=+t)&&(n+=t);else{let s=-1;for(let r of e)(r=+t(r,++s,e))&&(n+=r)}return n}function Se(e){if(!(r=e.length))return[];for(var t=-1,n=Q(e,Ae),s=new Array(n);++t<n;)for(var r,o=-1,i=s[t]=new Array(r);++o<r;)i[o]=e[o][t];return s}function Ae(e){return e.length}function Ce(){return Se(arguments)}function je(e,t){if("function"!=typeof t)throw new TypeError("test is not a function");let n=-1;for(const s of e)if(!t(s,++n,e))return!1;return!0}function Te(e,t){if("function"!=typeof t)throw new TypeError("test is not a function");let n=-1;for(const s of e)if(t(s,++n,e))return!0;return!1}function Me(e,t){if("function"!=typeof t)throw new TypeError("test is not a function");const n=[];let s=-1;for(const r of e)t(r,++s,e)&&n.push(r);return n}function Oe(e,t){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof t)throw new TypeError("mapper is not a function");return Array.from(e,((n,s)=>t(n,s,e)))}function Ie(e,t,n){if("function"!=typeof t)throw new TypeError("reducer is not a function");const s=e[Symbol.iterator]();let r,o,i=-1;if(arguments.length<3){if(({done:r,value:n}=s.next()),r)return;++i}for(;({done:r,value:o}=s.next()),!r;)n=t(n,o,++i,e);return n}function Ee(e){if("function"!=typeof e[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(e).reverse()}function Re(e,...t){e=new S.H(e);for(const n of t)for(const t of n)e.delete(t);return e}function Fe(e,t){const n=t[Symbol.iterator](),s=new S.H;for(const t of e){if(s.has(t))return!1;let e,r;for(;({value:e,done:r}=n.next())&&!r;){if(Object.is(t,e))return!1;s.add(e)}}return!0}function $e(e,...t){e=new S.H(e),t=t.map(De);e:for(const n of e)for(const s of t)if(!s.has(n)){e.delete(n);continue e}return e}function De(e){return e instanceof S.H?e:new S.H(e)}function Le(e,t){const n=e[Symbol.iterator](),s=new Set;for(const e of t){const t=Pe(e);if(s.has(t))continue;let r,o;for(;({value:r,done:o}=n.next());){if(o)return!1;const e=Pe(r);if(s.add(e),Object.is(t,e))break}}return!0}function Pe(e){return null!==e&&"object"==typeof e?e.valueOf():e}function Ge(e,t){return Le(t,e)}function Ue(...e){const t=new S.H;for(const n of e)for(const e of n)t.add(e);return t}},3745:(e,t,n)=>{"use strict";function s(e){return null===e?NaN:+e}function*r(e,t){if(void 0===t)for(let t of e)null!=t&&(t=+t)>=t&&(yield t);else{let n=-1;for(let s of e)null!=(s=t(s,++n,e))&&(s=+s)>=s&&(yield s)}}n.d(t,{K:()=>r,Z:()=>s})},6106:(e,t,n)=>{"use strict";n.d(t,{G9:()=>a,ZP:()=>i,ly:()=>l});var s=Math.sqrt(50),r=Math.sqrt(10),o=Math.sqrt(2);function i(e,t,n){var s,r,o,i,l=-1;if(n=+n,(e=+e)===(t=+t)&&n>0)return[e];if((s=t<e)&&(r=e,e=t,t=r),0===(i=a(e,t,n))||!isFinite(i))return[];if(i>0){let n=Math.round(e/i),s=Math.round(t/i);for(n*i<e&&++n,s*i>t&&--s,o=new Array(r=s-n+1);++l<r;)o[l]=(n+l)*i}else{i=-i;let n=Math.round(e*i),s=Math.round(t*i);for(n/i<e&&++n,s/i>t&&--s,o=new Array(r=s-n+1);++l<r;)o[l]=(n+l)/i}return s&&o.reverse(),o}function a(e,t,n){var i=(t-e)/Math.max(0,n),a=Math.floor(Math.log(i)/Math.LN10),l=i/Math.pow(10,a);return a>=0?(l>=s?10:l>=r?5:l>=o?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=s?10:l>=r?5:l>=o?2:1)}function l(e,t,n){var i=Math.abs(t-e)/Math.max(0,n),a=Math.pow(10,Math.floor(Math.log(i)/Math.LN10)),l=i/a;return l>=s?a*=10:l>=r?a*=5:l>=o&&(a*=2),t<e?-a:a}},1696:(e,t,n)=>{"use strict";function s(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function r(e,t){var n=Object.create(e.prototype);for(var s in t)n[s]=t[s];return n}function o(){}n.d(t,{ZP:()=>_,B8:()=>x});var i=.7,a=1/i,l="\\s*([+-]?\\d+)\\s*",c="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",u="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",f=/^#([0-9a-f]{3,8})$/,d=new RegExp(`^rgb\\(${l},${l},${l}\\)$`),p=new RegExp(`^rgb\\(${u},${u},${u}\\)$`),m=new RegExp(`^rgba\\(${l},${l},${l},${c}\\)$`),h=new RegExp(`^rgba\\(${u},${u},${u},${c}\\)$`),g=new RegExp(`^hsl\\(${c},${u},${u}\\)$`),y=new RegExp(`^hsla\\(${c},${u},${u},${c}\\)$`),b={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function v(){return this.rgb().formatHex()}function w(){return this.rgb().formatRgb()}function _(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=f.exec(e))?(n=t[1].length,t=parseInt(t[1],16),6===n?k(t):3===n?new N(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===n?q(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===n?q(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=d.exec(e))?new N(t[1],t[2],t[3],1):(t=p.exec(e))?new N(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=m.exec(e))?q(t[1],t[2],t[3],t[4]):(t=h.exec(e))?q(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=g.exec(e))?M(t[1],t[2]/100,t[3]/100,1):(t=y.exec(e))?M(t[1],t[2]/100,t[3]/100,t[4]):b.hasOwnProperty(e)?k(b[e]):"transparent"===e?new N(NaN,NaN,NaN,0):null}function k(e){return new N(e>>16&255,e>>8&255,255&e,1)}function q(e,t,n,s){return s<=0&&(e=t=n=NaN),new N(e,t,n,s)}function x(e,t,n,s){return 1===arguments.length?((r=e)instanceof o||(r=_(r)),r?new N((r=r.rgb()).r,r.g,r.b,r.opacity):new N):new N(e,t,n,null==s?1:s);var r}function N(e,t,n,s){this.r=+e,this.g=+t,this.b=+n,this.opacity=+s}function S(){return`#${T(this.r)}${T(this.g)}${T(this.b)}`}function A(){const e=C(this.opacity);return`${1===e?"rgb(":"rgba("}${j(this.r)}, ${j(this.g)}, ${j(this.b)}${1===e?")":`, ${e})`}`}function C(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function j(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function T(e){return((e=j(e))<16?"0":"")+e.toString(16)}function M(e,t,n,s){return s<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new I(e,t,n,s)}function O(e){if(e instanceof I)return new I(e.h,e.s,e.l,e.opacity);if(e instanceof o||(e=_(e)),!e)return new I;if(e instanceof I)return e;var t=(e=e.rgb()).r/255,n=e.g/255,s=e.b/255,r=Math.min(t,n,s),i=Math.max(t,n,s),a=NaN,l=i-r,c=(i+r)/2;return l?(a=t===i?(n-s)/l+6*(n<s):n===i?(s-t)/l+2:(t-n)/l+4,l/=c<.5?i+r:2-i-r,a*=60):l=c>0&&c<1?0:a,new I(a,l,c,e.opacity)}function I(e,t,n,s){this.h=+e,this.s=+t,this.l=+n,this.opacity=+s}function E(e){return(e=(e||0)%360)<0?e+360:e}function R(e){return Math.max(0,Math.min(1,e||0))}function F(e,t,n){return 255*(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)}s(o,_,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:v,formatHex:v,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return O(this).formatHsl()},formatRgb:w,toString:w}),s(N,x,r(o,{brighter(e){return e=null==e?a:Math.pow(a,e),new N(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?i:Math.pow(i,e),new N(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new N(j(this.r),j(this.g),j(this.b),C(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:S,formatHex:S,formatHex8:function(){return`#${T(this.r)}${T(this.g)}${T(this.b)}${T(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:A,toString:A})),s(I,(function(e,t,n,s){return 1===arguments.length?O(e):new I(e,t,n,null==s?1:s)}),r(o,{brighter(e){return e=null==e?a:Math.pow(a,e),new I(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?i:Math.pow(i,e),new I(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,s=n+(n<.5?n:1-n)*t,r=2*n-s;return new N(F(e>=240?e-240:e+120,r,s),F(e,r,s),F(e<120?e+240:e-120,r,s),this.opacity)},clamp(){return new I(E(this.h),R(this.s),R(this.l),C(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=C(this.opacity);return`${1===e?"hsl(":"hsla("}${E(this.h)}, ${100*R(this.s)}%, ${100*R(this.l)}%${1===e?")":`, ${e})`}`}}))},670:(e,t,n)=>{"use strict";n.d(t,{WU:()=>f,jH:()=>d});var s=n(2313);var r=n(7259);var o,i=n(4218);function a(e,t){var n=(0,i.V)(e,t);if(!n)return e+"";var s=n[0],r=n[1];return r<0?"0."+new Array(-r).join("0")+s:s.length>r+1?s.slice(0,r+1)+"."+s.slice(r+1):s+new Array(r-s.length+2).join("0")}const l={"%":(e,t)=>(100*e).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:i.Z,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>a(100*e,t),r:a,s:function(e,t){var n=(0,i.V)(e,t);if(!n)return e+"";var s=n[0],r=n[1],a=r-(o=3*Math.max(-8,Math.min(8,Math.floor(r/3))))+1,l=s.length;return a===l?s:a>l?s+new Array(a-l+1).join("0"):a>0?s.slice(0,a)+"."+s.slice(a):"0."+new Array(1-a).join("0")+(0,i.V)(e,Math.max(0,t+a-1))[0]},X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function c(e){return e}var u,f,d,p=Array.prototype.map,m=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function h(e){var t,n,i=void 0===e.grouping||void 0===e.thousands?c:(t=p.call(e.grouping,Number),n=e.thousands+"",function(e,s){for(var r=e.length,o=[],i=0,a=t[0],l=0;r>0&&a>0&&(l+a+1>s&&(a=Math.max(1,s-l)),o.push(e.substring(r-=a,r+a)),!((l+=a+1)>s));)a=t[i=(i+1)%t.length];return o.reverse().join(n)}),a=void 0===e.currency?"":e.currency[0]+"",u=void 0===e.currency?"":e.currency[1]+"",f=void 0===e.decimal?".":e.decimal+"",d=void 0===e.numerals?c:function(e){return function(t){return t.replace(/[0-9]/g,(function(t){return e[+t]}))}}(p.call(e.numerals,String)),h=void 0===e.percent?"%":e.percent+"",g=void 0===e.minus?"−":e.minus+"",y=void 0===e.nan?"NaN":e.nan+"";function b(e){var t=(e=(0,r.Z)(e)).fill,n=e.align,s=e.sign,c=e.symbol,p=e.zero,b=e.width,v=e.comma,w=e.precision,_=e.trim,k=e.type;"n"===k?(v=!0,k="g"):l[k]||(void 0===w&&(w=12),_=!0,k="g"),(p||"0"===t&&"="===n)&&(p=!0,t="0",n="=");var q="$"===c?a:"#"===c&&/[boxX]/.test(k)?"0"+k.toLowerCase():"",x="$"===c?u:/[%p]/.test(k)?h:"",N=l[k],S=/[defgprs%]/.test(k);function A(e){var r,a,l,c=q,u=x;if("c"===k)u=N(e)+u,e="";else{var h=(e=+e)<0||1/e<0;if(e=isNaN(e)?y:N(Math.abs(e),w),_&&(e=function(e){e:for(var t,n=e.length,s=1,r=-1;s<n;++s)switch(e[s]){case".":r=t=s;break;case"0":0===r&&(r=s),t=s;break;default:if(!+e[s])break e;r>0&&(r=0)}return r>0?e.slice(0,r)+e.slice(t+1):e}(e)),h&&0==+e&&"+"!==s&&(h=!1),c=(h?"("===s?s:g:"-"===s||"("===s?"":s)+c,u=("s"===k?m[8+o/3]:"")+u+(h&&"("===s?")":""),S)for(r=-1,a=e.length;++r<a;)if(48>(l=e.charCodeAt(r))||l>57){u=(46===l?f+e.slice(r+1):e.slice(r))+u,e=e.slice(0,r);break}}v&&!p&&(e=i(e,1/0));var A=c.length+e.length+u.length,C=A<b?new Array(b-A+1).join(t):"";switch(v&&p&&(e=i(C+e,C.length?b-u.length:1/0),C=""),n){case"<":e=c+e+u+C;break;case"=":e=c+C+e+u;break;case"^":e=C.slice(0,A=C.length>>1)+c+e+u+C.slice(A);break;default:e=C+c+e+u}return d(e)}return w=void 0===w?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w)),A.toString=function(){return e+""},A}return{format:b,formatPrefix:function(e,t){var n=b(((e=(0,r.Z)(e)).type="f",e)),o=3*Math.max(-8,Math.min(8,Math.floor((0,s.Z)(t)/3))),i=Math.pow(10,-o),a=m[8+o/3];return function(e){return n(i*e)+a}}}}u=h({thousands:",",grouping:[3],currency:["$",""]}),f=u.format,d=u.formatPrefix},2313:(e,t,n)=>{"use strict";n.d(t,{Z:()=>r});var s=n(4218);function r(e){return(e=(0,s.V)(Math.abs(e)))?e[1]:NaN}},4218:(e,t,n)=>{"use strict";function s(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function r(e,t){if((n=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"))<0)return null;var n,s=e.slice(0,n);return[s.length>1?s[0]+s.slice(2):s,+e.slice(n+1)]}n.d(t,{V:()=>r,Z:()=>s})},7259:(e,t,n)=>{"use strict";n.d(t,{Z:()=>r});var s=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function r(e){if(!(t=s.exec(e)))throw new Error("invalid format: "+e);var t;return new o({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}function o(e){this.fill=void 0===e.fill?" ":e.fill+"",this.align=void 0===e.align?">":e.align+"",this.sign=void 0===e.sign?"-":e.sign+"",this.symbol=void 0===e.symbol?"":e.symbol+"",this.zero=!!e.zero,this.width=void 0===e.width?void 0:+e.width,this.comma=!!e.comma,this.precision=void 0===e.precision?void 0:+e.precision,this.trim=!!e.trim,this.type=void 0===e.type?"":e.type+""}r.prototype=o.prototype,o.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},8486:(e,t,n)=>{"use strict";n.d(t,{Z:()=>s});const s=e=>()=>e},8403:(e,t,n)=>{"use strict";function s(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}n.d(t,{Z:()=>s})},4314:(e,t,n)=>{"use strict";n.d(t,{ZP:()=>c});var s=n(1696);function r(e,t,n,s,r){var o=e*e,i=o*e;return((1-3*e+3*o-i)*t+(4-6*o+3*i)*n+(1+3*e+3*o-3*i)*s+i*r)/6}var o=n(8486);function i(e,t){return function(n){return e+n*t}}function a(e){return 1==(e=+e)?l:function(t,n){return n-t?function(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(s){return Math.pow(e+s*t,n)}}(t,n,e):(0,o.Z)(isNaN(t)?n:t)}}function l(e,t){var n=t-e;return n?i(e,n):(0,o.Z)(isNaN(e)?t:e)}const c=function e(t){var n=a(t);function r(e,t){var r=n((e=(0,s.B8)(e)).r,(t=(0,s.B8)(t)).r),o=n(e.g,t.g),i=n(e.b,t.b),a=l(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=o(t),e.b=i(t),e.opacity=a(t),e+""}}return r.gamma=e,r}(1);function u(e){return function(t){var n,r,o=t.length,i=new Array(o),a=new Array(o),l=new Array(o);for(n=0;n<o;++n)r=(0,s.B8)(t[n]),i[n]=r.r||0,a[n]=r.g||0,l[n]=r.b||0;return i=e(i),a=e(a),l=e(l),r.opacity=1,function(e){return r.r=i(e),r.g=a(e),r.b=l(e),r+""}}}u((function(e){var t=e.length-1;return function(n){var s=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),o=e[s],i=e[s+1],a=s>0?e[s-1]:2*o-i,l=s<t-1?e[s+2]:2*i-o;return r((n-s/t)*t,a,o,i,l)}})),u((function(e){var t=e.length;return function(n){var s=Math.floor(((n%=1)<0?++n:n)*t),o=e[(s+t-1)%t],i=e[s%t],a=e[(s+1)%t],l=e[(s+2)%t];return r((n-s/t)*t,o,i,a,l)}}))},9009:(e,t,n)=>{"use strict";n.d(t,{Z:()=>i});var s=n(8403),r=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,o=new RegExp(r.source,"g");function i(e,t){var n,i,a,l=r.lastIndex=o.lastIndex=0,c=-1,u=[],f=[];for(e+="",t+="";(n=r.exec(e))&&(i=o.exec(t));)(a=i.index)>l&&(a=t.slice(l,a),u[c]?u[c]+=a:u[++c]=a),(n=n[0])===(i=i[0])?u[c]?u[c]+=i:u[++c]=i:(u[++c]=null,f.push({i:c,x:(0,s.Z)(n,i)})),l=o.lastIndex;return l<t.length&&(a=t.slice(l),u[c]?u[c]+=a:u[++c]=a),u.length<2?f[0]?function(e){return function(t){return e(t)+""}}(f[0].x):function(e){return function(){return e}}(t):(t=f.length,function(e){for(var n,s=0;s<t;++s)u[(n=f[s]).i]=n.x(e);return u.join("")})}},4090:(e,t,n)=>{"use strict";function s(e){for(var t=e.length/6|0,n=new Array(t),s=0;s<t;)n[s]="#"+e.slice(6*s,6*++s);return n}n.d(t,{Z:()=>s})},6169:(e,t,n)=>{"use strict";n.d(t,{JG:()=>_,ZP:()=>q,l4:()=>k});var s=n(5519),r=n(1696),o=n(4314);function i(e,t){var n,s=t?t.length:0,r=e?Math.min(s,e.length):0,o=new Array(r),i=new Array(s);for(n=0;n<r;++n)o[n]=p(e[n],t[n]);for(;n<s;++n)i[n]=t[n];return function(e){for(n=0;n<r;++n)i[n]=o[n](e);return i}}function a(e,t){var n=new Date;return e=+e,t=+t,function(s){return n.setTime(e*(1-s)+t*s),n}}var l=n(8403);function c(e,t){var n,s={},r={};for(n in null!==e&&"object"==typeof e||(e={}),null!==t&&"object"==typeof t||(t={}),t)n in e?s[n]=p(e[n],t[n]):r[n]=t[n];return function(e){for(n in s)r[n]=s[n](e);return r}}var u=n(9009),f=n(8486);function d(e,t){t||(t=[]);var n,s=e?Math.min(t.length,e.length):0,r=t.slice();return function(o){for(n=0;n<s;++n)r[n]=e[n]*(1-o)+t[n]*o;return r}}function p(e,t){var n,s,p=typeof t;return null==t||"boolean"===p?(0,f.Z)(t):("number"===p?l.Z:"string"===p?(n=(0,r.ZP)(t))?(t=n,o.ZP):u.Z:t instanceof r.ZP?o.ZP:t instanceof Date?a:(s=t,!ArrayBuffer.isView(s)||s instanceof DataView?Array.isArray(t)?i:"function"!=typeof t.valueOf&&"function"!=typeof t.toString||isNaN(t)?c:l.Z:d))(e,t)}function m(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}function h(e){return+e}var g=[0,1];function y(e){return e}function b(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:(n=isNaN(t)?NaN:.5,function(){return n});var n}function v(e,t,n){var s=e[0],r=e[1],o=t[0],i=t[1];return r<s?(s=b(r,s),o=n(i,o)):(s=b(s,r),o=n(o,i)),function(e){return o(s(e))}}function w(e,t,n){var r=Math.min(e.length,t.length)-1,o=new Array(r),i=new Array(r),a=-1;for(e[r]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++a<r;)o[a]=b(e[a],e[a+1]),i[a]=n(t[a],t[a+1]);return function(t){var n=(0,s.ZP)(e,t,1,r)-1;return i[n](o[n](t))}}function _(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function k(){var e,t,n,s,r,o,i=g,a=g,c=p,u=y;function f(){var e,t,n,l=Math.min(i.length,a.length);return u!==y&&(e=i[0],t=i[l-1],e>t&&(n=e,e=t,t=n),u=function(n){return Math.max(e,Math.min(t,n))}),s=l>2?w:v,r=o=null,d}function d(t){return null==t||isNaN(t=+t)?n:(r||(r=s(i.map(e),a,c)))(e(u(t)))}return d.invert=function(n){return u(t((o||(o=s(a,i.map(e),l.Z)))(n)))},d.domain=function(e){return arguments.length?(i=Array.from(e,h),f()):i.slice()},d.range=function(e){return arguments.length?(a=Array.from(e),f()):a.slice()},d.rangeRound=function(e){return a=Array.from(e),c=m,f()},d.clamp=function(e){return arguments.length?(u=!!e||y,f()):u!==y},d.interpolate=function(e){return arguments.length?(c=e,f()):c},d.unknown=function(e){return arguments.length?(n=e,d):n},function(n,s){return e=n,t=s,f()}}function q(){return k()(y,y)}},2998:(e,t,n)=>{"use strict";function s(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}n.d(t,{o:()=>s})},8877:(e,t,n)=>{"use strict";n.d(t,{Z:()=>u});var s=n(6106),r=n(6169),o=n(2998),i=n(7259),a=n(2313);var l=n(670);function c(e,t,n,r){var o,c=(0,s.ly)(e,t,n);switch((r=(0,i.Z)(null==r?",f":r)).type){case"s":var u=Math.max(Math.abs(e),Math.abs(t));return null!=r.precision||isNaN(o=function(e,t){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,a.Z)(t)/3)))-(0,a.Z)(Math.abs(e)))}(c,u))||(r.precision=o),(0,l.jH)(r,u);case"":case"e":case"g":case"p":case"r":null!=r.precision||isNaN(o=function(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,(0,a.Z)(t)-(0,a.Z)(e))+1}(c,Math.max(Math.abs(e),Math.abs(t))))||(r.precision=o-("e"===r.type));break;case"f":case"%":null!=r.precision||isNaN(o=function(e){return Math.max(0,-(0,a.Z)(Math.abs(e)))}(c))||(r.precision=o-2*("%"===r.type))}return(0,l.WU)(r)}function u(){var e=(0,r.ZP)();return e.copy=function(){return(0,r.JG)(e,u())},o.o.apply(e,arguments),function(e){var t=e.domain;return e.ticks=function(e){var n=t();return(0,s.ZP)(n[0],n[n.length-1],null==e?10:e)},e.tickFormat=function(e,n){var s=t();return c(s[0],s[s.length-1],null==e?10:e,n)},e.nice=function(n){null==n&&(n=10);var r,o,i=t(),a=0,l=i.length-1,c=i[a],u=i[l],f=10;for(u<c&&(o=c,c=u,u=o,o=a,a=l,l=o);f-- >0;){if((o=(0,s.G9)(c,u,n))===r)return i[a]=c,i[l]=u,t(i);if(o>0)c=Math.floor(c/o)*o,u=Math.ceil(u/o)*o;else{if(!(o<0))break;c=Math.ceil(c*o)/o,u=Math.floor(u*o)/o}r=o}return e},e}(e)}},5540:(e,t,n)=>{"use strict";n.d(t,{Z:()=>i});var s=n(8828),r=n(2998);const o=Symbol("implicit");function i(){var e=new s.L,t=[],n=[],a=o;function l(s){let r=e.get(s);if(void 0===r){if(a!==o)return a;e.set(s,r=t.push(s)-1)}return n[r%n.length]}return l.domain=function(n){if(!arguments.length)return t.slice();t=[],e=new s.L;for(const s of n)e.has(s)||e.set(s,t.push(s)-1);return l},l.range=function(e){return arguments.length?(n=Array.from(e),l):n.slice()},l.unknown=function(e){return arguments.length?(a=e,l):a},l.copy=function(){return i(t,n).unknown(a)},r.o.apply(l,arguments),l}},1868:(e,t,n)=>{"use strict";n.d(t,{Wem:()=>s.extent,J69:()=>s.mean,BYU:()=>Ut.Z,p2C:()=>tn,XgA:()=>sn,xHP:()=>rn});var s=n(9724);function r(){}function o(e){return null==e?r:function(){return this.querySelector(e)}}function i(){return[]}function a(e){return null==e?i:function(){return this.querySelectorAll(e)}}function l(e){return function(){return null==(t=e.apply(this,arguments))?[]:Array.isArray(t)?t:Array.from(t);var t}}function c(e){return function(){return this.matches(e)}}function u(e){return function(t){return t.matches(e)}}var f=Array.prototype.find;function d(){return this.firstElementChild}var p=Array.prototype.filter;function m(){return Array.from(this.children)}function h(e){return new Array(e.length)}function g(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function y(e,t,n,s,r,o){for(var i,a=0,l=t.length,c=o.length;a<c;++a)(i=t[a])?(i.__data__=o[a],s[a]=i):n[a]=new g(e,o[a]);for(;a<l;++a)(i=t[a])&&(r[a]=i)}function b(e,t,n,s,r,o,i){var a,l,c,u=new Map,f=t.length,d=o.length,p=new Array(f);for(a=0;a<f;++a)(l=t[a])&&(p[a]=c=i.call(l,l.__data__,a,t)+"",u.has(c)?r[a]=l:u.set(c,l));for(a=0;a<d;++a)c=i.call(e,o[a],a,o)+"",(l=u.get(c))?(s[a]=l,l.__data__=o[a],u.delete(c)):n[a]=new g(e,o[a]);for(a=0;a<f;++a)(l=t[a])&&u.get(p[a])===l&&(r[a]=l)}function v(e){return e.__data__}function w(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function _(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}g.prototype={constructor:g,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};var k="http://www.w3.org/1999/xhtml";const q={svg:"http://www.w3.org/2000/svg",xhtml:k,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function x(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),q.hasOwnProperty(t)?{space:q[t],local:e}:e}function N(e){return function(){this.removeAttribute(e)}}function S(e){return function(){this.removeAttributeNS(e.space,e.local)}}function A(e,t){return function(){this.setAttribute(e,t)}}function C(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function j(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function T(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function M(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function O(e){return function(){this.style.removeProperty(e)}}function I(e,t,n){return function(){this.style.setProperty(e,t,n)}}function E(e,t,n){return function(){var s=t.apply(this,arguments);null==s?this.style.removeProperty(e):this.style.setProperty(e,s,n)}}function R(e,t){return e.style.getPropertyValue(t)||M(e).getComputedStyle(e,null).getPropertyValue(t)}function F(e){return function(){delete this[e]}}function $(e,t){return function(){this[e]=t}}function D(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function L(e){return e.trim().split(/^|\s+/)}function P(e){return e.classList||new G(e)}function G(e){this._node=e,this._names=L(e.getAttribute("class")||"")}function U(e,t){for(var n=P(e),s=-1,r=t.length;++s<r;)n.add(t[s])}function z(e,t){for(var n=P(e),s=-1,r=t.length;++s<r;)n.remove(t[s])}function B(e){return function(){U(this,e)}}function J(e){return function(){z(this,e)}}function H(e,t){return function(){(t.apply(this,arguments)?U:z)(this,e)}}function W(){this.textContent=""}function V(e){return function(){this.textContent=e}}function Z(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function K(){this.innerHTML=""}function X(e){return function(){this.innerHTML=e}}function Y(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function Q(){this.nextSibling&&this.parentNode.appendChild(this)}function ee(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function te(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===k&&t.documentElement.namespaceURI===k?t.createElement(e):t.createElementNS(n,e)}}function ne(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function se(e){var t=x(e);return(t.local?ne:te)(t)}function re(){return null}function oe(){var e=this.parentNode;e&&e.removeChild(this)}function ie(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ae(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function le(e){return function(){var t=this.__on;if(t){for(var n,s=0,r=-1,o=t.length;s<o;++s)n=t[s],e.type&&n.type!==e.type||n.name!==e.name?t[++r]=n:this.removeEventListener(n.type,n.listener,n.options);++r?t.length=r:delete this.__on}}}function ce(e,t,n){return function(){var s,r=this.__on,o=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var i=0,a=r.length;i<a;++i)if((s=r[i]).type===e.type&&s.name===e.name)return this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=o,s.options=n),void(s.value=t);this.addEventListener(e.type,o,n),s={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(s):this.__on=[s]}}function ue(e,t,n){var s=M(e),r=s.CustomEvent;"function"==typeof r?r=new r(t,n):(r=s.document.createEvent("Event"),n?(r.initEvent(t,n.bubbles,n.cancelable),r.detail=n.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function fe(e,t){return function(){return ue(this,e,t)}}function de(e,t){return function(){return ue(this,e,t.apply(this,arguments))}}G.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var pe=[null];function me(e,t){this._groups=e,this._parents=t}function he(){return new me([[document.documentElement]],pe)}me.prototype=he.prototype={constructor:me,select:function(e){"function"!=typeof e&&(e=o(e));for(var t=this._groups,n=t.length,s=new Array(n),r=0;r<n;++r)for(var i,a,l=t[r],c=l.length,u=s[r]=new Array(c),f=0;f<c;++f)(i=l[f])&&(a=e.call(i,i.__data__,f,l))&&("__data__"in i&&(a.__data__=i.__data__),u[f]=a);return new me(s,this._parents)},selectAll:function(e){e="function"==typeof e?l(e):a(e);for(var t=this._groups,n=t.length,s=[],r=[],o=0;o<n;++o)for(var i,c=t[o],u=c.length,f=0;f<u;++f)(i=c[f])&&(s.push(e.call(i,i.__data__,f,c)),r.push(i));return new me(s,r)},selectChild:function(e){return this.select(null==e?d:function(e){return function(){return f.call(this.children,e)}}("function"==typeof e?e:u(e)))},selectChildren:function(e){return this.selectAll(null==e?m:function(e){return function(){return p.call(this.children,e)}}("function"==typeof e?e:u(e)))},filter:function(e){"function"!=typeof e&&(e=c(e));for(var t=this._groups,n=t.length,s=new Array(n),r=0;r<n;++r)for(var o,i=t[r],a=i.length,l=s[r]=[],u=0;u<a;++u)(o=i[u])&&e.call(o,o.__data__,u,i)&&l.push(o);return new me(s,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,v);var n,s=t?b:y,r=this._parents,o=this._groups;"function"!=typeof e&&(n=e,e=function(){return n});for(var i=o.length,a=new Array(i),l=new Array(i),c=new Array(i),u=0;u<i;++u){var f=r[u],d=o[u],p=d.length,m=w(e.call(f,f&&f.__data__,u,r)),h=m.length,g=l[u]=new Array(h),_=a[u]=new Array(h);s(f,d,g,_,c[u]=new Array(p),m,t);for(var k,q,x=0,N=0;x<h;++x)if(k=g[x]){for(x>=N&&(N=x+1);!(q=_[N])&&++N<h;);k._next=q||null}}return(a=new me(a,r))._enter=l,a._exit=c,a},enter:function(){return new me(this._enter||this._groups.map(h),this._parents)},exit:function(){return new me(this._exit||this._groups.map(h),this._parents)},join:function(e,t,n){var s=this.enter(),r=this,o=this.exit();return"function"==typeof e?(s=e(s))&&(s=s.selection()):s=s.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==n?o.remove():n(o),s&&r?s.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,s=t._groups,r=n.length,o=s.length,i=Math.min(r,o),a=new Array(r),l=0;l<i;++l)for(var c,u=n[l],f=s[l],d=u.length,p=a[l]=new Array(d),m=0;m<d;++m)(c=u[m]||f[m])&&(p[m]=c);for(;l<r;++l)a[l]=n[l];return new me(a,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var s,r=e[t],o=r.length-1,i=r[o];--o>=0;)(s=r[o])&&(i&&4^s.compareDocumentPosition(i)&&i.parentNode.insertBefore(s,i),i=s);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=_);for(var n=this._groups,s=n.length,r=new Array(s),o=0;o<s;++o){for(var i,a=n[o],l=a.length,c=r[o]=new Array(l),u=0;u<l;++u)(i=a[u])&&(c[u]=i);c.sort(t)}return new me(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var s=e[t],r=0,o=s.length;r<o;++r){var i=s[r];if(i)return i}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,n=0,s=t.length;n<s;++n)for(var r,o=t[n],i=0,a=o.length;i<a;++i)(r=o[i])&&e.call(r,r.__data__,i,o);return this},attr:function(e,t){var n=x(e);if(arguments.length<2){var s=this.node();return n.local?s.getAttributeNS(n.space,n.local):s.getAttribute(n)}return this.each((null==t?n.local?S:N:"function"==typeof t?n.local?T:j:n.local?C:A)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?O:"function"==typeof t?E:I)(e,t,null==n?"":n)):R(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?F:"function"==typeof t?D:$)(e,t)):this.node()[e]},classed:function(e,t){var n=L(e+"");if(arguments.length<2){for(var s=P(this.node()),r=-1,o=n.length;++r<o;)if(!s.contains(n[r]))return!1;return!0}return this.each(("function"==typeof t?H:t?B:J)(n,t))},text:function(e){return arguments.length?this.each(null==e?W:("function"==typeof e?Z:V)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?K:("function"==typeof e?Y:X)(e)):this.node().innerHTML},raise:function(){return this.each(Q)},lower:function(){return this.each(ee)},append:function(e){var t="function"==typeof e?e:se(e);return this.select((function(){return this.appendChild(t.apply(this,arguments))}))},insert:function(e,t){var n="function"==typeof e?e:se(e),s=null==t?re:"function"==typeof t?t:o(t);return this.select((function(){return this.insertBefore(n.apply(this,arguments),s.apply(this,arguments)||null)}))},remove:function(){return this.each(oe)},clone:function(e){return this.select(e?ae:ie)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var s,r,o=function(e){return e.trim().split(/^|\s+/).map((function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}}))}(e+""),i=o.length;if(!(arguments.length<2)){for(a=t?ce:le,s=0;s<i;++s)this.each(a(o[s],t,n));return this}var a=this.node().__on;if(a)for(var l,c=0,u=a.length;c<u;++c)for(s=0,l=a[c];s<i;++s)if((r=o[s]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?de:fe)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var s,r=e[t],o=0,i=r.length;o<i;++o)(s=r[o])&&(yield s)}};const ge=he;var ye={value:()=>{}};function be(){for(var e,t=0,n=arguments.length,s={};t<n;++t){if(!(e=arguments[t]+"")||e in s||/[\s.]/.test(e))throw new Error("illegal type: "+e);s[e]=[]}return new ve(s)}function ve(e){this._=e}function we(e,t){for(var n,s=0,r=e.length;s<r;++s)if((n=e[s]).name===t)return n.value}function _e(e,t,n){for(var s=0,r=e.length;s<r;++s)if(e[s].name===t){e[s]=ye,e=e.slice(0,s).concat(e.slice(s+1));break}return null!=n&&e.push({name:t,value:n}),e}ve.prototype=be.prototype={constructor:ve,on:function(e,t){var n,s,r=this._,o=(s=r,(e+"").trim().split(/^|\s+/).map((function(e){var t="",n=e.indexOf(".");if(n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!s.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}}))),i=-1,a=o.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++i<a;)if(n=(e=o[i]).type)r[n]=_e(r[n],e.name,t);else if(null==t)for(n in r)r[n]=_e(r[n],e.name,null);return this}for(;++i<a;)if((n=(e=o[i]).type)&&(n=we(r[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new ve(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,s,r=new Array(n),o=0;o<n;++o)r[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=0,n=(s=this._[e]).length;o<n;++o)s[o].value.apply(t,r)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var s=this._[e],r=0,o=s.length;r<o;++r)s[r].value.apply(t,n)}};const ke=be;var qe,xe,Ne=0,Se=0,Ae=0,Ce=1e3,je=0,Te=0,Me=0,Oe="object"==typeof performance&&performance.now?performance:Date,Ie="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ee(){return Te||(Ie(Re),Te=Oe.now()+Me)}function Re(){Te=0}function Fe(){this._call=this._time=this._next=null}function $e(e,t,n){var s=new Fe;return s.restart(e,t,n),s}function De(){Te=(je=Oe.now())+Me,Ne=Se=0;try{!function(){Ee(),++Ne;for(var e,t=qe;t;)(e=Te-t._time)>=0&&t._call.call(void 0,e),t=t._next;--Ne}()}finally{Ne=0,function(){var e,t,n=qe,s=1/0;for(;n;)n._call?(s>n._time&&(s=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:qe=t);xe=e,Pe(s)}(),Te=0}}function Le(){var e=Oe.now(),t=e-je;t>Ce&&(Me-=t,je=e)}function Pe(e){Ne||(Se&&(Se=clearTimeout(Se)),e-Te>24?(e<1/0&&(Se=setTimeout(De,e-Oe.now()-Me)),Ae&&(Ae=clearInterval(Ae))):(Ae||(je=Oe.now(),Ae=setInterval(Le,Ce)),Ne=1,Ie(De)))}function Ge(e,t,n){var s=new Fe;return t=null==t?0:+t,s.restart((n=>{s.stop(),e(n+t)}),t,n),s}Fe.prototype=$e.prototype={constructor:Fe,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?Ee():+n)+(null==t?0:+t),this._next||xe===this||(xe?xe._next=this:qe=this,xe=this),this._call=e,this._time=n,Pe()},stop:function(){this._call&&(this._call=null,this._time=1/0,Pe())}};var Ue=ke("start","end","cancel","interrupt"),ze=[],Be=0,Je=1,He=2,We=3,Ve=4,Ze=5,Ke=6;function Xe(e,t,n,s,r,o){var i=e.__transition;if(i){if(n in i)return}else e.__transition={};!function(e,t,n){var s,r=e.__transition;function o(e){n.state=Je,n.timer.restart(i,n.delay,n.time),n.delay<=e&&i(e-n.delay)}function i(o){var c,u,f,d;if(n.state!==Je)return l();for(c in r)if((d=r[c]).name===n.name){if(d.state===We)return Ge(i);d.state===Ve?(d.state=Ke,d.timer.stop(),d.on.call("interrupt",e,e.__data__,d.index,d.group),delete r[c]):+c<t&&(d.state=Ke,d.timer.stop(),d.on.call("cancel",e,e.__data__,d.index,d.group),delete r[c])}if(Ge((function(){n.state===We&&(n.state=Ve,n.timer.restart(a,n.delay,n.time),a(o))})),n.state=He,n.on.call("start",e,e.__data__,n.index,n.group),n.state===He){for(n.state=We,s=new Array(f=n.tween.length),c=0,u=-1;c<f;++c)(d=n.tween[c].value.call(e,e.__data__,n.index,n.group))&&(s[++u]=d);s.length=u+1}}function a(t){for(var r=t<n.duration?n.ease.call(null,t/n.duration):(n.timer.restart(l),n.state=Ze,1),o=-1,i=s.length;++o<i;)s[o].call(e,r);n.state===Ze&&(n.on.call("end",e,e.__data__,n.index,n.group),l())}function l(){for(var s in n.state=Ke,n.timer.stop(),delete r[t],r)return;delete e.__transition}r[t]=n,n.timer=$e(o,0,n.time)}(e,n,{name:t,index:s,group:r,on:Ue,tween:ze,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:Be})}function Ye(e,t){var n=et(e,t);if(n.state>Be)throw new Error("too late; already scheduled");return n}function Qe(e,t){var n=et(e,t);if(n.state>We)throw new Error("too late; already running");return n}function et(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}var tt,nt=n(8403),st=180/Math.PI,rt={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ot(e,t,n,s,r,o){var i,a,l;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(l=e*n+t*s)&&(n-=e*l,s-=t*l),(a=Math.sqrt(n*n+s*s))&&(n/=a,s/=a,l/=a),e*s<t*n&&(e=-e,t=-t,l=-l,i=-i),{translateX:r,translateY:o,rotate:Math.atan2(t,e)*st,skewX:Math.atan(l)*st,scaleX:i,scaleY:a}}function it(e,t,n,s){function r(e){return e.length?e.pop()+" ":""}return function(o,i){var a=[],l=[];return o=e(o),i=e(i),function(e,s,r,o,i,a){if(e!==r||s!==o){var l=i.push("translate(",null,t,null,n);a.push({i:l-4,x:(0,nt.Z)(e,r)},{i:l-2,x:(0,nt.Z)(s,o)})}else(r||o)&&i.push("translate("+r+t+o+n)}(o.translateX,o.translateY,i.translateX,i.translateY,a,l),function(e,t,n,o){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),o.push({i:n.push(r(n)+"rotate(",null,s)-2,x:(0,nt.Z)(e,t)})):t&&n.push(r(n)+"rotate("+t+s)}(o.rotate,i.rotate,a,l),function(e,t,n,o){e!==t?o.push({i:n.push(r(n)+"skewX(",null,s)-2,x:(0,nt.Z)(e,t)}):t&&n.push(r(n)+"skewX("+t+s)}(o.skewX,i.skewX,a,l),function(e,t,n,s,o,i){if(e!==n||t!==s){var a=o.push(r(o)+"scale(",null,",",null,")");i.push({i:a-4,x:(0,nt.Z)(e,n)},{i:a-2,x:(0,nt.Z)(t,s)})}else 1===n&&1===s||o.push(r(o)+"scale("+n+","+s+")")}(o.scaleX,o.scaleY,i.scaleX,i.scaleY,a,l),o=i=null,function(e){for(var t,n=-1,s=l.length;++n<s;)a[(t=l[n]).i]=t.x(e);return a.join("")}}}var at=it((function(e){const t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?rt:ot(t.a,t.b,t.c,t.d,t.e,t.f)}),"px, ","px)","deg)"),lt=it((function(e){return null==e?rt:(tt||(tt=document.createElementNS("http://www.w3.org/2000/svg","g")),tt.setAttribute("transform",e),(e=tt.transform.baseVal.consolidate())?ot((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):rt)}),", ",")",")");function ct(e,t){var n,s;return function(){var r=Qe(this,e),o=r.tween;if(o!==n)for(var i=0,a=(s=n=o).length;i<a;++i)if(s[i].name===t){(s=s.slice()).splice(i,1);break}r.tween=s}}function ut(e,t,n){var s,r;if("function"!=typeof n)throw new Error;return function(){var o=Qe(this,e),i=o.tween;if(i!==s){r=(s=i).slice();for(var a={name:t,value:n},l=0,c=r.length;l<c;++l)if(r[l].name===t){r[l]=a;break}l===c&&r.push(a)}o.tween=r}}function ft(e,t,n){var s=e._id;return e.each((function(){var e=Qe(this,s);(e.value||(e.value={}))[t]=n.apply(this,arguments)})),function(e){return et(e,s).value[t]}}var dt=n(1696),pt=n(4314),mt=n(9009);function ht(e,t){var n;return("number"==typeof t?nt.Z:t instanceof dt.ZP?pt.ZP:(n=(0,dt.ZP)(t))?(t=n,pt.ZP):mt.Z)(e,t)}function gt(e){return function(){this.removeAttribute(e)}}function yt(e){return function(){this.removeAttributeNS(e.space,e.local)}}function bt(e,t,n){var s,r,o=n+"";return function(){var i=this.getAttribute(e);return i===o?null:i===s?r:r=t(s=i,n)}}function vt(e,t,n){var s,r,o=n+"";return function(){var i=this.getAttributeNS(e.space,e.local);return i===o?null:i===s?r:r=t(s=i,n)}}function wt(e,t,n){var s,r,o;return function(){var i,a,l=n(this);if(null!=l)return(i=this.getAttribute(e))===(a=l+"")?null:i===s&&a===r?o:(r=a,o=t(s=i,l));this.removeAttribute(e)}}function _t(e,t,n){var s,r,o;return function(){var i,a,l=n(this);if(null!=l)return(i=this.getAttributeNS(e.space,e.local))===(a=l+"")?null:i===s&&a===r?o:(r=a,o=t(s=i,l));this.removeAttributeNS(e.space,e.local)}}function kt(e,t){var n,s;function r(){var r=t.apply(this,arguments);return r!==s&&(n=(s=r)&&function(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}(e,r)),n}return r._value=t,r}function qt(e,t){var n,s;function r(){var r=t.apply(this,arguments);return r!==s&&(n=(s=r)&&function(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}(e,r)),n}return r._value=t,r}function xt(e,t){return function(){Ye(this,e).delay=+t.apply(this,arguments)}}function Nt(e,t){return t=+t,function(){Ye(this,e).delay=t}}function St(e,t){return function(){Qe(this,e).duration=+t.apply(this,arguments)}}function At(e,t){return t=+t,function(){Qe(this,e).duration=t}}var Ct=ge.prototype.constructor;function jt(e){return function(){this.style.removeProperty(e)}}var Tt=0;function Mt(e,t,n,s){this._groups=e,this._parents=t,this._name=n,this._id=s}function Ot(){return++Tt}var It=ge.prototype;Mt.prototype=function(e){return ge().transition(e)}.prototype={constructor:Mt,select:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=o(e));for(var s=this._groups,r=s.length,i=new Array(r),a=0;a<r;++a)for(var l,c,u=s[a],f=u.length,d=i[a]=new Array(f),p=0;p<f;++p)(l=u[p])&&(c=e.call(l,l.__data__,p,u))&&("__data__"in l&&(c.__data__=l.__data__),d[p]=c,Xe(d[p],t,n,p,d,et(l,n)));return new Mt(i,this._parents,t,n)},selectAll:function(e){var t=this._name,n=this._id;"function"!=typeof e&&(e=a(e));for(var s=this._groups,r=s.length,o=[],i=[],l=0;l<r;++l)for(var c,u=s[l],f=u.length,d=0;d<f;++d)if(c=u[d]){for(var p,m=e.call(c,c.__data__,d,u),h=et(c,n),g=0,y=m.length;g<y;++g)(p=m[g])&&Xe(p,t,n,g,m,h);o.push(m),i.push(c)}return new Mt(o,i,t,n)},selectChild:It.selectChild,selectChildren:It.selectChildren,filter:function(e){"function"!=typeof e&&(e=c(e));for(var t=this._groups,n=t.length,s=new Array(n),r=0;r<n;++r)for(var o,i=t[r],a=i.length,l=s[r]=[],u=0;u<a;++u)(o=i[u])&&e.call(o,o.__data__,u,i)&&l.push(o);return new Mt(s,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,s=t.length,r=n.length,o=Math.min(s,r),i=new Array(s),a=0;a<o;++a)for(var l,c=t[a],u=n[a],f=c.length,d=i[a]=new Array(f),p=0;p<f;++p)(l=c[p]||u[p])&&(d[p]=l);for(;a<s;++a)i[a]=t[a];return new Mt(i,this._parents,this._name,this._id)},selection:function(){return new Ct(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,n=Ot(),s=this._groups,r=s.length,o=0;o<r;++o)for(var i,a=s[o],l=a.length,c=0;c<l;++c)if(i=a[c]){var u=et(i,t);Xe(i,e,n,c,a,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new Mt(s,this._parents,e,n)},call:It.call,nodes:It.nodes,node:It.node,size:It.size,empty:It.empty,each:It.each,on:function(e,t){var n=this._id;return arguments.length<2?et(this.node(),n).on.on(e):this.each(function(e,t,n){var s,r,o=function(e){return(e+"").trim().split(/^|\s+/).every((function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e}))}(t)?Ye:Qe;return function(){var i=o(this,e),a=i.on;a!==s&&(r=(s=a).copy()).on(t,n),i.on=r}}(n,e,t))},attr:function(e,t){var n=x(e),s="transform"===n?lt:ht;return this.attrTween(e,"function"==typeof t?(n.local?_t:wt)(n,s,ft(this,"attr."+e,t)):null==t?(n.local?yt:gt)(n):(n.local?vt:bt)(n,s,t))},attrTween:function(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;var s=x(e);return this.tween(n,(s.local?kt:qt)(s,t))},style:function(e,t,n){var s="transform"==(e+="")?at:ht;return null==t?this.styleTween(e,function(e,t){var n,s,r;return function(){var o=R(this,e),i=(this.style.removeProperty(e),R(this,e));return o===i?null:o===n&&i===s?r:r=t(n=o,s=i)}}(e,s)).on("end.style."+e,jt(e)):"function"==typeof t?this.styleTween(e,function(e,t,n){var s,r,o;return function(){var i=R(this,e),a=n(this),l=a+"";return null==a&&(this.style.removeProperty(e),l=a=R(this,e)),i===l?null:i===s&&l===r?o:(r=l,o=t(s=i,a))}}(e,s,ft(this,"style."+e,t))).each(function(e,t){var n,s,r,o,i="style."+t,a="end."+i;return function(){var l=Qe(this,e),c=l.on,u=null==l.value[i]?o||(o=jt(t)):void 0;c===n&&r===u||(s=(n=c).copy()).on(a,r=u),l.on=s}}(this._id,e)):this.styleTween(e,function(e,t,n){var s,r,o=n+"";return function(){var i=R(this,e);return i===o?null:i===s?r:r=t(s=i,n)}}(e,s,t),n).on("end.style."+e,null)},styleTween:function(e,t,n){var s="style."+(e+="");if(arguments.length<2)return(s=this.tween(s))&&s._value;if(null==t)return this.tween(s,null);if("function"!=typeof t)throw new Error;return this.tween(s,function(e,t,n){var s,r;function o(){var o=t.apply(this,arguments);return o!==r&&(s=(r=o)&&function(e,t,n){return function(s){this.style.setProperty(e,t.call(this,s),n)}}(e,o,n)),s}return o._value=t,o}(e,t,null==n?"":n))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=null==t?"":t}}(ft(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw new Error;return this.tween(t,function(e){var t,n;function s(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&function(e){return function(t){this.textContent=e.call(this,t)}}(s)),t}return s._value=e,s}(e))},remove:function(){return this.on("end.remove",function(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}(this._id))},tween:function(e,t){var n=this._id;if(e+="",arguments.length<2){for(var s,r=et(this.node(),n).tween,o=0,i=r.length;o<i;++o)if((s=r[o]).name===e)return s.value;return null}return this.each((null==t?ct:ut)(n,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?xt:Nt)(t,e)):et(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?St:At)(t,e)):et(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw new Error;return function(){Qe(this,e).ease=t}}(t,e)):et(this.node(),t).ease},easeVarying:function(e){if("function"!=typeof e)throw new Error;return this.each(function(e,t){return function(){var n=t.apply(this,arguments);if("function"!=typeof n)throw new Error;Qe(this,e).ease=n}}(this._id,e))},end:function(){var e,t,n=this,s=n._id,r=n.size();return new Promise((function(o,i){var a={value:i},l={value:function(){0==--r&&o()}};n.each((function(){var n=Qe(this,s),r=n.on;r!==e&&((t=(e=r).copy())._.cancel.push(a),t._.interrupt.push(a),t._.end.push(l)),n.on=t})),0===r&&o()}))},[Symbol.iterator]:It[Symbol.iterator]};var Et={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};function Rt(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}ge.prototype.interrupt=function(e){return this.each((function(){!function(e,t){var n,s,r,o=e.__transition,i=!0;if(o){for(r in t=null==t?null:t+"",o)(n=o[r]).name===t?(s=n.state>He&&n.state<Ze,n.state=Ke,n.timer.stop(),n.on.call(s?"interrupt":"cancel",e,e.__data__,n.index,n.group),delete o[r]):i=!1;i&&delete e.__transition}}(this,e)}))},ge.prototype.transition=function(e){var t,n;e instanceof Mt?(t=e._id,e=e._name):(t=Ot(),(n=Et).time=Ee(),e=null==e?null:e+"");for(var s=this._groups,r=s.length,o=0;o<r;++o)for(var i,a=s[o],l=a.length,c=0;c<l;++c)(i=a[c])&&Xe(i,e,t,c,a,n||Rt(i,t));return new Mt(s,this._parents,e,t)};const{abs:Ft,max:$t,min:Dt}=Math;function Lt(e){return[+e[0],+e[1]]}function Pt(e){return[Lt(e[0]),Lt(e[1])]}["w","e"].map(Gt),["n","s"].map(Gt),["n","w","e","s","nw","ne","sw","se"].map(Gt);function Gt(e){return{type:e}}var Ut=n(8877),zt=n(6106),Bt=n(7259),Jt=n(670);var Ht=n(6169),Wt=n(2998);function Vt(e){return Math.log(e)}function Zt(e){return Math.exp(e)}function Kt(e){return-Math.log(-e)}function Xt(e){return-Math.exp(-e)}function Yt(e){return isFinite(e)?+("1e"+e):e<0?0:e}function Qt(e){return(t,n)=>-e(-t,n)}function en(e){const t=e(Vt,Zt),n=t.domain;let s,r,o=10;function i(){return s=function(e){return e===Math.E?Math.log:10===e&&Math.log10||2===e&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}(o),r=function(e){return 10===e?Yt:e===Math.E?Math.exp:t=>Math.pow(e,t)}(o),n()[0]<0?(s=Qt(s),r=Qt(r),e(Kt,Xt)):e(Vt,Zt),t}return t.base=function(e){return arguments.length?(o=+e,i()):o},t.domain=function(e){return arguments.length?(n(e),i()):n()},t.ticks=e=>{const t=n();let i=t[0],a=t[t.length-1];const l=a<i;l&&([i,a]=[a,i]);let c,u,f=s(i),d=s(a);const p=null==e?10:+e;let m=[];if(!(o%1)&&d-f<p){if(f=Math.floor(f),d=Math.ceil(d),i>0){for(;f<=d;++f)for(c=1;c<o;++c)if(u=f<0?c/r(-f):c*r(f),!(u<i)){if(u>a)break;m.push(u)}}else for(;f<=d;++f)for(c=o-1;c>=1;--c)if(u=f>0?c/r(-f):c*r(f),!(u<i)){if(u>a)break;m.push(u)}2*m.length<p&&(m=(0,zt.ZP)(i,a,p))}else m=(0,zt.ZP)(f,d,Math.min(d-f,p)).map(r);return l?m.reverse():m},t.tickFormat=(e,n)=>{if(null==e&&(e=10),null==n&&(n=10===o?"s":","),"function"!=typeof n&&(o%1||null!=(n=(0,Bt.Z)(n)).precision||(n.trim=!0),n=(0,Jt.WU)(n)),e===1/0)return n;const i=Math.max(1,o*e/t.ticks().length);return e=>{let t=e/r(Math.round(s(e)));return t*o<o-.5&&(t*=o),t<=i?n(e):""}},t.nice=()=>n(function(e,t){var n,s=0,r=(e=e.slice()).length-1,o=e[s],i=e[r];return i<o&&(n=s,s=r,r=n,n=o,o=i,i=n),e[s]=t.floor(o),e[r]=t.ceil(i),e}(n(),{floor:e=>r(Math.floor(s(e))),ceil:e=>r(Math.ceil(s(e)))})),t}function tn(){const e=en((0,Ht.l4)()).domain([1,10]);return e.copy=()=>(0,Ht.JG)(e,tn()).base(e.base()),Wt.o.apply(e,arguments),e}var nn=n(4090);const sn=(0,nn.Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),rn=(0,nn.Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function on(e,t,n){this.k=e,this.x=t,this.y=n}on.prototype={constructor:on,scale:function(e){return 1===e?this:new on(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new on(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};new on(1,0,0);on.prototype},8828:(e,t,n)=>{"use strict";n.d(t,{H:()=>r,L:()=>s});class s extends Map{constructor(e,t=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const[t,n]of e)this.set(t,n)}get(e){return super.get(o(this,e))}has(e){return super.has(o(this,e))}set(e,t){return super.set(i(this,e),t)}delete(e){return super.delete(a(this,e))}}class r extends Set{constructor(e,t=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const t of e)this.add(t)}has(e){return super.has(o(this,e))}add(e){return super.add(i(this,e))}delete(e){return super.delete(a(this,e))}}function o({_intern:e,_key:t},n){const s=t(n);return e.has(s)?e.get(s):n}function i({_intern:e,_key:t},n){const s=t(n);return e.has(s)?e.get(s):(e.set(s,n),n)}function a({_intern:e,_key:t},n){const s=t(n);return e.has(s)&&(n=e.get(s),e.delete(s)),n}function l(e){return null!==e&&"object"==typeof e?e.valueOf():e}}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var o=t[s]={exports:{}};return e[s](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e=n(334),t=n.n(e),s=n(4013),r=n(7147),o=n.n(r),i=n(1017),a=n.n(i);{const e=o().readdirSync(a().join(t().binpath,"/routes")).filter((e=>e.endsWith(".ts"))).map((e=>{const t=n(126)(`./${e}`);return t.file=e,t}));!function(e,t,n={}){const s=Object.assign({basepath:""},n);for(const n of t){const t=n.api;for(const n in t.methods){const r=t.methods[n];e[n](`${s.basepath}/${t.endpoint}`,r.init(s))}}!function(e,t){if(t.apiJson){const n=JSON.stringify(e.map((e=>e.api))),s=i.dirname(t.apiJson);r.existsSync(s)||r.mkdirSync(s,{recursive:!0}),r.writeFileSync(t.apiJson,n)}if(t.types){const n=function(e,t){const n={};for(const{file:t,route:s}of e){const e=s.api;for(const s in e.methods){const r=e.methods[s];r.alternativeFor||(n[t]||(n[t]=new Set),r.request.typeId&&n[t].add(r.request.typeId),r.response.typeId&&n[t].add(r.response.typeId))}}const s=["import { createValidate } from 'typia'"],r=[];for(const e in n){const o=Array.from(n[e]);s.push(`import { ${o.join(", ")} } from '${t}/${e}'`);for(const e of o)r.push(`export const valid${e} = createValidate<${e}>()`)}return s.join("\n")+"\n\n"+r.join("\n")}(e.map((e=>({file:e.file,route:e}))),t.types.importDir),s=i.dirname(t.types.outputFile);r.existsSync(s)||r.mkdirSync(s,{recursive:!0}),r.writeFileSync(t.types.outputFile,n)}}(t,s)}(s.l2,e,{app:s.l2,genomes:s.g_,basepath:s.LJ,apiJson:a().join(__dirname,"../../public/docs/server-api.json"),types:{importDir:"../types/routes",outputFile:a().join(__dirname,"./shared/checkers-raw/index.ts")}})}(0,s.lE)(t()).then((async()=>{if(console.log(`\n${new Date} ${t().commitHash||""}`),console.log("\nValidation succeeded.\n"),"validate"!=process.argv[2])if("phewas-precompute"!=process.argv[2])await(0,s.OG)();else{const e=process.argv[3],t=process.argv[4],n=s.g_[e];if(!n)throw"invalid genome name: "+e;const r=n.datasets[t];if(!r)throw"invalid dataset: "+t;s.U_.do_precompute(r)}else console.log("You may now run the server.")})).catch((e=>{let n=1;if(!o().existsSync(t().tpmasterdir)){const e=t().maintenance||{};if("start"in e&&"stop"in e&&"tpErrorCode"in e){const t=+new Date(e.start),s=+new Date(e.stop),r=+new Date;t<=r&&r<=s&&(n=e.tpErrorCode)}}e.stack&&console.log(e.stack),n?console.error("\n!!!\n"+e+"\n\n"):console.log("\n!!!\n"+e+"\n\n"),process.exit(n)}))})()})();
|
|
2
2
|
//# sourceMappingURL=server.js.map
|