@sjcrh/proteinpaint-server 2.42.1-0 → 2.42.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/server.js CHANGED
@@ -1,2 +1,2 @@
1
- (()=>{var t={5037:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>c});var r=n(9157),s=n(1017),o=n.n(s),i=n(334),a=n.n(i),l=n(3345);const c={endpoint:"burden",methods:{get:{init:({genomes:t})=>async(e,n)=>{try{const s=t[e.query.genome];if(!s)throw`invalid q.genome=${e.query.genome}`;const i=e.query,c=s.datasets[i.dslabel];if(!c)throw`invalid q.genome=${e.query.dslabel}`;if(!c.cohort.cumburden?.files)throw"missing ds.cohort.cumburden.files";const f=await async function(t,e){const n=o().join(a().cachedir,Math.random().toString()+".json");for(const e in t.query)t.query[e]=Number(t.query[e]);const s=Object.assign({},u,t.query);await(0,l.Sf)(n,JSON.stringify(s));const{fit:i,surv:c,sample:f}=e.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}`],h=await(0,r.default)(o().join(a().binpath,"utils/burden.R"),[],d),p=JSON.parse(h[0]);return p}(e,c),{keys:d,rows:h}=function(t){const e=Object.keys(t[0]),n=[],r=[];for(const t of e)if("chc"==t)r.push(t),n.push(t);else{const e=Number(t.slice(1).split(",")[0]);e<=60&&e%2==0&&(r.push(t),n.push(`burden${e}`))}const s=[];for(const e of t)s.push(r.map((t=>e[t])));return{keys:n,rows:s}}(f);n.send({status:"ok",keys:d,rows:h})}catch(t){n.send({status:"error",error:t.message||t})}},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:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f,maxTotalSizeCompressed:()=>u});var r=n(1017),s=n.n(r),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:t}){return async(e,n)=>{try{const r=t.hg38;if(!r)throw"hg38 missing";const o=r.datasets.GDC;if(!o)throw"hg38 GDC missing";const a=await async function(t,e){const n={op:"and",content:[{op:"=",content:{field:"data_format",value:"MAF"}},{op:"=",content:{field:"experimental_strategy",value:t.experimentalStrategy}},{op:"=",content:{field:"analysis.workflow_type",value:c}},{op:"=",content:{field:"access",value:"open"}}]},r={op:"and",content:[]};t.filter0&&r.content.push(t.filter0);const{host:o,headers:a}=e.getHostHeaders(t),d={filters:n,case_filters:r,size:l,fields:["id","file_size","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},h=await i().post(s().join(o.rest,"files"),{headers:a,body:JSON.stringify(d)});let p;try{p=JSON.parse(h.body)}catch(t){throw"invalid JSON from "+f.endpoint}if(!Number.isInteger(p.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(p.data?.hits))throw"re.data.hits[] not array";const m=[];for(const t of p.data.hits){const e=t.cases?.[0];if(!e)throw"h.cases[0] missing";const n={id:t.id,project_id:e.project.project_id,file_size:t.file_size};n.case_submitter_id=e.submitter_id,e.samples&&(n.sample_types=e.samples.map((t=>t.sample_type)).sort()),m.push(n)}return{files:m,filesTotal:p.data.pagination.total,maxTotalSizeCompressed:u}}(e.query,o);n.send(a)}catch(t){n.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcMafRequest"},response:{typeId:"GdcMafResponse"},examples:[{request:{body:{experimentalStrategy:"WXS",embedder:"localhost"}},response:{header:{status:200}}}]}}}},86:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f});var r=n(6452),s=n.n(r),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:t}){return async(e,n)=>{try{const r=t.hg38;if(!r)throw"hg38 missing";const o=r.datasets.GDC;if(!o)throw"hg38 GDC missing";await async function(t,e,n){const r=Date.now(),{host:o,headers:l}=n.getHostHeaders(t),f=await async function(t,e,n){if(0==t.length)throw"fileIdLst[] not array or blank";const r={filters:{op:"in",content:{field:"file_id",value:t}},size:1e4,fields:"file_size"},o=await s().post(i().join(e.rest,"files"),{headers:n,body:JSON.stringify(r)});let a;try{a=JSON.parse(o.body)}catch(t){throw"invalid json from getFileLstUnderSizeLimit"}if(!Array.isArray(a.data?.hits))throw"re.data.hits[] not array";const l=[];let c=0;for(const t of a.data.hits){if(c>=u.maxTotalSizeCompressed)break;if(!t.id)throw".id missing";if(!Number.isInteger(t.file_size))throw".file_size not integer";c+=t.file_size,l.push(t.id)}if(0==l.length)throw"no file available";return l}(t.fileIdLst,o,l);c().debugmode&&console.log(`${f.length} out of ${t.fileIdLst.length} input MAF files accepted by size limit`,Date.now()-r);const d={fileIdLst:f,columns:t.columns,host:i().join(o.rest,"data")},h=(0,a.run_rust_stream)("gdcmaf",JSON.stringify(d));e.setHeader("Content-Type","application/octet-stream"),e.setHeader("Content-Disposition","attachment; filename=cohort.maf.gz"),h.pipe(e),h.on("end",(()=>{c().debugmode&&console.log("rust gdcmaf",Date.now()-r),e.end()})),h.on("error",(t=>{console.error(t),e.statusCode=500,e.end("Internal Server Error")}))}(e.query,n,o)}catch(t){t.stack&&console.log(t.stack),n.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcMafBuildRequest"},response:{typeId:null}}}}},889:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>l});var r=n(2273),s=n(6452),o=n.n(s),i=n(334),a=n.n(i);const l={endpoint:"gdc/topMutatedGenes",methods:{all:{init:function({genomes:t}){return async(e,n)=>{const s=e.query,i=t.hg38;if(!i)throw"hg38 missing";const l=i.datasets.GDC;if(!l)throw"hg38 GDC missing";try{const t=await async function(t,e){let n,s;const{host:i,headers:l}=e.getHostHeaders(t);a().features?.geneExpHost?(n=c.query,s=c.getVariables(t)):(n=u.query,s=u.getVariables(t));const f=await o().post(i.graphql,{headers:l,body:JSON.stringify({query:n,variables:s})}),d=JSON.parse(f.body),h=[];for(const t of d.data.genesTableViewer.explore.genes.hits.edges){if("object"!=typeof t.node)throw"node missing from re.data.genesTableViewer.explore.genes.hits.edges[]";const e=[];Number.isInteger(t.node.case_cnv_gain?.hits?.total)&&t.node.case_cnv_gain.hits.total>0&&e.push({class:r.mclasscnvgain,count:t.node.case_cnv_gain.hits.total}),Number.isInteger(t.node.case_cnv_loss?.hits?.total)&&t.node.case_cnv_loss.hits.total>0&&e.push({class:r.mclasscnvloss,count:t.node.case_cnv_loss.hits.total}),Number.isInteger(t.node.ssm_case?.hits?.total)&&t.node.ssm_case.hits.total>0&&e.push({dt:r.dtsnvindel,count:t.node.ssm_case.hits.total}),h.push({gene:t.node.symbol,mutationStat:e})}return h}(s,l),e={genes:t};n.send(e)}catch(t){n.send({status:"error",error:t.message||t})}}},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:t=>{const e={genesTable_filters:{op:"and",content:[]},genesTable_size:t.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 t.filter0&&(e.genesTable_filters.content.push(JSON.parse(JSON.stringify(t.filter0))),e.geneCaseFilter.content.push(JSON.parse(JSON.stringify(t.filter0))),e.cnvTested.content.push(JSON.parse(JSON.stringify(t.filter0))),e.cnvGainFilters.content.push(JSON.parse(JSON.stringify(t.filter0))),e.cnvLossFilters.content.push(JSON.parse(JSON.stringify(t.filter0)))),"CGC"==t.geneFilter&&(e.genesTable_filters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),e.geneCaseFilter.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),e.cnvTested.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),e.cnvGainFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),e.cnvLossFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"})),e}},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:t=>{const e={caseFilters:{op:"and",content:[]},genesTable_filters:{op:"and",content:[]},genesTable_size:t.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 t.filter0&&(e.caseFilters.content.push(JSON.parse(JSON.stringify(t.filter0))),e.geneCaseFilter.content.push(JSON.parse(JSON.stringify(t.filter0))),e.cnvLossFilters.content.push(JSON.parse(JSON.stringify(t.filter0))),e.cnvGainFilters.content.push(JSON.parse(JSON.stringify(t.filter0))),e.cnvTested.content.push(JSON.parse(JSON.stringify(t.filter0)))),"CGC"==t.geneFilter&&(e.genesTable_filters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),e.cnvLossFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"}),e.cnvGainFilters.content.push({content:{field:"genes.is_cancer_gene_census",value:["true"]},op:"in"})),e}}},3202:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(4065);function s({genomes:t}){return(e,n)=>{try{e.query;const s=t[e.query.genome];if(!s)throw"invalid genome name";const o=(0,r.S)(s,e.query);n.send(o)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}const o={endpoint:"genelookup",methods:{get:{init:s,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:s}}}},1746:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>s});var r=n(2062);const s={endpoint:"healthcheck",methods:{get:{init:({genomes:t})=>async(e,n)=>{try{const e=await(0,r.W)(t);n.send(e)}catch(t){n.send({status:"error",error:t.message||t})}},request:{typeId:null},response:{typeId:"HealthCheckResponse"}}}}},3932:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>c});var r=n(3345),s=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(t,e)=>{try{const n=await function(t){return new Promise(((e,n)=>{const[o,a,c]=(0,r.ZX)({query:t});o&&n({error:"illegal file name"});const u=["log(oe)"==t.matrixType?"oe":t.matrixType?t.matrixType:"observed",t.nmeth||"NONE",a,t.pos1,t.pos2,t.isfrag?"FRAG":"BP",t.resolution],f=(0,s.spawn)(l().hicstraw,u),d=i().createInterface({input:f.stdout}),h=[],p=[];let m=0,g=0;d.on("line",(e=>{const n=e.split("\t");if(3!=n.length)return void m++;const r=Number.parseInt(n[0]),s=Number.parseInt(n[1]),o="log(oe)"==t.matrixType?Math.log(Number.parseFloat(n[2])):Number.parseFloat(n[2]);Number.isNaN(r)||Number.isNaN(s)||Number.isNaN(o)?g++:null!=t.mincutoff&&o<=t.mincutoff||h.push([r,s,o])})),f.stderr.on("data",(t=>p.push(t))),f.on("close",(()=>{const t=p.join("");t&&n({error:t}),m&&n({error:m+" lines have other than 3 fields"}),g&&n({error:g+" lines have non-numerical values in any of the 3 fields"}),e({items:h})}))}))}(t.query);e.send(n)}catch(t){e.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},6310:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>u});var r=n(3345),s=n(7147),o=n.n(s),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(t,e)=>{try{const[n,s,i]=(0,r.ZX)(t);if(n)throw"illegal file name";i||await(0,r.Ic)(s);const l=await async function(t,e){const n={},r=e?await S(t,0,32e3):await N(t,0,32e3),s=new DataView(r);let i=0;if("HIC"!==A())throw Error("Unsupported hic file");const l=M();if(7!==l&&8!==l&&9!=l)throw Error("Unsupported hic version: "+l);n.version=l;const u=Number(T());let f=[];const d=1e5;if(8==l||7==l){let e=await k(t,u,d);const n=e.getInt32(0,!0);n>0&&(e=await k(t,u+n+4,d),f=await q(e,u+n+4))}const h=A();if(n["Genome ID"]=h,9==l){const e=Number(T()),n=Number(T());if(e>0&&n>0){const r=await k(t,e,n);f=await q(r,0)}}const p={},m=M();let g=0;for(;g!==m;)p[A()]=A(),g++;n.Chromosomes={},n.chrorder=[];const y=M();let b=0;for(;b!==y;){const t=A();n.chrorder.push(t),n.Chromosomes[t]=7==l||8==l?M():T(),b++}n["Base pair-delimited resolutions"]=[];const v=M();let w=0;for(;w!==v;){const t=M();n["Base pair-delimited resolutions"].push(t),w++}n["Fragment-delimited resolutions"]=[];const _=M();let x=0;for(;x!==_;){const t=M();n["Fragment-delimited resolutions"].push(t),x++}return BigInt.prototype.toJSON||Object.defineProperty(BigInt.prototype,"toJSON",{get(){return()=>String(this)}}),n.normalization=f,n;async function k(t,n,r){const s=e?await S(t,n,r):await N(t,n,r);return new DataView(s)}async function q(e,n){const r=Date.now();let s=[];const o=e.getInt32(0,!0);let i=4;for(let t=1;t<=o;t++){let t=await f("string");s.push(t),8==l||7==l?(t=await f("string"),c(4),c(8*await f("int32")),c(12*await f("int32"))):9==l&&(i+=4,t=await f("string"),i+=20)}s=[...new Set(s)];const a=Date.now()-r;return console.log(`Read normalization on ${t} on ${a/1e3} seconds`),s;async function c(t){i+t>d&&u(),i+=t}async function u(){e=await k(t,n+i,d),n+=i,i=0}async function f(t){let n;if("string"==t){let t,r="";for(;i<e.byteLength&&0!=(t=e.getUint8(i++));)i>d&&await u(),r+=String.fromCharCode(t);n=r}else{if("int32"!=t)throw"No value assigned [server/src/hicstat.ts getViewValue()]";if(i<0)return;i+4>e.byteLength&&await u(),n=e.getInt32(i,!0),i+=4}return n}}async function N(t,e,n){const r=a().promisify(o().open),s=a().promisify(o().read),i=Buffer.alloc(n),l=await r(t,"r"),c=await s(l,i,0,n,e);o().close(l,(function(t){return t}));const u=c.buffer;return u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength)}async function S(t,e,n){try{const r=e+"-"+(e+n-1);return(await c()(t,{headers:{Range:"bytes="+r}}).buffer()).buffer}catch(t){throw console.log(t.response),"error reading file, check file details"}}function A(){let t,e="";for(;0!=(t=s.getUint8(i++));)e+=String.fromCharCode(t);return e}function M(){const t=s.getInt32(i,!0);return i+=4,t}function T(){const t=s.getBigInt64(i,!0);return i+=8,t}}(s,i);e.send({out:l})}catch(t){e.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},5852:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(938),s=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:t}){return async(e,n)=>{const o=e.query;try{const i=t[e.query.genome];if(!i)throw"invalid genome name";const l=i.datasets[e.query.dslabel];if(!l)throw"invalid dataset name";const c=l.cohort.termdb;if(!c)throw"invalid termdb object";await async function(t,e,n,o,i){if(!t.tid)throw".tid missing";const l="geneVariant"==t.type?{name:t.tid,type:"geneVariant",isleaf:!0}:n.q.termjsonByOneid(t.tid),c={filter:t.filter,terms:"geneVariant"==t.type?[{term:l,q:{isAtomic:!0}}]:[{id:t.tid,term:l,q:t.term1_q||a(l,t)}],currentGeneNames:t.currentGeneNames,rglst:t.rglst},u=await(0,s.Yu)(c,o,i);if(u.error)throw u.error;const f=[];if("geneVariant"==t.type){const e=u.samples,n=new Map;if(o.assayAvailability?.byDt)for(const[t,e]of Object.entries(o.assayAvailability.byDt))e.byOrigin&&n.set(parseInt(t),{byOrigin:{germline:{},somatic:{}}});const r=new Set;for(const[s,o]of Object.entries(e)){const e=o[t.tid].values;r.clear();for(const t of e){n.has(t.dt)||n.set(t.dt,{});const e=n.get(t.dt);e.byOrigin?(e.byOrigin[t.origin][t.class]||(e.byOrigin[t.origin][t.class]=1,r.add(`${t.dt} ${t.origin} ${t.class}`)),r.has(`${t.dt} ${t.origin} ${t.class}`)||(r.add(`${t.dt} ${t.origin} ${t.class}`),e.byOrigin[t.origin][t.class]+=1)):(e[t.class]||(r.add(`${t.dt} ${t.class}`),e[t.class]=1),r.has(`${t.dt} ${t.class}`)||(r.add(`${t.dt} ${t.class}`),e[t.class]+=1))}}for(const[t,e]of n)f.push({dt:t,classes:e})}else{const e=new Map;for(const n in u.samples){const r=u.samples[n][t.tid];r&&("key"in r&&e.set(r.key,1+(e.get(r.key)||0)))}for(const[n,r]of e)f.push({samplecount:r,key:n,label:u.refs?.byTermId?.[t.tid]?.events?.find((t=>t.event===n)).label||l?.values?.[n]?.label||n})}const d=(0,r.Tt)(l,u.refs?.byTermId?.[t.tid]?.bins||[],u.refs?.byTermId?.[t.tid]?.events,t.term1_q);d.length&&f.sort(((t,e)=>d.indexOf(t.label)-d.indexOf(e.label)));e.send({lst:f,orderedLabels:d})}(o,n,c,l,i)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}function a(t,e){if("categorical"==t.type)return{};if("survival"==t.type)return{};if("integer"==t.type||"float"==t.type)return t.bins.default;if("condition"==t.type)return{mode:e.mode,breaks:e.breaks,bar_by_grade:e.bar_by_grade,bar_by_children:e.bar_by_children,value_by_max_grade:e.value_by_max_grade,value_by_most_recent:e.value_by_most_recent,value_by_computable_grade:e.value_by_computable_grade};if("geneVariant"==t.type)return{};throw"unknown term type"}},4924:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>p,validate_query_geneExpression:()=>g});var r=n(1017),s=n.n(r),o=n(7147),i=n.n(o),a=n(9157),l=n(3345),c=n(334),u=n.n(c),f=n(1169),d=n(901),h=n(2273);const p={endpoint:"termdb/cluster",methods:{all:{init:function({genomes:t}){return async(e,n)=>{const r=e.query;let o;try{const e=t[r.genome];if(!e)throw"invalid genome name";const n=e.datasets[r.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(r.dataType!=h.dtgeneexpression)throw"unknown q.dataType "+r.dataType;if(!n.queries?.geneExpression)throw"no geneExpression data on this dataset";o=await async function(t,e){const{gene2sample2value:n,byTermId:r,bySampleId:o}=await e.queries.geneExpression.get(t);if(0==n.size)throw"no data";if(1==n.size){const t=Array.from(n.keys())[0];return{gene:t,data:n.get(t)}}const c=Date.now(),f=await async function(t,e){const n=new Set;for(const e of t.values()){for(const t in e)n.add(t);break}const r={matrix:[],row_names:[],col_names:[...n],cluster_method:e.clusterMethod,plot_image:!1};for(const[e,n]of t){r.row_names.push(e);const t=[];for(const e of r.col_names)t.push(n[e]||0);r.matrix.push(m(t))}const o=s().join(u().cachedir,Math.random().toString()+".json");await l.Sf(o,JSON.stringify(r));const c=JSON.parse(await(0,a.default)(s().join(u().binpath,"utils/hclust.R"),[],[o]));await i().promises.unlink(o);const f=c.RowOrder.map((t=>r.row_names.indexOf(t.name))),d=c.ColOrder.map((t=>r.col_names.indexOf(t.name))),h=[];for(const t of f){const e=[];for(const n of d)e.push(r.matrix[t][n]);h.push(e)}return{row:{merge:c.RowMerge,height:c.RowHeight,order:c.RowOrder,inputOrder:r.row_names},col:{merge:c.ColumnMerge,height:c.ColumnHeight,order:c.ColOrder,inputOrder:r.col_names},matrix:h}}(n,t);u().debugmode&&console.log("clustering done:",Date.now()-c,"ms");return{clustering:f,byTermId:r,bySampleId:o}}(r,n)}catch(t){t.stack&&console.log(t.stack),o={status:t.status||400,error:t.message||t}}n.send(o)}},request:{typeId:"TermdbClusterRequest"},response:{typeId:"TermdbClusterResponse"}}}};function m(t){const e=t.reduce(((t,e)=>t+e),0)/t.length,n=Math.sqrt(t.reduce(((t,n)=>t+Math.pow(n-e,2)),0)/t.length);return 0==n?t:t.map((t=>(t-e)/n))}async function g(t,e){const n=t.queries.geneExpression;if(n)if("gdcapi"!=n.src){if("native"!=n.src)throw"unknown queries.geneExpression.src";await async function(t,e,n){t.file.startsWith(u().tpmasterdir)||(t.file=s().join(u().tpmasterdir,t.file));t.samples||(t.samples=[]);await l.LC(t.file),t.nochr=await l.Jy(t.file,null,n),t.samples=[];{const n=await l.ZD(t.file);if(!n[0])throw"header line missing from "+t.file;const r=n[0].split("\t");if("#chr\tstart\tstop\tgene"!=r.slice(0,4).join("\t"))throw"header line has wrong content for columns 1-4";for(let n=4;n<r.length;n++){const s=e.cohort.termdb.q.sampleName2id(r[n]);if(null==s)throw"queries.geneExpression: unknown sample from header: "+r[n];t.samples.push(s)}console.log(t.samples.length,"samples from geneExpression of",e.label)}t.get=async r=>{const s=await(0,d.T)(r,t.samples,e);if(0==s?.size)return{gene2sample2value:new Set,byTermId:{},bySampleId:{}};const o={},i=t.samples||[];if(s)for(const t of s)o[t]={label:e.cohort.termdb.q.id2sampleName(t)};else for(const t of i)o[t]={label:e.cohort.termdb.q.id2sampleName(t)};const a=new Map;for(const e of r.genes){if(!e.gene)continue;if(!e.chr){const t=n.genedb.getjsonbyname.all(e.gene);if(0==t.length)continue;const r=JSON.parse(t.find((t=>t.isdefault)).genemodel||t[0].genemodel);e.start=r.start,e.stop=r.stop,e.chr=r.chr}const r={};await l.UE({args:[t.file,(t.nochr?e.chr?.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop],callback:t=>{const n=t.split("\t");if(n[3].toLowerCase()==e.gene.toLowerCase())for(let t=4;t<n.length;t++){const e=i[t-4];if(s&&!s.has(e))continue;if(!n[t])continue;const o=Number(n[t]);if(Number.isNaN(o))throw"exp value not number";r[e]=o}}}),Object.keys(r).length&&a.set(e.gene,r)}return{gene2sample2value:a,byTermId:{},bySampleId:o}}}(n,t,e)}else(0,f.eG)(t,e)}},2262:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(8907),s=n(8615);const o={endpoint:"termdb/descrstats",methods:{all:{init:function({genomes:t}){return async(e,n)=>{const o=e.query;try{const i=t[e.query.genome];if(!i)throw"invalid genome name";const a=i.datasets[e.query.dslabel];if(!a)throw"invalid dataset name";if(!a.cohort.termdb)throw"invalid termdb object";await async function(t,e,n){const o=n.cohort.termdb.q.termjsonByOneid(t.tid);if(!o)throw"invalid termid";if("float"!=o.type&&"integer"!=o.type)throw"not numerical term";const i=await(0,r.J4)({ds:n,key:t.tid,filter:t.filter}),a=[];for(const{value:e}of i)o.values?.[e]?.uncomputable||"log"===t.settings?.violin?.unit&&0===e||a.push(e);e.send((0,s.Z)(a))}(o,n,a)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}},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:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>s});var r=n(8907);const s={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:t}){return async(e,n)=>{const s=e.query;try{const o=t[e.query.genome];if(!o)throw"invalid genome name";const i=o.datasets[e.query.dslabel];if(!i)throw"invalid dataset name";const a=i.cohort.termdb;if(!a)throw"invalid termdb object";await async function(t,e,n,s){if(!t.tid)throw".tid missing";n.q.termjsonByOneid(t.tid);const o={ds:s,term_id:t.tid,filter:t.filter},i=await r.tt(o);e.send({lst:i})}(s,n,a,i)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},2630:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(8907),s=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:t}){return async(e,n)=>{const o=e.query;try{const i=t[e.query.genome];if(!i)throw"invalid genome name";const a=i.datasets[e.query.dslabel];if(!a)throw"invalid dataset name";await async function(t,e,n){const o=n.cohort.termdb.q.termjsonByOneid(t.tid);if(!o)throw"invalid termid";if("float"!=o.type&&"integer"!=o.type)throw"not numerical term";const i=t.getpercentile,a=[],l=[],c=await r.J4({ds:n,key:t.tid,filter:t.filter?"string"==typeof t.filter?JSON.parse(t.filter):t.filter:null});for(const{value:t}of c)o.values&&o.values[t]&&o.values[t].uncomputable||o.skip0forPercentile&&0==t||l.push(Number(t));for(const t of i){const e=(0,s.Z)(l,t);a.push(e)}e.send({values:a})}(o,n,a)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},7095:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>s});var r=n(2826);const s={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:t}){return async(e,n)=>{const s=e.query;s.cohortValues&&s.cohortValues,s.treeFilter&&s.treeFilter;try{const o=t[e.query.genome];if(!o)throw"invalid genome name";const[i,a]=(0,r.pq)(o,s);if(!i)throw"invalid dataset name";if(!a)throw"invalid termdb object";await async function(t,e,n){const r=t.cohortValues?t.cohortValues:"",s=t.treeFilter?t.treeFilter:"";e.send({lst:await n.q.getRootTerms(r,s)})}(s,n,a)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},3967:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>s});var r=n(2826);const s={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:t}){return async(e,n)=>{const s=e.query;try{const o=t[e.query.genome];if(!o)throw"invalid genome name";const[i,a]=await(0,r.pq)(o,s);if(!i)throw"invalid dataset name";if(!a)throw"invalid termdb object";await async function(t,e,n){if(!t.tid)throw"no parent term id";const s=t.cohortValues?t.cohortValues:"",o=t.treeFilter?t.treeFilter:"",i=await n.q.getTermChildren(t.tid,s,o);e.send({lst:i.map(r.iK)})}(s,n,a)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},3677:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f,validate_query_singleSampleMutation:()=>d});var r=n(7147),s=n.n(r),o=n(1017),i=n.n(o),a=n(3345),l=n(334),c=n.n(l),u=n(1169);const f={endpoint:"termdb/singleSampleMutation",methods:{get:{init:function({genomes:t}){return async(e,n)=>{const r=e.query;let s;try{const e=t[r.genome];if(!e)throw"invalid genome name";const n=e.datasets[r.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleSampleMutation)throw"not supported on this dataset";s=await n.queries.singleSampleMutation.get(r)}catch(t){t.stack&&console.log(t.stack),s={status:t.status||400,error:t.message||t}}n.send(s)}},request:{typeId:"TermdbSingleSampleMutationRequest"},response:{typeId:"TermdbSingleSampleMutationResponse"}}}};async function d(t,e){const n=t.queries.singleSampleMutation;if(n)if("gdcapi"==n.src)(0,u.sV)(t,e);else{if("native"!=n.src)throw"unknown singleSampleMutation.src";n.get=async e=>{let r=e.sample;if(t.cohort?.termdb?.q?.sampleName2id&&(r=t.cohort.termdb.q.sampleName2id(e.sample),null==r))return[];const o=i().join(c().tpmasterdir,n.folder,r.toString());try{await s().promises.stat(o)}catch(t){if("EACCES"==t.code)throw"cannot read file, permission denied";if("ENOENT"==t.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:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>r});const r={endpoint:"termdb/singlecellData",methods:{get:{init:s,request:{typeId:"TermdbSinglecellDataRequest"},response:{typeId:"TermdbSinglecellDataResponse"}},post:{alternativeFor:"get",init:s}}};function s({genomes:t}){return async(e,n)=>{const r=e.query;let s;try{const e=t[r.genome];if(!e)throw"invalid genome name";const n=e.datasets[r.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleCell)throw"no singlecell data on this dataset";s=await n.queries.singleCell.data.get(r)}catch(t){t.stack&&console.log(t),s={status:t.status||400,error:t.message||t}}n.send(s)}}},7934:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f,validate_query_singleCell:()=>h});var r=n(7147),s=n.n(r),o=n(1017),i=n.n(o),a=n(3345),l=n(334),c=n.n(l),u=n(1169);const f={endpoint:"termdb/singlecellSamples",methods:{get:{init:d,request:{typeId:"TermdbSinglecellsamplesRequest"},response:{typeId:"TermdbSinglecellsamplesResponse"}},post:{alternativeFor:"get",init:d}}};function d({genomes:t}){return async(e,n)=>{const r=e.query;let s;try{const e=t[r.genome];if(!e)throw"invalid genome name";const n=e.datasets[r.dslabel];if(!n)throw"invalid dataset name";if(!n.queries?.singleCell)throw"no singlecell data on this dataset";s=await n.queries.singleCell.samples.get(r),s.sameLegend=n.queries.singleCell.samples.sameLegend}catch(t){t.stack&&console.log(t.stack),s={status:t.status||400,error:t.message||t}}n.send(s)}}async function h(t,e){const n=t.queries.singleCell;if(n){if("gdcapi"==n.samples.src)(0,u.z7)(t,e);else{if("native"!=n.samples.src)throw"unknown singleCell.samples.src";!function(t,e){const n=[],r=e.cohort.termdb.q.getAllValues4term(t.isSampleTerm);for(const t of r.keys())n.push({sample:e.cohort.termdb.q.id2sampleName(t)});if(0==n.length)throw"no sample with sc data";t.get=()=>({samples:n,fields:["sample"],columnNames:["Sample"]})}(n.samples,t)}if("gdcapi"==n.data.src)(0,u.r8)(t,e);else{if("native"!=n.data.src)throw"unknown singleCell.data.src";!function(t,e){const n=new Set;for(const e of t.plots){if(n.has(e.name))throw"duplicate plot.name";n.add(e.name)}const r=[];for(const n of t.termIds){const t=e.cohort.termdb.q.termjsonByOneid(n);if(!t)throw"invalid term id from queries.singleCell.data.termIds[]";r.push(t)}t.get=async e=>{try{const n={};for(const e of t.termIds)n[e]={};const o=[];for(const r of t.plots){const l=i().join(c().tpmasterdir,r.folder,e.sample+r.fileSuffix);try{await s().promises.stat(l)}catch(t){if("ENOENT"==t.code)continue;if("EACCES"==t.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 e=1;e<u.length;e++){const s=u[e].split("\t"),o=s[0],i=Number(s[r.coordsColumns.x]),a=Number(s[r.coordsColumns.y]),l=s[r.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 e of t.termIds)n[e][o]=s[1]}o.push({name:r.name,cells:f,colorBy:r.colorColumn?.name,colorMap:r.colorMap})}return 0==o.length?{nodata:!0}:{plots:o,terms:r,tid2cellvalue:n}}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}}(n.data,t)}}}},605:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>s});var r=n(2826);const s={endpoint:"termdb/termsbyids",methods:{get:{init:o,request:{typeId:"gettermsbyidsRequest"},response:{typeId:"gettermsbyidsResponse"}},post:{alternativeFor:"get",init:o}}};function o({genomes:t}){return async(e,n)=>{const s=e.query;try{const o=t[e.query.genome];if(!o)throw"invalid genome name";const i=o.datasets[e.query.dslabel];if(!i)throw"invalid dataset name";const a=i.cohort.termdb;if(!a)throw"invalid termdb object";await async function(t,e,n){const s={};for(const e of t.ids){const t=n.q.termjsonByOneid(e);t&&("categorical"!=t.type||t.values||t.groupsetting?.inuse||(t.values={},t.samplecount={})),s[e]=t?(0,r.iK)(t):void 0}e.send({terms:s})}(s,n,a)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},5057:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>d,validate_query_TopVariablyExpressedGenes:()=>h});var r=n(1169),s=n(1017),o=n.n(s),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:t}){return async(e,n)=>{try{const r=e.query,s=t[r.genome];if(!s)throw"invalid genome";const o=s.datasets?.[r.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(r);u().debugmode&&console.log("topVariablyExpressedGenes",Date.now()-i,"ms"),n.send({genes:a})}catch(t){n.send({status:"error",error:t.message||t})}}},request:{typeId:"TermdbTopVariablyExpressedGenesRequest"},response:{typeId:"TermdbTopVariablyExpressedGenesResponse"}}}};function h(t,e){const n=t.queries.topVariablyExpressedGenes;if(n)if("gdcapi"==n.src)!function(t,e){function n(t,n){return{case_ids:n,gene_ids:p(e),selection_size:Number(t.maxGenes)}}t.queries.topVariablyExpressedGenes.getGenes=async s=>{if(u().features.gdcGenes)return console.log("!!GDC!! using serverconfig.features.gdcGenes[]"),u().features.gdcGenes;if(!t.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";const i=await(0,r.Z5)(s,t);if(0==i.length)return[];const{host:a,headers:c}=t.getHostHeaders(s),f=o().join(a.geneExp,"/gene_expression/gene_selection");try{const t=await l().post(f,{headers:c,body:JSON.stringify(n(s,i))}),r=JSON.parse(t.body),o=[];if(!Array.isArray(r.gene_selection))throw"re.gene_selection[] is not array";for(const t of r.gene_selection)if(t.gene_id&&"string"==typeof t.gene_id){const n=e.genedb.getNameByAlias.get(t.gene_id);n&&o.push(n.name)}else{if(!t.symbol||"string"!=typeof t.symbol)throw"one of re.gene_selection[] is missing both gene_id and symbol";o.push(t.symbol)}return o}catch(t){throw console.log(t.stack||t),t}}}(t,e);else{if("native"!=n.src)throw"unknown topVariablyExpressedGenes.src";!function(t,e){const n=t.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";t.queries.topVariablyExpressedGenes.getGenes=async e=>{const r=[];if(e.filter){const s=await(0,f.cf)(e.filter,t);for(const e of s)if(n.samples.includes(e.id)){const n=t.cohort.termdb.q.id2sampleName(e.id);if(!n)throw"sample id cannot convert to string name";r.push(n)}}else for(const e of n.samples){const n=t.cohort.termdb.q.id2sampleName(e.id);if(!n)throw"sample id cannot convert to string name";r.push(n)}const s=await async function(t,e,n,r){const s={input_file:n,samples:r.join(","),filter_extreme_values:!0,num_genes:Number(t.maxGenes),param:"var"},o=(await(0,i.run_rust)("topGeneByExpressionVariance",JSON.stringify(s))).split("\n");let a;for(const t of o)t.includes("output_json:")?a=JSON.parse(t.replace("output_json:","")):console.log(t);return a.map((t=>t.gene_symbol))}(e,0,n.file,r);return s}}(t)}}function p(t){const e=[];for(const n of t.geneset[0].lst){const r=t.genedb.getAliasByName.all(n);if(r)for(const t of r)t.alias.startsWith("ENSG")&&e.push(t.alias)}return e}},2386:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>v});var r=n(7147),s=n(3016),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),h=n(7011),p=n(8615),m=n(938);async function g(t,e,n,o){const l=n.cohort.termdb.q.termjsonByOneid(t.termid);if(!l)throw".termid invalid";if("integer"!=l.type&&"float"!=l.type)throw"term type is not integer/float.";const g=[{id:t.termid,term:l,q:{mode:"continuous"}}];t.divideTw&&(null===t.divideTw||void 0===t.divideTw||"object"!=typeof t.divideTw||"id"in t.divideTw||(t.divideTw.id=t.divideTw.term.name,t.divideTw.term.id=t.divideTw.term.name),g.push(t.divideTw),t.term2_q=t.divideTw.q);const v=await(0,f.Yu)({terms:g,filter:t.filter,currentGeneNames:t.currentGeneNames},n,o);if(v.error)throw v.error;t.divideTw&&v.refs.byTermId[t.divideTw?.id]&&(v.refs.byTermId[t.divideTw?.id].orderedLabels=(0,m.Tt)(t.divideTw,v.refs.byTermId[t.divideTw?.id]?.bins,void 0,t.divideTw.q)),t.scale&&function(t,e,n){if(!t.scale)return;const r=Number(t.scale);for(const[t,s]of Object.entries(e.samples))s[n.id]&&(n.values?.[s[n.id]?.value]?.uncomputable||(s[n.id].key=s[n.id].key/r,s[n.id].value=s[n.id].value/r))}(t,v,l);const w=function(t,e,n,r){const s="log"==t.unit,o=new Map;let i=1/0,a=-1/0;const l={};let c=0;for(const[t,u]of Object.entries(e.samples)){const t=u[n.id]?.value;if(Number.isFinite(t))if(n.values?.[t]?.uncomputable){const e=n.values[t].label;l[e]=(l[e]||0)+1}else if(s&&t<=0)c++;else if(i>t&&(i=t),a<t&&(a=t),"log"===s&&0===i&&(i=Math.max(i,t)),r){if(!u[r?.id])continue;if(r.term?.values?.[u[r.id]?.key]?.uncomputable){const t=r.term.values[u[r.id]?.value]?.label;l[t]=(l[t]||0)+1}o.has(u[r.id]?.key)||o.set(u[r.id]?.key,[]),o.get(u[r.id]?.key).push(t)}else o.has("All samples")||o.set("All samples",[]),o.get("All samples").push(t)}return{key2values:o,minMaxValues:{min:i,max:a},uncomputableValueObj:b(l),skipNonPositiveCount:c}}(t,v,l,t.divideTw),_=function(t,e,n){const r=n.divideTw,s={min:t.minMaxValues.min,max:t.minMaxValues.max,plots:[],pvalues:[],uncomputableValueObj:Object.keys(t.uncomputableValueObj).length>0?t.uncomputableValueObj:null};for(const[n,o]of function(t,e,n){const r=t.refs.byTermId[n?.term?.id]?.orderedLabels;return e=new Map([...e].sort(r?(t,e)=>r.indexOf(t[0])-r.indexOf(e[0]):"categorical"===n?.term?.type?(t,e)=>e[1].length-t[1].length:"condition"===n?.term?.type?(t,e)=>t[0]-e[0]:(t,e)=>t.toString().replace(/[^a-zA-Z0-9<]/g,"").localeCompare(e.toString().replace(/[^a-zA-Z0-9<]/g,""),void 0,{numeric:!0}))),e}(e,t.key2values,r))r?s.plots.push({label:r?.term?.values?.[n]?.label||n,values:o,seriesId:n,plotValueCount:o?.length,color:r?.term?.values?.[n]?.color||null,divideTwBins:y(r,e).has(n)?y(r,e).get(n):null,uncomputableValueObj:Object.keys(t.uncomputableValueObj).length>0?t.uncomputableValueObj:null}):s.plots.push({label:"All samples",values:o,plotValueCount:o.length});return s}(w,v,t);if(await async function(t,e){if(!t)return;const n=e.plots.length;if(n<2)return;const s=[];for(let t=0;t<n;t++){const r=e.plots[t].label,o=e.plots[t].values;for(let i=t+1;i<n;i++){const t=e.plots[i].label,n=e.plots[i].values;s.push({group1_id:r,group1_values:o,group2_id:t,group2_values:n})}}const o=c().join(i().cachedir,Math.random().toString()+".json");await(0,u.Sf)(o,JSON.stringify(s));const l=await(0,a.default)(c().join(i().binpath,"utils/wilcoxon.R"),[],[o]);(0,r.unlink)(o,(()=>{}));const f=JSON.parse(l);for(const t of f)null==t.pvalue||"null"==t.pvalue?e.pvalues.push([{value:t.group1_id},{value:t.group2_id},{html:"NA"}]):e.pvalues.push([{value:t.group1_id},{value:t.group2_id},{html:t.pvalue.toPrecision(4)}])}(t.divideTw,_),function(t,e,n){t.radius||(t.radius=5);if(t.radius<=0)throw"q.radius is not a number";t.radius=+t.radius;t.strokeWidth||(t.strokeWidth=.2);const r=4*t.radius;let o;const i="log"==t.unit;o=i?(0,s.scaleLog)().base(n.cohort.termdb.logscaleBase2?2:10).domain([e.min,e.max]).range("horizontal"===t.orientation?[0,t.svgw]:[t.svgw,0]):(0,s.scaleLinear)().domain([e.min,e.max]).range("horizontal"===t.orientation?[0,t.svgw]:[t.svgw,0]);const[a,l]="horizontal"==t.orientation?[t.svgw*t.devicePixelRatio,r*t.devicePixelRatio]:[r*t.devicePixelRatio,t.svgw*t.devicePixelRatio],c=t.radius/t.devicePixelRatio,u=c*Math.PI;let f=0;for(const n of e.plots){const e=(0,d.createCanvas)(a,l),r=e.getContext("2d");r.strokeStyle="rgba(0,0,0,0.8)",r.lineWidth=t.strokeWidth/t.devicePixelRatio,r.globalAlpha=.5,r.fillStyle="#ffe6e6",1!=t.devicePixelRatio&&r.scale(t.devicePixelRatio,t.devicePixelRatio),"rug"===t.datasymbol?n.values.forEach((e=>{r.beginPath(),"horizontal"==t.orientation?(r.moveTo(+o(e),0),r.lineTo(+o(e),2*c)):(r.moveTo(0,+o(e)),r.lineTo(2*c,+o(e))),r.stroke()})):"bean"===t.datasymbol&&n.values.forEach((e=>{r.beginPath(),"horizontal"===t.orientation?r.arc(+o(e),t.radius,c,0,u):r.arc(t.radius,+o(e),c,0,u),r.fill(),r.stroke()})),n.src=e.toDataURL();const s=t.isKDE;n.density=(0,h.q)(o,n,s,t.ticks,t.bandwidth),n.summaryStats=(0,p.Z)(n.values),delete n.values}e.biggestBin=f}(t,_,n),!e)return _;e.send(_)}function y(t,e){const n=new Map,r=e.refs.byTermId[t?.term?.id]?.bins;if(r)for(const t of r)n.set(t.label,t);return n}function b(t){return Object.fromEntries(Object.entries(t).sort((([,t],[,e])=>t-e)))}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:t}){return async(e,n)=>{e.query;try{const r=t[e.query.genome],s=r.datasets[e.query.dslabel];if(!r)throw"invalid genome name";const o=await g(e.query,null,s,r);n.send(o)}catch(t){n.send({error:t?.message||t}),t instanceof Error&&t.stack&&console.log(t)}}}},6733:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>o,parseline:()=>i});var r=n(2273),s=n(8064);function o(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for CNV";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let s=r("gene");return-1==s?"gene missing from header":(n[s]="gene",s=r("cnv"),-1==s?"CNV missing from header":(n[s]="cnv",s=r("sample","sample_name","tumor_sample_barcode"),-1!=s&&(n[s]="sample"),s=r("patient","donor","target_case_id"),-1!=s&&(n[s]="patient"),s=r("disease"),-1!=s&&(n[s]="disease"),s=r("origin"),-1!=s&&(n[s]="origin"),s=r("sampletype","sample type","sample_type"),-1!=s&&(n[s]="sampletype"),e.cnv.header=n,e.cnv.loaded=!0,!1))}function i(t,e,n){if(""==e||"#"==e[0])return;const o=e.split("\t"),i={};for(let t=0;t<n.cnv.header.length;t++)i[n.cnv.header[t]]=o[t];if(!i.gene)return void n.cnv.badlines.push([t,"missing gene",o]);if(!i.cnv)return void n.cnv.badlines.push([t,"missing cnv value",o]);switch(i.cnv.toLowerCase()){case"amplification":case"gain":i.class=r.mclasscnvgain;break;case"deletion":case"loss":i.class=r.mclasscnvloss;break;case"loh":i.class=r.mclasscnvloh;break;default:n.cnv.badlines.push([t,"invalid cnv value: "+i.cnv,o]),i.class=null}if(!i.class)return;if(s.EJ(i,n,t,o,n.cnv.badlines))return;i.dt=r.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:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>o,parseline:()=>i});var r=n(2273),s=n(8064);function o(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for intragenic deletion";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let s=r("gene");if(-1==s)return"gene missing from header";if(n[s]="gene",s=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==s)return"isoform missing from header";if(n[s]="isoform",s=r("rnaposition"),-1!=s){if(n[s]="rnaposition",s=r("rnadellength"),-1==s)return"rnadellength is required when rnaPosition is used";n[s]="rnadellength"}if(s=r("chromosome","chr"),-1!=s){if(n[s]="chr",s=r("chr_start"),-1==s)return"chr_start is required when chr is used";if(n[s]="chrpos1",s=r("chr_stop"),-1==s)return"chr_stop is required when chr is used";n[s]="chrpos2"}return s=r("sample","sample_name","tumor_sample_barcode"),-1!=s&&(n[s]="sample"),s=r("patient","donor","target_case_id"),-1!=s&&(n[s]="patient"),s=r("disease"),-1!=s&&(n[s]="disease"),s=r("origin"),-1!=s&&(n[s]="origin"),s=r("sampletype","sample type","sample_type"),-1!=s&&(n[s]="sampletype"),e.del.header=n,e.del.loaded=!0,!1}function i(t,e,n){if(""==e||"#"==e[0])return;const o=e.split("\t"),i={};for(let t=0;t<n.del.header.length&&null!=o[t];t++)i[n.del.header[t]]=o[t];if(i.gene){if(i.rnaposition){let e=Number.parseInt(i.rnaposition);if(Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid rnaPosition value",o]);if(i.rnaposition=e,!i.rnadellength)return void n.del.badlines.push([t,"missing rnaDellength value",o]);if(e=Number.parseInt(i.rnadellength),Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid rnaDellength value",o]);i.rnadellength=e}if(i.chr){let e=Number.parseInt(i.chrpos1);if(Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid chr_start value",o]);if(i.chrpos1=e,e=Number.parseInt(i.chrpos2),Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid chr_stop value",o]);i.chrpos2=e}if(!s.EJ(i,n,t,o,n.del.badlines)){i.dt=r.dtdel,i.class=r.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([t,"missing gene",o])}},3602:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>o,parseline:()=>i});var r=n(2273),s=n(8064);function o(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for ITD";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let s=r("gene");if(-1==s)return"gene missing from header";if(n[s]="gene",s=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==s)return"isoform missing from header";if(n[s]="isoform",s=r("rnaposition"),-1!=s){if(n[s]="rnaposition",s=r("rnaduplength"),-1==s)return"rnaduplength is required when rnaposition is present";n[s]="rnaduplength"}if(s=r("chromosome","chr"),-1!=s){if(n[s]="chr",s=r("chr_start"),-1==s)return"chr_start is required when chr is present";if(n[s]="chrpos1",s=r("chr_stop"),-1==s)return"chr_stop is required when chr is present";n[s]="chrpos2"}return s=r("sample","sample_name","tumor_sample_barcode"),-1!=s&&(n[s]="sample"),s=r("patient","donor","target_case_id"),-1!=s&&(n[s]="patient"),s=r("disease"),-1!=s&&(n[s]="disease"),s=r("origin"),-1!=s&&(n[s]="origin"),s=r("sampletype","sample type","sample_type"),-1!=s&&(n[s]="sampletype"),e.itd.header=n,e.itd.loaded=!0,!1}function i(t,e,n){if(""==e||"#"==e[0])return;const o=e.split("\t"),i={};for(let t=0;t<n.itd.header.length&&null!=o[t];t++)i[n.itd.header[t]]=o[t];if(i.gene){if(i.rnaposition){let e=Number.parseInt(i.rnaposition);if(Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid rnaPosition value",o]);if(i.rnaposition=e,!i.rnaduplength)return void n.itd.badlines.push([t,"missing rnaDuplength value",o]);if(e=Number.parseInt(i.rnaduplength),Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid rnaDuplength value",o]);i.rnaduplength=e}if(i.chr){let e=Number.parseInt(i.chrpos1);if(Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid chr_start value",o]);if(i.chrpos1=e,e=Number.parseInt(i.chrpos2),Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid chr_stop value",o]);i.chrpos2=e}if(!s.EJ(i,n,t,o,n.itd.badlines)){i.dt=r.dtitd,i.class=r.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([t,"missing gene",o])}},8064:(t,e,n)=>{"use strict";n.d(e,{Dz:()=>s,EJ:()=>o});var r=n(2273);function s(t){if(!t)return null;const e={};for(const t in r.mclass)e[r.mclass[t].label.toUpperCase()]=t;return{genome:t,mclasslabel2key:e,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(t,e,n,s,o){let i=r.moriginsomatic;if(t.sampletype){switch(t.sampletype.toLowerCase()){case"relapse":i=r.moriginrelapse;break;case"germline":i=r.morigingermline}t.sample?t.patient||(t.patient=t.sample+" "+t.sampletype):t.patient&&(t.sample=t.patient+" "+t.sampletype)}else t.patient?t.sample?t.sampletype=t.sample:t.sample=t.sampletype=t.patient:t.sample&&(t.sampletype=t.sample);if(t.origin){switch(t.origin.toLowerCase()){case"r":case"relapse":i=r.moriginrelapse,t.isrim2=!0;break;case"g":case"germline":i=r.morigingermline,t.isrim1=!0;break;case"gp":case"germline pathogenic":i=r.morigingermlinepathogenic,t.isrim1=!0;break;case"gnp":case"germline nonpathogenic":case"germline non-pathogenic":i=r.morigingermlinenonpathogenic,t.isrim1=!0;break;case"s":case"somatic":case"diagnosis":i=r.moriginsomatic}}if(t.origin=i,!t.sample&&!t.patient)return;const a="no patient/individual name";if(t.patient?(e.patient2st[t.patient]||(e.patient2st[t.patient]={}),e.patient2st[t.patient][t.sampletype]=t.sample):(e.patient2st[a]||(e.patient2st[a]={}),e.patient2st[a][t.sampletype]=t.sample),t.sample&&t.disease)if(t.sample in e.sample2disease){if(t.disease!=e.sample2disease[t.sample])return e.snv.badlines.push([n,'conflict of disease types for sample "'+t.sample+'": '+t.disease+", "+e.sample2disease[t.sample],s]),!0}else e.sample2disease[t.sample]=t.disease;return!1}},5494:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>o,parseline:()=>i});var r=n(2273),s=n(8064);function o(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for snv/indel";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let s=r("annovar_gene","annovar_sj_gene","gene","genename","gene_symbol","hugo_symbol");return-1==s?"gene missing from header":(n[s]="gene",s=r("annovar_aachange","amino_acid_change","annovar_sj_aachange","aachange","protein_change","variant"),-1==s?"amino_acid_change missing from header":(n[s]="mname",s=r("annovar_class","class","mclass","variant_class","variant_classification","annovar_sj_class"),-1==s?"variant_class missing from header":(n[s]="class",s=r("chromosome","chr"),-1==s?"chromosome missing from header":(n[s]="chr",s=r("wu_hg19_pos","start","start_position","chr_position","position"),-1==s?"start missing from header":(n[s]="pos",s=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==s?"isoform missing from header":(n[s]="isoform",s=r("sample","sample_name","tumor_sample_barcode"),-1!=s&&(n[s]="sample"),s=r("patient","donor","target_case_id"),-1!=s&&(n[s]="patient"),s=r("quantitative_measurements"),-1!=s&&(n[s]="qmset"),s=r("mutant_reads_in_case","mutant_in_tumor","tumor_readcount_alt"),-1!=s&&(n[s]="maf_tumor_v1"),s=r("total_reads_in_case","total_in_tumor","tumor_readcount_total"),-1!=s&&(n[s]="maf_tumor_v2"),s=r("mutant_reads_in_control","mutant_in_normal","normal_readcount_alt"),-1!=s&&(n[s]="maf_normal_v1"),s=r("total_reads_in_control","total_in_normal","normal_readcount_total"),-1!=s&&(n[s]="maf_normal_v2"),s=r("cdna_change"),-1!=s&&(n[s]="cdna_change"),s=r("sampletype","sample type","sample_type"),-1!=s&&(n[s]="sampletype"),s=r("origin"),-1!=s&&(n[s]="origin"),s=r("cancer","disease","diagnosis"),-1!=s&&(n[s]="disease"),e.snv.header=n,e.snv.loaded=!0,!1))))))}function i(t,e,n){if(""==e||"#"==e[0])return;const o=e.split("\t"),i={};for(let t=0;t<n.snv.header.length&&null!=o[t];t++)i[n.snv.header[t]]=o[t];if(!i.gene)return void n.snv.badlines.push([t,"missing gene",o]);if("UNKNOWN"==i.gene.toUpperCase())return void n.snv.badlines.push([t,"gene name is UNKNOWN",o]);if(!i.isoform)return void n.snv.badlines.push([t,"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([t,"missing amino acid change",o]);if(!i.class)return void n.snv.badlines.push([t,"missing mutation class",o]);let a=n.mclasslabel2key[i.class.toUpperCase()];if(a)i.class=a;else{if(a=r.mclasstester(i.class),!a)return void n.snv.badlines.push([t,"wrong mutation class: "+i.class,o]);i.class=a}if(s.EJ(i,n,t,o,n.snv.badlines))return;if(!i.chr)return void n.snv.badlines.push([t,"missing chromosome",o]);if(0!=i.chr.toLowerCase().indexOf("chr")&&(i.chr="chr"+i.chr),!i.pos)return void n.snv.badlines.push([t,"missing chromosome position",o]);const l=Number.parseInt(i.pos);if(Number.isNaN(l))return void n.snv.badlines.push([t,"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 e=Number.parseInt(i.maf_tumor_v1),r=Number.parseInt(i.maf_tumor_v2);if(Number.isNaN(e)||Number.isNaN(r))return void n.snv.badlines.push([t,"invalid maf_tumor mutant and/or total read count",o]);i.maf_tumor={f:e/r,v1:e,v2:r}}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 e=Number.parseInt(i.maf_normal_v1),r=Number.parseInt(i.maf_normal_v2);if(Number.isNaN(e)||Number.isNaN(r))return void n.snv.badlines.push([t,"invalid maf_normal mutant and/or total read count",o]);i.maf_normal={f:e/r,v1:e,v2:r}}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=r.dtsnvindel,n.data[c].push(i)}},6279:(t,e,n)=>{"use strict";n.r(e),n.d(e,{duplicate:()=>a,parseheader:()=>o,parseline:()=>i});var r=n(8064),s=n(2273);function o(t,e,n){const r=t.toLowerCase().split("\t");if(r.length<=1)return"invalid file header for fusions";const s=(...t)=>{for(const e of t){const t=r.indexOf(e);if(-1!=t)return t}return-1};let o=s("gene_a","gene1","genea");return-1==o?"gene_a missing from header":(r[o]="gene1",o=s("gene_b","gene2","geneb"),-1==o?"gene_b missing from header":(r[o]="gene2",o=s("chr_a","chr1","chra"),-1==o?"chr_a missing from header":(r[o]="chr1",o=s("chr_b","chr2","chrb"),-1==o?"chr_b missing from header":(r[o]="chr2",o=s("pos_a","position_a","position1","posa"),-1==o?"pos_a missing from header":(r[o]="position1",o=s("pos_b","position_b","position2","posb"),-1==o?"pos_b missing from header":(r[o]="position2",o=s("isoform_a","refseq_a","refseq1","isoform1","sv_refseqa"),-1==o?"isoform_a missing from header":(r[o]="isoform1",o=s("isoform_b","refseq_b","refseq2","isoform2","sv_refseqb"),-1==o?"isoform_b missing from header":(r[o]="isoform2",o=s("strand_a","orta"),-1==o?"strand_a missing from header":(r[o]="strand1",o=s("strand_b","ortb"),-1==o?"strand_b missing from header":(r[o]="strand2",o=s("sample","sample_name","tumor_sample_barcode"),-1!=o&&(r[o]="sample"),o=s("patient","donor","target_case_id"),-1!=o&&(r[o]="patient"),o=s("sampletype","sample type","sample_type"),-1!=o&&(r[o]="sampletype"),o=s("disease"),-1!=o&&(r[o]="disease"),o=s("origin"),-1!=o&&(r[o]="origin"),n?(e.sv.loaded=!0,e.sv.header=r):(e.fusion.loaded=!0,e.fusion.header=r),!1))))))))))}function i(t,e,n,o){if(""==e||"#"==e[0])return;const i=e.split("\t"),a={},l=o?n.sv.header:n.fusion.header,c=o?n.sv.badlines:n.fusion.badlines;for(let t=0;t<l.length;t++)a[l[t]]=i[t];if(!a.chr1)return void c.push([t,"missing chr1",i]);if(0!=a.chr1.toLowerCase().indexOf("chr")&&(a.chr1="chr"+a.chr1),!a.chr2)return void c.push([t,"missing chr2",i]);0!=a.chr2.toLowerCase().indexOf("chr")&&(a.chr2="chr"+a.chr2);let u=a.position1;if(!u)return void c.push([t,"missing position1",i]);let f=Number.parseInt(u);if(Number.isNaN(f)||f<=0)c.push([t,"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([t,"invalid value for position2",i]);else if(a.position2=f,!r.EJ(a,n,t,i,c)){if(a.isoform1&&-1!=a.isoform1.indexOf(",")){const t=a.isoform1.split(",");a.isoform1=void 0;for(const e of t)""!=e&&(a.isoform1=e)}if(a.isoform2&&-1!=a.isoform2.indexOf(",")){const t=a.isoform2.split(",");a.isoform2=void 0;for(const e of t)""!=e&&(a.isoform2=e)}if(a.gene1||(a.isoform1=void 0),a.gene2||(a.isoform2=void 0),a.gene1){n.good++;const t={dt:o?s.dtsv:s.dtfusionrna,class:o?s.mclasssv:s.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}}]},e=n.geneToUpper?a.gene1.toUpperCase():a.gene1;n.data[e]||(n.data[e]=[]),n.data[e].push(t)}if(a.gene2&&a.gene2!=a.gene1){n.good++;const t={dt:o?s.dtsv:s.dtfusionrna,class:o?s.mclasssv:s.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}}]},e=n.geneToUpper?a.gene2.toUpperCase():a.gene2;n.data[e]||(n.data[e]=[]),n.data[e].push(t)}}}else c.push([t,"missing position2",i])}function a(t){const e={};for(const n in t){if("pairlst"==n)continue;const r=t[n];"object"!=typeof r&&(e[n]=r)}if(t.pairlst){e.pairlst=[];for(const n of t.pairlst){const t={};for(const e in n)"a"!=e&&"b"!=e&&"interstitial"!=e&&(t[e]=n[e]);if(n.a){t.a={};for(const e in n.a){const r=n.a[e];"object"!=typeof r&&(t.a[e]=r)}}if(n.b){t.b={};for(const e in n.b){const r=n.b[e];"object"!=typeof r&&(t.b[e]=r)}}if(n.interstitial){t.interstitial={};for(const e in n.interstitial){const r=n.interstitial[e];"object"!=typeof r&&(t.interstitial[e]=r)}}e.pairlst.push(t)}}return e}},8423:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>o,parseline:()=>i});var r=n(2273),s=n(8064);function o(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for svjson";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let s=r("sample");return-1!=s&&(n[s]="sample"),s=r("sampletype"),-1!=s&&(n[s]="sampletype"),s=r("patient"),-1!=s&&(n[s]="patient"),s=r("json","jsontext"),-1==s?["json missing from header"]:(n[s]="jsontext",[null,n])}function i(t,e,n,o){if(""==e||"#"==e[0])return;const i=e.split("\t"),l={},c=n.svjson.badlines;for(let t=0;t<o.length;t++)l[o[t]]=i[t];if(!l.jsontext)return void c.push([t,"missing jsontext",i]);if(s.EJ(l,n,t,i,c))return;let u;try{u=JSON.parse(l.jsontext)}catch(e){return void c.push([t,"invalid JSON text",i])}if(Array.isArray(u))for(const t of u){if(t.a&&t.a.name&&t.a.isoform){n.good++;const e={dt:r.dtfusionrna,class:r.mclassfusionrna,isoform:t.a.isoform,mname:t.b.name};for(const t in l)"jsontext"!=t&&(e[t]=l[t]);e.pairlst=a(u);const s=t.a.name.toUpperCase();n.data[s]||(n.data[s]=[]),n.data[s].push(e)}if(t.b&&t.b.name&&t.b.isoform){n.good++;const e={dt:r.dtfusionrna,class:r.mclassfusionrna,isoform:t.b.isoform,mname:t.a.name};for(const t in l)"jsontext"!=t&&(e[t]=l[t]);e.pairlst=a(u);const s=t.b.name.toUpperCase();n.data[s]||(n.data[s]=[]),n.data[s].push(e)}}else{switch(u.dt=u.typecode,delete u.typecode,u.dt){case r.dtitd:u.class=r.mclassitd,u.mname="ITD";break;case r.dtnloss:u.class=r.mclassnloss,u.mname="N-loss";break;case r.dtcloss:u.class=r.mclasscloss,u.mname="C-loss";break;case r.dtdel:u.class=r.mclassdel,u.mname="Del";break;case r.dtsv:u.class=r.mclasssv,u.mname="SV";break;default:return void c.push([t,"unknown datatype",i])}if(!u.gene)return void c.push([t,"json.gene missing",i]);n.good++;for(const t in l)"jsontext"!=t&&(u[t]=l[t]);const e=(n.geneToUpper,u.gene.toUpperCase());n.data[e]||(n.data[e]=[]),n.data[e].push(u)}}function a(t){const e=[];for(const n of t){const t={a:{},b:{}};for(const e in n)"a"!=e&&"b"!=e&&(t[e]=n[e]);for(const e in n.a)t.a[e]=n.a[e];for(const e in n.b)t.b[e]=n.b[e];e.push(t)}return e}},8235:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>o,parseline:()=>i});var r=n(2273),s=n(8064);function o(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for truncation";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let s=r("gene");if(-1==s)return"gene missing from header";if(n[s]="gene",s=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==s)return"isoform missing from header";n[s]="isoform";let o=!1;if(s=r("rnaposition"),-1!=s&&(n[s]="rnaposition",o=!0),s=r("losstype"),-1==s)return"lossType missing from header";n[s]="losstype";let i=!1;if(s=r("chromosome","chr"),-1!=s){if(n[s]="chr",s=r("start","start_position","wu_hg19_pos","chr_position","position"),-1==s)return"genomic position missing from header";n[s]="pos",i=!0}return o||i?(s=r("sample","sample_name","tumor_sample_barcode"),-1!=s&&(n[s]="sample"),s=r("patient","donor","target_case_id"),-1!=s&&(n[s]="patient"),s=r("disease"),-1!=s&&(n[s]="disease"),s=r("origin"),-1!=s&&(n[s]="origin"),s=r("sampletype","sample type","sample_type"),-1!=s&&(n[s]="sampletype"),e.truncation.header=n,e.truncation.loaded=!0,!1):"neither rnaposition nor genomic position is given"}function i(t,e,n){if(""==e||"#"==e[0])return;const o=e.split("\t"),i={};for(let t=0;t<n.truncation.header.length;t++)i[n.truncation.header[t]]=o[t];if(!i.gene)return void n.truncation.badlines.push([t,"missing gene",o]);if(i.rnaposition){const e=Number.parseInt(i.rnaposition);if(Number.isNaN(e)||e<0)return void n.truncation.badlines.push([t,"invalid rnaPosition value",o]);i.rnaposition=e}if(i.pos){const e=Number.parseInt(i.pos);if(Number.isNaN(e)||e<0)return void n.truncation.badlines.push([t,"invalid genomic position",o]);i.pos=e}if(!i.losstype)return void n.truncation.badlines.push([t,"missing lossType value",o]);if("n"!=i.losstype&&"c"!=i.losstype)return void n.truncation.badlines.push([t,'lossType value not "n" or "c"',o]);if(s.EJ(i,n,t,o,n.truncation.badlines))return;"n"==i.losstype?(i.dt=r.dtnloss,i.class=r.mclassnloss,i.mname="N-loss"):(i.dt=r.dtcloss,i.class=r.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:(t,e,n)=>{"use strict";n.r(e),n.d(e,{IN_frame:()=>c,OUT_frame:()=>u,alleleInGenotypeStr:()=>mt,applyOverrides:()=>U,basecolor:()=>it,basecompliment:()=>at,bplen:()=>ot,codon:()=>nt,codon_stop:()=>rt,contigNameNoChr:()=>dt,contigNameNoChr2:()=>ht,custommdstktype:()=>et,default_text_color:()=>a,defaultcolor:()=>i,dt2color:()=>Z,dt2label:()=>x,dtcloss:()=>v,dtcnv:()=>p,dtdel:()=>y,dtfusionrna:()=>d,dtgeneexpression:()=>h,dtitd:()=>g,dtloh:()=>w,dtnloss:()=>b,dtsnvindel:()=>f,dtsv:()=>m,exoncolor:()=>l,fasta2gmframecheck:()=>ut,germlinelegend:()=>G,getColorScheme:()=>kt,getColors:()=>qt,getMax_byiqr:()=>pt,gmmode:()=>gt,kernelDensityEstimator:()=>vt,kernelEpanechnikov:()=>wt,mclass:()=>k,mclasscloss:()=>A,mclasscnvgain:()=>R,mclasscnvloh:()=>P,mclasscnvloss:()=>F,mclassdel:()=>N,mclassdeletion:()=>z,mclassfusionrna:()=>O,mclassinsertion:()=>$,mclassitd:()=>q,mclassmnv:()=>L,mclassnloss:()=>S,mclassnoncoding:()=>j,mclassnonstandard:()=>C,mclasssnv:()=>D,mclasssv:()=>I,mclasstester:()=>E,mclassutr3:()=>M,mclassutr5:()=>T,mdsvcftype:()=>tt,morigin:()=>J,morigingermline:()=>W,morigingermlinenonpathogenic:()=>K,morigingermlinepathogenic:()=>Y,moriginrelapse:()=>V,moriginsomatic:()=>H,not_annotated:()=>bt,nt2aa:()=>st,plotColor:()=>_,proteinChangingMutations:()=>St,reversecompliment:()=>lt,schemeCategory2:()=>xt,schemeCategory20:()=>_t,spliceeventchangegmexon:()=>ct,tkt:()=>X,truncatingMutations:()=>Nt,validate_vcfinfofilter:()=>ft,validtkt:()=>Q,vcfcopymclass:()=>yt,vepinfo:()=>B});var r=n(1495);const s=n(4635),o=n(3016),i=(0,r.B8)("#8AB1D4").darker(),a=(0,r.B8)("#aaa").darker().darker(),l="#4F8053",c=!0,u=!1,f=1,d=2,h=3,p=4,m=5,g=6,y=7,b=8,v=9,w=10,_="#ce768e",x={[f]:"SNV/indel",[d]:"Fusion RNA",[p]:"CNV",[m]:"SV",[g]:"ITD",[y]:"Deletion",[b]:"N-loss",[v]:"C-loss",[w]:"LOH",[h]:"Gene Expression"},k={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"}},q="ITD";k[q]={label:"ITD",color:"#ff70ff",dt:g,desc:"In-frame internal tandem duplication.",key:q};const N="DEL";k[N]={label:"DELETION, intragenic",color:"#858585",dt:y,desc:"Intragenic deletion.",key:N};const S="NLOSS";k[S]={label:"N-terminus loss",color:"#545454",dt:b,desc:"N-terminus loss due to translocation",key:S};const A="CLOSS";k[A]={label:"C-terminus loss",color:"#545454",dt:v,desc:"C-terminus loss due to translocation",key:A};const M="Utr3";k[M]={label:"UTR_3",color:"#998199",dt:f,desc:"A variant in the 3' untranslated region.",key:M};const T="Utr5";k[T]={label:"UTR_5",color:"#819981",dt:f,desc:"A variant in the 5' untranslated region.",key:T};const C="X";k[C]={label:"NONSTANDARD",color:"black",dt:f,desc:"A mutation class that either does not match our notation, or is unspecified.",key:C};const j="noncoding";function E(t){switch(t.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 j;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 C;case"3'utr":return M;case"5'utr":return T;case"blank":return"Blank";default:return null}}k[j]={label:"NONCODING",color:"black",dt:f,desc:"Noncoding mutation.",key:j};const O="Fuserna";k[O]={label:"Fusion transcript",color:"#545454",dt:d,desc:"Marks the break points leading to fusion transcripts.<br><span style=\"font-size:150%\">&#9680;</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%\">&#9681;</span> - 5' end of the break point is fused to the 3' end of another break point in a different gene.",key:O};const I="SV";k[I]={label:"Structural variation",color:"#858585",dt:m,desc:"Structural variation detected in genomic DNA.",key:I};const R="CNV_amp";k[R]={label:"Copy number gain",color:"#e9a3c9",dt:p,desc:"Copy number gain",key:R};const F="CNV_loss";k[F]={label:"Copy number loss",color:"#a1d76a",dt:p,desc:"Copy number loss",key:F};const P="CNV_loh";k[P]={label:"LOH",color:"#12EDFC",dt:p,desc:"Loss of heterozygosity",key:P};const D="snv";k[D]={label:"SNV",color:"#92a2d4",dt:f,desc:"Single nucleotide variation",key:D};const L="mnv";k[L]={label:"MNV",color:"#92a2d4",dt:f,desc:"Multiple nucleotide variation",key:L};const $="insertion";k[$]={label:"Sequence insertion",color:"#bd8e91",dt:f,desc:"Sequence insertion",key:$};const z="deletion";k[z]={label:"Sequence deletion",color:"#b5a174",dt:f,desc:"Sequence deletion",key:z};const Z={[f]:k.M.color};function U(t={}){if(t.mclass)for(const e in t.mclass){k[e]||(k[e]={});for(const n in t.mclass[e])k[e][n]=t.mclass[e][n]}}const B=function(t){const e=t.toLowerCase().split(",");let n=1;return-1!=e.indexOf("transcript_ablation")?[y,N,n]:(n++,-1!=e.indexOf("splice_acceptor_variant")?[f,"L",n]:(n++,-1!=e.indexOf("splice_donor_variant")?[f,"L",n]:(n++,-1!=e.indexOf("stop_gained")?[f,"N",n]:(n++,-1!=e.indexOf("frameshift_variant")?[f,"F",n]:(n++,-1!=e.indexOf("stop_lost")?[f,"N",n]:(n++,-1!=e.indexOf("start_lost")?[f,"N",n]:(n++,-1!=e.indexOf("transcript_amplification")?[f,C,n]:(n++,-1!=e.indexOf("inframe_insertion")||-1!=e.indexOf("conservative_inframe_insertion")||-1!=e.indexOf("disruptive_inframe_insertion")?[f,"I",n]:(n++,-1!=e.indexOf("inframe_deletion")||-1!=e.indexOf("conservative_inframe_deletion")||-1!=e.indexOf("disruptive_inframe_deletion")?[f,"D",n]:(n++,-1!=e.indexOf("missense_variant")?[f,"M",n]:(n++,-1!=e.indexOf("protein_altering_variant")?[f,"N",n]:(n++,-1!=e.indexOf("splice_region_variant")?[f,"P",n]:(n++,-1!=e.indexOf("incomplete_terminal_codon_variant")?[f,"N",n]:(n++,-1!=e.indexOf("stop_retained_variant")?[f,"S",n]:(n++,-1!=e.indexOf("synonymous_variant")?[f,"S",n]:(n++,-1!=e.indexOf("coding_sequence_variant")?[f,C,n]:(n++,-1!=e.indexOf("mature_mirna_variant")?[f,"E",n]:(n++,-1!=e.indexOf("5_prime_utr_variant")?[f,T,n]:(n++,-1!=e.indexOf("3_prime_utr_variant")?[f,M,n]:(n++,-1!=e.indexOf("non_coding_transcript_exon_variant")?[f,"E",n]:(n++,-1!=e.indexOf("intron_variant")?[f,"Intron",n]:(n++,-1!=e.indexOf("nmd_transcript_variant")?[f,"S",n]:(n++,-1!=e.indexOf("non_coding_transcript_variant")?[f,"E",n]:(n++,-1!=e.indexOf("upstream_gene_variant")?[f,j,n]:(n++,-1!=e.indexOf("downstream_gene_variant")?[f,j,n]:(n++,-1!=e.indexOf("tfbs_ablation")?[f,j,n]:(n++,-1!=e.indexOf("tfbs_amplification")?[f,j,n]:(n++,-1!=e.indexOf("tf_binding_site_variant")?[f,j,n]:(n++,-1!=e.indexOf("regulatory_region_ablation")?[f,j,n]:(n++,-1!=e.indexOf("regulatory_region_amplification")?[f,j,n]:(n++,-1!=e.indexOf("feature_elongation")?[f,j,n]:(n++,-1!=e.indexOf("regulatory_region_variant")?[f,j,n]:(n++,-1!=e.indexOf("feature_truncation")?[f,j,n]:(n++,-1!=e.indexOf("intergenic_variant")?[f,j,n]:(n++,[f,C,n])))))))))))))))))))))))))))))))))))},G='<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>',J={},H="S";J[H]={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 W="G";J[W]={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:G},J.germline=J[W],J.somatic=J[H];const V="R";J[V]={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 Y="GP";J[Y]={label:"Germline pathogenic",desc:"A constitutional variant with pathogenic allele.",legend:G};const K="GNP";J[K]={label:"Germline non-pathogenic",desc:"A constitutional variant with non-pathogenic allele.",legend:G,hidden:!0};const X={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(t){for(const e in X)if(t==X[e])return!0;return!1}const tt={vcf:"vcf"},et={vcf:"vcf",svcnvitd:"svcnvitd",geneexpression:"geneexpression"},nt={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"},rt="*";function st(t){if(!t.genomicseq)return;const e=[];if(t.coding)for(const[n,r]of t.coding.entries()){const n=t.genomicseq.substr(r[0]-t.start,r[1]-r[0]);"-"==t.strand?e.push(lt(n)):e.push(n)}const n=e.join(""),r=[];for(let e=t.startCodonFrame?3-t.startCodonFrame:0;e<n.length;e+=3){const t=nt[n.substr(e,3)];r.push(t||rt)}return t.cdseq=n,r.join("")}function ot(t,e){return t>=1e9?(t/1e9).toFixed(1)+" Gb":t>=1e7?Math.ceil(t/1e6)+" Mb":t>=1e6?(t/1e6).toFixed(1)+" Mb":t>=1e4?Math.ceil(t/1e3)+" Kb":t>=1e3?(t/1e3).toFixed(1)+" Kb":t+(e?"bytes":" bp")}const it={A:"#ca0020",T:"#f4a582",C:"#92c5de",G:"#0571b0"};function at(t){switch(t){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 t}}function lt(t){const e=[];for(let n=t.length-1;n>=0;n--)e.push(at(t[n]));return e.join("")}function ct(t,e){const n={chr:t.chr,start:t.start,stop:t.stop,strand:t.strand,coding:[]};if(e.isskipexon||e.isaltexon)for(let r=0;r<t.exon.length;r++){const s=Math.max(t.codingstart,t.exon[r][0]),o=Math.min(t.codingstop,t.exon[r][1]);s>o||-1==e.skippedexon.indexOf(r)&&n.coding.push([s,o])}else if(e.a5ss||e.a3ss){const r=t.exon.map((t=>[t[0],t[1]])),s="+"==t.strand;e.a5ss?s?r[e.exon5idx][1]=e.junctionB.start:r[e.exon5idx+1][0]=e.junctionB.stop:s?r[e.exon5idx+1][0]=e.junctionB.stop:r[e.exon5idx][1]=e.junctionB.start;for(const e of r){const r=Math.max(t.codingstart,e[0]),s=Math.min(t.codingstop,e[1]);r>s||n.coding.push([r,s])}}return n}function ut(t,e){const n=e.split("\n");n.shift(),t.genomicseq=n.join("").toUpperCase();const r=st(t);let s=u;return r.indexOf(rt)==r.length-1&&(s=c),s}function ft(t){if(!t.lst)return".lst missing";if(!Array.isArray(t.lst))return"input is not an array";for(const e of t.lst){if(!e.name)return"name missing from a set of .vcfinfofilter.lst";if(e.autocategory||e.categories){if(!e.autocategory)for(const t in e.categories){const n=e.categories[t];if(!e.autocolor&&!n.color)return".color missing for class "+t+" from .categories of set "+e.name;n.label||(n.label=t)}if(e.categoryhidden){for(const t in e.categoryhidden)if(!e.categories[t])return"unknown hidden-by-default category "+t+" from set "+e.name}else e.categoryhidden={}}else if(e.numericfilter){const t=[];for(const n of e.numericfilter)"number"==typeof n?t.push({side:"<",value:n}):t.push({side:n.side||"<",value:n.value});e.numericfilter=t}if(e.altalleleinfo){if(!e.altalleleinfo.key)return".key missing from .altalleleinfo from set "+e.name}else{if(!e.locusinfo)return"neither .altalleleinfo or .locusinfo is available from set "+e.name;if(!e.locusinfo.key)return".key missing from .locusinfo from set "+e.name}}}function dt(t,e){for(const n in t.majorchr)if(-1!=e.indexOf(n.replace("chr","")))return!0;if(t.minorchr)for(const n in t.minorchr)if(-1!=e.indexOf(n.replace("chr","")))return!0;return!1}function ht(t,e){let n=0,r=0;for(const s in t.majorchr)e.includes(s)?r++:e.includes(s.replace("chr",""))&&n++;if(t.minorchr)for(const s in t.minorchr)e.includes(s)?r++:e.includes(s.replace("chr",""))&&n++;return[n,r]}function pt(t,e){if(0==t.length)return e;t.sort(((t,e)=>t-e));const n=t[t.length-1];if(t.length<=5)return n;const r=t[Math.floor(t.length/4)],s=t[Math.floor(3*t.length/4)];return Math.min(s+1.5*(s-r),n)}function mt(t,e){return!!t&&(-1!=t.indexOf("/")?-1!=t.split("/").indexOf(e):-1!=t.split("|").indexOf(e))}const gt={genomic:"genomic",splicingrna:"splicing RNA",exononly:"exon only",protein:"protein",gmsum:"aggregated exons"};function yt(t,e){if(t.csq){let n;if(e.usegm&&(n=t.csq.find((t=>t._isoform==e.usegm.isoform))),!n&&(n=t.csq.find((t=>t.CANONICAL)),!n)){n=t.csq[0];for(const e of t.csq)e._csqrank<n._csqrank&&(n=e)}n&&(t.gene=n._gene,t.isoform=n._isoform,t.class=n._class,t.dt=n._dt,t.mname=n._mname,t.class==j&&delete t.class)}else if(t.ann){let n=null;if(e.usegm){for(const r of t.ann)r._isoform==e.usegm.isoform&&(n?r._csqrank<n._csqrank&&(n=r):n=r);n||e.gmmode!=gt.genomic||(n=t.ann[0])}else{n=t.ann[0];for(const e of t.ann)e._csqrank<n._csqrank&&(n=e)}n&&(t.gene=n._gene,t.isoform=n._isoform,t.class=n._class,t.dt=n._dt,t.mname=n._mname,t.class==j&&delete t.class)}null==t.class&&(k[t.type]?(t.class=t.type,t.dt=k[t.type].dt,t.mname=t.id&&"."!=t.id?t.id:t.ref+">"+t.alt,t.mname.length>15&&(t.mname=t.type)):(t.class=C,t.dt=f,t.mname=t.type)),delete t.type}const bt="Unannotated";function vt(t,e){return function(n){return e.map((e=>[e,n.map((n=>t(e-n))).reduce(((t,e)=>t+e),0)/n.length]))}}function wt(t){return function(e){return Math.abs(e/=t)<=1?.75*(1-e*e)/t:0}}const _t=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],xt=["#e75480","blue"];function kt(t){return t>12?_t:t>8?o.schemePaired:t>2?o.schemeDark2:xt}function qt(t){return s.scaleOrdinal(kt(t))}const Nt=["F","N","D","I","L"],St=["F","N","D","I","L","M","P"]},7027:(t,e,n)=>{"use strict";function r(t,e){t.sort(((t,e)=>t-e));const n=Math.abs(e/100*t.length-1);return Number.isInteger(n)?(t[n]+t[n+1])/2:t[Math.ceil(n)]}n.d(e,{Z:()=>r})},8615:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(7027);function s(t,e){const n=Number(t);return Number.isInteger(n)?n:Math.abs(n)<1?Number(n.toPrecision(e)):Number(n.toFixed(e))}function o(t){let e=t;"string"==typeof t[0]&&(e=t.map(Number));const n=e.length;function o(t){return t.reduce(((t,e)=>t+e))/n}const i=(0,r.Z)(e,50),a=e.map((t=>(t-o(e))**2)).reduce(((t,e)=>t+e),0)/(n-1),l=Math.sqrt(a),c=(0,r.Z)(e,25),u=(0,r.Z)(e,75),f=u-c,d=Math.min(...e),h=Math.max(...e);return{values:[{id:"total",label:"Total",value:n},{id:"min",label:"Minimum",value:s(d,2)},{id:"p25",label:"1st quartile",value:s(c,2)},{id:"median",label:"Median",value:s(i,2)},{id:"mean",label:"Mean",value:s(o(e),2)},{id:"p75",label:"3rd quartile",value:s(u,2)},{id:"max",label:"Maximum",value:s(h,2)},{id:"SD",label:"Standard deviation",value:s(l,2)},{id:"variance",label:"Variance",value:s(a,2)},{id:"IQR",label:"Inter-quartile range",value:s(f,2)}]}}},478:(t,e,n)=>{"use strict";function r(t){if(!t||0==t.length)return;let e=JSON.parse(JSON.stringify(t[0]));if(1==t.length)return e;if(e.lst.length<2){if(""!==e.join)throw'filter.join must be an empty string "" when filter.lst.length < 2';e.join="and"}else if("or"==e.join)e={type:"tvslst",join:"and",in:!0,lst:[e]};else if("and"!=e.join)throw'filter.join must be either "and" or "or" when .lst length > 1';for(let n=1;n<t.length;n++){const r=JSON.parse(JSON.stringify(t[n]));"or"==r.join?e.lst.push(r):e.lst.push(...r.lst)}return 1==e.lst.length&&"tvs"==e.lst[0].type&&(e.join=""),e}n.d(e,{xH:()=>r})},4048:(t,e,n)=>{"use strict";n.d(e,{gp:()=>a});var r=n(2163),s=n(2273);function o(t){return!isNaN(parseFloat(t))&&isFinite(t)}function i(t,e,n,r,s){if(r>=1){const e=Math.floor(t*r);return s?`${e}${n.charAt(0)}`:`${e} ${e>1?n+"s":""}`}const o=Math.floor(t*r),i=Math.ceil(t%(1/r));return 0==i?s?`${o}${n.charAt(0)}`:`${o} ${o>1?n+"s":""}`:s?`${o}${n.charAt(0)}${i}${e.charAt(0)}`:`${o} ${o>1?n+"s":""} ${i} ${i>1?e+"s":""}`}function a(t,e,n){const r=t;if(function(t){const e=t;if(!e||"object"!=typeof e)throw"bin schema must be an object";if("type"in e||(e.type="regular-bin"),"custom-bin"==e.type){if(!Array.isArray(e.lst))throw"binconfig.lst must be an array";if(!e.lst.length)throw"binconfig.lst must have entries";const t=e.lst[0],n=e.lst[e.lst.length-1];for(const r of e.lst){if(!("startinclusive"in r)&&!("stopinclusive"in r))throw"custom bin.startinclusive and/or bin.stopinclusive must be defined";if(r==t){if("startunbounded"in r&&!r.startunbounded)throw"a custom first bin must not set bin.startunbounded to false";if(r.startunbounded=!0,"start"in r)throw"a custom first bin must not set a bin.start value";if("start_percentile"in r)throw"the first bin must not set a bin.start_percentile value";if(!("stop"in r))throw"a custom first bin must define a bin.stop value";if(!o(r.stop))throw"a custom first bin.stop value should be numeric"}else if(r==n){if(!("start"in r))throw"a custom last bin must define a bin.start value";if(!o(r.start))throw"a custom last bin.start must be numeric";if("stopunbounded"in r&&!r.stopunbounded)throw"a custom last bin must not set bin.stopunbounded to false";if(r.stopunbounded=!0,"stop"in r)throw"a custom last bin must not set a bin.stop value"}else{if(!o(r.start))throw"bin.start must be numeric for a non-first bin";if(!o(r.stop))throw"bin.stop must be numeric for a non-last bin"}}}else{if("regular-bin"!=e.type)throw`invalid binconfig.type="${e.type}"`;if(!Number.isFinite(e.bin_size))throw"non-numeric bin_size";if(e.bin_size<=0)throw"bin_size must be greater than 0";if(e.startinclusive||e.stopinclusive||(e.startinclusive=1,e.stopinclusive=0),!e.first_bin)throw"first_bin{} missing";if("object"!=typeof e.first_bin)throw"first_bin{} is not an object";if(!Object.keys(e.first_bin).length)throw"first_bin is an empty object";{const t=e.first_bin;if(t.startunbounded=!0,t.stop_percentile){if(!Number.isInteger(t.stop_percentile))throw"first_bin.stop_percentile should be integer";if(t.stop_percentile<=0||t.stop_percentile>=100)throw"first_bin.stop_percentile out of bound (0-100)"}else if(!Number.isFinite(t.stop))throw"first_bin.stop not a number when stop_percentile is not set"}if(e.last_bin){const t=e.last_bin;if(t.start_percentile){if(!Number.isInteger(t.start_percentile))throw"last_bin.start_percentile should be integer";if(t.start_percentile<=0||t.start_percentile>=100)throw"last_bin.start_percentile out of bound (0-100)"}else if(!Number.isFinite(t.start))throw"last_bin.start not a number when start_percentile is not set";if(t.stopunbounded=!0,"stop"in t)throw"a regular last bin must not set a bin.stop value"}}}(r),r.lst){const t=(0,s.getColors)(r.lst.length);for(const e of r.lst)e.color=t(e.label)}if("custom-bin"==r.type)return JSON.parse(JSON.stringify(r.lst));if("function"!=typeof e)throw"summaryfxn required for modules/termdb.bins.js compute_bins()";const i=function(t){const e=[],n=t.first_bin;n&&o(n.start_percentile)&&e.push(n.start_percentile);n&&o(n.stop_percentile)&&e.push(n.stop_percentile);const r=t.last_bin;r&&o(r.start_percentile)&&e.push(r.start_percentile);r&&o(r.stop_percentile)&&e.push(r.stop_percentile);return e}(r),a=e(i);if(!a||"object"!=typeof a)throw"invalid returned value by summaryfxn";r.results={summary:a},r.binLabelFormatter||(r.binLabelFormatter=l(r));const u=Math.floor(100*a.min)/100,f=Math.ceil(100*a.max)/100,d=r.first_bin.startunbounded?u:r.first_bin.start_percentile?a["p"+r.first_bin.start_percentile]:r.first_bin.start;let h,p,m=f;if(r.last_bin)m=r.last_bin.stopunbounded?f:r.last_bin.stop_percentile?a["p"+r.last_bin.stop_percentile]:o(r.last_bin.stop)&&r.last_bin.stop<=a.max?r.last_bin.stop:f,h=o(r.last_bin.start_percentile)?a["p"+r.last_bin.start_percentile]:o(r.last_bin.start)?r.last_bin.start:void 0,p=r.last_bin.stopunbounded?null:r.last_bin.stop_percentile?a["p"+r.last_bin.stop_percentile]:o(r.last_bin.stop)?r.last_bin.stop:null;else if(r.lst){const t=r.lst[r.lst.length-1];h=t.start,p="stop"in t&&!t.stopunbounded?t.stop:f,m=p}else h=f,p=f;const g=o(m),y=o(h),b=o(p);if(!g&&!y)return[];const v=[];let w={startunbounded:r.first_bin.startunbounded,start:r.first_bin.startunbounded?void 0:d,stop:o(r.first_bin.stop_percentile)?+a["p"+r.first_bin.stop_percentile]:o(r.first_bin.stop)?+r.first_bin.stop:d+r.bin_size,startinclusive:r.startinclusive,stopinclusive:r.stopinclusive};if(!o(w.stop))throw"the computed first_bin.stop is non-numeric"+w.stop;for(;(g&&w.stop<=m||w.startunbounded&&!v.length||w.stopunbounded)&&(v.push(w),w.stop>=m&&(w.stopunbounded=!0,v.length>1&&delete w.stop),w.label=c(w,r,n),!w.stopunbounded);){const t=w.stop+r.bin_size,e=w.stop;if(w={startinclusive:r.startinclusive,stopinclusive:r.stopinclusive,start:e,stop:b&&(e==h||t>p)?p:y&&t>h&&e!=h?h:t},w.stop>=m&&(w.stop=m,r.last_bin&&r.last_bin.stopunbounded&&(w.stopunbounded=1),r.last_bin&&r.last_bin.stopinclusive&&(w.stopinclusive=1)),y&&w.start==h&&r.last_bin&&r.last_bin.stopunbounded&&(w.stopunbounded=1),w.start>w.stop){if(!(y&&w.stop==h&&r.last_bin&&r.last_bin.stopunbounded))break;w.stopunbounded=!0}if(v.length+1>=100){r.error="max_num_bins_reached";break}}delete r.binLabelFormatter,v.length>1&&delete v[v.length-1].stop;const _=(0,s.getColors)(v.length);for(const t of v)t.color=_(t.label);return v}function l(t){return"rounding"in t?(0,r.WU)(t.rounding):t=>t}function c(t,e,n){const r=e;r.binLabelFormatter||(r.binLabelFormatter=l(r)),t.startunbounded||t.stopunbounded||"startinclusive"in t||"stopinclusive"in t||(r.startinclusive?t.startinclusive=!0:r.stopinclusive&&(t.stopinclusive=!0));const s="bins"==r.use_as||t.start,o="bins"==r.use_as||t.stop;let a=0;if("label_offset"in r?(r.label_offset_ignored="bin_size"in r&&r.bin_size<r.label_offset,r.label_offset_ignored||(a=r.label_offset)):1===r.bin_size&&"integer"==r.termtype&&(a=1),t.startunbounded){return(t.stopinclusive?"≤":"<")+(n?i(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o))}if(t.stopunbounded||s===o){return(t.startinclusive?"≥":">")+(n?i(s,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(s))}if(a&&t.startinclusive&&!t.stopinclusive){if(Number.isInteger(r.bin_size)&&Math.abs(s-o)===a)return""+(n?i(s,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(s));{const t=n?i(s,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(s),e=n?i(o-a,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o-a);return+t>=+e?t.toString():t+" to "+e}}{const e=t.startinclusive?"":">",a=t.stopinclusive?"":"<",l=n?i(s,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(s)?s:r.binLabelFormatter(s),c=n?i(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(o)?o:r.binLabelFormatter(o);if(+l>=+c){return(t.startinclusive?"≥":">")+l}return e+l+" to "+a+c}}},1575:(t,e,n)=>{"use strict";n.d(e,{CG:()=>s});new Set(["snplst","prs","snplocus","geneVariant","samplelst"]);const r=new Set(["categorical","integer","float","condition","survival","snplst","snplocus","geneVariant","samplelst"]);function s(t,e,n){const s=e||{};if(n&&n.usecase&&use.target in n.usecase)return n.usecase[use.target](t,use);const a=new Set,l=t.child_types||[];switch(s.target){case"barchart":case"summary":case"matrix":return"term0"==s.detail&&"geneVariant"==t.type||("term2"==s.detail&&"geneVariant"==t.type&&"geneVariant"==s.term1type||(t.type&&"survival"!==t.type&&a.add("plot"),o(l)&&a.add("branch"))),a;case"table":return"term"==s.detail&&a.add("plot"),l.length>1&&a.add("branch"),a;case"scatterplot":return"float"!=t.type&&"integer"!=t.type||a.add("plot"),i(l)&&a.add("branch"),a;case"sampleScatter":return"numeric"==s.detail?("float"!=t.type&&"integer"!=t.type||a.add("plot"),i(l)&&a.add("branch")):(r.has(t.type)&&a.add("plot"),t.isleaf||a.add("branch")),a;case"boxplot":return"float"!=t.type&&"integer"!=t.type||a.add("plot"),"term2"===s.detail&&i(l)&&a.add("branch"),a;case"cuminc":if("term"==s.detail)return"condition"==t.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a;if("term2"===s.detail)return t.type&&"survival"!=t.type&&a.add("plot"),o(l)&&a.add("branch"),a;if("term0"==s.detail)return a.add("plot"),a;case"survival":return"term"==s.detail?("survival"==t.type&&a.add("plot"),l.includes("survival")&&a.add("branch"),a):"term2"===s.detail?("survival"!=t.type&&(t.type&&a.add("plot"),o(l)&&a.add("branch")),a):"term0"==s.detail?(t.type&&a.add("plot"),o(l)&&a.add("branch"),a):(t.isleaf?a.add("plot"):a.add("branch"),a);case"regression":if("outcome"==s.detail){if("linear"==s.regressionType)return"float"!=t.type&&"integer"!=t.type||a.add("plot"),i(l)&&a.add("branch"),a;if("logistic"==s.regressionType)return t.type&&"survival"!=t.type&&a.add("plot"),o(l)&&a.add("branch"),a;if("cox"==s.regressionType)return"condition"==t.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a}if("independent"==s.detail)return"float"!=t.type&&"integer"!=t.type&&"categorical"!=t.type||a.add("plot"),function(t,e){for(const n of e)if(t.includes(n))return!0}(l,["categorical","float","integer"])&&a.add("branch"),a;default:return r.has(t.type)&&a.add("plot"),t.isleaf||a.add("branch"),a}}function o(t){return!!t.length&&(t.length>1||"survival"!=t[0])}function i(t){return t.includes("float")||t.includes("integer")}},1881:(t,e,n)=>{"use strict";n.d(e,{N:()=>o});const r="root",s="...";function o(t,e){const n=Object.create(null),o=Object.create(null),a=Object.create(null);for(const r of t)for(const[t,s]of e.entries()){const l=i(r,t,e),c=i(r,t-1,e);if(!r[s.k]){t>0&&(a[c]+=1);break}if(n[l]=c,l in a||(a[l]=0),!(l in o)){const n={lst:[]};s.full&&(n.full=r[s.full]),n.id0=e[0].k,n.v0=r[e[0].k],1==t&&(n.id1=e[1].k,n.v1=r[e[1].k]),2==t&&(n.id2=e[2].k,n.v1=r[e[2].k]),o[l]=n}o[l].lst.push(r),t==e.length-1&&(a[l]+=1)}const l=[{id:r,name:r}];for(const t in n){const e=n[t],r=o[t],i=t.split(s);l.push({id:t,parentId:e,lst:r.lst,value:a[t],name:i[i.length-1],full:r.full,id0:r.id0,v0:r.v0,id1:r.id1,v1:r.v1,id2:r.id2,v2:r.v2})}return l}function i(t,e,n){const o=[r];for(let r=0;r<e;r++)o.push(t[n[r].k]);return e>=0&&o.push(t[n[e].k]),o.join(s)}},4298:(t,e,n)=>{"use strict";n.d(e,{A:()=>s});var r=n(2273);function s(t,e,n){if(!e)return null;for(const s of t.split(",")){const t=s.replace(/&/g,",").split("|"),o={};for(let n=0;n<e.length;n++)t[n]&&(o[e[n].name]=t[n]);if(!o.Allele)continue;let i=null;for(const t of n.mlst||n.alleles)if(t.allele_original==o.Allele){i=t;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 t of n.mlst||n.alleles)if(t.allele_original.substr(1)==o.Allele){i=t;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[t,e,n]=(0,r.vepinfo)(o.Consequence);o._dt=t,o._class=e,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:(t,e,n)=>{"use strict";function r(t){let e=!1,n=!0,r=0,s=0;const o={};let i;for(;r<t.length;){const a=t[r];n?"="==a?(e=!0,n=!1,i=t.substring(s,r),s=r+1):";"==a&&(o[t.substring(s,r)]=1,s=r+1):e&&";"==a&&(n=!0,e=!1,o[i]=t.substring(s,r),i=null,s=r+1),r++}const a=t.substr(s,r);return i?o[i]=a:o[a]=1,o}n.d(e,{w:()=>r})},6819:(t,e,n)=>{"use strict";n.d(e,{S:()=>d,e:()=>f});var r=n(2273),s=n(9380),o=n(4298);function a(t,e,n){if(!e)return null;for(const s of t.split(",")){const t=s.replace(/&/g,",").split("|"),o={};for(let n=0;n<e.length;n++)t[n]&&(o[e[n].name]=t[n]);if(!o.Allele)continue;let i=null;for(const t of n.alleles)if(t.allele==o.Allele){i=t;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[t,e,n]=(0,r.vepinfo)(o.Annotation);o._dt=t,o._class=e,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 t in r.mclass)u[r.mclass[t].label.toUpperCase()]=t;function f(t){let e=[],n=[],r={},s=!1,o={},i=!1;for(const a of t)if(a.startsWith("#"))if(a.startsWith("#C"))e=a.split("\t").slice(9);else if(a.startsWith("##INFO")){const t=p(a.substring(8,a.length-1),r);t?n.push("INFO error: "+t):s=!0}else if(a.startsWith("##FORMAT")){const t=p(a.substring(10,a.length-1),o);t?n.push("FORMAT error: "+t):i=!0}const a=[];for(const t of e){const e={name:t};a.push(e)}if(r.CSQ){const t=r.CSQ.Description.split(" Format: ");if(t[1]){const e=t[1].split("|");if(e.length>1){r.CSQ.csqheader=[];for(const t of e){const e={name:t};r.CSQ.csqheader.push(e)}}else n.push("unknown format for CSQ header: "+r.CSQ.Description)}else n.push("unknown format for CSQ header: "+r.CSQ.Description)}if(r.ANN){const t=r.ANN.Description.split("'");if(t[1]){const e=t[1].split(" | ");if(e.length){r.ANN.annheader=[];for(const t of e){const e={name:t};r.ANN.annheader.push(e)}}else n.push('no " | " joined annotation fields for ANN (snpEff annotation): '+r.ANN.Description)}else n.push("no single-quote enclosed annotation fields for ANN (snpEff annotation): "+r.ANN.Description)}return[s?r:null,i?o:null,a,n.length?n:null]}function d(t,e){const n=t.split("\t");if(n.length<8)return["line has less than 8 fields",null,null];const r=Number.parseInt(n[1]);if(!Number.isInteger(r))return["invalid value for genomic position",null,null];const i=n[3],u={vcf_ID:n[2],chr:(e.nochr?"chr":"")+n[0],pos:r-1,ref:i,altstr:n[4],alleles:[{allele:i,sampledata:[]}],info:{},name:"."==n[2]?null:n[2]},f=[];for(const t of n[4].split(",")){const e={ref:u.ref,allele:t,allele_original:t,sampledata:[],_m:u,info:{}};if(u.alleles.push(e),"<"==t[0]){const n=t.match(c);if(!n){f.push(t);continue}e.type=n[1],e.allele=n[1],e.issymbolicallele=!0}else{const[t,n,r]=h(u.pos,u.ref,e.allele);e.pos=t,e.ref=n,e.allele=r}}n[8]&&n[9]&&function(t,e,n){const r=t[8].split(":");for(let s=9;s<t.length;s++){const o=t[s].split(":");{let t=!0;for(const e of o)if("."!=e){t=!1;break}if(t)continue}const i=s-9;for(let t=1;t<e.alleles.length;t++){const r={};if(n.samples&&n.samples[i])for(const t in n.samples[i])r[t]=n.samples[i][t];else r.name="missing_samplename_from_vcf_header";e.alleles[t].sampledata.push({sampleobj:r})}for(let t=0;t<r.length;t++){const s=r[t],i=o[t];if("."==i)continue;if("GT"==s){const t=-1!=i.indexOf("/")?"/":"|";let n=0,r=!1;const s=[];for(const o of i.split(t)){if("."==o){r=!0;continue}const t=Number.parseInt(o);if(Number.isNaN(t)){r=!0;continue}n+=t;const i=e.alleles[t];i&&s.push(i.allele)}let o=!1;r||(o=0==n);const a=s.join(t);for(let t=1;t<e.alleles.length;t++){const n=e.alleles[t].sampledata[e.alleles[t].sampledata.length-1];n.GT=i,n.genotype=a,o&&(n.gtallref=!0),n.__gtalleles=s}continue}const a=n.format?n.format[s]:null;if(!a){for(let t=1;t<e.alleles.length;t++)e.alleles[t].sampledata[e.alleles[t].sampledata.length-1][s]=i;continue}const l="Integer"==a.Type,c="Float"==a.Type;if(a.Number&&"R"==a.Number||"AD"==s){const t=i.split(",").map((t=>l?Number.parseInt(t):c?Number.parseFloat(t):t));for(let n=1;n<e.alleles.length;n++)if(null!=t[n]){const r=e.alleles[n],o=r.sampledata[r.sampledata.length-1];o[s]={},o[s][r.ref]=t[0],o[s][r.allele]=t[n]}}else if(a.Number&&"A"==a.Number){const t=i.split(",").map((t=>l?Number.parseInt(t):c?Number.parseFloat(t):t));for(let n=1;n<e.alleles.length;n++)if(null!=t[n-1]){const r=e.alleles[n],o=r.sampledata[r.sampledata.length-1];o[s]={},o[s][r.allele]=t[n-1]}}else for(let t=1;t<e.alleles.length;t++)e.alleles[t].sampledata[e.alleles[t].sampledata.length-1][s]=i}}for(const t of e.alleles)for(const e of t.sampledata)if(e.AD){e.allele2readcount={};for(const t in e.AD)e.allele2readcount[t]=e.AD[t]}}(n,u,e),u.alleles.shift();const d="."==n[7]?[]:(0,s.w)(n[7]);let p=[];e.info?p=function(t,e,n){const r=[];for(const s in t){if(null==n.info[s]){r.push(s);continue}const i=t[s];if("CSQ"==s){(0,o.A)(i,n.info.CSQ.csqheader,e)||(e.info[s]=i);continue}if("ANN"==s){a(i,n.info.ANN.annheader,e)||(e.info[s]=i);continue}if("Flag"==n.info[s].Type){e.info[s]=s;continue}const l=n.info[s].Number,c="Integer"==n.info[s].Type,u="Float"==n.info[s].Type;if("0"==l){e.info[s]=s;continue}if("A"==l){const t=i.split(",");for(let n=0;n<t.length;n++)e.alleles[n]&&(e.alleles[n].info[s]=c?Number.parseInt(t[n]):u?Number.parseFloat(t[n]):t[n]);continue}if("1"==l){e.info[s]=c?Number.parseInt(i):u?Number.parseFloat(i):i;continue}if(!i.split)continue;const f=i.split(",");e.info[s]=c?f.map(Number.parseInt):u?f.map(Number.parseFloat):f}return r}(d,u,e):u.info=d;const m=[];for(const t of u.alleles){const e={};for(const t in u)"alleles"!=t&&(e[t]=u[t]);for(const n in t)"allele"==n?e.alt=t[n]:"info"==n?e.altinfo=t[n]:e[n]=t[n];e.issymbolicallele||"NON_REF"==e.alt||(e.type=(0,l.P)(e.ref,e.alt)),m.push(e)}return[p.length?"unknown info keys: "+p.join(","):null,m,f.length>0?f:null]}function h(t,e,n){for(;e.length>1&&n.length>1&&e[e.length-1]==n[n.length-1];)e=e.substr(0,e.length-1),n=n.substr(0,n.length-1);for(;e.length>1&&n.length>1&&e[0]==n[0];)e=e.substr(1),n=n.substr(1),t++;return[t,e,n]}function p(t,e){const n={},r=[];let s=0,o=!1,a=null;for(let e=0;e<t.length;e++)if('"'!=t[e])"="!=t[e]?","!=t[e]||(o?o=!1:a?(n[a]=t.substring(s,e),a=null):r.push("k undefined"),s=e+1):(a=t.substring(s,e),s=e+1);else{e++;const s=e;for(;'"'!=t[e];)e++;a?(n[a]=t.substring(s,e),a=null):r.push("k undefined before double quotes"),o=!0}return a&&(n[a]=t.substring(s,i)),n.ID?(e[n.ID]=n,r.length?r.join("\n"):void 0):"no ID"}},736:(t,e,n)=>{"use strict";n.d(e,{P:()=>s});var r=n(2273);function s(t,e){return 1==t.length&&1==e.length?"."==e?r.mclassdeletion:r.mclasssnv:t.length==e.length?r.mclassmnv:t.length<e.length?r.mclassinsertion:t.length>e.length?r.mclassdeletion:r.mclassnonstandard}},7011:(t,e,n)=>{"use strict";n.d(e,{q:()=>o});var r=n(3016);const{bin:s}=n(9060);function o(t,e,n=!1,s=20,o=5){const[a,l]=t.domain(),[c,u]=r.extent(e.values),f=Math.abs(l-a)/s;if(c==u)return{bins:[{x0:c,x1:u,density:1}],densityMax:u};let d=n?function(t,e,n,s,o){const i=e.map((e=>[e,r.mean(n,(n=>t(e-n)))])),a=[];let l=0;for(const t of i){const e={x0:t[0],x1:t[0]+o,density:t[1]};if(e.density>l&&(l=e.density),0!=e.density||0!=l){if(e.x1>s)break;a.push(e)}}return a.push({x0:s,x1:s,density:0}),{bins:a,densityMax:l}}(function(t){return e=>Math.abs(e/=t)<=1?.75*(1-e*e)/t:0}(o),t.ticks(s),e.values,u,f):i(t,e.values,s,u);return n&&0==d.densityMax&&(console.log("using histogram as max density with KDE is 0"),d=i(t,e.values,s,u)),d.bins.unshift({x0:a,x1:a,density:0}),d}function i(t,e,n,r){const o=s().domain(t.domain()).thresholds(t.ticks(n)).value((t=>t))(e),i=[];let a=0;for(const t of o)if(t.length>a&&(a=t.length),(0!=t.length||0!=a)&&(i.push({x0:t.x0,x1:t.x1,density:t.length}),t.x1>r))break;return i.push({x0:r,x1:r,density:0}),{bins:i,densityMax:a}}},3065:(t,e,n)=>{"use strict";n.d(e,{l2:()=>ks,LJ:()=>qs,g_:()=>bs,U_:()=>ms,lE:()=>lo,SC:()=>js,OG:()=>As});var r=n(334),s=n.n(r);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 h=n.n(d),p=n(7147),m=n.n(p),g=n(1017),y=n.n(g),b=n(6452),v=n.n(b);const w=require("lazy");var _=n.n(w);const x=require("compression");var k=n.n(x),q=n(2081),N=n.n(q),S=n(6718),A=n(1881);const M=require("body-parser");var T=n.n(M),C=n(7219),j=n.n(C),E=n(4521),O=n.n(E),I=n(9344),R=n.n(I),F=n(3345),P=n(2273),D=n(6819),L=n(8064),$=n(5494),z=n(6733),Z=n(5558),U=n(3602),B=n(6279),G=n(8423),J=n(8235),H=n(5026);function W(t){delete t.mclasslabel2key,delete t.sample2disease,delete t.patient2ori2sample}var V=n(4766);const Y=require("express-basic-auth");var K=n.n(Y),X=n(2826),Q=n(1271),tt=n(1495);async function et(t,e,n,r,s,o,i,a){const l=nt().height(t.query.barheight).min(r).max(s),c=e.width/(e.stop-e.start);await F.UE({args:[o,e.chr+":"+e.start+"-"+e.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?t.query.pcolor:t.query.ncolor;const h=l(d),p=n+(Math.max(u,e.start)-e.start)*c,m=n+(Math.min(f,e.stop)-e.start)*c,g=Math.max(1,m-p);a.fillRect(p,h.y,g,h.h),d>s?(a.fillStyle=t.query.pcolor2,a.fillRect(p,0,g,2)):d<r&&(a.fillStyle=t.query.ncolor2,a.fillRect(p,t.query.barheight-2,g,2))}})}function nt(){var t=50,e=0,n=100;function r(r){var s,o=!1,i=0;return 0==e&&0==n||e<=0&&n>=0&&(o=!0,i=t*n/(n-e)),o?r>=n?{y:0,h:i}:r>=0?{y:i-(s=i*r/n),h:s}:r<=e?{y:i,h:t-i}:{y:i,h:s=(t-i)*r/e}:r<=e?{y:t,h:0}:{y:t-(s=t*(r-e)/(n-e)),h:s}}return r.height=function(e){return t=e,r},r.min=function(t){return e=t,r},r.max=function(t){return n=t,r},r}function rt(t,e,n){return new Promise(((r,o)=>{const i=(0,q.spawn)(s().bigwigsummary,["-udcDir="+s().cachedir,n,e.chr,e.start,e.stop,Math.ceil(e.width*(t.query.dotplotfactor||1))]),a=[],l=[];i.stdout.on("data",(t=>a.push(t))),i.stderr.on("data",(t=>l.push(t))),i.on("close",(t=>{const e=l.join("");e.length?e.startsWith("no data")?r():o("Cannot read bigWig file"):r(a.join(""))}))}))}function st(t,e,n,r,s){const[o,i]=function(t,e){let n=t.width/e.size,r=0;n>40&&(n=40,r=(t.width-n*e.size)/2);const s=new Map,o=t.reverse?[...e].sort(((t,e)=>e-t)):[...e].sort(((t,e)=>t-e));let i=r;for(const t of o)s.set(t,i+n/2),i+=n;return[n,s]}(t,n),a=new Map;{const e=(t.stop-t.start)/t.width;for(const r of n)t.reverse?a.set(r,(t.stop-r)/e):a.set(r,(r-t.start)/e)}let l=0;for(const t of e)l=Math.max(l,(i.get(t.stop)-i.get(t.start))/2);const c=r+l+o/2,u=(0,S.createCanvas)(t.width*s,c*s),f=u.getContext("2d");s>1&&f.scale(s,s),f.strokeStyle="black";for(const t of n)f.beginPath(),f.moveTo(a.get(t),0),f.lineTo(i.get(t),r),f.closePath(),f.stroke();for(const t of e){const e=i.get(t.start),n=i.get(t.stop),s=(e+n)/2,a=r+Math.abs(n-e)/2,l=Math.floor(255*(1-t.r2));f.fillStyle="rgb(255,"+l+","+l+")",f.beginPath(),f.moveTo(s,a-o/2),f.lineTo(s-o/2,a),f.lineTo(s,a+o/2),f.lineTo(s+o/2,a),f.lineTo(s,a-o/2),f.closePath(),f.fill()}return{height:c,src:u.toDataURL()}}var ot=n(938);async function it(t,e,n){const r={rglst:[]};let s=0,o=0;if(t.autoscale){for(const r of t.rglst){const i=(n?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop;await F.UE({args:[t.file,i],dir:e,callback:t=>{const[e,n,r,i]=t.split("\t");for(const t of i.split(",")){const e=Number(t);s=Math.min(s,e),o=Math.max(o,e)}}})}r.minv=s,r.maxv=o}else s=t.minv,o=t.maxv;const i=app.makeyscale().height(t.barheight).min(s).max(o);for(const a of t.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,t.barheight),u=c.getContext("2d"),f=(n?a.chr.replace("chr",""):a.chr)+":"+a.start+"-"+a.stop;await F.UE({args:[t.file,f],dir:e,callback:e=>{const[n,r,l,c]=e.split("\t"),f=Math.max(Number.parseInt(r),a.start),d=Math.min(Number.parseInt(l),a.stop),h=(a.reverse?a.stop-d:f-a.start)*a.width/(a.stop-a.start),p=(a.reverse?a.stop-f:d-a.start)*a.width/(a.stop-a.start);for(const e of c.split(",")){const n=Number(e);u.fillStyle=n>0?t.pcolor:t.ncolor;const r=i(n),a=Math.max(1,p-h);u.fillRect(h,r.y,a,2),n>o?(u.fillStyle=req.query.pcolor2,u.fillRect(h,0,a,2)):n<s&&(u.fillStyle=req.query.ncolor2,u.fillRect(h,t.barheight-2,a,2))}}}),l.img=c.toDataURL(),r.rglst.push(l)}return r}var at=n(2781);const lt="all",ct="support_ref",ut="support_alt",ft="support_no",dt="support_amb",ht="support_sv";function pt(t){const e={};if(t.variant)if(t.grouptype)e[t.grouptype]={partstack:t.partstack};else{e[ct]={},e[ft]={},e[dt]={};for(let n=0;n<t.variant.length;n++)e[ut+n.toString()]={}}else{if(!t.sv)throw"q.variant or q.sv missing";t.grouptype?e[t.grouptype]={partstack:t.partstack}:(e[ht]={},e[ct]={})}for(const n in e){const r=e[n];r.type=n,r.templates=[],r.regions=mt(t.regions),r.messages=[]}return e}function mt(t){return t.map((t=>({x:t.x,scale:t.scale,ntwidth:t.ntwidth})))}var gt=n(6113),yt=n.n(gt),bt=n(490);require("jstat"),s().features,s().clustalo;function vt(t){return t>1e9?(t/1e9).toFixed(2)+" GB":t>1e6?(t/1e6).toFixed(2)+" MB":t>1e3?(t/1e3).toFixed(2)+" KB":t+" Bytes"}const wt={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},_t={end_point:"cases/",fields:["case_id"]},xt=[{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"}],kt="STAR 2-Pass Transcriptome",qt=100,Nt=1e3;let St;async function At(t,e,n,r){for(const s of xt)if(await Mt(t,s.field,n,r))return e.isCaseSample=s.type,await Tt(t,s.field,10,r);const s=await Ct(t,"file_id",r);if(s.data.hits.length)return e.is_file_uuid=!0,s;const o=await Ct(t,"file_name",r);return o.data.hits.length&&(e.is_file_id=!0),o}async function Mt(t,e,n,r){const s={op:"and",content:[{op:"=",content:{field:e,value:t}}]};return(await St(s,_t,null,n,r)).data.hits.length>0}async function Tt(t,e,n,r){const s={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 t&&e&&s.content.push({op:"in",content:{field:e,value:t}}),await St(s,wt,n,null,r)}async function Ct(t,e,n){const r={op:"and",content:[{op:"in",content:{field:e,value:t}}]},s=await St(r,wt,null,null,n),o=s.data.hits[0];if(o&&"Aligned Reads"!=o.data_type)throw"Requested file is not a BAM file.";return s}async function jt(t,e,n){const{host:r,headers:s}=e.getHostHeaders(n);s.Range="bytes=0-0";const o=r.rest+"/data/"+t;try{const t=await v()(o,{headers:s,decompress:!1});if(!(t.statusCode>=200&&t.statusCode<400))throw console.log(`gdcCheckPermission() error for got(${o})`,t),"Invalid status code: "+t.statusCode}catch(t){throw console.log("gdcCheckPermission error: ",t?.code||t),"Permission denied"}}const Et=s().clustalo,Ot=(0,a.promisify)(at.pipeline),It="rgb(120,120,120)",Rt="rgb(230,230,230)",Ft=(0,bt.ZP)(Rt,It),Pt="#d48b37",Dt=(0,bt.ZP)("#dbc6ad",Pt),Lt="#3B7A57",$t=(0,bt.ZP)("#E5FFCC",Lt),zt="#d13232",Zt="#ffdbdd",Ut=(0,bt.ZP)(Zt,zt),Bt="#4888bf",Gt="#c9e6ff",Jt=(0,bt.ZP)(Gt,Bt),Ht="#6B4423",Wt=(0,bt.ZP)("#987654",Ht),Vt="#fc6df3",Yt=(0,bt.ZP)("#dea4da",Vt),Kt="#47FFFC",Xt="#B2D7D7",Qt=(0,bt.ZP)(Xt,Kt),te=12,ee=7,ne="black",re="#ededed",se="blue",oe="#e0e0e0",ie="#FF0000",ae="#6cc24a",le="#ffff00",ce="#DEB887",ue="#CD853F",fe="#9a92ec",de="#47C8FF",he=1,pe=1,me=.4,ge=.9,ye=7,be=7,ve=10,we=7,_e=40,xe=.5,ke=2,qe=5,Ne=7e3,Se=1500,Ae=2e3,Me=7,Te=200,Ce=20,je=(new Set(["A","T","C","G"]),Math.random.toString()),Ee=3e5;function Oe(t){const e=t.hg38?.datasets?.GDC;if(!e)throw"hg38.datasets.GDC missing";return e}async function Ie(t,e,n,r,s){const o=t.diff_score_plotwidth/(r-s),i=r*o-s*o,a=(0,S.createCanvas)(i*t.devicePixelRatio,e.canvasheight*t.devicePixelRatio),l=a.getContext("2d");t.devicePixelRatio>1&&l.scale(t.devicePixelRatio,t.devicePixelRatio);const c=n.map((t=>t.__tempscore)),u=e.canvasheight/c.length;let f=0;const d=e.stackspace/e.canvasheight;for(const t of c){let e=0;for(const n of t)"alt0"==n?l.fillStyle=ie:"ref"==n?l.fillStyle=de:"alt1"==n?l.fillStyle=ae:"alt2"==n?l.fillStyle=le:"alt3"==n?l.fillStyle=ce:"alt4"==n?l.fillStyle=ue:"alt5"==n&&(l.fillStyle=fe),l.fillRect(o*e,f*u,o,u-d*u),e+=1;f+=1}return{height:e.canvasheight,width:i,src:a.toDataURL(),read_height:u}}function Re(t,e,n,r){for(const s of n)for(const n of s.segments)if(!(n.ridx!=t||Math.max(n.segstart,e.start)>Math.min(n.segstop,e.stop)))for(const t of n.boxes)if(e.ntwidth>=1){if(("S"==t.opr||"X"==t.opr)&&t.s)for(let e=0;e<t.s.length;e++){const n=t.start+e,s=r.find((t=>t.position==n));if(!s)continue;const o=t.s[e];s[o]=1+(s[o]||0),"S"==t.opr&&s.total++}}else if("S"==t.opr){const n=Math.floor((t.start-e.start)*e.ntwidth),s=Math.floor((t.start+t.len-e.start)*e.ntwidth);for(let t=n;t<=s;t++){const e=r[t];e&&(e.softclip=1+(e.softclip||0),e.total++)}}}async function Fe(t){if(t.query.gdcFileUUID){const e=y().join(s().cachedir_bam,t.query.file);return await async function(t,e){try{if(!await F.yE(e))return;const n=t.query.regions,r=t.query.gdcFilePosition.split(".");t.query.regions=[{chr:r[0],start:Number(r[1]),stop:Number(r[2])}],await rn(t),t.query.regions=n}catch(t){throw t}}(t,e),[e,null]}const[e,n,r]=F.ZX(t);if(e)throw e;return[n,r?await F.d1(n,t.query.indexURL||n+".bai"):null]}async function Pe(t,e,n,r,s){const o=t.map((t=>t.segments[0].seq)),i=t.map((t=>t.segments[0].qual));let a="",l="";s&&(a+=">seq\n"+s.replace("\n","")+"\n");let c=0;for(const t of o){if(!(c<Te))break;a+=">seq\n"+t.replace("\n","")+"\n",l+=We(i[c].replace("\n",""))+"\n",c+=1}return await function(t,e,n,r,s,o,i,a){return new Promise(((n,l)=>{const c=(0,q.spawn)(Et,["-i","-","-t","DNA","--outfmt=clu","--wrap=5000","--maxnumseq="+(e+1),"--maxseqlen=1000"]),u=[],f=[];at.Readable.from(t).pipe(c.stdin),c.stdout.on("data",(t=>u.push(t))),c.stderr.on("data",(t=>f.push(t))),c.on("error",(t=>{console.log("stderr (clustalo):",f),l(t)})),c.on("close",(t=>{let e=0;const c=[],f={final_read_align:[],qual_r:[],qual_g:[],qual_b:[]};let d=0;for(const t of u.toString().split("\n"))if(t.includes("seq ")){let n=0,l="",u=0,h="";0!=e&&a?h=r.split("\n")[e-1].split(","):a||(h=r.split("\n")[e].split(","));let p="",m="",g="";for(const r of t.replace("seq ",""))if(","!=r){if("-"!=r){if(n+=1,l+=r,0==e&&a)c.push(r);else if(r==c[u]&&a||!a){const t=Ft(h[n-1]/_e).replace("rgb(","").replace(")","").split(",");p+=t[0]+",",m+=t[1]+",",g+=t[2]+","}else if(r!=c[u]&&a){const t=Ut(h[n-1]/_e).replace("rgb(","").replace(")","").split(",");p+=t[0]+",",m+=t[1]+",",g+=t[2]+","}}else n>0&&n<t.replace(/-/g,"").replace(/,/g,"").replace("seq ","").length?(l+=r,0==e&&(c.push(r),u<s&&(d+=1))):(l+=" ",0==e&&c.push(r)),p+="255,",m+="255,",g+="255,";u+=1}e+=1,f.gaps_before_variant=d,f.read_count=a?e-1:e,f.qual_r.push(p),f.qual_g.push(m),f.qual_b.push(g),f.final_read_align.push(l),0!=o&&0!=i&&(f.partstack_start=o,f.partstack_stop=i)}else(t.includes("FATAL:")||t.includes("ERROR:"))&&(console.log(t),l(t));n(f)}))}))}(a,Te,o.length,l,e,n,r,s)}async function De(t,e){let n=0;for(const r of e){const e=["view","-c",t.file];t.gdc_case_id||e.push((t.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop),await F.UE({isbam:!0,args:e,dir:t.dir,callback:t=>{const e=Number(t);if(!Number.isInteger(e))throw"total number of reads from a region not integer";n+=e}})}if(n<1.1*Ne)return;const r=(n-Ne)/(.1*Ne);t.downsample={keep:10,skip:Math.floor(r),pointer:0},t.read_limit_reached=n}async function Le(t,e){t.lines=[];const n=["view",e.file];e.gdc_case_id||n.push((e.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop),await F.UE({isbam:!0,args:n,dir:e.dir,callback:(n,r)=>{const s=n.split("\t")[1];if(!(1024&s&&e.drop_pcrduplicates||2048&s&&e.drop_supplementary_alignments)){if(e.downsample){const t=e.downsample;if(t.pointer++,t.pointer>=t.keep&&t.pointer<t.keep+t.skip)return;t.pointer>=t.keep+t.skip&&(t.pointer=0)}t.lines.push(n)}}})}async function $e(t,e){const n=[],r=["depth","-r",(t.nochr?e.chr.replace("chr",""):e.chr)+":"+(e.start+1)+"-"+e.stop,"-g","DUP",t.file||t.url];if(t.drop_pcrduplicates&&(r.push("-G"),r.push("0x400")),t.drop_supplementary_alignments&&(r.push("-G"),r.push("0x800")),await F.UE({isbam:!0,args:r,dir:t.dir,callback:t=>{const r=t.split("\t"),s=Number.parseInt(r[1])-1,o=Number.parseInt(r[2]);if(e.ntwidth>=1)return void n.push({position:s,total:o});const i=Math.floor((s-e.start)*e.ntwidth);n[i]||(n[i]={position:s,sum:0,count:0}),n[i].sum+=o,n[i].count++}}),e.ntwidth<1)for(const t of n)t&&(t.total=t.sum/t.count,delete t.sum,delete t.count);return n}async function ze(t,e){for(const t of e.regions)t.lines.length>0&&t.ntwidth>=ge&&(t.to_checkmismatch=!0,t.referenceseq=await Je(e.genome,t.chr+":"+(t.start+1)+"-"+t.stop));for(const n of t)for(const t of n.segments){const n=e.regions[t.ridx];if(!n.to_checkmismatch)continue;const r=[];for(const e of t.boxes)null!=e.cidx&&"M"==e.opr&&(e.s=t.seq.substr(e.cidx,e.len),Ye(r,n,e,e.s));r.length&&t.boxes.push(...r)}for(const t of e.regions)delete t.to_checkmismatch,delete t.referenceseq}function Ze(t,e){if(!t.asPaired){const n=[];for(let r=0;r<t.regions.length;r++){const s=t.regions[r];for(const o of e.templates){o.ridx=r;const e=Ue(o,s,t);e&&n.push({x1:e.x1,x2:e.x2,__tempscore:e.tempscore,segments:[e]})}}return n}const n=new Map;for(let r=0;r<t.regions.length;r++){const s=t.regions[r];for(const o of e.templates){o.ridx=r;const e=Ue(o,s,t);if(!e||!e.qname)continue;const i=n.get(e.qname);i?(i.segments.push(e),i.x2=Math.max(i.x2,e.x2)):n.set(e.qname,{x1:Math.max(e.x1,s.x),x2:Math.min(e.x2,s.x+s.width),__tempscore:e.tempscore,segments:[e]})}}return[...n.values()]}function Ue(t,e,n){const{sam_info:r,tempscore:s,ridx:o,keepallboxes:i,keepmatepos:a,keepunmappedread:l}=t,c=r.trim().split("\t");if(c.length<11)return;const u=c[0],f=c[1],d=Number.parseInt(c[3]),h=c[5],p=c[6],m=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:h,tlen:g,flag:f,tempscore:s};if(function(t,e,n,r,s,o){const i=t.flag;if(!(1&i))return;64&i?t.isfirst=!0:128&i&&(t.islast=!0);if("="!=e&&"*"!=e&&e!=r.chr)return t.rnext=e,void(t.pnext=n);if(8&i)return void(t.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||(t.discord_orientation=!0,s&&(16&i?32&i?t.discord_orientation_direction="R1R2":n>o&&(t.discord_orientation_direction="R1F2"):32&i?n<o&&(t.discord_orientation_direction="R1F2"):t.discord_orientation_direction="F1F2")),2&i||(t.discord_wrong_insertsize=!0,s&&(t.pnext=n))}(w,p,m,e,a,d),4&f)return l?(w.boxes.push({opr:h,start:v,len:y.length,cidx:0,qual:b}),w.discord_unmapped1=!0,w):void 0;if("*"!=h){let t=v,r=0,s=0;for(let n=0;n<h.length;n++){const o=h[n];if(o.match(/[0-9]/))continue;const a=Number.parseInt(h.substring(r,n));if("H"!=o)if("N"==o||"P"==o||"D"==o||(s+=a),r=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||t>e.start&&t<e.stop){const e={opr:"P",start:t,len:a,cidx:s-a};w.boxes.push(e)}}else{const n={opr:o,start:t,len:a,cidx:s-a};0==w.boxes.length?(n.start-=a,(i||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push(n)):w.boxes.push(n)}else{if(i||Math.max(t,e.start)<Math.min(t+a-1,e.stop)){const e={opr:o,start:t,len:a,cidx:s-a};w.boxes.push(e)}t+=a}else(t>=e.start&&t<=e.stop||t+a-1>=e.start&&t+a-1<=e.stop||i)&&w.boxes.push({opr:o,start:t,len:a}),t+=a;else(i||t>e.start&&t<e.stop)&&a*e.ntwidth>=he&&w.boxes.push({opr:"I",start:t,len:a,cidx:s-a});else(i||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push({opr:o,start:t,len:a,cidx:s-a}),t+=a;else{const l={opr:o,start:t,len:a,cidx:s-a};0==w.boxes.length?(l.start-=a,l.cidx=0,(i||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push(l)):w.boxes.push(l),r=n+1}}if(0==w.boxes.length)return void(n&&n.readcount_skipped++);w.segstop=t,w.x1=e.x+e.scale(w.boxes[0].start),w.x2=e.x+e.scale((_=w.boxes,Math.max(..._.map((t=>t.start+t.len)))))}var _;return w}async function Be(t,e,n){const[r,s]=function(t,e){let n=(e.groups.length>1?Se/2:Se)/t;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]}(t.stacks.length,e);t.stackheight=r,t.stackspace=s;for(const e of t.regions)e.to_printnt=t.stackheight>7&&e.ntwidth>=7,e.to_qual=e.ntwidth>=pe;if(t.stacks.length&&(t.stackheight>=Me&&n.length<Ae?t.returntemplatebox=[]:t.partstack||(t.allowpartstack=!0)),t.stackheight>=ye){let e=0;for(const t of n)for(const n of t.segments)e=Math.max(e,n.x2-n.x1);e>.7*t.stackheight&&(t.canClipArrowhead=!0)}}function Ge(t,e,n){if(e.asPaired){t.stacks=[];const r=[],s=[];for(const t of n){let n=t.segments[0].ridx;1==t.segments.length||2==t.segments.length&&t.segments[0].ridx==t.segments[1].ridx?(t.x1=Math.max(e.regions[n].x,t.x1),t.x2=Math.min(e.regions[n].x+e.regions[n].width,t.x2),r.push(t)):2==t.segments.length&&t.segments[0].ridx!=t.segments[1].ridx&&(t.x1=t.x1,t.x2=t.x2,s.push(t))}if(r.sort(((t,e)=>t.x1-e.x1)),s.sort(((t,e)=>t.x1-e.x1)),s.length>0){const t=[],e=[],o=s[0];for(const n of r)n.x1<o.x1&&n.x2<o.x1?t.push(n):e.push(n);n=[...t,...s,...e]}for(const r of n){let n=r.segments[0].ridx,s=null;if(!e.variant)for(let o=0;o<t.stacks.length;o++){if(r.x2==e.regions[n].x+e.regions[n].width&&t.stacks[o]<r.x1){s=o,t.stacks[o]=r.x2;break}if(t.stacks[o]+e.stacksegspacing<r.x1){s=o,t.stacks[o]=r.x2;break}}null==s&&(s=t.stacks.length,t.stacks[s]=r.x2),r.y=s}}else{n.sort(((t,e)=>t.x1-e.x1)),t.stacks=[];for(let r=0;r<e.regions.length;r++)for(const s of n)if(s.segments[0].ridx==r){let n=null;if(!e.variant&&!e.sv)for(let o=0;o<t.stacks.length;o++)if(t.stacks[o]+e.stacksegspacing<s.x1&&t.stacks[o]+e.stacksegspacing<e.regions[r].x+e.regions[r].width){n=o,t.stacks[o]=s.x2;break}null==n&&(n=t.stacks.length,t.stacks[n]=s.x2),s.y=n}}return n=function(t,e,n){if(!t.partstack)return e;const r=e.filter((e=>e.y>=t.partstack.start&&e.y<=t.partstack.stop));r.forEach((e=>e.y-=t.partstack.start)),e=r,t.stacks=[];for(let e=t.partstack.start;e<=t.partstack.stop;e++)t.stacks.push(0);return t.returntemplatebox=[],e}(t,n),n}async function Je(t,e){const n=(await F.Kf(t,e)).split("\n");return n.shift(),n.join("").toUpperCase()}function He(t,e,n){const r=function(t,e,n){const r=[];for(let e=0;e<t.stacks.length;e++)r.push(t.stackheight);if(function(t,e){if(!e.asPaired)return;for(const e of t.regions)if(e.ntwidth<=me)return;t.overlapRP_multirows=!0,t.overlapRP_hlline=t.stackspace>0}(t,n),t.overlapRP_multirows)for(const n of e)n.segments.length<=1||n.segments[0].ridx!=n.segments[1].ridx||(n.height=Ve(n,t.stackheight),r[n.y]=Math.max(r[n.y],n.height));const s=[];let o=t.stackspace;for(const e of r)s.push(o),o+=e+t.stackspace;return t.canvasheight=o,s}(t,e,n);for(const n of e){n.y=r[n.y];for(const e of n.segments){const n=t.regions[e.ridx].to_qual?We(e.qual):null;for(const t of e.boxes)null!=t.cidx&&"H"!=t.opr&&(n&&(t.qual=n.slice(t.cidx,t.cidx+t.len)),"I"==t.opr?t.s=e.seq.substr(t.cidx,t.len):"X"!=t.opr&&"S"!=t.opr||(t.s=e.seq.substr(t.cidx,t.len)),delete t.cidx);delete e.seq,delete e.qual}}}function We(t){if("*"==t)return null;const e=[];for(let n=0;n<t.length;n++){const r=t[n].charCodeAt(0)-33;e.push(r)}return e}function Ve(t,e){if(2==t.segments.length){const[n,r]=t.segments;return n.x2>r.x1?(r.shiftdownrow=1,2*e):e}console.log("more than 2 segments",t.segments.length);const n=[];for(const e of t.segments){let t=null;for(let r=0;r<n.length;r++)if(n[r]<e.x1){t=r,n[r]=e.x2;break}null==t&&(t=n.length,n[t]=e.x2),e.shiftdownrow=t}return e*n.length}function Ye(t,e,n,r){for(let s=0;s<r.length;s++){if(n.start+s<e.start||n.start+s>e.stop)continue;const o=r[s];if(e.referenceseq[n.start+s-e.start]!=o.toUpperCase()){const e={opr:"X",start:n.start+s,len:1,s:o,cidx:n.cidx+s};t.push(e)}}}function Ke(t,e,n,r){if(n.returntemplatebox){const t=n.regions[e.segments[0].ridx];let s;if(t.width=n.widths[e.segments[0].ridx],r.asPaired)if(2==e.segments.length)s=e.segments[0].ridx!=e.segments[1].ridx?{qname:e.segments[0].qname,x1:e.x1,x2:e.x2,y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop))),multi_region:!0}:{qname:e.segments[0].qname,x1:Math.max(t.x,e.x1),x2:Math.min(e.x2,t.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))};else{const t=e.segments[0],r=n.regions[t.ridx];r.width=n.widths[t.ridx],s={qname:e.segments[0].qname,x1:Math.max(r.x,e.x1),x2:Math.min(e.x2,r.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))}}else s={qname:e.segments[0].qname,x1:Math.max(t.x,e.x1),x2:Math.min(e.x2,t.x+t.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))},e.segments[0].isfirst&&(s.isfirst=!0),e.segments[0].islast&&(s.islast=!0);n.returntemplatebox.push(s)}for(let s=0;s<e.segments.length;s++){const o=e.segments[s],i=n.regions[o.ridx];if(i.width=n.widths[o.ridx],0==s){Xe(t,o,e.y,n,r);continue}const a=e.segments[s-1],l=n.regions[a.ridx];if(l.width=n.widths[a.ridx],a.x2<=o.x1||e.segments[0].ridx!=e.segments[1].ridx){Xe(t,o,e.y,n,r);const s=Math.floor(e.y+n.stackheight/2)+.5;if(t.strokeStyle=n.stackheight<=2?re:It,t.setLineDash([5,3]),t.beginPath(),l.x==i.x?(t.moveTo(a.x2,s),t.lineTo(o.x1,s)):l.x<a.x2&&o.x1<i.width&&(t.moveTo(Math.min(a.x2,l.width),s),t.lineTo(Math.max(o.x1,i.x),s)),t.stroke(),n.overlapRP_hlline){const r=a.boxes.reduce(((t,e)=>t.start+t.len>e.start+e.len?t:e));if(r.start+r.len==o.boxes[0].start){t.strokeStyle=se,t.setLineDash([]),t.beginPath();const r=Math.floor(o.x1)+.5;t.moveTo(r,e.y),t.lineTo(r,e.y+n.stackheight),t.stroke()}}}else if(n.overlapRP_multirows){if(Xe(t,o,e.y+n.stackheight,n,r),n.overlapRP_hlline){const r=Math.floor(e.y+n.stackheight)+.5;t.strokeStyle=se,t.setLineDash([]),t.beginPath(),l.x<=a.x2&&o.x1<=i.width&&(t.moveTo(Math.max(o.x1,i.x),r),t.lineTo(Math.min(a.x2,l.width),r)),t.stroke()}}else Xe(t,o,e.y,n,r)}null!=e.__tempscore&&s().features.indel_read_alignment_scores&&(t.fillStyle="blue",t.font=n.stackheight+"pt Arial",t.fillText(e.__tempscore,r.regions[0].width-100,e.y+n.stackheight/2))}function Xe(t,e,n,r,s){const o=r.regions[e.ridx];o.width=r.widths[e.ridx];for(const s of e.boxes){const i=o.x+o.scale(s.start);if("P"!=s.opr&&"I"!=s.opr)if("H"!=s.opr)if("D"!=s.opr&&"N"!=s.opr)if("*"!=s.opr){if("X"!=s.opr&&"S"!=s.opr){if("M"!=s.opr&&"="!=s.opr)throw"unknown opr at rendering: "+s.opr;if(o.to_qual&&s.qual){let a=i;s.qual.forEach((s=>{e.rnext?t.fillStyle=Dt(s/_e):e.discord_orientation?t.fillStyle=Yt(s/_e):e.discord_wrong_insertsize?t.fillStyle=$t(s/_e):e.discord_unmapped2?t.fillStyle=Wt(s/_e):t.fillStyle=Ft(s/_e),a+o.ntwidth+xe<o.width&&o.x<=a?t.fillRect(a,n,o.ntwidth+xe,r.stackheight):a<o.width&&a+o.ntwidth+xe>=o.width&&o.x<=a?t.fillRect(a,n,o.width-a,r.stackheight):a<=o.x&&a+o.ntwidth+xe>o.x&&t.fillRect(o.x,n,o.ntwidth+xe+a-o.x,r.stackheight),a+=o.ntwidth}))}else s.qual?e.rnext?t.fillStyle=Pt:e.discord_orientation?t.fillStyle=Vt:e.discord_wrong_insertsize?t.fillStyle=Lt:e.discord_unmapped2?t.fillStyle=Ht:t.fillStyle=It:o.to_printnt?t.fillStyle="white":e.rnext?t.fillStyle=Pt:e.discord_orientation?t.fillStyle=Vt:e.discord_wrong_insertsize?t.fillStyle=Lt:e.discord_unmapped2?t.fillStyle=Ht:t.fillStyle=It,i+s.len*o.ntwidth+xe<o.width&&i<o.width&&o.x<i+xe?t.fillRect(i,n,s.len*o.ntwidth+xe,r.stackheight):i+s.len*o.ntwidth+xe<o.width&&o.x>=i?t.fillRect(o.x,n,s.len*o.ntwidth+xe+i-o.x,r.stackheight):i+s.len*o.ntwidth+xe>=o.width&&o.x<i?t.fillRect(i,n,o.width-i,r.stackheight):i+s.len*o.ntwidth+xe>=o.width&&o.x>=i&&t.fillRect(o.x,n,o.width-i,r.stackheight);if(o.to_printnt){t.font=Math.min(o.ntwidth,r.stackheight-2)+"pt Arial",s.qual?t.fillStyle="white":t.fillStyle="black";for(let e=0;e<s.s.length;e++)i+o.ntwidth*(e+.5)<o.width&&i<o.width&&o.x<=i+o.ntwidth*(e+.5)&&t.fillText(s.s[e],i+o.ntwidth*(e+.5),n+r.stackheight/2)}}else if(o.to_qual&&s.qual){o.to_printnt&&(t.font=Math.min(o.ntwidth,r.stackheight-2)+"pt Arial");let e=i;for(let i=0;i<s.qual.length;i++){const a=s.qual[i]/_e;t.fillStyle="S"==s.opr?Jt(a):Ut(a),e+o.ntwidth+xe<o.x+o.width&&o.x<=e?t.fillRect(e,n,o.ntwidth+xe,r.stackheight):e<o.x+o.width&&e+o.ntwidth+xe>=o.x+o.width&&o.x<=e?t.fillRect(e,n,o.width+o.x-e,r.stackheight):e<=o.x&&e+o.ntwidth+xe>o.x&&t.fillRect(o.x,n,o.ntwidth+xe+e-o.x,r.stackheight),o.to_printnt&&(s.qual?t.fillStyle="white":t.fillStyle="black",e+o.ntwidth/2<o.width&&e<o.width&&o.x<=e+o.ntwidth/2&&t.fillText(s.s[i],e+o.ntwidth/2,n+r.stackheight/2)),e+=o.ntwidth}}else if(t.fillStyle="S"==s.opr?Bt:zt,i+s.len*o.ntwidth+xe<o.width&&o.x<i?t.fillRect(i,n,s.len*o.ntwidth+xe,r.stackheight):i+s.len*o.ntwidth+xe<o.width&&o.x>=i?t.fillRect(o.x,n,s.len*o.ntwidth+xe+i-o.x,r.stackheight):i+s.len*o.ntwidth+xe<=o.width&&o.x<i&&t.fillRect(i,n,o.width-i,r.stackheight),o.to_printnt&&!s.qual){t.font=Math.min(o.ntwidth,r.stackheight-2)+"pt Arial",s.qual?t.fillStyle="white":t.fillStyle="black";for(let e=0;e<s.s.length;e++)i+o.ntwidth*(e+.5)<o.width&&i<o.width&&o.x<=i+o.ntwidth*(e+.5)&&t.fillText(s.s[e],i+o.ntwidth*(e+.5),n+r.stackheight/2)}}else{if(o.to_qual&&s.qual){let a=i;s.qual.forEach((s=>{e.discord_unmapped2&&(t.fillStyle=Wt(s/_e)),t.fillRect(a,n,o.ntwidth+xe,r.stackheight),a+=o.ntwidth}))}else e.discord_unmapped2&&(t.fillStyle=Ht),t.fillRect(i,n,s.len*o.ntwidth+xe,r.stackheight);o.to_printnt&&(t.font=Math.min(o.ntwidth,r.stackheight-2)+"pt Arial")}else{"D"==s.opr?t.strokeStyle=ne:t.strokeStyle=r.stackheight<=2?re:It,t.setLineDash([]);const e=Math.floor(n+r.stackheight/2)+.5;if(t.beginPath(),t.moveTo(Math.max(i,o.x),e),t.lineTo(Math.min(i+s.len*o.ntwidth,o.x+o.width),e),t.stroke(),r.stackheight>be){const e=Math.max(o.x,i),a=Math.min(o.x+o.width,i+s.len*o.ntwidth);if(a-e>=50){const i=Math.min(ve,Math.max(we,r.stackheight-2));t.font=i+"pt Arial";const l=t.measureText(s.len+" bp").width;l<a-e-20&&(t.fillStyle="white",(a+e)/2+l/2<o.width&&o.x<(a+e)/2-l/2?(t.fillRect((a+e)/2-l/2,n,l,r.stackheight),t.fillStyle=It,t.fillText(s.len+" bp",(a+e)/2,n+r.stackheight/2)):(a+e)/2+l/2<o.width&&o.x>=(a+e)/2-l/2?(t.fillRect(o.x,n,l+(a+e)/2-l/2-o.x,r.stackheight),t.fillStyle=It,t.fillText(s.len+" bp",(a+e)/2,n+r.stackheight/2)):(a+e)/2+l/2>=o.width&&o.x<(a+e)/2-l/2&&(t.fillRect((a+e)/2-l/2,n,o.width-(a+e)/2+l/2,r.stackheight),t.fillStyle=It,t.fillText(s.len+" bp",(a+e)/2,n+r.stackheight/2)))}}}else t.fillStyle="white",i+s.len*o.ntwidth+xe<o.width&&o.x<i?t.fillRect(i,n,s.len*o.ntwidth+xe,r.stackheight):i+s.len*o.ntwidth+xe<o.width&&o.x>=i?t.fillRect(o.x,n,s.len*o.ntwidth+xe+i-o.x,r.stackheight):i+s.len*o.ntwidth+xe<=o.width&&o.x<i&&t.fillRect(i,n,o.width-i,r.stackheight)}!function(t,e,n,r,s){if(!n.canClipArrowhead)return;if(e.x2-e.x1<5)return;if(e.forward){const o=Math.ceil(e.x2+xe);o<=r.width+n.stackheight/2&&(t.fillStyle="white",t.beginPath(),t.moveTo(o-n.stackheight/2,s),t.lineTo(o,s),t.lineTo(o,s+n.stackheight/2),t.lineTo(o-n.stackheight/2,s),t.closePath(),t.fill(),t.beginPath(),t.moveTo(o-n.stackheight/2,s+n.stackheight),t.lineTo(o,s+n.stackheight),t.lineTo(o,s+n.stackheight/2),t.lineTo(o-n.stackheight/2,s+n.stackheight),t.closePath(),t.fill())}else{const o=e.x1;o>=r.x&&(t.fillStyle="white",t.beginPath(),t.moveTo(o+n.stackheight/2,s),t.lineTo(o,s),t.lineTo(o,s+n.stackheight/2),t.lineTo(o+n.stackheight/2,s),t.closePath(),t.fill(),t.beginPath(),t.moveTo(o+n.stackheight/2,s+n.stackheight),t.lineTo(o,s+n.stackheight),t.lineTo(o,s+n.stackheight/2),t.lineTo(o+n.stackheight/2,s+n.stackheight),t.closePath(),t.fill())}}(t,e,r,o,n),e.rnext&&(o.to_qual||e.x2-e.x1>=20&&r.stackheight>=7&&(t.font=Math.min(te,Math.max(ee,r.stackheight-4))+"pt Arial",t.fillStyle="white",t.fillText((s.nochr?"chr":"")+e.rnext,(e.x1+e.x2)/2,n+r.stackheight/2,e.x2-e.x1)))}function Qe(t,e,n,r){for(const[t,n]of e.regions.entries()){if(!n.to_printnt)continue;const e=new Set;for(const s of r)for(const r of s.segments){if(r.ridx!=t)continue;const s=r.boxes.filter((t=>"I"==t.opr));if(s.length)for(const t of s)e.add(n.x+n.scale(t.start))}}for(const n of r)for(const r of n.segments){const s=e.regions[r.ridx],o=r.boxes.filter((t=>"I"==t.opr));if(o.length){t.font=Math.max(te,e.stackheight-2)+"pt Arial";for(const i of o){const o=s.x+s.scale(i.start);let a;i.qual?t.fillStyle=Qt(i.qual.reduce(((t,e)=>t+e),0)/i.qual.length/_e):t.fillStyle=Kt,a=""==i.s?i.len:1==i.s.length?i.s:i.s.length,t.fillText(a,o,n.y+e.stackheight*(r.on2ndrow||0)+e.stackheight/2)}}}}async function tn(t,e,n){const r=We(t.qual),s=['<td style="color:black;text-align:left">Read</td>'];for(const e of t.boxes)for(let n=0;n<e.len;n++){t.seq[e.cidx+n];s.push('<td style="background:'+Ft(r[e.cidx+n]/_e)+'">'+t.seq[e.cidx+n]+"</td>")}const o=[];o.push('<li><span style="background:'+Ht+';color:white">This segment in template is unmapped</span></li>'),1&t.flag&&o.push("<li>Template has multiple segments</li>"),2&t.flag&&o.push("<li>Each segment properly aligned</li>"),16&t.flag&&o.push("<li>Reverse complemented</li>"),32&t.flag&&o.push("<li>Next segment in the template is reverse complemented</li>"),64&t.flag&&o.push("<li>This is the first segment in the template</li>"),128&t.flag&&o.push("<li>This is the last segment in the template</li>"),256&t.flag&&o.push("<li>Secondary alignment</li>"),512&t.flag&&o.push("<li>Not passing filters</li>"),1024&t.flag&&o.push("<li>PCR or optical duplicate</li>"),2048&t.flag&&o.push("<li>Supplementary alignment</li>");let i={seq:t.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center">\n\t\t\t <tr style="color:white">${s.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(t.seq.length)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${t.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${t.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${t.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${o.join("")}</ul>`};return t.discord_unmapped2&&(i.unmapped_mate=!0),i}async function en(t,e,n){const r=t.boxes[0].start,s=t.boxes[t.boxes.length-1],o=s.start+s.len,i=await Je(e,n.chr+":"+(r+1)+"-"+o),a=We(t.qual);let l,c;if("*"==t.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 e of t.boxes)if("H"!=e.opr)if("I"!=e.opr)if("D"!=e.opr&&"N"!=e.opr)if("S"!=e.opr)if("M"!=e.opr&&"="!=e.opr&&"X"!=e.opr&&"*"!=e.opr);else for(let n=0;n<e.len;n++){const s=i[e.start-r+n],o=t.seq[e.cidx+n];l.push("<td>"+s+"</td>"),"*"==t.qual?c.push('<td style="color:black;background:'+(s.toUpperCase()==o.toUpperCase()?Ft:Ut)+'">'+t.seq[e.cidx+n]+"</td>"):c.push('<td style="background:'+(s.toUpperCase()==o.toUpperCase()?Ft:Ut)(a[e.cidx+n]/_e)+'">'+t.seq[e.cidx+n]+"</td>")}else for(let n=0;n<e.len;n++)l.push("<td>"+i[e.start-r+n]+"</td>"),"*"==t.qual?c.push('<td style="background:'+Jt(1)+'">'+t.seq[e.cidx+n]+"</td>"):c.push('<td style="background:'+Jt(a[e.cidx+n]/_e)+'">'+t.seq[e.cidx+n]+"</td>");else if(e.len>=Ce)l.push('<td style="font-size:.8em;opacity:.5;white-space:nowrap">'+e.len+" bp</td>"),c.push('<td style="color:black;white-space:nowrap">-----------</td>');else for(let t=0;t<e.len;t++)l.push("<td>"+i[e.start-r+t]+"</td>"),c.push('<td style="color:black">-</td>');else for(let n=e.cidx;n<e.cidx+e.len;n++)l.push("<td>-</td>"),"*"==t.qual?c.push('<td style="color:'+Kt+';background:white">'+t.seq[n]+"</td>"):c.push('<td style="color:'+Kt+";background:"+Ft(a[n]/_e)+'">'+t.seq[n]+"</td>")}let u=0,f=0,d=[],h=[],p=0;for(const e of t.boxes)u=f,f+=e.len,"S"==e.opr&&(p=1,d.push(u),h.push(f));const m=[];t.rnext&&m.push('<li>Next segment on <span style="background:'+Pt+'">'+(n.nochr?"chr":"")+t.rnext+", "+t.pnext+"</span></li>"),t.discord_wrong_insertsize&&t.discord_orientation?m.push('<li><span style="background:'+Lt+';color:white">Wrong insert size</span> mate position: '+t.pnext+'</li><li><span style="background:'+Vt+';color:white">Segments also having wrong orientation</span> '+t.discord_orientation_direction+"</li>"):t.discord_wrong_insertsize?m.push('<li><span style="background:'+Lt+';color:white">Wrong insert size</span> mate position: '+t.pnext+"</li>"):t.discord_orientation?m.push('<li><span style="background:'+Vt+';color:white">Segments having wrong orientation</span> '+t.discord_orientation_direction+"</li>"):t.discord_unmapped2&&m.push('<li><span style="background:'+Ht+';color:white">Other segment in template is unmapped</span></li>'),1&t.flag&&m.push("<li>Template has multiple segments</li>"),2&t.flag&&m.push("<li>Each segment properly aligned</li>"),16&t.flag&&m.push("<li>Reverse complemented</li>"),32&t.flag&&m.push("<li>Next segment in the template is reverse complemented</li>"),64&t.flag&&m.push("<li>This is the first segment in the template</li>"),128&t.flag&&m.push("<li>This is the last segment in the template</li>"),256&t.flag&&m.push("<li>Secondary alignment</li>"),512&t.flag&&m.push("<li>Not passing filters</li>"),1024&t.flag&&m.push("<li>PCR or optical duplicate</li>"),2048&t.flag&&m.push("<li>Supplementary alignment</li>");let g={seq:t.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>: ${t.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>: ${t.seq.length} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE LENGTH</span>: ${Math.abs(t.tlen)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${t.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${t.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${t.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${m.join("")}</ul>`,start_readpos:r+1,boxes:t.boxes,readpanel_DN_maxlength:Ce};return 1==p&&(g.soft_starts=d,g.soft_stops=h),t.discord_unmapped2&&(g.unmapped_mate=!0),g}function nn(t){const e=yt().createHmac("md5",je),n=[t.get("X-Auth-Token")||t.cookies.sessionid,t.query.gdcFileUUID,t.query.gdcFilePosition];return e.update(n.join("")).digest("hex")+".bam"}async function rn(t){if(!t.query.gdcFileUUID||!t.query.gdcFilePosition||!t.query.file)throw"cannot download GDC BAM slice: request is unauthorized";const e=t.query.regions;if(!Array.isArray(e)||0==e.length)throw"req.query.regions[] not non-empty array";const n=[];for(const r of e){const e=await hn(r.chr,r.start,r.stop,t.query.gdcFileUUID,nn(t),t);n.push({filesize:e})}return n}const sn=s().features?.bamCache||{},on=sn.maxAge||72e5,an=sn.maxSize||5e9,ln=sn.checkWait||6e4;let cn,un=0;function fn(t=0){const e=Date.now()+t;if(cn){if(un&&un<=e+5)return;clearTimeout(cn),cn=void 0}un=e,console.log(`will trigger mayDeleteCacheFiles() in ${t} ms`),cn=setTimeout(dn,t)}async function dn(){console.log("checking for cached bam files to delete ...");try{const t=Date.now()-on,e=await m().promises.readdir(s().cachedir_bam),n=[];let r=0,o=0,i=0,a=0;for(const l of e){if(!l.endsWith(".bam")&&!l.endsWith(".bai"))continue;i++;const e=y().join(s().cachedir_bam,l),c=await m().promises.stat(e);if(!c.isFile())continue;const u=c.mtimeMs;u<t?(await m().promises.unlink(e),a++,o+=c.size):(n.push({path:e,time:u,size:c.size}),r+=c.size)}if(n.sort(((t,e)=>e.time-t.time)),r>=an){const t=Date.now()-ln;for(const e of n){if(e.time>t)break;if(await m().promises.unlink(e.path),e.deleted=!0,a++,o+=e.size,r-=e.size,r<an)break}}console.log(`deleted ${a} of ${i} cached bam files (${o} bytes deleted, ${r} remaining)`),cn=void 0,un=0;const l=r&&n.find((t=>!t.deleted));if(l){fn(ln+Math.round(r>=an?0:Math.max(0,l.time+on-Date.now())))}}catch(t){console.error("Error in mayDeleteCacheFiles(): "+t)}}async function hn(t,e,n,r,o,i){fn(ln);const{host:a,headers:l}=Oe(i.query.__genomes).getHostHeaders(i.query);l.compression=!1;const c=y().join(s().cachedir_bam,o),u=a.rest+"/slicing/view/"+r+"?region="+t+":"+e+"-"+n;try{const t=Math.round(Date.now()/1e3);if(await F.yE(c)){if(await Ot(v().stream(u,{method:"GET",headers:l}),m().createWriteStream(c)),await F.yE(c))throw"BAM file slice is not found after downloading"}else await m().promises.utimes(c,t,t);const e=c+".bai";if(await F.yE(e)){if(await async function(t){await F.UE({isbam:!0,args:["index",t],callback:()=>{}})}(c),await F.yE(e))throw"index file is missing after indexing"}else await m().promises.utimes(e,t,t);const n=await m().promises.stat(c);return(0,P.bplen)(n.size,!0)}catch(t){throw t.stack&&console.log(t.stack),"Error with BAM slicing: "+(t.message||t)}}s().features?.bamCache&&fn(ln);const pn="Unannotated";function mn(t){return t.file?t.file:t.file2?t.file2:t.url}function gn(t,e,n,r){const s=[];for(const o of t.samples)if(Number.isFinite(o.readcount)&&(o.readcount=Math.floor(o.readcount),!(o.readcount<=0||e.readcountCutoff&&o.readcount<e.readcountCutoff))){if(r.samples&&n.cohort&&n.cohort.annotation){const t=r.samples[o.i];if(!t)continue;const s=n.cohort.annotation[t];if(o.anno=s,e.cohortOnlyAttr&&n.cohort&&n.cohort.annotation){if(!s)continue;let t=!1;for(const n in e.cohortOnlyAttr){const r=s[n];if(r&&e.cohortOnlyAttr[n][r]){t=!0;break}}if(!t)continue}if(e.cohortHiddenAttr&&n.cohort&&n.cohort.annotation&&n.cohort.attributes){if(!s)continue;let t=!1;for(const r in e.cohortHiddenAttr){n.cohort.attributes.lst.find((t=>t.key==r)).isNumeric;const o=s[r];if(o){if(e.cohortHiddenAttr[r][o]){t=!0;break}}else if(e.cohortHiddenAttr[r][pn]){t=!0;break}}if(t)continue}}if(o.events&&e.spliceEventPercentage){let n=!1;for(const r in o.events){if(!t.events[r])continue;const s=t.events[r].attrValue,i=e.spliceEventPercentage[s];if(!i)continue;const a=o.events[r].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}s.push(o)}return s}function yn(t,...e){if(0==t.length)return 0;const n=t.sort(((t,e)=>t.readcount-e.readcount)),r=[];return e.forEach((t=>{!Number.isFinite(t)||t<0||t>1?r.push(null):r.push(n[Math.floor(n.length*t)].readcount)})),r}var bn=n(1169);function vn(t){return new Promise(((e,n)=>{const r=O().createInterface({input:m().createReadStream(t.file,{encoding:"utf8"})}),s=[];let o=!0;r.on("line",(e=>{if(o)return void(o=!1);const n=e.split("\t"),[i,a,l,c,u,f]=n[0].split(/[:,]/);if(i!=t.chr)return;const d=Number.parseInt(a),h=Number.parseInt(u);if(Number.isNaN(d)||Number.isNaN(h))return;const p=d-1,m=h-1;if(p>t.start&&p<t.stop||m>t.start&&m<t.stop){const t=Number.parseInt(n[1]),e=n[2];s.push({chr:i,start:p,stop:m,type:e,rawdata:[t]})}else p>t.stop&&r.close()})),r.on("close",(()=>{e(s)}))}))}const wn=new Set(["-1","0","1","2"]);function _n(t,e){t[0];const n=Number(t[1]),r=(t[2],t[3].split(".")[0]),s=t[5];if("+"!=s&&"-"!=s)return{name:r};const o="+"==s,i=Number(t[6]),a=Number(t[7]);if(!Number.isInteger(i)||!Number.isInteger(a))return{name:r,strand:s};const l=[],c=[],u=[],f=[],d=[],h=t[15],p=t[17],m=t[20];if(!t[10].includes(",")||!t[11].includes(","))return{name:r,strand:s};const g=t[10].split(",");g.pop();const y=g.map(Number),b=t[11].split(",");b.pop();const v=b.map(Number);if(y.includes(NaN)||v.includes(NaN))return{name:r,strand:s};let w=null,_=0,x=0;for(const[t,e]of y.entries()){_+=e;const r=n+v[t],s=r+e;o?d.push([r,s]):d.unshift([r,s]),t>0&&(o?f.push([w,r]):f.unshift([w,r])),w=s,r<i?s<i?o?c.push([r,s]):l.unshift([r,s]):(o?c.push([r,i]):l.unshift([r,i]),s>a?(i<a&&(o?u.push([i,a]):u.unshift([i,a]),x+=a-i),o?l.push([a,s]):c.unshift([a,s])):i<s&&(o?u.push([i,s]):u.unshift([i,s]),x+=s-i)):r<a?s<=a?r<s&&(o?u.push([r,s]):u.unshift([r,s]),x+=s-r):(r<a&&(o?u.push([r,a]):u.unshift([r,a]),x+=a-r),o?l.push([a,s]):c.unshift([a,s])):o?l.push([r,s]):c.unshift([r,s])}const k={name:p,isoform:r,strand:s,exon:d,rnalen:_};26==t.length&&(k.category=m),e&&e.has(r)&&(k.description=e.get(r)),f.length>0&&(k.intron=f),i==a||(k.cdslen=x,k.codingstart=i,k.codingstop=a,k.coding=u,c.length&&(k.utr5=c),l.length&&(k.utr3=l));const q=h.split(",");return q.pop(),q.length<1||q.some((t=>!wn.has(t)))||function(t,e){if(!t.codingstart)return;const n="+"==t.strand?t.codingstart:t.codingstop;let r=t.exon.findIndex((t=>t[1]>=n&&t[0]<=n));if(-1==r)throw"start codon not matched to an exon: "+JSON.stringify(t);"-"==t.strand&&(r=t.exon.length-r-1);const s=e.split(",")[r];if("-1"==s)throw"start codon frame is -1: "+t.isoform;if("0"!=s){if("1"!=s&&"2"!=s)throw"start codon frame not 0/1/2: "+s+" "+t.isoform;t.startCodonFrame=Number.parseInt(s)}}(k,h),k}const xn=1,kn=10,qn=400,Nn=600,Sn=50,An="rgba(122,103,44,.7)",Mn="red",Tn="#edad0c",Cn="rgba(255,0,0,.5)",jn="#ccc";function En(t,e,n,r,s){if(!t)return;if(!s.name&&!s.isoform)return;const o=[];s.name&&o.push(s.name),s.isoform&&o.push(s.isoform),t.push({chr:s.chr,start:s.start,stop:s.stop,x1:e,x2:n,y:r,isoform:s.isoform,name:o.join(" ")})}function On(t,e,n,r,s,o){const i=o/2,a=o/2,l=Math.max(o/2,6);if(s-2*i<a)return;const c=Math.ceil((s-2*i)/(a+l));if(c<=0)return;const u="+"==e;let f=Math.ceil(n+(s-a*c-l*(c-1))/2);for(let e=0;e<c;e++)t.beginPath(),u?(t.moveTo(f,r),t.lineTo(f+a,r+o/2),t.moveTo(f+a,r+o/2+1),t.lineTo(f,r+o)):(t.moveTo(f+a,r),t.lineTo(f,r+o/2),t.moveTo(f,r+o/2+1),t.lineTo(f+a,r+o)),t.stroke(),f+=a+l}function In(t,e){return new Promise(((n,r)=>{const o=(0,q.spawn)(s().gfServer,["status",e.blat.host,e.blat.port]),i=[],a=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>a.push(t))),o.on("close",(e=>{a.join("").trim()&&n(t+" OFF");const r=i.join("").trim().split("\n");let s=0;for(const t of r)t.startsWith("blat requests")&&(s=t.split(" ")[2]);n(t+" ON, "+s+" requests")}))}))}function Rn(t,e){const n=y().join(s().cachedir,Math.random().toString());return new Promise(((r,o)=>{const i=(0,q.spawn)(s().gfClient,[t.blat.host,t.blat.port,t.blat.seqDir,e,n,"-q=dna","-nohead","-minScore=20","-minIdentity=0","-out=psl"]),a=[];i.stderr.on("data",(t=>a.push(t))),i.on("close",(t=>{const e=a.join("");e&&(console.log("BLAT error",e),o("blat server problem")),r(n)}))}))}var Fn=n(9064),Pn=n(1575);const Dn="ssm_occurrence_centrics";async function Ln(t){const e=new Map,{host:n,headers:r}=t.getHostHeaders(),o=y().join(n.rest,"ssm_occurrences/_mapping");let i;try{const{body:t}=await(0,F.fk)(o,{headers:r});i=t}catch(t){throw console.log(t),"failed to get GDC API _mapping: "+(t.message||t)}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,h=0;for(const t of i.fields){if(Bn(t)){l++;continue}const n=t.split(".");for(let t=1;t<n.length;t++){const r=n.slice(0,t).join("."),s=r+"."+n[t],o=n[t][0].toUpperCase()+n[t].slice(1).replace(/_/g," "),l={id:s.toLowerCase(),name:o,included_types_set:new Set,child_types_set:new Set};if(t==n.length-1){l.isleaf=!0;const t=i._mapping[Dn+"."+s];t&&("keyword"==t.type?(l.type="categorical",u++):"long"==t.type?(l.type="integer",f++):"double"==t.type?(l.type="float",d++):console.log("GDC !!! ERR !!! Unknown variable type: "+t.type)),l.type||c++,$n(l)}if(1==t);else if(l.parent_id=r,l.type){l.included_types_set.add(l.type);let t=e.get(r);for(;t&&(t.included_types_set.add(l.type),t.child_types_set.add(l.type),t.parent_id);)t=e.get(t.parent_id)}a.has(s)&&(l.isObjectList=!0),e.set(s,l)}}try{await async function(t,e){const n=[],r=new Map;for(const e of t.values()){if("integer"!=e.type&&"float"!=e.type)continue;if(Zn[e.id]){e.bins=Zn[e.id];continue}const t=e.id.replace("case.","").replace(/\./g,"__");r.set(t,e.id),n.push(t+" {\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 s=`\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}=e.getHostHeaders(),{body:u}=await(0,F.fk)(l.graphql,{method:"POST",body:{query:s,variables:o}});if("object"!=typeof u.data?.viewer?.explore?.cases?.aggregations)throw"return not object: re.data.viewer.explore.cases.aggregations{}";for(const[e,n]of r){const r=t.get(n);if(!(e in u.data.viewer.explore.cases.aggregations)){console.log("GDC: no stats object returned for numeric term",n),r.bins=zn,a++;continue}const s=u.data.viewer.explore.cases.aggregations[e].stats;if("object"!=typeof s){console.log("GDC: aggregations[facet].stats{} is not object"),r.bins=zn,a++;continue}if(!Number.isFinite(s.Max)||!Number.isFinite(s.Min)){r.bins=zn,a++;continue}if(s.Max<=s.Min){r.bins=zn,a++;continue}const o=(s.Max-s.Min)/5,l="integer"==r.type?Math.ceil(o):o;r.bins={default:{mode:"discrete",type:"regular-bin",bin_size:l,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:s.Min+l}}},i++}console.log(`GDC default binning: ${i} assigned, ${a} unassigned`)}(e,t)}catch(t){throw console.log(t),"assignDefaultBins() failed: "+(t.message||t)}for(const t of e.values())t.type||h++,t.included_types=[...t.included_types_set],t.child_types=[...t.child_types_set],delete t.included_types_set,delete t.child_types_set;console.log("GDC dictionary:",e.size,"total variables,",l,"lines skipped,",c,"lines with unknown term type,","categorical="+u,"integer="+f,"float="+d,"parent="+h),Object.freeze(e),function(t,e){const n=t.cohort.termdb.q={};async function r(e,n){if(0==e.length||!n)return;const r=await t.termdb.termid2totalsize2.get(e.map((t=>t.id)),JSON.parse(n));for(const t of e)if(t){const e=r.get(t.id);"categorical"==t.type&&e?e.length?t.samplecount=e.map((t=>t[1])).reduce(((t,e)=>t+e)):(t.disabled=!0,t.samplecount=0):"integer"!=t.type&&"float"!=t.type||(t.samplecount=e.total,0==e.total&&(t.disabled=!0))}}n.getRootTerms=async(t,n=null)=>{const s=[];for(const t of e.values())null==t.parent_id&&s.push(JSON.parse(JSON.stringify(t)));return await r(s,n),s},n.getTermChildren=async(t,n=null,s=null)=>{const o=[];for(const n of e.values())n.parent_id==t&&o.push(JSON.parse(JSON.stringify(n)));return await r(o,s),o},n.findTermByName=async(t,n=null,s,o=null,i=null)=>{(t=t.toLowerCase()).includes(" ")&&(t=t.replace(/\s/g,"_"));const a=[];for(const n of e.values())i&&!(0,Pn.CG)(n,i)||n.id.includes(t)&&a.push(JSON.parse(JSON.stringify(n)));return await r(a,o),a},n.getAncestorIDs=t=>{if(!e.has(t))return;const n=t.split("."),r=[];for(let t=1;t<n.length;t++)r.push(n.slice(0,t+1).join("."));return r},n.getAncestorNames=n.getAncestorIDs,n.termjsonByOneid=t=>{const n=e.get(t);return n?JSON.parse(JSON.stringify(n)):null},n.getSupportedChartTypes=()=>{const t={},n={};for(const r of e.values())r.type&&(r.cohort in t||(t[r.cohort]=["barchart","table","regression"],n[r.cohort]=0),"survival"!=r.type||t[r.cohort].includes("survival")||t[r.cohort].push("survival"),"condition"!=r.type||t[r.cohort].includes("cuminc")||t[r.cohort].push("cuminc"),"float"!=r.type&&"integer"!=r.type||(n[r.cohort]+=r.samplecount));for(const e in n)n[e]>0&&t[e].push("boxplot"),n[e]>1&&t[e].push("scatterplot");return t}}(t,e),t.cohort.termdb.termtypeByCohort=[],u&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"categorical"}),f&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"integer"}),d&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"float"}),t.__gdc={aliquot2submitter:{cache:new Map,get:async e=>t.__gdc.aliquot2submitter.cache.has(e)?t.__gdc.aliquot2submitter.cache.get(e):e},map2caseid:{cache:new Map,get:e=>t.__gdc.map2caseid.cache.get(e)},caseid2submitter:new Map,caseIds:new Set,casesWithExpData:new Set,gdcOpenProjects:new Set,doneCaching:0};try{await async function(t){const e={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:r}=t.getHostHeaders(),{body:s}=await(0,F.fk)(y().join(n.rest,"files"),{method:"POST",headers:r,body:e});if(!Array.isArray(s?.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 e of s.data.aggregations["cases.project.project_id"].buckets)e.key&&t.__gdc.gdcOpenProjects.add(e.key);console.log("GDC open-access projects:",t.__gdc.gdcOpenProjects.size)}(t)}catch(t){throw console.log(t),"getOpenProjects() failed: "+(t.message||t)}!async function(t){await async function(t){const{host:e,headers:n}=t.getHostHeaders();try{{const t=y().join(e.rest,"ssms"),n=await Gn(t);if(n)throw`${t} returns error code: ${n}`}{const t=y().join(e.rest,"ssm_occurrences"),n=await Gn(t);if(n)throw`${t} returns error code: ${n}`}{const t=y().join(e.rest,"cases"),n=await Gn(t);if(n)throw`${t} returns error code: ${n}`}{const t=y().join(e.rest,"files"),n=await Gn(t);if(n)throw`${t} returns error code: ${n}`}{const t=y().join(e.rest,"analysis/top_mutated_genes_by_project"),n=await Gn(t);if(n)throw`${t} returns error code: ${n}`}{const t=await async function(t,e){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}}",r=await v().post(t,{headers:e,body:JSON.stringify({query:n,variables:{}})});if(r.statusCode>399)return r.statusCode}catch(e){if(console.log(e),e.code)return e.code;throw"see above error from graphql API "+t}console.log("GDC GraphQL API okay: "+t,new Date-n,"ms")}(e.graphql,JSON.parse(JSON.stringify(n)));if(t)throw`${e.graphql} returns error code: ${t}`}}catch(t){throw console.log(t),`\n##########################################\n#\n# Some GDC API unavailable, see error above\n# ${e.rest}\n# ${e.graphql}\n#\n##########################################`}}(t);try{await async function(t){if("stopGdcCacheAliquot"in s().features){if(!Number.isInteger(s().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 e=1e3,n=await Jn(t,1,0);if(!Number.isInteger(n))throw"totalCases not integer";const r=new Date;console.log("GDC: Start to cache sample IDs of",n,"cases...");for(let r=0;r<Math.ceil(n/e)&&(await Jn(t,e,1e3*r),!(Number.isInteger(s().features.stopGdcCacheAliquot)&&r>=s().features.stopGdcCacheAliquot));r++);await async function(t){const{host:e,headers:n}=t.getHostHeaders(),r=`${e.geneExp}/gene_expression/availability`;try{const e=[...t.__gdc.caseIds],{body:s}=await(0,F.fk)(r,{method:"post",headers:n,body:{case_ids:e,gene_ids:["ENSG00000141510"]}});if(!Array.isArray(s.cases?.details))throw"re.cases.details[] not array";for(const e of s.cases.details)e.has_gene_expression_values&&t.__gdc.casesWithExpData.add(e.case_id);delete t.__gdc.caseIds}catch(t){console.log("You don't have access to /gene_expression/availability/, you cannot run GDC hierCluster")}}(t),t.__gdc.doneCaching=!0,console.log("GDC: Done caching sample IDs. Time:",Math.ceil((new Date-r)/1e3),"s"),console.log("\t",t.__gdc.aliquot2submitter.cache.size,"aliquot IDs to sample submitter id,"),console.log("\t",t.__gdc.caseid2submitter.size,"case uuid to submitter id,"),console.log("\t",t.__gdc.map2caseid.cache.size,"different ids to case uuid,"),console.log("\t",t.__gdc.casesWithExpData.size,"cases with gene expression data.")}(t)}catch(t){throw t.stack&&console.log(t.stack),"cacheSampleIdMapping() failed: "+(t.message||t)}}(t)}function $n(t){"case.diagnoses.age_at_diagnosis"!=t.id||(t.valueConversion={scaleFactor:1/365,fromUnit:"day",toUnit:"year"})}const zn={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}}},Zn={"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 Un=new Set(["case.consent_type","case.days_to_consent","case.days_to_index"]);function Bn(t){return!!(t.startsWith("ssm")||t.startsWith("case.observation")||t.startsWith("case.available_variation_data"))||(!(!t.endsWith("_id")||t.endsWith("project_id"))||(!!Un.has(t)||void 0))}async function Gn(t){try{const e=new Date,n=await v()(t);if(n.statusCode>399)return n.statusCode;console.log("GDC API okay: "+t,new Date-e,"ms")}catch(e){if(console.log("See error from",t),console.log(e),e.code)return e.code;throw"gdc api down: "+t}}async function Jn(t,e,n,r){const s=["fields=submitter_id,samples.portions.analytes.aliquots.aliquot_id,samples.submitter_id"];if(r)s.push('filters={"op":"and","content":[{"op":"=","content":{"field":"samples.portions.analytes.aliquots.aliquot_id","value":["'+r+'"]}}]}');else{if(!Number.isInteger(e)||!Number.isInteger(n))throw"size and from not integers";s.push("size="+e),s.push("from="+n)}const{host:o,headers:i}=t.getHostHeaders(),{body:a}=await(0,F.fk)(o.rest+"/cases?"+s.join("&"),{headers:i});if(!Array.isArray(a?.data?.hits))throw"re.data.hits[] not array";for(const e of a.data.hits){const n=e.id;if(!n)throw"h.id (case uuid) missing";t.__gdc.caseIds.add(n);const r=e.submitter_id;if(!r)throw"h.submitter_id missing";if(t.__gdc.caseid2submitter.set(n,r),t.__gdc.map2caseid.cache.set(r,n),Array.isArray(e.samples))for(const r of e.samples){const e=r.submitter_id;if(!e)throw"sample.submitter_id missing";if(t.__gdc.map2caseid.cache.set(e,n),Array.isArray(r.portions))for(const s of r.portions)if(Array.isArray(s.analytes))for(const r of s.analytes)if(Array.isArray(r.aliquots))for(const s of r.aliquots){const r=s.aliquot_id;if(!r)throw"aliquot.aliquot_id missing";t.__gdc.aliquot2submitter.cache.set(r,e),t.__gdc.map2caseid.cache.set(r,n)}}}return a.data?.pagination?.total}var Hn=n(4973),Wn=n(3625),Vn=n(478),Yn=n(8907),Kn=n(394);function Xn(t,e){if(e.updateAttr&&!t.label){for(const n of e.updateAttr){let e=t;for(const t of n)if(e)if("object"==typeof t)for(const n in t)e[n]=t[n];else e=e[t]}t.label&&delete e.updateAttr}}function Qn(t,e,n){if(!t.cohort?.db?.refresh)return;const r=t.cohort.db.refresh;delete t.cohort.db.refresh,e.get(`${n}/${r.route}`,(async(e,n)=>{n.send({label:t.label,files:[]})})),e.post(`${n}/${r.route}`,(async(e,n)=>{try{const r=t.cohort.db?.file?.startsWith(s().tpmasterdir)?t.cohort.db.file:y().join(s().tpmasterdir,t.cohort.db.file||""),o=e.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 e=y().join(s().tpmasterdir,o.dbfile);if(!await m().stat(e))throw`dbfile not found: '${e}'`;const n=t.cohort.db.file_fullpath||r;if(e===n)throw"db file source and target are the same";console.log(`copying ${e} to ${n}`),await m().copyFile(e,n)}await fr(t),n.send({status:"ok"})}catch(t){console.log(t),n.send({error:t.error||t})}}))}var tr=n(2188),er=n(2974),nr=n(3795),rr=n(7934),sr=n(5057),or=n(3677),ir=n(4924),ar=n(901);const lr="Unannotated";async function cr(t,e,n,r=null,o=null){await fr(t),t.queries&&(await async function(t,e){const n=t.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)bn.xq(t);else if(n.byrange.bcffile)n.byrange.bcffile=n.byrange.bcffile.startsWith(s().tpmasterdir)?n.byrange.bcffile:y().join(s().tpmasterdir,n.byrange.bcffile),n.byrange._tk={file:n.byrange.bcffile},n.byrange.get=await pr(t,e),n.byrange._tk?.samples.length||delete n.byrange._tk.samples,hr(t,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 t in n.byrange.chr2bcffile)n.byrange._tk.chr2files[t]={file:y().join(s().tpmasterdir,n.byrange.chr2bcffile[t])};delete n.byrange.chr2bcffile,n.byrange.get=await pr(t,e),n.byrange._tk.samples.length||delete n.byrange._tk.samples,hr(t,n.byrange._tk.samples,"snvindel.byrange.bcffile")}if(n.byisoform){if(!n.byisoform.gdcapi)throw"unknown query method for queries.snvindel.byisoform";bn.CN(t)}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";bn.wm(t)}}(t,e),await async function(t,e){const n=t.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(s().tpmasterdir)?n.byrange.file:y().join(s().tpmasterdir,n.byrange.file),n.byrange.get=await async function(t,e){const n=t.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,e);{const t=await F.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}return async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";const r=mr(e),s=await(0,ar.T)(e,n.samples,t);if(0==s?.size)return[];const o=new Map;for(const t of e.rglst)await F.UE({args:[n.file||n.url,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.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(t){return}if(l.dt!=P.dtfusionrna&&l.dt!=P.dtsv)return;if(l.class=l.dt==P.dtsv?P.mclasssv:P.mclassfusionrna,e.hiddenmclass&&e.hiddenmclass.has(l.class))return;if(l.sample&&s&&!s.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:t.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:t.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 t=l.pairlst.findIndex((t=>t.chr==chr&&t.pos==a));if(-1==t)throw"current point missing from pairlst";c=t}}const h=[l.dt,t.chr,a,f,c,encodeURIComponent(u)].join(Hn.dq);let p;if(l.sample&&(p={sample_id:l.sample},l.mattr)){if(r)for(const t in r){const e=t in l.mattr?l.mattr[t]:lr;if(r[t].has(e))return}e.addFormatValues&&(p.formatK2v=l.mattr)}o.has(h)||o.set(h,{ssm_id:h,dt:l.dt,class:l.class,chr:t.chr,pos:a,strand:f,pairlstIdx:c,mname:u,pairlst:d,samples:[]}),p&&o.get(h).samples.push(p)}});return[...o.values()]}}(t,e),hr(t,n.byrange.samples,"svfusion.byrange")}}(t,e),await async function(t,e){const n=t.queries.geneCnv;if(!n)return;if(!n.bygene)throw"geneCnv.bygene missing";n.bygene.gdcapi&&bn.IK(t)}(t),await async function(t,e){const n=t.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(s().tpmasterdir)?n.byrange.file:y().join(s().tpmasterdir,n.byrange.file),n.byrange.get=await async function(t,e){const n=t.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,e);{const t=await F.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}return async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";if(e.cnvMaxLength&&!Number.isInteger(e.cnvMaxLength))throw"cnvMaxLength is not integer";if(e.cnvGainCutoff&&!Number.isFinite(e.cnvGainCutoff))throw"cnvGainCutoff is not finite";if(e.cnvLossCutoff&&!Number.isFinite(e.cnvLossCutoff))throw"cnvLossCutoff is not finite";const r=mr(e),s=await(0,ar.T)(e,n.samples,t);if(0==s?.size)return[];const o=[];for(const t of e.rglst)await F.UE({args:[n.file||n.url,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:n=>{const i=n.split("\t"),a=Number(i[1]),l=Number(i[2]);if(e.cnvMaxLength&&l-a>=e.cnvMaxLength)return;let c;try{c=JSON.parse(i[3])}catch(t){return}if(c.dt==P.dtcnv){if(c.chr=t.chr,c.start=a,c.stop=l,Number.isFinite(c.value)){if(c.value>0&&e.cnvGainCutoff&&c.value<e.cnvGainCutoff)return;if(c.value<0&&e.cnvLossCutoff&&c.value>e.cnvLossCutoff)return;c.class=c.value>0?P.mclasscnvgain:P.mclasscnvloss}else if(c.class!=P.mclasscnvgain&&c.class!=P.mclasscnvloss)return;if(c.ssm_id=[t.chr,c.start,c.stop,c.class].join(Hn.dq),(!e.hiddenmclass||!e.hiddenmclass.has(c.class))&&(!c.sample||!s||s.has(c.sample))){if(c.sample){const t={sample_id:c.sample};if(c.mattr){if(r)for(const t in r){const e=t in c.mattr?c.mattr[t]:lr;if(r[t].has(e))return}e.addFormatValues&&(t.formatK2v=c.mattr)}delete c.sample,c.samples=[t]}o.push(c)}}}});return o}}(t,e),void hr(t,n.byrange.samples,"cnv.byrange")}throw"unknown cnv.byrange.src"}(t,e),await async function(t,e){const n=t.queries.ld;if(!n)return;if(!Array.isArray(n.tracks)||!n.tracks.length)throw"ld.tracks[] not nonempty array";for(const t of n.tracks){if(!t.name)throw"name missing from one of ld.tracks[]";if(!t.file)throw".file missing from one of ld.tracks[]";t.file0=t.file,t.file=y().join(s().tpmasterdir,t.file),await F.LC(t.file),t.nochr=await F.Jy(t.file,null,e)}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"}(t,e),await(0,ir.validate_query_geneExpression)(t,e),await async function(t,e){const n=t.queries.rnaseqGeneCount;if(!n)return;if(!n.file)throw"unknown data type for rnaseqGeneCount";n.file=y().join(s().tpmasterdir,n.file);{const e=(await(r=n.file,new Promise(((t,e)=>{const n=[],s=[],o=(0,q.spawn)("head",["-1",r]);o.stdout.on("data",(t=>n.push(t.toString()))),o.stderr.on("data",(t=>s.push(t.toString()))),o.on("error",(t=>{s.length&&e(s.join(""))})),o.on("close",(r=>{0!=r&&e("head command exited with non-zero status and this error: "+s.join("")),t(n.join(""))}))})))).trim().split("\t").slice(4);n.allSampleSet=new Set(e);const s=[];for(const e of n.allSampleSet)t.cohort.termdb.q.sampleName2id(e)||s.push(e);console.log(n.allSampleSet.size,`rnaseqGeneCount samples from ${t.label}`)}var r;n.get=async function(e){if(2!=e.samplelst?.groups?.length)throw".samplelst.groups.length!=2";if(e.samplelst.groups[0].values?.length<1)throw"samplelst.groups[0].values.length<1";if(e.samplelst.groups[1].values?.length<1)throw"samplelst.groups[1].values.length<1";const r=[];let o=0;for(const s of e.samplelst.groups[0].values){if(!Number.isInteger(s.sampleId))continue;const e=t.cohort.termdb.q.id2sampleName(s.sampleId);e&&(n.allSampleSet.has(e)?r.push(e):o+=1)}const i=[];let a=0;for(const r of e.samplelst.groups[1].values){if(!Number.isInteger(r.sampleId))continue;const e=t.cohort.termdb.q.id2sampleName(r.sampleId);e&&(n.allSampleSet.has(e)?i.push(e):a+=1)}const l=r.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:r.map((t=>t)).join(","),control:i.map((t=>t)).join(","),input_file:n.file,output_path:y().join(s().binpath,"utils")},f=8;let d;if(r.length<=f&&i.length<=f||"edgeR"==e.method){const t=new Date,n=(await async function(t,e){return new Promise(((n,r)=>{y().join(s().Rscript,t);const o=(0,q.spawn)(s().Rscript,[t]),i=[],a=[];try{at.Readable.from(e).pipe(o.stdin)}catch(e){o.kill();let n=e;a.length&&(n+=`killed edgeR('${t}'), stderr: ${a.join("").trim()}`),r(n)}o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>a.push(t))),o.on("error",(e=>{a.length&&console.log(`edgeR('${t}') ps.on('error') stderr:`,a),r(e)})),o.on("close",(e=>{0!==e?r(`spawned '${t}' exited with a non-zero status and this stderr:\n${a.join("")}`):n(i.toString())}))}))}(y().join(s().binpath,"utils","edge.R"),JSON.stringify(u)),new Date);console.log("Time taken to run edgeR:",n-t,"ms"),e.method="edgeR";const r=y().join(s().binpath,"utils","r_output.txt");d=JSON.parse(m().readFileSync(r,"utf8")),m().unlink(r,(()=>{}))}else if("wilcoxon"==e.method){const t=new Date,n=await(0,Q.run_rust)("DEanalysis",JSON.stringify(u)),r=new Date;for(const t of n.split("\n"))t.startsWith("adjusted_p_values:")&&(d=JSON.parse(t.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",r-t,"ms"),e.method="wilcoxon"}else{const t=new Date,n=await(0,Q.run_rust)("DEanalysis",JSON.stringify(u)),r=new Date;for(const t of n.split("\n"))t.startsWith("adjusted_p_values:")&&(d=JSON.parse(t.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",r-t,"ms"),e.method="wilcoxon"}return{data:d,sample_size1:l,sample_size2:c,method:e.method}}}(t),await(0,or.validate_query_singleSampleMutation)(t,e),await async function(t,e){const n=t.queries.singleSampleGenomeQuantification;if(!n)return;for(const r in n){if(!Number.isFinite(n[r].min))throw"min not a number";if(!Number.isFinite(n[r].max))throw"max not a number";if(n[r].min>=n[r].max)throw"min>=max";if(!n[r].folder)throw"unknown query method for singleSampleGenomeQuantification";n[r].get=async(o,i)=>{let a=o;if(t.cohort?.termdb?.q?.sampleName2id&&(a=t.cohort.termdb.q.sampleName2id(o),null==a))return[];const l=y().join(s().tpmasterdir,n[r].folder,a.toString());try{await m().promises.stat(l)}catch(t){if("EACCES"==t.code)throw"cannot read file, permission denied";if("ENOENT"==t.code)throw"no data for this sample";throw"failed to load data"}return await wr(l,e,n[r],i)}}}(t,e),await async function(t,e){const n=t.queries.singleSampleGbtk;if(!n)return;for(const e in n){if(!Number.isFinite(n[e].min))throw"min not a number";if(!Number.isFinite(n[e].max))throw"max not a number";if(n[e].min>=n[e].max)throw"min>=max";if(!n[e].folder)throw"unknown query method for singleSampleGbtk";n[e].get=async r=>{let o=r;if(t.cohort?.termdb?.q?.sampleName2id&&(o=t.cohort.termdb.q.sampleName2id(r),null==o))return{};const i=y().join(n[e].folder,o+".gz");try{return await m().promises.stat(y().join(s().tpmasterdir,i)),{path:i}}catch(t){return{}}}}}(t),await(0,rr.validate_query_singleCell)(t,e),await(0,sr.validate_query_TopVariablyExpressedGenes)(t,e),await(0,Hn.uK)(t),await function(t){if(!t.ssm2canonicalisoform)return;if(t.ssm2canonicalisoform.gdcapi)return void bn.vK(t.ssm2canonicalisoform,t.getHostHeaders);throw"ssm2canonicalisoform.gdcapi is false"}(t),await function(t,e){if(!e.genedb.hasTable_refseq2ensembl)return;t.refseq2ensembl_query=e.genedb.db.prepare("select ensembl from refseq2ensembl where refseq=?")}(t,e),await function(t,e){if(!t.queries.snvindel&&!t.queries.svfusion&&!t.queries.geneCnv)return;t.mayGetGeneVariantData=async(n,r)=>{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 s=[];if("snp"==n.term.subtype){if(!t.queries.snvindel?.allowSNPs)throw"snvindel does not allow snp";const o=(await kr(t,n.term,e,r)).find((t=>n.term.alleles.includes(t.ref)&&n.term.alleles.includes(t.alt)));if(o){const t=[];for(const e of o.samples){if(!e.formatK2v?.GT)continue;const n=[];for(const t of e.formatK2v.GT.split("/"))0==t?n.push(o.ref):1==t?n.push(o.alt):console.log("unknown allele idx");n.join("/"),n.join("/");t.push({sample_id:e.sample_id,GT:n.join("/")})}const e={samples:t};s.push(e)}}else{if(t.queries.snvindel){const o=await kr(t,n.term,e,r);s.push(...o)}if(t.queries.svfusion){const o=await async function(t,e,n,r){const s={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,sessionid:r.sessionid};if(t.queries.svfusion.byrange)return await xr(e,n),s.rglst=[e],await t.queries.svfusion.byrange.get(s);throw"unknown queries.svfusion method"}(t,n.term,e,r);s.push(...o)}if(t.queries.cnv){const o=await async function(t,e,n,r){const s={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,cnvMaxLength:e?.q?.cnvMaxLength,cnvGainCutoff:e?.q?.cnvGainCutoff,cnvLossCutoff:e?.q?.cnvLossCutoff,sessionid:r.sessionid};if(t.queries.cnv.byrange)return await xr(e.term,n),s.rglst=[e.term],await t.queries.cnv.byrange.get(s);throw"unknown queries.cnv method"}(t,n,e,r);s.push(...o)}if(t.queries.geneCnv){const e=await async function(t,e,n,r){const s={filter0:r.filter0,sessionid:r.sessionid};if(t.queries.geneCnv.bygene)return e.name?(s.gene=e.name,await t.queries.geneCnv.bygene.get(s)):[];throw"unknown queries.geneCnv method"}(t,n.term,0,r);s.push(...e)}}const o=new Map;for(const t of s)if(Array.isArray(t.samples))for(const e of t.samples){o.has(e.sample_id)||o.set(e.sample_id,{sample:e.sample_id}),o.get(e.sample_id)[n.term.name]||(o.get(e.sample_id)[n.term.name]={key:n.term.name,label:n.term.name,values:[]});const r={gene:n.term.name,isoform:t.isoform,dt:t.dt,chr:n.term.chr,class:t.class,pos:t.pos||(t.start?t.start+"-"+t.stop:""),mname:t.mname};if("value"in t&&(r.value=t.value),e.formatK2v)for(const t in e.formatK2v)r[t]=e.formatK2v[t];t.dt==P.dtsnvindel?e.GT&&(r.value=e.GT,r.key=e.GT):t.dt!=P.dtfusionrna&&t.dt!=P.dtsv||(r.pairlst=t.pairlst),o.get(e.sample_id)[n.term.name].values.push(r)}return await async function(t,e,n,r){if(!e.assayAvailability?.byDt)return;const s=t.filter?new Set((await(0,Yn.cf)(t.filter,e)).map((t=>t.id))):null;for(const t in e.assayAvailability.byDt){const o=e.assayAvailability.byDt[t];if(o.byOrigin)for(const e in o.byOrigin){_r(t,o.byOrigin[e],n,r,e,s)}else _r(t,o,n,r,!1,s)}}(r,t,o,n.term.name),o}}(t,e)),await function(t){if(!t.assayAvailability)return;if(t.assayAvailability.byDt)for(const e in t.assayAvailability.byDt){const n=t.assayAvailability.byDt[e];if(n.byOrigin)for(const e in n.byOrigin){const r=n.byOrigin[e];if(!r.yes||!r.no||!r.term_id)throw"ds.assayAvailability.byDt.*.byOrigin properties require .term_id .yes{} .no{}";qr(t,r)}else{if(!n.yes||!n.no||!n.term_id)throw"ds.assayAvailability.byDt properties require .term_id .yes{} .no{}";qr(t,n)}}}(t),await function(t){if(!t.viewModes)return;if(!Array.isArray(t.viewModes))throw"ds.viewModes[] not array";for(const e of t.viewModes)if(e.byInfo){if(!t?.queries?.snvindel?.info)throw"view mode byInfo but queries.snvindel.info missing";const n=t.queries.snvindel.info[e.byInfo];if(!n)throw"unknown INFO field for viewmode byInfo";if("Float"!=n.Type&&"Integer"!=n.Type)throw"viewmode byInfo Type is not numeric";e.type="numeric",e.label=e.byInfo}else if(!e.byAttribute)throw"view mode not byInfo or byAttribute"}(t),t.cohort?.db?.refresh&&r&&await Qn(t,r,o)}function ur(t){const e={isMds3:!0,label:t.label};if(t.viewModes&&(e.skewerModes=t.viewModes),t.noGenomicMode4lollipopTk&&(e.noGenomicMode4lollipopTk=!0),function(t,e){if(!t.queries)return;const n={};t.queries.singleSampleMutation&&(n.singleSampleMutation={sample_id_key:t.queries.singleSampleMutation.sample_id_key,discoSkipChrM:t.queries.singleSampleMutation.discoSkipChrM});if(t.queries.singleSampleGenomeQuantification){n.singleSampleGenomeQuantification={};for(const e in t.queries.singleSampleGenomeQuantification)n.singleSampleGenomeQuantification[e]=JSON.parse(JSON.stringify(t.queries.singleSampleGenomeQuantification[e])),delete n.singleSampleGenomeQuantification[e].folder}if(t.queries.singleSampleGbtk){n.singleSampleGbtk={};for(const e in t.queries.singleSampleGbtk)n.singleSampleGbtk[e]=JSON.parse(JSON.stringify(t.queries.singleSampleGbtk[e])),delete n.singleSampleGbtk[e].folder}const r=t.queries.snvindel;r&&(e.has_skewer=!0,n.snvindel={forTrack:r.forTrack,vcfid4skewerName:r.vcfid4skewerName,skewerRim:r.skewerRim,ssmUrl:r.ssmUrl},r.m2csq&&(n.snvindel.m2csq={by:r.m2csq.by}),r.info&&(e.bcf={info:r.info}),r.format&&(e.bcf||(e.bcf={}),e.bcf.format=r.format));if(t.queries.ld){n.ld=JSON.parse(JSON.stringify(t.queries.ld));for(const t of n.ld.tracks)delete t.file}e.queries=n}(t,e),t.cohort?.termdb&&(e.termdb={},t.cohort.termdb.allowCaseDetails&&(e.termdb.allowCaseDetails={sample_id_key:t.cohort.termdb.allowCaseDetails.sample_id_key})),t.variant2samples){const n=t.variant2samples;e.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 e}async function fr(t){if(t.cohort){if(!t.cohort.termdb)throw"ds.cohort is set but cohort.termdb{} missing";if(!t.cohort.db)throw"ds.cohort is set but cohort.db{} missing";if(!t.cohort.db.file&&!t.cohort.db.file_fullpath)throw"ds.cohort.db.file missing"}else{if(!t.termdb)return;t.cohort={},t.cohort.termdb=t.termdb,delete t.termdb}const e=t.cohort.termdb;if(e?.dictionary?.gdcapi)await Ln(t);else if(e?.dictionary?.dbFile)t.cohort.db={file:e.dictionary.dbFile},delete e.dictionary.dbFile,(0,Kn.JV)(t);else{if(!t.cohort.db)throw"unknown method to initiate dictionary";(0,Kn.JV)(t)}if(e.termid2totalsize2&&(e.termid2totalsize2.gdcapi,e.termid2totalsize2.get=async(n,r={},s=null)=>e.termid2totalsize2.gdcapi?await bn.ws(n,r,s,t):await async function(t,e,n,r){const s=dr(e,r),o=new Map;for(const e of t)if(e.term&&"categorical"==e.term.type){const t={term1_id:e.id,term1_q:{type:"values"},filter:s},n=await(0,ot.e8)(t,r,r.cohort.termdb);if(!n?.data?.charts?.[0])continue;const i=[];for(const t of n.data.charts[0].serieses)i.push([t.seriesId,t.total]);o.set(e.id,i)}return n?[o,n]:o}(n,r,s,t)),function(t){const e=t.selectCohort;if(!e)return;if("object"!=typeof e)throw"selectCohort{} not object";if(!e.term)throw"term{} missing from termdb.selectCohort";if(!e.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof e.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=e.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';{const n=t.q.termjsonByOneid(e.term.id);if(!n)throw"termdb.selectCohort.term.id is invalid";if("categorical"!=n.type)throw"termdb.selectCohort.term type is not categorical"}if(!e.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(e.values))throw"termdb.selectCohort.values is not array";if(0==e.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const t of e.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[]"}}(e),await async function(t){if(!t.restrictAncestries)return;if(!Array.isArray(t.restrictAncestries)||0==t.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const e of t.restrictAncestries){if(!e.name)throw"name missing from one of restrictAncestries";if("object"!=typeof e.tvs)throw".tvs{} missing from one of restrictAncestries";if(!e.tvs.term)throw"tvs.term{} missing from an ancestry";if(!e.tvs.term.id)throw"tvs.term.id missing from an ancestry";{const n=t.q.termjsonByOneid(e.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(e.PCcount))throw"PCcount is not integer";if(e.PCcount<=1)throw"PCcount must be greater than 1";if(e.PCTermId){e.pcs=new Map;for(let n=1;n<=e.PCcount;n++){const r=e.PCTermId+n,s=t.q.termjsonByOneid(r);if(!s)throw"a PC term is not found in termdb";const o=t.q.getAllValues4term(r);if(!o||!o.size)throw"no sample PC values are retrieved by restrictAncestries term: "+r;e.pcs.set(s.name,o)}}else{if(!e.PCBySubcohort)throw"unknown PC source and configuration for restrictAncestries";for(const n in e.PCBySubcohort){let r=!0;for(const e of t.selectCohort.values)if(n==e.keys.sort().join(",")){r=!1;break}if(r)throw"unknown subcohort from PCBySubcohort";const s=e.PCBySubcohort[n];if(!s.termId)throw"termId missing from a subcohort of PCBySubcohort";s.pcs=new Map;for(let n=1;n<=e.PCcount;n++){const e=s.termId+n,r=t.q.termjsonByOneid(e);if(!r)throw"a PC term is not found in termdb";const o=t.q.getAllValues4term(e);if(!o||!o.size)throw"no sample PC values are retrieved by restrictAncestries.PCBySubcohort.<>.termId";s.pcs.set(r.name,o)}}}}}(e),await(0,tr.wz)(t),await(0,er.te)(t),"minTimeSinceDx"in e){if(!Number.isFinite(e.minTimeSinceDx))throw"termdb.minTimeSinceDx not number";if(e.minTimeSinceDx<=0)throw"termdb.minTimeSinceDx<=0"}if("ageEndOffset"in e){if(!Number.isFinite(e.ageEndOffset))throw"termdb.ageEndOffset not number";if(e.ageEndOffset<=0)throw"termdb.ageEndOffset<=0"}if(e.convertSampleId){if(!e.convertSampleId.gdcapi)throw"unknown implementation of tdb.convertSampleId";bn.Ak(e,t)}if(await async function(t){if(!t.cohort?.cumburden)return;t.cohort.cumburden.files;const e=t.cohort.cumburden.files;for(const t of["fit","surv","sample"]){const n=e[t];if(!n)throw`missing ds.cohort.burden.files.${t}`;const r=(0,q.spawnSync)(s().Rscript,["-e",`load('${s().tpmasterdir}/${n}')`],{encoding:"utf-8"});if(r?.status||r?.stderr)throw console.log(r),`error with ds.cohort.cumburden.files.${t}`}}(t),t.cohort?.db?.connection){t.sampleName2Id=new Map,t.sampleId2Name=new Map;const e="SELECT * FROM sampleidmap",n=t.cohort.db.connection.prepare(e).all();for(const e of n)t.sampleId2Name.set(e.id,e.name),t.sampleName2Id.set(e.name,e.id);t.getSampleIdMap=e=>{const n={};for(const r in e)n[sampleId]=t.sampleId2Name.get(+sampleId);return n}}if(t.cohort.mutationset){const{mayGetGeneVariantData:e,getTermTypes:r,mayGetMatchingGeneNames:s}=n(7833);t.mayGetGeneVariantData=e,t.getTermTypes=r,t.mayGetMatchingGeneNames=s}}function dr(t,e){const n=[];if(t.filterObj&&n.push(t.filterObj),t.tid2value&&n.push((0,ar.w)(t.tid2value,e)),0!=n.length)return 1==n.length?n[0]:(0,Vn.xH)(n)}function hr(t,e,n){if(!e)return;let r;if(t?.cohort?.termdb){for(const t of e){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer sample id from "+n;t.name=e}r=", all integer IDs"}console.log(e.length,"samples from "+n+" of "+t.label+r)}async function pr(t,e){const n=t.queries.snvindel.byrange;if(n._tk.file)await F._H(n._tk,e,!0);else if(n._tk.chr2files){let t;for(const r in n._tk.chr2files){if("chr17"!=r)continue;const s=n._tk.chr2files[r];try{await F._H(s,e,!0);const o=JSON.stringify(s.samples);if(t){if(o!=t)throw"Different samples found in bcf file of "+r}else t=o,n._tk.samples=s.samples,n._tk.format=s.format,n._tk.info=s.info,n._tk.nochr=s.nochr}catch(t){console.log("missing file ignored:",s.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 t in n._tk.format)"GT"==t&&(n._tk.format[t].isGT=!0);if(t.queries.snvindel.format4filters){if(!Array.isArray(t.queries.snvindel.format4filters))throw"snvindel.format4filters[] is not array";for(const e of t.queries.snvindel.format4filters)n._tk.format[e]&&(n._tk.format[e].isFilter=!0);delete t.queries.snvindel.format4filters}}if(n._tk.info){if(n.infoFields){for(const t of n.infoFields){if(!t.key)throw".key missing from one of snvindel.byrange.infoFields[]";t.name||(t.name=t.key);const e=n._tk.info[t.key];if(!e)throw"invalid key from one of snvindel.byrange.infoFields[]";e.categories=t.categories,e.name=t.name,e.separator=t.separator}delete n.infoFields}if(t.queries.snvindel.infoUrl){for(const e of t.queries.snvindel.infoUrl){const t=n._tk.info[e.key];if(!t)throw"invalid key from one of snvindel.infoUrl[]";t.urlBase=e.base}delete t.queries.snvindel.infoUrl}}return t.queries.snvindel.info=n._tk.info,t.queries.snvindel.format=n._tk.format,async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";const r=mr(e);let s;if(n._tk.chr2files){const t=n._tk.chr2files[e.rglst[0].chr];if(!t)throw"unknown chr for chr2files";s=t.file}else s=n._tk.file||n._tk.url;const o=["query",s,"-r",e.rglst.map((t=>(n._tk.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+(t.stop+1))).join(","),"-f","%ID\t%CHROM\t%POS\t%REF\t%ALT\t%INFO\t%FORMAT\n"],i=await(0,ar.T)(e,n._tk.samples,t);if(i){if(0==i.size)return[];o.push("-s",[...i].join(","))}e.variantFilter&&(0,nr.u)(e.variantFilter,o);const a=[];return await F.UE({isbcf:!0,args:o,dir:n._tk.dir,callback:s=>{const o=s.split("\t"),l=o[0],c=o[1],u=Number(o[2]),f=o[3],d=o[4].split(","),h=o[5],p={pos:u-1};(0,Wn.H)(n._tk,f,d,p,h,l,e.isoform);for(const s of p.mlst)e.hiddenmclass&&e.hiddenmclass.has(s.class)||gr(s,e)||p.mlst.length>1&&e.variantFilter?.lst&&yr(s,e)||(s.chr=(n._tk.nochr?"chr":"")+c,s.ssm_id=[s.chr,s.pos,s.ref,s.alt].join(Hn.dq),n._tk?.samples?.length&&(br(n,s,o,e.addFormatValues,t,i,r),!s.samples)||a.push(s))}}),a}}function mr(t){const e=t.formatFilter||{};return"format"==t.skewerRim?.type&&t.skewerRim.hiddenvalues?.size&&(e[t.skewerRim.formatKey]=t.skewerRim.hiddenvalues),Object.keys(e).length?e:void 0}function gr(t,e){if(!e.infoFilter)return!1;for(const n in e.infoFilter){const r=t.info[n];if(r)if(Array.isArray(r)){for(const t of e.infoFilter[n])if(r.includes(t))return!0}else if(e.infoFilter[n].includes(r))return!0}return!1}function yr(t,e){for(const n of e.variantFilter.lst){const e=t.info[n.tvs.term.id];if(null==e)return!0;if("integer"==n.tvs.term.type||"float"==n.tvs.term.type){const t=Number(e);if(Number.isNaN(t))return!0;const r=n.tvs.ranges?.[0];if(r){if("start"in r)if(r.startinclusive){if(t<r.start)return!0}else if(t<=r.start)return!0;if("stop"in r)if(r.stopinclusive){if(t>r.stop)return!0}else if(t>=r.stop)return!0}}}return!1}function br(t,e,n,r,s,o,i){if(!n[6]||"."==n[6])return;const a=[];for(const e of n[6].split(":")){const n=t._tk.format[e];if(!n)throw"invalid format field: "+n;a.push(n)}const l=[];let c=t._tk.samples;o&&(c=[...o].map((t=>({name:t}))));for(const[t,e]of c.entries()){const s=n[t+7];if(!s||"."==s)continue;const o=vr(s.split(":"),a,e,r);if(o){if(i){let t=!1;for(const e in i){const n=e in o.formatK2v?o.formatK2v[e]:lr;if(i[e].has(n)){t=!0;break}}if(t)continue}l.push(o)}}l.length&&(e.samples=l)}function vr(t,e,n,r){const s={};for(const[n,r]of e.entries()){const e=t[n];if(e&&"."!=e)if(r.isGT){if("./."==e||".|."==e)continue;s.GT=e}else s[r.ID]=e}if(0==Object.keys(s).length)return null;const o={sample_id:n.name};return r&&(o.formatK2v=s),o}function wr(t,e,n,r=1){r=Number(r);const s=200,o=20;let i=0;for(const t in e.majorchr)i+=e.majorchr[t];const a=800/i,l={};let c=0;const u=[];for(const t in e.majorchr){const n=e.majorchr[t];l[t]=(0,Fn.Z)().domain([0,n]).range([a*c,a*(c+n)]),c+=n,u.push({chr:t,chrLen:n,xStart:a*(c-n),xStop:a*c})}const f=(0,Fn.Z)().domain([n.min,n.max]).range([s,0]),d=(0,S.createCanvas)(890*r,240*r),h=d.getContext("2d");r>1&&h.scale(r,r),g(n.max),g(0),g(n.min);const p=O().createInterface({input:m().createReadStream(t)});return new Promise(((t,r)=>{p.on("line",(t=>{const e=t.split("\t"),r=e[0];if(!r)return;if(!l[r])return;const s=Number(e[1]);if(!Number.isInteger(s))return;const i=Number(e[2]);if(!Number.isFinite(i))return;if(i<n.min||i>n.max)return;h.fillStyle=i>0?n.positiveColor:n.negativeColor;const a=l[r](s),c=o+f(i);h.fillRect(70+a,c,1,1)})),p.on("close",(()=>{!function(){h.strokeStyle="black",h.beginPath();{const t=220-f(0);h.moveTo(70,t),h.lineTo(870,t),h.stroke()}let t=!0;h.fillStyle="black",h.font="12px Arial",h.textAlign="center";for(const n in l){if(h.fillText(n.replace("chr",""),70+l[n](e.majorchr[n]/2),234),t){t=!1;continue}const r=Math.floor(70+l[n](0))+.5;h.moveTo(r,o),h.lineTo(r,220),h.stroke()}h.closePath()}(),t({src:d.toDataURL(),canvasWidth:890,canvasHeight:240,xoff:70,chrLst:u})}))}));function g(t){h.fillStyle="black",h.font="12px Arial",h.textAlign="right";const e=o+f(t);h.fillText(t,64,e+5),h.strokeStyle="black",h.beginPath(),h.moveTo(66,e),h.lineTo(70,e),h.stroke(),h.closePath()}}function _r(t,e,n,r,s,o){for(const i of e.yesSamples){if(o&&!o.has(i))continue;n.has(i)||n.set(i,{sample:i});const e=n.get(i);r in e||(e[r]={key:r,values:[],label:r}),s?e[r].values.some((e=>e.dt==t&&e.origin==s))||e[r].values.push({dt:Number.parseInt(t),class:"WT",_SAMPLEID_:i,origin:s}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:Number.parseInt(t),class:"WT",_SAMPLEID_:i})}for(const i of e.noSamples){if(o&&!o.has(i))continue;n.has(i)||n.set(i,{sample:i});const e=n.get(i);r in e||(e[r]={key:r,values:[],label:r}),s?e[r].values.some((e=>e.dt==t&&e.origin==s))||e[r].values.push({dt:Number.parseInt(t),class:"Blank",_SAMPLEID_:i,origin:s}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:Number.parseInt(t),class:"Blank",_SAMPLEID_:i})}}async function xr(t,e){if(t.chr&&Number.isInteger(t.start)&&Number.isInteger(t.stop))return;if(!t.name)throw"both term.name and term.chr/start/stop missing";const n=e.genedb.getjsonbyname.all(t.name);if(0==n.length)throw"unknown gene name";const r=n.find((t=>t.isdefault))||n[0],s=JSON.parse(r.genemodel);if(!s.chr||!Number.isInteger(s.start)||!Number.isInteger(s.stop))throw"invalid chr/start/stop from returned gm";return t.chr=s.chr,t.start=s.start,t.stop=s.stop,s.isoform}async function kr(t,e,n,r){const s={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,sessionid:r.sessionid,gdcUseCaseuuid:!0};if(t.queries.snvindel.byisoform)return await async function(t,e){if(t.isoform&&"string"==typeof t.isoform)return;if(!t.name)throw"both term.name and term.isoform";const n=e.genedb.getjsonbyname.all(t.name);if(0==n.length)return;const r=n.find((t=>t.isdefault))||n[0],s=JSON.parse(r.genemodel);if(!s.isoform)throw"isoform missing from returned gm";t.isoform=s.isoform}(e,n),e.isoform?(s.isoform=e.isoform,await t.queries.snvindel.byisoform.get(s)):[];if(t.queries.snvindel.byrange)return s.isoform=await xr(e,n),s.rglst=[e],await t.queries.snvindel.byrange.get(s);throw"unknown queries.snvindel method"}function qr(t,e){e.yesSamples=new Set,e.noSamples=new Set;const n=`SELECT sample, value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = '${e.term_id}'`,r=t.cohort.db.connection.prepare(n).all();for(const t of r)e.yes.value.includes(t.value)?e.yesSamples.add(t.sample):e.no.value.includes(t.value)&&e.noSamples.add(t.sample)}function Nr(t,e,n){if(e.skewerRim){if("format"!=e.skewerRim.type)throw"unknown skewerRim.type";t.rim1count=0;for(const n of t.samples)n.formatK2v?.[e.skewerRim.formatKey]==e.skewerRim.rim1value&&t.rim1count++}}function Sr(t,e){if(e.queries.snvindel?.format)for(const n in e.queries.snvindel.format)if(e.queries.snvindel.format[n].isFilter){t.formatK2count||(t.formatK2count={}),t.formatK2count[n]||(t.formatK2count[n]={v2c:{},unannotatedCount:0});for(const e of t.samples){const r=e.formatK2v?.[n];null==r?t.formatK2count[n].unannotatedCount++:t.formatK2count[n].v2c[r]=1+(t.formatK2count[n].v2c[r]||0)}}}function Ar(t,e){if(t.startunbounded){if(t.stopunbounded)throw"both start & stop are unbounded from "+e;if(!Number.isFinite(t.stop))throw".stop undefined when start is unbounded from "+e}else if(t.stopunbounded){if(!Number.isFinite(t.start))throw".start undefined when stop is unbounded from "+e}else{if(!Number.isFinite(t.start))throw".start undefined when start is not unbounded from "+e;if(!Number.isFinite(t.stop))throw".stop undefined when stop is not unbounded from "+e;if(t.start>=t.stop)throw".start is not lower than stop from "+e}}const Mr="Ancestry_PC_";async function Tr(t,e=null,r=null){if(!t.cohort.termdb)throw"cohort.termdb missing when cohort.db is used";await async function(t){if(t.phewas){if(t.phewas.samplefilter4termtype&&t.phewas.samplefilter4termtype.condition&&!t.phewas.samplefilter4termtype.condition.filter)throw"filter{} missing from tdb.phewas.samplefilter4termtype.condition";if(t.phewas.comparison_groups){if(!Array.isArray(t.phewas.comparison_groups))throw"tdb.phewas.comparison_groups is not array";if(0==t.phewas.comparison_groups.length)throw"tdb.phewas.comparison_groups[] cannot be empty"}}if(t.selectCohort){if(!t.selectCohort.term)throw"term{} missing from termdb.selectCohort";if(!t.selectCohort.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof t.selectCohort.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=t.selectCohort.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';if(!t.selectCohort.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(t.selectCohort.values))throw"termdb.selectCohort.values is not array";if(0==t.selectCohort.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const e of t.selectCohort.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[]"}}if(t.restrictAncestries){if(!Array.isArray(t.restrictAncestries)||0==t.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const e of t.restrictAncestries){if(!e.name)throw"name missing from one of restrictAncestries";if("object"!=typeof e.tvs)throw".tvs{} missing from one of restrictAncestries";if(!Number.isInteger(e.PCcount))throw"PCcount is not integer";if(e.PCfile)e.pcs=await jr(e.PCfile,e.PCcount);else if(e.PCfileBySubcohort)for(const t in e.PCfileBySubcohort){const n=e.PCfileBySubcohort[t];if(!n.file)throw".file missing for a subcohort in PCfileBySubcohort";n.pcs=await jr(n.file,e.PCcount)}}}}(t.cohort.termdb),await async function(t){if("scatterplots"in t)for(const e of t.scatterplots.plots){const t=y().join(s().tpmasterdir,e.file);await F.Ic(t)}}(t.cohort),(0,Kn.JV)(t),function(t){t.sampleName2Id=new Map,t.sampleId2Name=new Map;const e="SELECT * FROM sampleidmap",n=t.cohort.db.connection.prepare(e).all();for(const e of n)t.sampleId2Name.set(e.id,e.name),t.sampleName2Id.set(e.name,e.id);t.getSampleIdMap=e=>{const n={};for(const r in e)n[r]=t.sampleId2Name.get(+r);return n}}(t);const{mayGetGeneVariantData:o,getTermTypes:i,mayGetMatchingGeneNames:a}=n(7833);t.mayGetGeneVariantData=o,t.getTermTypes=i,t.mayGetMatchingGeneNames=a,t.cohort?.db?.refresh&&e&&Qn(t,e,r)}async function Cr(t,e){if(!t.track)throw"no mds2 track; missing ds.track{}";const n=t.track;n.name||(n.name=t.label),function(t){if(!t.populations)return;if(!Array.isArray(t.populations))throw"populations should be array";for(const e of t.populations){if(!e.key)throw"key missing from a population";if(e.label||(e.label=e.key),!Array.isArray(e.sets))throw".sets is not an array in population: "+e.key;for(const t of e.sets){if(!t.infokey_AC)throw"infokey_AC missing from a set of population: "+e.key;if(!t.infokey_AN)throw"infokey_AN missing from a set of population: "+e.key;if(e.termfilter&&!t.termfilter_value)throw"termfilter_value missing from a set of population where termfilter is set: "+e.key}}}(n),await async function(t,e,n){if(!t)return;if(!t.chr2bcffile)throw"vcftk.chr2bcffile is missing";{if("object"!=typeof t.chr2bcffile)throw"chr2bcffile not an object";for(const e in t.chr2bcffile)t.chr2bcffile[e]=y().join(s().tpmasterdir,t.chr2bcffile[e]);const n={file:t.chr2bcffile[e.defaultcoord.chr]};if(!n.file)throw"default chr missing from chr2bcffile";await F._H(n,e,!0),t.info=n.info,t.format=n.format,t.samples=n.samples,t.nochr=n.nochr}if(t.AD&&t.AD.chr2bcffile){if("object"!=typeof t.AD.chr2bcffile)throw"AD.chr2bcffile not an object";for(const e in t.AD.chr2bcffile)t.AD.chr2bcffile[e]=y().join(s().tpmasterdir,t.AD.chr2bcffile[e]);const r={file:t.AD.chr2bcffile[e.defaultcoord.chr]};if(!r.file)throw"default chr missing from AD.chr2bcffile";await F._H(r,e,!0),t.AD.info=r.info,t.AD.format=r.format,t.AD.samples=r.samples,t.AD.nochr=r.nochr,console.log(n.label+" vcf: AD: "+t.AD.samples.length+" samples");for(const e of t.AD.samples){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer vcf sample: "+e.name;e.name=t}}if(t.samples){for(const e of t.samples){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer vcf sample: "+e.name;e.name=t}console.log(n.label+" vcf: "+t.samples.length+" samples")}else console.log(n.label+" vcf: no samples");if(t.numerical_axis&&t.numerical_axis.info_keys){if(!Array.isArray(t.numerical_axis.info_keys))throw"numerical_axis.info_keys should be an array";for(const e of t.numerical_axis.info_keys){const n=t.info[e.key];if(!n)throw'INFO field "'+e.key+'" not found for numerical_axis';if("Float"!=n.Type&&"Integer"!=n.Type)throw'INFO field "'+e.key+'" from numerical_axis not of integer or float type';if("1"!=n.Number&&"A"!=n.Number)throw'for numerical axis, INFO field "'+e.key+'" only allows to be Number=1 or Number=A'}}if(t.plot_mafcov){if(!t.AD)throw".plot_mafcov enabled but .AD{} missing from vcf";if(!t.AD.samples)throw".plot_mafcov enabled but no samples from vcf";if(!t.AD.format)throw".plot_mafcov enabled but no FORMAT fields from vcf";if(!t.AD.format.AD)throw".plot_mafcov enabled but the AD FORMAT field is missing";if("R"!=t.AD.format.AD.Number)throw"AD FORMAT field Number=R is not true";if("Integer"!=t.AD.format.AD.Type)throw"AD FORMAT field Type=Integer is not true";if(t.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 e=n.cohort.termdb.q.termjsonByOneid(t.plot_mafcov.overlay_term);if(!e)throw'unknown term id "'+t.plot_mafcov.overlay_term+'" from vcftk.plot_mafcov.overlay_term';t.plot_mafcov.overlay_term=e}}if(t.termdb_bygenotype){if(!t.samples)throw".termdb_bygenotype enabled but no samples from vcf";if(!t.format)throw".termdb_bygenotype enabled but no FORMAT fields from vcf";if(!t.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(t.termdb_bygenotype.getAF){if(!t.termdb_bygenotype.termid_sex)throw"termid_sex missing for getAF at termdb_bygenotype";if(!t.termdb_bygenotype.value_male)throw"value_male missing for getAF at termdb_bygenotype";const e=n.cohort.termdb.q.getSample2value(t.termdb_bygenotype.termid_sex);t.termdb_bygenotype.male_samples=new Set;for(const n of e)n.value==t.termdb_bygenotype.value_male&&t.termdb_bygenotype.male_samples.add(n.sample);if(!t.termdb_bygenotype.sex_chrs)throw"sex_chrs missing for getAF at termdb_bygenotype";if(!Array.isArray(t.termdb_bygenotype.sex_chrs))throw"sex_chrs is not array";t.termdb_bygenotype.sex_chrs=new Set(t.termdb_bygenotype.sex_chrs)}}if(t.samples){t.sample2arrayidx=new Map;for(const[e,n]of t.samples.entries())t.sample2arrayidx.set(n.name,e)}}(n.vcf,e,t),function(t){if(!t.info_fields)return;if(!Array.isArray(t.info_fields))throw"tk.info_fields is not array";for(const e of t.info_fields){if(!e.key)throw".key missing from one of tk.info_fields[]";if(t.vcf&&t.vcf.info&&!t.vcf.info[e.key])throw`info field ${e.key} missing from tk.vcf.info{}`;if(e.label||(e.label=e.key),e.iscategorical){if(!Array.isArray(e.values))throw".values[] not an array of categorical INFO field: "+e.key;for(const t of e.values){if(!t.key)throw"key missing from a value of categorical INFO: "+e.key;t.label||(t.label=t.key)}}else if(e.isfloat||e.isinteger){if(!e.range)throw".range{} missing from a numerical INFO: "+e.key;Ar(e.range,"tk.info_fields[]")}else if(!e.isflag)throw"tk.info_fields unknown type: "+e.key}}(n),await async function(t,e,n){if(!t)return;if(!Array.isArray(t.tracks))throw"ld.tracks[] not an array";if(0==t.tracks.length)throw"ld.tracks[] is empty array";for(const n of t.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(s().tpmasterdir)||(n.file=y().join(s().tpmasterdir,n.file)),await F.LC(n.file),n.nochr=await F.Jy(n.file,null,e),console.log(n.file+": "+(n.nochr?"no chr":"has chr"));else if(!n.chr2file)throw"ld tk has no file or chr2file"}}(n.ld,e),await async function(t,e){if(!t)return}(n.svcnv,0),function(t){const e=new Set;if(t.vcf&&t.vcf.samples)for(const n of t.vcf.samples)e.add(n.name);t.svcnv;e.size&&(t.samples=[...e])}(n),n.samples&&console.log(t.label+": mds2: "+n.samples.length+" samples")}async function jr(t,e){const n=new Map;for(let t=1;t<=e;t++)n.set(Mr+t,new Map);let r=0;for(const o of(await F.b5(y().join(s().tpmasterdir,t))).trim().split("\n")){r++;const t=o.split("\t"),s=Number(t[0]);if(!Number.isInteger(s))throw"non-integer sample id from a line of restrictAncestries pc file";for(let r=1;r<=e;r++){const e=Mr+r,o=Number(t[r]);if(Number.isNaN(o))throw"non-numeric PC value from restrictAncestries file";n.get(e).set(s,o)}}return console.log(r,"samples loaded from "+t),Object.freeze(n)}var Er=n(9157);const Or=n(334),Ir="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO";async function Rr(t,e,n,r){if(!t.rglst)throw".rglst[] missing";const s=n.track.vcf;if(!s)throw"ds.track.vcf missing";const o={info:s.info,format:s.format,samples:s.samples};await async function(t,e,n){if(t.querymode={},t.AFtest){if(n.iscustom)throw"custom track does not support AFtest";for(const e of t.AFtest.groups)if(!e.is_infofield)if(e.is_termdb)e.columnidx=await Fr(e.filter,n);else{if(!e.is_population)throw"Cannot set query mode: unknown group type";{if(!n.track.populations)throw"ds.track.populations missing";const r=n.track.populations.find((t=>t.key==e.key));if(!r)throw"unknown population key: "+e.key;if(e.population=JSON.parse(JSON.stringify(r)),t.AFtest.termfilter&&t.AFtest.termfilter[0].term.id==e.population.termfilter){const n=e.population.sets.find((e=>e.termfilter_value==t.AFtest.termfilter[0].values[0].key));if(!n)throw"no matching set found for a termfilter from a population";e.population.sets=[n]}}}if(t.AFtest.testby_fisher&&t.AFtest.groups.find((t=>t.is_infofield)))throw"cannot do fisher test for an INFO field";{const e=t.AFtest.groups.find((t=>t.is_population));if(e&&e.adjust_race){const r=t.AFtest.groups.find((t=>t.is_termdb));if(!r)throw"cannot adjust race: termdb group missing";r.pop2average=await async function(t,e,n,r){const s=new Map;let o=0;for(const e of t){const t={infokey_AC:e.infokey_AC,infokey_AN:e.infokey_AN,average:0},r=await Yn.J4({ds:n,key:e.key});for(const e of r){if(!n.track.vcf.sample2arrayidx.has(e.sample))continue;const r=Number(e.value);Number.isFinite(r)&&(t.average+=r,o+=r)}s.set(e.key,t)}for(const[t,e]of s)e.average/=o;return s}(e.population.sets,r.columnidx,n)}}return void(t.querymode.range_AFtest=!0)}t.querymode.range_variantonly=!0}(t,0,n),function(t,e){if(e.querymode.range_variantonly||e.querymode.range_AFtest){delete t.samples;for(const t of e.rglst)t.variants=[]}e.bcfformat=Ir,e.exportgenotype||e.querymode.range_AFtest?e.bcfformat+="\t%FORMAT\n":e.querymode.range_variantonly&&(e.querymode.slicecolumnindex||(e.bcfformat+="\\n"))}(o,t),t.exportgenotype&&(r.mlst=[]),function(t,e){const n=(r=t.rglst[0],r.usegm_isoform?{gmmode:"protein",usegm:{isoform:r.usegm_isoform}}:{});var r;t.m_is_filtered=r=>{let s=!1;if(t.info_fields)for(const n of t.info_fields){const t=e.info_fields[n.key];let o;if(r.info&&(o=r.info[n.key]),null==o&&r.altinfo&&(o=r.altinfo[n.key]),n.iscategorical)null==o?(t.unannotated_count=1+(t.unannotated_count||0),n.unannotated_ishidden&&(s=!0)):(t.value2count[o]=1+(t.value2count[o]||0),n.hiddenvalues[o]&&(s=!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&&(s=!0):o<=n.range.start&&(s=!0)),n.range.stopunbounded||(n.range.stopinclusive?o>n.range.stop&&(s=!0):o>=n.range.stop&&(s=!0)),s&&t.filteredcount++;else{if(!n.isflag)throw"unknown info type";o?t.count_yes++:t.count_no++,(n.remove_yes&&o||n.remove_no&&!o)&&(s=!0)}}return!!s||(P.vcfcopymclass(r,n),e.mclass2count[r.class]=(e.mclass2count[r.class]||0)+1,t.hidden_mclass&&t.hidden_mclass.has(r.class)&&(s=!0),s)}}(t,r);for(const e of t.rglst){if(s.viewrangeupperlimit&&e.stop-e.start>=s.viewrangeupperlimit){e.rangetoobig="Zoom in under "+P.bplen(s.viewrangeupperlimit)+" to view VCF data";continue}const n=(s.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop,r=s.chr2bcffile[e.chr];if(!r)throw"chr not found in chr2bcffile";await F.UE({isbcf:!0,args:["query",r,"-r",n,"-f",t.bcfformat],dir:s.dir,callback:i(e)})}function i(e){return n=>{if(t.exportgenotype){const e=n.split("\t"),[s,i,a]=D.S(e.slice(0,8).join("\t"),o);for(const n of i){if(t.m_is_filtered(n))continue;const s=[n.chr+"."+(n.pos+1)+"."+n.ref+"."+n.alt,n.name||""];for(let t=9;t<e.length;t++){const r=e[t].split(":",1)[0];if("."==r){s.push(".");continue}const o=r.split(-1==r.indexOf("/")?"|":"/");s.push(("0"==o[0]?n.ref:n.alt)+("0"==o[1]?n.ref:n.alt))}r.mlst.push(s.join("\t"))}return}let i;if(t.querymode.range_variantonly)if(t.querymode.slicecolumnindex);else{const[e,r,s]=D.S(n,o);i=[];for(const e of r)t.m_is_filtered(e)||i.push(e)}else t.querymode.range_AFtest&&(i=function(t,e,n,r){const s=t.split("\t"),[o,i,a]=D.S(s.slice(0,8).join("\t"),n),l=i.filter((t=>!e.m_is_filtered(t)));if(0==l.length)return;const c=[s[3],...s[4].split(",")],u=[];for(const t of l){const n=Dr(s,t,c,e);if(Pr(n)){if(u.push(t),e.AFtest.testby_AFdiff){for(const t of n)if(t.is_infofield)t.v=t.infofieldvalue;else{if(!t.is_termdb&&!t.is_population)throw"unknown group type";t.v=t.altcount/(t.refcount+t.altcount)}t.AFtest_group_values=[n[0].v,n[1].v],t.nm_axis_value=n[0].v-n[1].v}else e.AFtest.testby_fisher&&(t.contigencytable=[n[0].altcount,n[0].refcount,n[1].altcount,n[1].refcount]);{const r=e.AFtest.groups.find((t=>t.is_population));if(r&&r.adjust_race){const e=n.find((t=>t.is_population));t.popsetadjvalue=[];for(const[n,r]of e.set2value)t.popsetadjvalue.push([n,r.ACraw,r.ANraw-r.ACraw,Number.parseInt(r.ACadj),Number.parseInt(r.ANadj-r.ACadj)])}}}}return u}(n,t,o));if(i)for(const t of i)t.csq&&(t.csq_count=t.csq.length,delete t.csq),delete t._m,delete t.vcf_ID,delete t.sampledata,s.nochr&&(t.chr="chr"+t.chr),e.variants.push(t)}}await async function(t){if(!t.querymode.range_AFtest)return;if(!t.AFtest.testby_fisher)return;const e=[],n={};for(const r of t.rglst)if(r.variants)for(const t of r.variants)if(t.contigencytable){const r=t.chr+"."+t.pos+"."+t.ref+"."+t.alt;e.push(r+"\t"+t.contigencytable.join("\t")),n[r]=t}if(0==e.length)return;const r=await Er(y().join(Or.binpath,"/utils/fisher.R"),e);for(const t of r){const e=t.split("\t"),r=n[e[0]];if(r){const t=Number.parseFloat(e[5]);r.AFtest_pvalue=t,r.nm_axis_value=Number.isNaN(t)?0:-Math.log10(t)}}}(t),function(t,e,n,r){if(e.exportgenotype)return t.exportgenotype="variant\tSNP\t"+n.samples.map((t=>r.cohort.termdb.id2sampleName(t.name))).join("\t")+"\n"+t.mlst.join("\n"),void delete t.mlst;t.vcf={rglst:[]};for(const n of e.rglst){const e={chr:n.chr,start:n.start,stop:n.stop,width:n.width,reverse:n.reverse,xoff:n.xoff};t.vcf.rglst.push(e),n.rangetoobig?(e.rangetoobig=n.rangetoobig,delete n.rangetoobig):n.variants?(e.variants=n.variants,delete n.variants):n.canvas&&(e.img=n.canvas.toDataURL(),delete n.canvas)}if(e.AFtest&&e.AFtest.groups.find((t=>t.is_termdb))){t.AFtest_termdbgroup=[];let n=e.AFtest.groups[0];if(n.is_termdb&&(t.AFtest_termdbgroup[0]={samplecount:n.columnidx.length},n.pop2average)){t.AFtest_termdbgroup[0].popsetaverage=[];for(const[e,r]of n.pop2average)t.AFtest_termdbgroup[0].popsetaverage.push([e,r.average])}if(n=e.AFtest.groups[1],n.is_termdb&&(t.AFtest_termdbgroup[1]={samplecount:n.columnidx.length},n.pop2average)){t.AFtest_termdbgroup[1].popsetaverage=[];for(const[e,r]of n.pop2average)t.AFtest_termdbgroup[1].popsetaverage.push([e,r.average])}}}(r,t,s,n)}async function Fr(t,e){if(!e.track)throw"ds.track{} missing";return(await Yn.cf(t,e)).reduce(((t,n)=>{const r=e.track.vcf.sample2arrayidx.get(n);return r>=0&&t.push(r),t}),[])}function Pr(t){if(t.find((t=>t.is_infofield)))return!0;return t[0].altcount+t[1].altcount>0}function Dr(t,e,n,r){return r.AFtest.groups.reduce(((s,o)=>{if(o.is_infofield)s.push({is_infofield:!0,infofieldvalue:Lr(e,o)});else if(o.is_termdb){const r=function(t,e,n){let r=!0;const s=new Map;for(const e of t)s.set(e,0);for(const o of n){if(!e[9+o])continue;const n=e[9+o].split(":")[0];"."!=n&&n.split(-1==n.indexOf("/")?"|":"/").forEach((e=>{const n=Number.parseInt(e);if(Number.isNaN(n))return;const o=t[n];o&&(0!=n&&(r=!1),s.set(o,1+s.get(o)))}))}return{allref:r,alleles:s}}(n,t,o.columnidx);s.push({is_termdb:!0,allref:r.allref,refcount:r.alleles.get(e.ref)||0,altcount:r.alleles.get(e.alt)||0})}else{if(!o.is_population)throw"unknown group type";{const t=new Map;for(const n of o.population.sets)t.set(n.key,{ACraw:Lr(e,{key:n.infokey_AC,missing_value:0}),ANraw:Lr(e,{key:n.infokey_AN,missing_value:0})});let n=0,i=0;if(o.adjust_race)[n,i]=function(t,e){if(!e)throw"group_termdb missing";if(!e.pop2average)throw"group_termdb.pop2average missing";let n=0;for(const e of t.values())n+=e.ANraw;let r=0,s=0;for(const[o,i]of t)i.ANadj=n*e.pop2average.get(o).average,i.ACadj=0==i.ANadj?0:i.ACraw*i.ANadj/i.ANraw,r+=i.ACadj,s+=i.ANadj;return[s-r,r]}(t,r.AFtest.groups.find((t=>t.is_termdb)));else for(const e of t.values())i+=e.ACraw,n+=e.ANraw-e.ACraw;s.push({is_population:!0,refcount:n,altcount:i,set2value:t})}}return s}),[])}function Lr(t,e){if(t.info){const n=t.info[e.key];if(null!=n)return n}if(t.altinfo){const n=t.altinfo[e.key];if(null!=n)return n}return e.missing_value}var $r=n(5540),zr=n(7763);const Zr="#aaa",Ur="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO\t%FORMAT\n";async function Br(t,e,n,r,s){const o=r.track.ld.tracks.find((e=>e.name==t.name));if(!o)throw"ld track not found by name: "+t.name;if(!e.rglst)throw"rglst missing";s.ld[o.name]={rglst:[]};const i=e.trigger_ld.connheight||50;for(const t of e.rglst){const e={chr:t.chr,start:t.start,stop:t.stop,width:t.width,reverse:t.reverse,xoff:t.xoff};if(s.ld[o.name].rglst.push(e),t.stop-t.start>=o.viewrangelimit){e.rangetoobig="Zoom in under "+(0,P.bplen)(o.viewrangelimit)+" to view LD data";continue}const n=[],r=new Set,a=(o.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;await F.UE({args:[o.file,a],dir:o.dir,callback:e=>{const o=e.split("\t"),i=Number.parseInt(o[1]);if(i<t.start)return;const a=Number.parseInt(o[2]);if(a>t.stop)return;if(s.__mposset){if(!s.__mposset.has(i))return;if(!s.__mposset.has(a))return}const l=Number.parseFloat(o[5]);n.push({start:i,stop:a,r2:l}),r.add(i),r.add(a)}}),e.img=Gr(t,n,r,i)}}function Gr(t,e,n,r){const[s,o]=function(t,e){let n=t.width/e.size,r=0;n>40&&(n=40,r=(t.width-n*e.size)/2);const s=new Map,o=t.reverse?[...e].sort(((t,e)=>e-t)):[...e].sort(((t,e)=>t-e));let i=r;for(const t of o)s.set(t,i+n/2),i+=n;return[n,s]}(t,n),i=new Map;{const e=(t.stop-t.start)/t.width;for(const r of n)t.reverse?i.set(r,(t.stop-r)/e):i.set(r,(r-t.start)/e)}let a=0;for(const t of e)a=Math.max(a,(o.get(t.stop)-o.get(t.start))/2);const l=r+a+s/2,c=(0,S.createCanvas)(t.width,l),u=c.getContext("2d");u.strokeStyle="black";for(const t of n)u.beginPath(),u.moveTo(i.get(t),0),u.lineTo(o.get(t),r),u.closePath(),u.stroke();for(const t of e){const e=o.get(t.start),n=o.get(t.stop),i=(e+n)/2,a=r+Math.abs(n-e)/2,l=Math.floor(255*(1-t.r2));u.fillStyle="rgb(255,"+l+","+l+")",u.beginPath(),u.moveTo(i,a-s/2),u.lineTo(i-s/2,a),u.lineTo(i,a+s/2),u.lineTo(i+s/2,a),u.lineTo(i,a-s/2),u.closePath(),u.fill()}return{height:l,src:c.toDataURL()}}var Jr=n(6191);function Hr(t,e){const{filename:n,route:r,dslabel:o,embedder:i}=t,a=e.email.replace("@","_at_");return`${s().cachedir}/sessionsByCred/${i}/${a}/${r}/${o}`}const Wr=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];function Vr(t){const e=t.toString(16);return 1==e.length?"0"+e:e}function Yr(t,e,n){return Vr(t)+Vr(e)+Vr(n)}function Kr(t){if(!t.cellfile)throw"cellfile missing";{const[e,n,r]=F.ZX({query:{file:t.cellfile}});if(e)throw"cellfile error: "+e;t.cellfile=n}if(!t.delimiter)throw"delimiter missing";if(!Number.isInteger(t.barcodecolumnidx))throw"barcodecolumnidx missing";if(!Number.isInteger(t.categorycolumnidx))throw"categorycolumnidx missing";return new Promise(((e,n)=>{const r=new Map,s=O().createInterface({input:m().createReadStream(t.cellfile)});let o=!0;s.on("line",(e=>{if(o)return void(o=!1);const n=e.split(t.delimiter);r.set(n[t.barcodecolumnidx],{category:n[t.categorycolumnidx],expvalue:0})})),s.on("close",(()=>{e(r)}))}))}const Xr=s().fimo||"fimo";async function Qr(t,e,n){const r=y().join(s().cachedir,Math.random().toString());return await F.Sf(r,n),new Promise(((n,s)=>{const o=["--parse-genomic-coord","--verbosity",1,"--text"];t.fimo_thresh&&(o.push("--thresh"),o.push(t.fimo_thresh)),o.push(e.fimo_motif.db),o.push(r);const i=(0,q.spawn)(Xr,o),a=[];i.stdout.on("data",(t=>a.push(t))),i.on("close",(s=>{m().unlink(r,(()=>{}));const o=a.join("").trim();o||n([]);const i=[],l=o.split("\n");for(let n=1;n<l.length;n++){const r=l[n].split("\t"),s=r[0].split("_")[0],o=Number.parseInt(r[3]),a=Number.parseInt(r[4]);if(o>t.m.pos||a<t.m.pos+1)continue;const c=Number.parseFloat(r[7]),u={start:o,stop:a,strand:r[5],name:s,pvalue:c,score:Number.parseFloat(r[6]),logpvalue:-Math.log10(c)};e.fimo_motif.tf2attr&&(u.attr=e.fimo_motif.tf2attr[u.name]),i.push(u)}n(i)}))}))}function ts(t){!function(t){if(!t.sample2term)throw".sample2term missing";if(!t.terms)throw".terms[] missing";if(!t.config)throw".config{} missing"}(t);const e=function(t){const e=new Map;for(const n of t.sample2term.values())for(const t of n.keys())e.set(t,1+(e.get(t)||0));if(t.config.termidorder){const n=[];for(const r of t.config.termidorder){const t=e.get(r);null!=t&&n.push({id:r,samplecount:t})}return n}return[...e].sort(((t,e)=>e[1]-t[1])).map((t=>({id:t[0],samplecount:t[1]})))}(t),n=function(t,e){const n=[];for(const[r,s]of t.sample2term)e.find((t=>s.has(t.id)))&&n.push(r);return n}(t,e);return function(t,e,n){for(const[r,s]of e.entries()){const o=0==r?[{samples:n}]:e[r-1].blocks;s.blocks=es(o,s.id,t)}}(t,e,n),function(t,e){for(const n of t){const t=e.terms.find((t=>t.id==n.id));n.name=t.name;for(const e of n.blocks)e.samplecount=e.samples.length,delete e.samples,e.value&&(e.color=t.values[e.value].color)}}(e,t),function(t){for(let e=t.length-1;e>=0;e--){const n=t[e];for(const t of n.blocks){let e=0;for(const n of t.children)e+=n.symbolwidth;const n=t.isgap?1:t.samplecount.toString().length;t.symbolwidth=Math.max(n,e)}}let e=0;for(const n of t[0].blocks){n.x=e;let t=e;for(const e of n.children)e.x=t,t+=e.symbolwidth;e+=n.symbolwidth}for(let e=1;e<t.length;e++)for(const n of t[e].blocks){let t=n.x;for(const e of n.children)e.x=t,t+=e.symbolwidth}for(const e of t)delete e.children}(e),e}function es(t,e,n){const r=[];for(const s of t){const t=new Map,o=[];for(const r of s.samples){const s=n.sample2term.get(r);if(s){const n=s.get(e);null==n?o.push(r):(t.has(n)||t.set(n,[]),t.get(n).push(r))}else o.push(r)}const i=[...t].sort(((t,e)=>e[1].length-t[1].length));for(const t of i){const e={value:t[0],samples:t[1],children:[]};r.push(e),s.children&&s.children.push(e)}if(o.length){const t={isgap:!0,samples:o,children:[]};r.push(t),s.children&&s.children.push(t)}}return r}async function ns(t){const e=["futime\tfustat\trx"];for(const[n,r]of t.entries())for(const t of r.lst)e.push(t.serialtime+"\t"+t.censored+"\t"+n);const n=await(0,Er.default)(y().join(s().binpath,"/utils/km.R"),e);return Number(n.join(""))}async function rs(t,e,n,r){const s=new Set(t.map((t=>t.name))),o=e.samplerule.set;let i,a;for(const t in n.queries){const e=n.queries[t];e.type==P.tkt.mdsvcf?i=e:e.type==P.tkt.mdssvcnv&&(a=e)}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(r)return await ss(a,s,e,!0);const t=await ss(a,s,e);for(const e of t)l.add(e)}if(o.snvindel){if(!i)throw"no vcf found in ds.queries";for(const t of i.tracks)await os(i,t,s,l,e)}return t.filter((t=>l.has(t.name)))}async function ss(t,e,n,r){const o=n.samplerule.set,i=t.url?await F.d1(t.url,t.indexURL):null,a=new Set,l=new Set,c=new Set;return await F.UE({args:[t.file?y().join(s().tpmasterdir,t.file):t.url,(t.nochr?o.chr.replace("chr",""):o.chr)+":"+o.start+"-"+(o.stop+1)],dir:i,callback:t=>{const n=t.split("\t"),s=Number.parseInt(n[1]),i=Number.parseInt(n[2]),u=JSON.parse(n[3]);if(e.has(u.sample)){if(u.dt==P.dtcnv){if(!o.cnv)return;if(o.cnv.focalsizelimit&&i-s>=o.cnv.focalsizelimit)return;if(o.cnv.valuecutoff&&Math.abs(u.value)<o.cnv.valuecutoff)return;return r?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==P.dtloh){if(!o.loh)return;if(o.loh.focalsizelimit&&i-s>=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==P.dtsv){if(!o.sv)return;return c.add(u.sample),void o.samples_sv.add(u.sample)}if(u.dt==P.dtfusionrna){if(!o.fusion)return;return c.add(u.sample),void o.samples_fusion.add(u.sample)}if(u.dt==P.dtitd){if(!o.itd)return;return c.add(u.sample),void o.samples_itd.add(u.sample)}}}}),r?[a,l]:c}async function os(t,e,n,r,o){const i=o.samplerule.set,a=e.url?await F.d1(e.url,e.indexURL):null;await F.UE({args:[e.file?y().join(s().tpmasterdir,e.file):e.url,(e.nochr?i.chr.replace("chr",""):i.chr)+":"+i.start+"-"+(i.stop+1)],dir:a,callback:s=>{if(e.type==P.mdsvcftype.vcf){const[o,a,l]=D.S(s,{nochr:e.nochr,samples:e.samples,info:t.info,format:e.format});for(const t of a)if(t.sampledata&&!(i.snvindel.ref&&(t.ref!=i.snvindel.ref||t.alt!=i.snvindel.alt)||i.snvindel.hiddenclass&&(P.vcfcopymclass(t,{}),i.snvindel.hiddenclass[t.class])))for(const e of t.sampledata)n.has(e.sampleobj.name)&&(r.add(e.sampleobj.name),i.samples_snvindel.add(e.sampleobj.name))}}})}async function is(t,e,n){if(!n.queries)throw".queries{} missing from ds";let r;for(const t in n.queries)n.queries[t].isgenenumeric&&(r=n.queries[t]);if(!r)throw"no gene numeric query from ds";const o=r.url?await F.d1(r.url,r.indexURL):null,i=e.samplerule.set,a=new Map;await F.UE({args:[r.file?y().join(s().tpmasterdir,r.file):r.url,i.chr+":"+i.start+"-"+i.stop],dir:o,callback:t=>{const e=JSON.parse(t.split("\t")[3]);e.sample&&Number.isFinite(e.value)&&e.gene==i.gene&&a.set(e.sample,e.value)}});const l=[];for(const e of t)a.has(e.name)&&(e.genevalue=a.get(e.name),l.push(e));return l.sort(((t,e)=>t.genevalue-e.genevalue)),[r,l]}function as(t){t.lst.sort(((t,e)=>t.serialtime-e.serialtime));let e=t.lst.length,n=[],r=0;t.steps=[];for(const s of t.lst){if(0==s.censored){n.push(s.serialtime);continue}const o=1*(1-r)/(e-n.length);t.steps.push({x:s.serialtime,y:r,drop:o,censored:n}),r+=o,e-=n.length+1,n=[]}n.length>0&&t.steps.push({x:t.lst[t.lst.length-1].serialtime,y:r,drop:0,censored:n})}exports.do_plot=as;const ls={};function cs(t,e,n){const r=+new Date;if(t.ip in ls||(ls[t.ip]={time:r,count:0}),r-ls[t.ip].time>3e4)delete ls[t.ip];else{if(ls[t.ip].count>10)return void e.send({error:"busy"});ls[t.ip].count++}throw e.send({error:n}),new Date+" "+n}const us={genome(t){if("string"!=typeof t)throw"genome should be a non-empty string";if(/\s+/.test(t))throw"invalid genome character";return t},chr(t){if("string"!=typeof t)throw"chr should be a string";if(/\s+/.test(t))throw"invalid chr character";return t},start:t=>Number(t),term(t){const e="string"==typeof t?JSON.parse(t):t;if(!("id"in e))throw"missing termWrapper.id";if(!("q"in e))throw"missing termWrapper.q";return e}},fs=require("cookie-parser");var ds=n.n(fs),hs=n(2062);function ps(t){return!isNaN(parseFloat(t))&&isFinite(t)&&""!==t}var ms=n(5708);const gs=t=>t.startsWith("[E::idx_test_and_fetch]"),ys=(new Map,Object.freeze(s().features||{})),bs={},vs=s().tabix,ws=s().samtools,_s=s().bcftools,xs=(s().bigwigsummary,s().hicstraw,"Unannotated"),ks=i()();ks.disable("x-powered-by"),s().users&&ks.use(K()({users:s().users,challenge:!0}));const qs=s().basepath||"";function Ns(t){t.header("Vary","Origin"),t.header("Access-Control-Allow-Origin","*"),t.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS, HEAD"),t.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(!s().backend_only){const t=i().static(y().join(process.cwd(),"./public"),{setHeaders:Ns});ks.use(t)}function Ss(t){const e={};for(const n in t.query)"jwt"!=n&&(e[n]=t.query[n]);console.log("%s\t%s\t%s\t%s",c().parse(t.url).pathname,new Date,t.header("x-forwarded-for")||t.connection.remoteAddress,JSON.stringify(e).replace(/\\"/g,'"'))}async function As(){try{if(s().preListenScript){const{cmd:t,args:e}=s().preListenScript,n=N().spawnSync(t,e,{encoding:"utf-8"});if(n.stderr.trim())throw n.stderr.trim();console.log(n.stdout)}s().appEnable&&s().appEnable.forEach((t=>ks.enable(t)));const t=s().port,e=`STANDBY AT PORT ${t}`;if(s().ssl){const n={key:m().readFileSync(s().ssl.key),cert:m().readFileSync(s().ssl.cert)},r=await h().createServer(n,ks);return r.listen(t,"0.0.0.0",(()=>{console.log(`HTTPS ${e}`)})),r}{const n=await f().createServer(ks);return n.listen(t,"0.0.0.0",(()=>{process.send&&process.send("ready"),console.log(e)})),n}}catch(t){throw t}}function Ms(t){const e=bs[t],n={species:e.species,name:t,hasSNP:!!e.snp,hasIdeogram:e.genedb.hasIdeogram,fimo_motif:!!e.fimo_motif,blat:!!e.blat,geneset:e.geneset,defaultcoord:e.defaultcoord,isdefault:e.isdefault,majorchr:e.majorchr,majorchrorder:e.majorchrorder,minorchr:e.minorchr,tracks:e.tracks,hicenzymefragment:e.hicenzymefragment,datasets:{}};if(e.termdbs){n.termdbs={};for(const t in e.termdbs)n.termdbs[t]={label:e.termdbs[t].label}}for(const t in e.datasets){const r=e.datasets[t];r.isMds3?n.datasets[r.label]={isMds3:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}:r.isMds?n.datasets[r.label]={isMds:!0,mdsIsUninitiated:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}:n.datasets[r.label]={isofficial:!0,legacyDsIsUninitiated:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}}if(e.hicdomain){n.hicdomain={groups:{}};for(const t in e.hicdomain.groups){const r=e.hicdomain.groups[t];n.hicdomain.groups[t]={name:r.name,reference:r.reference,sets:{}};for(const e in r.sets)n.hicdomain.groups[t].sets[e]={name:r.sets[e].name,longname:r.sets[e].longname}}}return n}function Ts(t){const e={noHandleOnClient:t.noHandleOnClient,sampleselectable:t.sampleselectable,label:t.label,dsinfo:t.dsinfo,stratify:t.stratify,cohort:t.cohort,vcfinfofilter:t.vcfinfofilter,info2table:t.info2table,info2singletable:t.info2singletable,url4variant:t.url4variant,itemlabelname:t.itemlabelname};if(t.snvindel_attributes){e.snvindel_attributes=[];for(const n of t.snvindel_attributes){const t={};for(const e in n)if("lst"==e){t.lst=[];for(const e of n.lst){const n={};for(const t in e)n[t]=e[t];t.lst.push(n)}}else t[e]=n[e];e.snvindel_attributes.push(t)}}t.snvindel_legend&&(e.snvindel_legend=t.snvindel_legend);const n={};let r=!1;for(const e of t.queries)e.vcf&&(r=!0,n[e.vcf.vcfid]=e.vcf);return r&&(e.id2vcf=n),e}function Cs(t){const e={isMds:!0,noHandleOnClient:t.noHandleOnClient,label:t.label,version:t.version,annotationsampleset2matrix:t.annotationsampleset2matrix,mutationAttribute:t.mutationAttribute,locusAttribute:t.locusAttribute,alleleAttribute:t.alleleAttribute,hide_genotypedownload:t.hide_genotypedownload,hide_phewas:t.hide_phewas,sample2bam:t.sample2bam};if(t.queries&&(e.queries={}),t.track&&(e.track=function(t){const e=t.track,n={name:e.name,info_fields:e.info_fields,sample_termfilter:e.sample_termfilter};return e.vcf&&(n.vcf={numerical_axis:e.vcf.numerical_axis,format:e.vcf.format,info:e.vcf.info,check_pecanpie:e.vcf.check_pecanpie},e.vcf.plot_mafcov&&(n.vcf.plot_mafcov={},t.cohort&&t.cohort.termdb&&(n.vcf.plot_mafcov.overlay_term=e.vcf.plot_mafcov.overlay_term||{})),e.vcf.termdb_bygenotype&&(n.vcf.termdb_bygenotype=!0),e.populations&&(n.populations=e.populations)),e.ld&&(n.ld={tracks:e.ld.tracks.map((t=>({name:t.name,shown:t.shown}))),overlay:e.ld.overlay}),n}(t)),t.singlesamplemutationjson&&(e.singlesamplemutationjson=1),t.gene2mutcount&&(e.gene2mutcount=!0,e.mutCountType=t.gene2mutcount.mutationTypes),t.assayAvailability&&(e.assayAvailability=1),t.cohort&&t.cohort.sampleAttribute){const n={};for(const e in t.cohort.sampleAttribute.attributes){const r=t.cohort.sampleAttribute.attributes[e];r.clientnoshow||(n[e]=r)}e.sampleAttribute={attributes:n}}if(t.cohort){if(t.cohort.termdb&&(e.termdb={selectCohort:t.cohort.termdb.selectCohort}),t.cohort.attributes&&t.cohort.attributes.defaulthidden&&(e.cohortHiddenAttr=t.cohort.attributes.defaulthidden),t.cohort.survivalplot){e.survivalplot={samplegroupattrlst:t.cohort.survivalplot.samplegroupattrlst,plots:[]};for(const n in t.cohort.survivalplot.plots){const r=t.cohort.survivalplot.plots[n];e.survivalplot.plots.push({key:n,name:r.name,timelabel:r.timelabel})}}if(t.cohort.mutation_signature){const n={};for(const e in t.cohort.mutation_signature.sets){const r=t.cohort.mutation_signature.sets[e];n[e]={name:r.name,signatures:r.signatures}}e.mutation_signature={sets:n}}}for(const n in t.queries){const r=t.queries[n],s={name:r.name,hideforthemoment:r.hideforthemoment};if(r.istrack){if(s.istrack=!0,s.type=r.type,s.isfull=r.isfull,null!=r.nochr&&(s.nochr=r.nochr),r.infoFilter&&(s.infoFilter=r.infoFilter),r.readcountCutoff&&(s.readcountCutoff=r.readcountCutoff),r.valueLabel&&(s.valueLabel=r.valueLabel),r.valueCutoff&&(s.valueCutoff=r.valueCutoff),r.bplengthUpperLimit&&(s.bplengthUpperLimit=r.bplengthUpperLimit),r.segmeanValueCutoff&&(s.segmeanValueCutoff=r.segmeanValueCutoff),r.lohLengthUpperLimit&&(s.lohLengthUpperLimit=r.lohLengthUpperLimit),r.type==P.tkt.mdssvcnv){if(r.groupsamplebyattr&&(s.groupsamplebyattr=r.groupsamplebyattr),s.multihidelabel_fusion=r.multihidelabel_fusion,s.multihidelabel_sv=r.multihidelabel_sv,s.multihidelabel_vcf=r.multihidelabel_vcf,s.showfullmode=r.showfullmode,s.legend_vorigin=r.legend_vorigin,s.no_loh=r.no_loh,r.expressionrank_querykey){const e=t.queries[r.expressionrank_querykey];if(s.checkexpressionrank={querykey:r.expressionrank_querykey,datatype:e.datatype},e.boxplotbysamplegroup&&e.boxplotbysamplegroup.additionals){const t=[];e.boxplotbysamplegroup.attributes&&t.push(e.boxplotbysamplegroup.attributes.map((t=>t.label)).join(", "));for(const n of e.boxplotbysamplegroup.additionals)t.push(n.label);s.checkexpressionrank.boxplotgroupers=t}}if(r.vcf_querykey){s.checkvcf={querykey:r.vcf_querykey,info:t.queries[r.vcf_querykey].info,format:{}};for(const e of t.queries[r.vcf_querykey].tracks)if(e.format)for(const t in e.format)s.checkvcf.format[t]=e.format[t]}}}else{if(!r.isgenenumeric)continue;s.isgenenumeric=!0,s.datatype=r.datatype,s.no_ase=r.no_ase}e.queries[n]=s}return e}async function js(t,e){if(!e)throw"invalid genome";if(!e.snp)throw"snp is not configured for this genome";const n=[];if(t.byCoord){if(e.genomicNameRegexp.test(t.chr))throw"invalid chr name";if(!Array.isArray(t.ranges))throw"ranges not an array";for(const r of t.ranges){if(!Number.isInteger(r.start)||!Number.isInteger(r.stop)||r.start<0||r.stop<r.start)throw"invalid start/stop";if(r.stop-r.start>=100)throw"range too big";const s=await F.z5(e.snp.bigbedfile,t.chr,r.start,r.stop);for(const e of s){const r=Es(e);if(t.alleleLst){let e=!1;for(const n of t.alleleLst)if(n&&!r.alleles.includes(n)){e=!0;break}if(e)continue}n.push(r)}}}else{if(!t.byName)throw"unknown query method";if(!Array.isArray(t.lst))throw".lst[] missing";for(const r of t.lst){if(e.genomicNameRegexp.test(r))continue;const t=await F.mr(e.snp.bigbedfile,r);for(const e of t){const t=Es(e);n.push(t)}}}return n}function Es(t){const e=t.split("\t"),n=e[4],r=e[6].split(",").filter(Boolean),s=n+"/"+r.join("/");return{chrom:e[0],chromStart:Number(e[1]),chromEnd:Number(e[2]),name:e[3],observed:s,alleles:[n,...r]}}function Os(t,e,n){if(n.query.isoform&&bs[n.query.genome].genomicNameRegexp.test(n.query.isoform))return;const[r,s]=e.makequery(n.query);if(!r)return;const o=t.newconn.prepare(r).all(s);let i;i=e.tidy?o.map((t=>e.tidy(t))):o;const a={};if(e.isgeneexpression){a.lst=i,a.isgeneexpression=!0,a.config=e.config;for(const e of t.queries)if(e.dsblocktracklst)for(const t of e.dsblocktracklst)t.type==P.tkt.junction&&(a.config.dsjunctiontk=t)}else a.lst=i;return a}function Is(t,e){const n=[y().join(s().tpmasterdir,t.vcffile),(t.vcf.nochr?e.query.range.chr.replace("chr",""):e.query.range.chr)+":"+e.query.range.start+"-"+e.query.range.stop];return new Promise(((e,r)=>{const s=(0,q.spawn)(vs,n),o=[],i=[];s.stdout.on("data",(t=>o.push(t))),s.stderr.on("data",(t=>i.push(t))),s.on("close",(n=>{""!=i.join("").trim()&&r("error querying vcf file");const s=o.join("").trim();e({lines:""==s?[]:s.split("\n"),vcfid:t.vcf.vcfid})}))}))}function Rs(t){if(!t.genome)return["no genome"];const e=bs[t.genome];if(!e)return["invalid genome"];if(!e.datasets)return["genome is not equipped with datasets"];if(!t.dslabel)return["dslabel missing"];const n=e.datasets[t.dslabel];if(!n)return["invalid dslabel"];if(!n.queries)return["dataset is not equipped with queries"];if(!t.querykey)return["querykey missing"];const r=n.queries[t.querykey];return r?[null,e,n,r]:["invalid querykey"]}async function Fs(t,e,n,r,o,i){const a=await async function(t,e,n,r){const o=t.checkvcf.tracks[0],i={file:o.file,url:o.url,indexURL:o.indexURL,dir:o.dir,nochr:o.nochr,samples:o.samples,info:t.checkvcf.info,format:o.format},a=await Ws(i.file?y().join(s().tpmasterdir,i.file):i.url,(i.nochr?e.replace("chr",""):e)+":"+n+"-"+r,i.dir),l=[];for(const t of a||[]){const[e,n,r]=D.S(t,i);for(const t of n)P.basecolor[t.ref]&&P.basecolor[t.alt]&&t.sampledata&&l.push(t)}return l}(o,e,n,r),l=[];for(const t in o.checkrnabam.samples){const n=o.checkrnabam.samples[t];n.hetsnps=[];for(const e of a){const r=Js(e,t,o.checkrnabam);r&&r.dnacount.ishet&&n.hetsnps.push(r)}if(n.url?n.dir=await F.d1(n.url,n.indexURL||n.url+".bai"):n.file&&(n.file=y().join(s().tpmasterdir,n.file)),n.hetsnps.length>0){await Ls(n,n.hetsnps,e,o.checkrnabam);for(const e of n.hetsnps)e.rnacount.nocoverage||e.rnacount.ref+e.rnacount.alt<o.checkrnabam.rna_mintotalreads||l.push(t+"."+e.pos+"."+e.ref+"."+e.alt+"\t\t\t\t\t\t\t\t"+e.rnacount.ref+"\t"+e.rnacount.alt)}}l.length>0&&await async function(t,e){const n=await function(t){const e=y().join(s().cachedir,Math.random().toString());return new Promise(((n,r)=>{m().writeFile(e,t.join("\n")+"\n",(t=>{t&&r("cannot write"),n(e)}))}))}(t),r=await Bs(n);await function(t,e){return new Promise(((n,r)=>{m().readFile(t,"utf8",((t,s)=>{if(t&&r("cannot read binom pvalue"),s){for(const t of s.trim().split("\n")){const n=t.split("\t"),r=n[0].split("."),s=e[r[0]];if(!s)continue;const o=s.hetsnps.find((t=>t.pos+"."+t.ref+"."+t.alt==r[1]+"."+r[2]+"."+r[3]));o&&(o.rnacount.pvalue=Number.parseFloat(n[10]))}n()}else n()}))}))}(r,e),m().unlink(n,(()=>{})),m().unlink(r,(()=>{}))}(l,o.checkrnabam.samples),i.checkrnabam=[];for(const n in o.checkrnabam.samples){const r=o.checkrnabam.samples[n],s=[];for(const[n,i]of t){const t={gene:n,chr:e,start:i.start,stop:i.stop},a=r.hetsnps.filter((t=>t.pos>=i.start&&t.pos<=i.stop)),l=a.filter((t=>!t.rnacount.nocoverage));if(l.length>0){const e=l.reduce(((t,e)=>t+Math.abs(e.rnacount.f-.5)),0);let n=null,r=0;for(const t of l)null!=t.rnacount.pvalue&&(null==n?n=t.rnacount.pvalue:n*=t.rnacount.pvalue,t.rnacount.pvalue<=o.checkrnabam.binompvaluecutoff&&r++);null!=n&&(t.ase={markers:a.filter((t=>t.dnacount.ishet)).length,ase_markers:r,mean_delta:e/l.length,geometricmean:Math.pow(n,1/l.length)})}let c;c=r.pairedend?await Ds(r,e,i):await Ps(r,e,i),t.fpkm=1e9*c/(r.totalreads*i.exonlength),t.snps=a,s.push(t)}s.length&&i.checkrnabam.push({sample:n,genes:s})}}async function Ps(t,e,n){const r=["view","-c","-M",t.url||t.file];for(const s of n.exonunion)r.push((t.nochr?e.replace("chr",""):e)+":"+(s[0]+1)+"-"+(s[1]+1));let s;return await F.UE({isbam:!0,args:r,dir:t.dir,callback:t=>s=t}),Number.parseInt(s)}function Ds(t,e,n){return new Promise(((r,s)=>{const o=["view","-M",t.url||t.file];for(const r of n.exonunion)o.push((t.nochr?e.replace("chr",""):e)+":"+(r[0]+1)+"-"+(r[1]+1));const i=(0,q.spawn)(ws,o,{cwd:t.dir}),a=(0,q.spawn)("cut",["-f1"],{cwd:t.dir}),l=(0,q.spawn)("sort",["-u"],{cwd:t.dir}),c=(0,q.spawn)("wc",["-l"],{cwd:t.dir});i.stdout.pipe(a.stdin),a.stdout.pipe(l.stdin),l.stdout.pipe(c.stdin);const u=[],f=[];c.stdout.on("data",(t=>u.push(t))),c.stderr.on("data",(t=>f.push(t))),c.on("close",(()=>{r(Number.parseInt(u.join("")))}))}))}function Ls(t,e,n,r){const s=[];for(const r of e)r.rnacount={nocoverage:1},s.push((t.nochr?n.replace("chr",""):n)+":"+(r.pos+1)+"-"+(r.pos+1));return new Promise(((n,o)=>{const i=(0,q.spawn)(_s,["mpileup","--no-reference","-a","INFO/AD","-d",999999,"-r",s.join(","),"-q",r.rnapileup_q,"-Q",r.rnapileup_Q,t.url||t.file],{cwd:t.dir});O().createInterface({input:i.stdout}).on("line",(t=>{if("#"==t[0])return;const n=Gs(t);if(!n)return;const r=e.find((t=>t.pos==n.pos));if(r){const t=n.allele2count[r.ref]||0,e=n.allele2count[r.alt]||0;t+e>0&&(r.rnacount={ref:t,alt:e,f:e/(t+e)})}})),i.on("close",(()=>{n()}))}))}function $s(t,e,n,r,s,o){e.hideLOHwithCNVoverlap&&zs(s);const i=[];if(o){const t=new Map;for(const[e,n]of s){const r=o.sample2group.get(e);t.has(r)||t.set(r,[]),t.get(r).push({samplename:e,items:n})}if(r)for(const e of r)if(e.dt!=P.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+e.dt);else for(const n of e.sampledata){const e=o.sample2group.get(n.sampleobj.name);t.has(e)||t.set(e,[]),t.get(e).find((t=>t.samplename==n.sampleobj.name))||t.get(e).push({samplename:n.sampleobj.name,items:[]})}for(const[e,n]of t)i.push({name:e,samples:n})}else if(t.cohort&&t.cohort.annotation&&e.groupsamplebyattr){const n=new Map,o=[];for(const[r,i]of s)Zs(r,i,n,o,t,e);if(r)for(const s of r)if(s.dt!=P.dtsnvindel)console.log("unknown dt when grouping samples from vcf data: "+s.dt);else for(const r of s.sampledata)Zs(r.sampleobj.name,[],n,o,t,e);for(const t of n.values())if(i.push(t),e.groupsamplebyattr.key2group){const n=e.groupsamplebyattr.key2group.get(t.name);n&&(t.sampletotalnum=n.samples.length)}o.length&&i.push({name:"Unannotated",samples:o});for(const e of i)for(const n of e.samples)t.cohort.annotation[n.samplename]&&(n.sampletype=t.cohort.annotation[n.samplename].sample_type)}else{const t=[];for(const[e,n]of s)t.push({samplename:e,items:n});if(r)for(const e of r)if(e.dt!=P.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+e.dt);else for(const n of e.sampledata){let e=!0;for(const r of t)if(r.samplename==n.sampleobj.name){e=!1;break}e&&t.push({samplename:n.sampleobj.name,items:[]})}t.length&&i.push({samples:t})}return i}function zs(t){for(const[e,n]of t){const r=new Map,s=new Map,o=[];for(const t of n)t.dt!=P.dtloh?(t.dt==P.dtcnv&&(s.has(t.chr)||s.set(t.chr,[]),s.get(t.chr).push(t)),o.push(t)):(r.has(t.chr)||r.set(t.chr,[]),r.get(t.chr).push(t));if(0!=r.size){for(const[t,e]of r){const n=s.get(t);if(n)for(const t of e){let e=!0;for(const r of n)if(Math.max(t.start,r.start)<Math.min(t.stop,r.stop)){e=!1;break}e&&o.push(t)}else for(const t of e)o.push(t)}t.set(e,o)}}}function Zs(t,e,n,r,s,o){const i=s.cohort.annotation[t];if(!i)return void r.push({samplename:t,items:e});const a=i[o.groupsamplebyattr.attrlst[0].k];if(null==a)return void r.push({samplename:t,items:e});const l=[];for(let t=1;t<o.groupsamplebyattr.attrlst.length;t++){const e=i[o.groupsamplebyattr.attrlst[t].k];if(null==e)break;l.push(e)}l.unshift(a);const c=l.join(o.groupsamplebyattr.attrnamespacer);if(!n.has(c)){const t=[];for(const e of o.groupsamplebyattr.attrlst){const n=i[e.k];if(null==n)break;const r={k:e.k,kvalue:n};e.full&&(r.full=e.full,r.fullvalue=i[e.full]),t.push(r)}const e=[];for(const t of o.groupsamplebyattr.attrlst){const n=i[t.k];if(null==n)break;const r=(t.full?i[t.full]:null)||n;e.push(r)}n.set(c,{name:c,samples:[],attributes:t})}let u=!0;for(const r of n.get(c).samples)if(r.samplename==t){for(const t of e)r.items.push(t);u=!1;break}u&&n.get(c).samples.push({samplename:t,items:e})}function Us(t){return Number.isFinite(t.dna_mintotalreads)?Number.isFinite(t.rna_mintotalreads)?Number.isFinite(t.hetsnp_minbaf)?Number.isFinite(t.hetsnp_maxbaf)?Number.isFinite(t.rnapileup_q)?Number.isFinite(t.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 Bs(t){const e=t+".pvalue";return new Promise(((n,r)=>{const o=(0,q.spawn)("Rscript",[y().join(s().binpath,"utils/binom.R"),t,e]);o.on("close",(()=>{n(e)})),o.on("error",(t=>{r(`cannot do binom test: ${t}`)})),o.stderr.on("data",(t=>{r(`cannot do binom test: ${t}`)}))}))}function Gs(t){const e=t.split("\t");if(e.length<8)return;const n={pos:Number.parseInt(e[1])-1},r=[e[3],...e[4].split(",")],s={};for(const t of e[7].split(";")){const e=t.split("=");s[e[0]]=e[1]}if(s.DP&&(n.DP=Number.parseInt(s.DP)),s.AD){n.allele2count={};const t=s.AD.split(",");for(const[e,s]of r.entries())n.allele2count[s]=Number.parseInt(t[e])}return n}function Js(t,e,n){const r=t.sampledata.find((t=>t.sampleobj.name==e));if(r){if(r.AD){const e=r.AD[t.ref]||0,s=r.AD[t.alt]||0,o={chr:t.chr,pos:t.pos,ref:t.ref,alt:t.alt,dnacount:{ref:e,alt:s}};return o.dnacount.f=s+e==0?0:s/(s+e),e+s>=n.dna_mintotalreads&&o.dnacount.f>=n.hetsnp_minbaf&&o.dnacount.f<=n.hetsnp_maxbaf&&(o.dnacount.ishet=!0),o}return null}}async function Hs(t,e,n,r,o){const i=await Ws(y().join(s().tpmasterdir,e.file),n+":"+r+"-"+o),a=new Map;if(i)for(const t of i){const e=t.split("\t"),n=JSON.parse(e[3]),r=Number.parseInt(e[1]),s=Number.parseInt(e[2]);if(a.has(n.name)){const t=a.get(n.name);t.start=Math.min(t.start,r),t.stop=Math.max(t.stop,s)}else a.set(n.name,{gene:n.name,start:r,stop:s,exonunion:[]});const o=a.get(n.name);if(n.exon)for(const t of n.exon){const e=o.exonunion.find((e=>Math.max(e[0],t[0])<Math.min(e[1],t[1])));e?(e[0]=Math.min(t[0],e[0]),e[1]=Math.max(t[1],e[1])):o.exonunion.push([t[0],t[1]])}}for(const[t,e]of a)e.exonlength=e.exonunion.reduce(((t,e)=>t+e[1]-e[0]),0);return a}async function Ws(t,e,n){return new Promise(((r,s)=>{const o=(0,q.spawn)(vs,[t,e],{cwd:n}),i=[],a=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>a.push(t))),o.on("close",(()=>{const t=a.join("");t&&s(t);const e=i.join("").trim();e||r(),r(e.split("\n"))}))}))}function Vs(t,e){return new Promise(((n,r)=>{const s=(0,q.spawn)(vs,["-H",t],{cwd:e}),o=[],i=[];s.stdout.on("data",(t=>o.push(t))),s.stderr.on("data",(t=>i.push(t))),s.on("close",(()=>{const t=i.join("");t&&r(t);const e=o.join("").trim();e||r("cannot list vcf meta lines"),n(e.split("\n"))}))}))}function Ys(t,e){const n=e.findIndex((e=>e.value>=t));return-1==n||n==e.length-1?100:0==n?0:Math.ceil(100*n/e.length)}function Ks(t,e,n){if(!t.key)return[".key missing"];if(!e.cohort)return["ds.cohort missing"];if(!e.cohort.annotation)return["ds.cohort.annotation missing"];return[null,Promise.resolve().then((()=>{const r=[];for(const s in e.cohort.annotation){if(n&&!n.has(s))continue;const o=e.cohort.annotation[s][t.key];null!=o&&r.push({sample:s,value:o})}return{id:t.id,items:r}}))]}function Xs(t,e,n,r){if(!t.genename)return["genename missing"];const o=t.genename.toLowerCase();if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["gene feature too long (> 10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,a)=>{const l=[],c=(0,q.spawn)(vs,[n.file?y().join(s().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:c.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.gene&&n.gene.toLowerCase()==o&&n.sample&&(r&&!r.has(n.sample)||l.push(n))}));const u=[];c.stderr.on("data",(t=>u.push(t))),c.on("close",(e=>{const n=u.join("");!n||gs(n)?i({id:t.id,items:l}):a(n)}))}))))]}function Qs(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];if(null!=t.valuecutoff&&!Number.isFinite(t.valuecutoff))return["invalid value for valuecutoff"];if(null!=t.focalsizelimit&&!Number.isInteger(t.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((e=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(vs,[n.file?y().join(s().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),s=JSON.parse(n[3]);s.dt==P.dtcnv&&(t.valuecutoff&&Math.abs(s.value)<t.valuecutoff||(s.chr=n[0],s.start=Number.parseInt(n[1]),s.stop=Number.parseInt(n[2]),t.focalsizelimit&&s.stop-s.start>=t.focalsizelimit||s.sample&&(r&&!r.has(s.sample)||a.push(s))))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||gs(n)?o({id:t.id,items:a}):i(n)}))}))))]}function to(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];if(null!=t.valuecutoff&&!Number.isFinite(t.valuecutoff))return["invalid value for valuecutoff"];if(null!=t.focalsizelimit&&!Number.isInteger(t.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((e=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(vs,[n.file?y().join(s().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),s=JSON.parse(n[3]);s.dt==P.dtloh&&(t.valuecutoff&&s.segmean<t.valuecutoff||(s.chr=n[0],s.start=Number.parseInt(n[1]),s.stop=Number.parseInt(n[2]),t.focalsizelimit&&s.stop-s.start>=t.focalsizelimit||s.sample&&(r&&!r.has(s.sample)||a.push(s))))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||gs(n)?o({id:t.id,items:a}):i(n)}))}))))]}function eo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((e=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(vs,[n.file?y().join(s().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.dt==P.dtitd&&(n.chr=e[0],n.start=Number.parseInt(e[1]),n.stop=Number.parseInt(e[2]),n.sample&&(r&&!r.has(n.sample)||a.push(n)))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||gs(n)?o({id:t.id,items:a}):i(n)}))}))))]}function no(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((e=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(vs,[n.file?y().join(s().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.dt!=P.dtsv&&n.dt!=P.dtfusionrna||n.sample&&(r&&!r.has(n.sample)||(n._chr=e[0],n._pos=Number.parseInt(e[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",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||gs(n)?o({id:t.id,items:a}):i(n)}))}))))]}function ro(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return F.d1(n.url,n.indexURL)})).then((e=>new Promise(((o,i)=>{const a=[],l=(0,q.spawn)(vs,[n.file?y().join(s().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),s=JSON.parse(n[3]);if(s.sample&&(!r||r.has(s.sample))){if(s.dt==P.dtsv||s.dt==P.dtfusionrna){if(s.dt==P.dtsv&&t.sv&&t.sv.hidden)return;if(s.dt==P.dtfusionrna&&t.fusion&&t.fusion.hidden)return;s._chr=n[0],s._pos=Number.parseInt(n[1]),s.chrA?(s.chrB=s._chr,s.posB=s._pos):(s.chrA=s._chr,s.posA=s._pos)}else if(s.dt==P.dtcnv){if(t.cnv&&t.cnv.hidden)return;if(t.cnv&&t.cnv.valuecutoff&&Math.abs(s.value)<t.cnv.valuecutoff)return;if(s.chr=n[0],s.start=Number.parseInt(n[1]),s.stop=Number.parseInt(n[2]),t.cnv&&t.cnv.focalsizelimit&&s.stop-s.start>=t.cnv.focalsizelimit)return}else if(s.dt==P.dtloh){if(t.loh&&t.loh.hidden)return;if(t.loh&&t.loh.valuecutoff&&s.segmean<t.loh.valuecutoff)return;if(s.chr=n[0],s.start=Number.parseInt(n[1]),s.stop=Number.parseInt(n[2]),t.loh&&t.loh.focalsizelimit&&s.stop-s.start>=t.loh.focalsizelimit)return}else{if(s.dt!=P.dtitd)return void console.error("unknown datatype",s.dt);if(t.itd&&t.itd.hidden)return;s.chr=n[0],s.start=Number.parseInt(n[1]),s.stop=Number.parseInt(n[2])}a.push(s)}}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const r=c.join("");if(r&&!gs(r))return void i(r);const s=new Map;for(const t of a)s.has(t.sample)||s.set(t.sample,[]),s.get(t.sample).push(t);n.hideLOHwithCNVoverlap&&zs(s);const l=[];for(const[t,e]of s)for(const t of e)l.push(t);o({id:t.id,items:l})}))}))))]}function so(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];const s=[];for(const o of n)if(o.type==P.tkt.mdsvcf){const[n,i]=oo(t,e,o,r);if(n)return[n];s.push(i)}else{if(o.type!=P.tkt.mdssvcnv)return["unsupported track type: "+o.type];{const[e,n]=ro(t,0,o,r);if(e)return[e];s.push(n)}}return[null,Promise.all(s).then((t=>{const e=[];for(const n of t)for(const t of n.items)e.push(t);return{id:t[0].id,items:e}}))]}function oo(t,e,n,r){if(!n.tracks)return"tracks[] missing from dsquery";if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>3e6)return["look range too big (>3Mb)"];const o=[];for(const e of n.tracks){const i=Promise.resolve().then((()=>{if(!e.file)return F.d1(e.url,e.indexURL)})).then((o=>new Promise(((i,a)=>{const l=[],c=(0,q.spawn)(vs,[e.file?y().join(s().tpmasterdir,e.file):e.url,(e.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+(t.stop+1)],{cwd:o});O().createInterface({input:c.stdout}).on("line",(s=>{if(n.iscustom)l.push(s);else if(e.type==P.mdsvcftype.vcf){const[o,i,a]=D.S(s,{nochr:e.nochr,samples:e.samples,info:n.info,format:e.format});for(const e of i)if(e.sampledata&&(P.vcfcopymclass(e,{}),!(t.snvindel&&t.snvindel.excludeclasses&&t.snvindel.excludeclasses[e.class]))){if(r){const t=[];for(const n of e.sampledata)r.has(n.sampleobj.name)&&t.push(n);if(0==t.length)continue;e.sampledata=t}for(const t of e.sampledata)delete t.allele2readcount;delete e._m,delete e.vcf_ID,delete e.name,e.dt=P.dtsnvindel,l.push(e)}}else console.error("type not one of mdsvcftype: "+e.type)}));const u=[];c.stderr.on("data",(t=>u.push(t))),c.on("close",(t=>{const e=u.join("");!e||gs(e)?i(l):a(e)}))}))));o.push(i)}return[null,Promise.all(o).then((e=>{const n=[];for(const t of e)for(const e of t)n.push(e);return{id:t.id,items:n}}))]}function io(t){if(!t.endsWith(".gz"))return["no .gz suffix (file should be compressed by bgzip)"];const e=y().join(s().tpmasterdir,t);return m().existsSync(e)?m().existsSync(e+".tbi")||m().existsSync(e+".csi")?[null,e]:[".tbi/.csi index missing"]:[".gz file not found"]}ks.use(k()()),ks.use(((t,e,n)=>{"POST"==t.method.toUpperCase()&&(t.headers["content-type"]="application/json");try{t.query.encoding;!function(t){const e=t.encoding;for(const[n,r]of Object.entries(t))("json"==e||"null"==r||"true"==r||"false"==r||ps(r)||r.startsWith('"')&&r.endsWith('"')||r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))&&(t[n]=JSON.parse(r))}(t.query)}catch(t){return void e.send({error:t})}n()})),ks.use(ds()()),ks.use(T().json({limit:"5mb"})),ks.use(T().text({limit:"5mb"})),ks.use(T().urlencoded({extended:!0})),ks.use(((t,e,n)=>{"POST"==t.method.toUpperCase()&&t.body&&"application/json"!=t.headers["content-type"]?e.send({error:"invalid HTTP request.header['content-type'], must be 'application/json'"}):("application/json"==t.headers["content-type"]&&(t.query||(t.query={}),Object.assign(t.query,t.body)),Ss(t),t.query.__protected__={},t.cookies?.sessionid&&(t.query.__protected__.sessionid=t.cookies.sessionid),Object.freeze(t.query.__protected__),Ns(e),e.header("Access-Control-Allow-Origin",t.get("origin")||t.get("referrer")||t.protocol+"://"+t.get("host").split(":")[0]||"*"),e.header("Access-Control-Allow-Credentials",!0),"GET"!=t.method||t.path.includes(".")&&!t.path.endsWith("proteinpaint.js")||e.header("Cache-control",`immutable,max-age=${s().responseMaxAge||1}`),n())})),ks.catch=cs,ks.use((function(t,e,n){try{const e=t.query;for(const t in e)t in us&&(e[t]=us[t](e[t]));n()}catch(n){cs(t,e,n.message||n)}})),ks.use(((t,e,n,r)=>{Ss(e),t&&(t&&"entity.parse.failed"==t.type?n.send({error:"invalid request body, must be a valid JSON-encoded object"}):n.send({error:t}))})),s().jwt&&(console.log("JWT is activated"),ks.use(((t,e,n)=>{let r={};t.body&&"POST"==t.method&&(r=t.body);const o=r.jwt?r.jwt:t.headers&&t.headers.authorization&&t.headers.authorization.startsWith("Bearer ")?t.headers.authorization.split(" ")[1]:null;if(!o)return e.send({error:"json web token missing"});R().verify(o,s().jwt.secret,((t,r)=>t?e.send({error:"Invalid token"}):r[s().jwt.permissioncheck]?void n():e.send({error:"Not authorized"})))}))),function(){if(!s().routeSetters)return;for(const t of s().routeSetters)if(t.endsWith(".js")){require(t)(ks,qs)}}(),Jr.i.maySetAuthRoutes(ks,qs,s()),ks.get(qs+"/cardsjson",(async function(t,e){try{if(t.query.datafile&&t.query.tabixCoord)return new Promise(((n,r)=>{const o=(0,q.spawn)(vs,[y().join(s().tpmasterdir,t.query.datafile),t.query.tabixCoord]),i=[],a=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>a.push(t))),o.on("close",(t=>{""!=a.join("").trim()&&r("error querying bedj file");const s=i.join("").trim();n(e.send({file:s.split("\n")}))}))})).catch((t=>{t.stack&&console.error(t.stack)}));throw"invalid cards request"}catch(t){e.send({error:t.message||t})}})),ks.post(qs+"/mdsjsonform",(async function(t,e){if(!ys.mdsjsonform)return e.send({error:"This feature is not enabled on this server."});if(t.query.deposit){const n=Math.random().toString(),r=await function(){const t=y().join(s().cachedir,"mdsjsonform");return new Promise(((e,n)=>{m().stat(t,((r,s)=>{if(r){if("ENOENT"==r.code)return void m().mkdir(t,(r=>{r&&n("error creating dir"),e(t)}));n("error checking directory")}else s.isDirectory()?e(t):n('"mdsjsonform" exists but not directory')}))}))}(),o=y().join(r,n);return await F.Sf(o,JSON.stringify(t.query.deposit)),void e.send({id:n})}if(t.query.draw){const n=y().join(s().cachedir,"mdsjsonform",t.query.draw),r=await F.b5(n);try{const t=JSON.parse(r);e.send({json:t})}catch(t){e.send({error:"Invalid JSON"})}return}e.send({})})),ks.get(qs+"/genomes",(async function(t,e){try{await m().promises.stat(s().tpmasterdir)}catch(t){let n="Error with TP directory ("+t.code+")";const r=s().maintenance||{};if("start"in r&&"stop"in r&&r.tpMessage){const t=+new Date(r.start),e=+new Date(r.stop),s=+new Date;t<=s&&s<=e&&(n=r.tpMessage)}return void e.send({error:n})}const n={};if(t.query&&t.query.genome)n[t.query.genome]=Ms(t.query.genome);else for(const t in bs)n[t]=Ms(t);let r=!1;for(const t in bs)bs[t].blat&&(r=!0);e.send({genomes:n,debugmode:s().debugmode,headermessage:s().headermessage,base_zindex:s().base_zindex,codedate:hs.A.codedate,launchdate:hs.A.launchdate,hasblat:r,features:ys,dsAuth:Jr.i.getDsAuth(t),commonOverrides:s().commonOverrides,targetPortal:s().targetPortal,cardsPath:s().cards?.path})})),ks.get(qs+"/getDataset",(function(t,e){try{const n=bs[t.query.genome];if(!n)throw"unknown genome";if(!n.datasets)throw"genomeobj.datasets{} missing";let r;for(const e in n.datasets)if(e.toLowerCase()==t.query.dsname.toLowerCase()){r=n.datasets[e];break}if(!r)throw"invalid dsname";return r.isMds3?e.send({ds:ur(r)}):r.isMds?e.send({ds:Cs(r)}):e.send({ds:Ts(r)})}catch(t){e.send({error:t.message||t})}})),ks.all(qs+"/ntseq",(async function(t,e){try{if(!t.query.coord)throw"coord missing";const n=bs[t.query.genome];if(!n)throw"invalid genome";if(!n.genomefile)throw"no sequence file available";const r=await F.Kf(n,t.query.coord);e.send({seq:r.split("\n").slice(1).join("")})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.post(qs+"/pdomain",(function(t,e){try{const n=t.query.genome;if(!n)throw"no genome";const r=bs[n];if(!r)throw"invalid genome "+n;if(!r.proteindomain)return e.send({lst:[]});if(!Array.isArray(t.query.isoforms))throw"isoforms[] missing";const s=[];for(const e of t.query.isoforms){if(r.genomicNameRegexp.test(e))continue;const t=r.proteindomain.getbyisoform.all(e);s.push({name:e,pdomains:t.map((t=>{const n=JSON.parse(t.data);return n.refseq=e,n}))})}e.send({lst:s})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.post(qs+"/tkbedj",function(t){return async(e,n)=>{try{n.send(await async function(t,e){const[n,r,s]=F.ZX(t);if(n)throw n;let o,i,a,l,c;if(t.query.fileIsBigbed=await F.aS(r),t.query.getdata)t.query.getBED;else{if(o=Number(t.query.stackheight),i=Number(t.query.stackspace),a=Number(t.query.regionspace),l=Number(t.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(t.query.usevalue){if(!t.query.usevalue.key)throw".key missing from .usevalue";if(t.query.usevalue.dropBelowCutoff&&(t.query.usevalue.dropBelowCutoff=Number(t.query.usevalue.dropBelowCutoff),Number.isNaN(t.query.usevalue.dropBelowCutoff)))throw".usevalue.dropBelowCutoff is not number"}if(t.query.bplengthUpperLimit&&(t.query.bplengthUpperLimit=Number(t.query.bplengthUpperLimit),Number.isNaN(t.query.bplengthUpperLimit)))throw"bplengthUpperLimit not number";if(!t.query.rglst)throw"no rglst[]";if(!Array.isArray(t.query.rglst))throw"rglst is not an array";if(0==t.query.rglst.length)throw"empty rglst";for(const e of t.query.rglst)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));const u=t.query.color||"#3D7A4B",f=t.query.gmregion||null,d=t.query.isoform,h=t.query.onerow,p=t.query.categories||null,m=t.query.__isgene;let g;!t.query.fileIsBigbed&&s&&(g=await F.d1(r,t.query.indexURL));const y=await async function(t,e,n,r,s){let o;if(r){const i=[];if(t.fileIsBigbed){const n=await F.z5(e,r.chr,r.start,r.stop);for(const e of n){const n=e.split("\t"),r=_n(n);r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[];for(let e=0;e<t.rglst.length;e++){const n=t.rglst[e];Math.max(r.start,n.start)<Math.min(r.stop,n.stop)&&r.rglst.push({idx:e})}0!=r.rglst.length&&i.push(r)}}else await F.UE({args:[e,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:e=>{const n=e.split("\t");let r={};if(t.getBED)r.rest=n.slice(3);else if(n[3])try{r=JSON.parse(n[3])}catch(t){return void(o=e)}if(!r.isoformonly||r.isoformonly==s){r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[];for(let e=0;e<t.rglst.length;e++){const n=t.rglst[e];Math.max(r.start,n.start)<Math.min(r.stop,n.stop)&&r.rglst.push({idx:e})}0!=r.rglst.length&&i.push(r)}}});if(o)throw"Line with invalid JSON: "+o;return[i]}const i=[];for(const[r,s]of t.rglst.entries()){const a=[];if(t.fileIsBigbed){const t=await F.z5(e,s.chr,s.start,s.stop);for(const e of t){const t=e.split("\t"),n=_n(t);n.chr=t[0],n.start=Number(t[1]),n.stop=Number(t[2]),n.rglst=[{idx:r}],a.push(n)}}else await F.UE({args:[e,s.chr+":"+s.start+"-"+s.stop],dir:n,callback:e=>{const n=e.split("\t");let s={};if(t.getBED)s.rest=n.slice(3);else if(n[3])try{s=JSON.parse(n[3])}catch(t){return void(o=e)}s.chr=n[0],s.start=Number(n[1]),s.stop=Number(n[2]),s.rglst=[{idx:r}],a.push(s)}});i.push(a)}if(o)throw"Line with invalid JSON: "+o;return i}(t.query,r,g,f,d);let b;t.query.filterByName&&(b=new Set(t.query.filterByName.split(/[\s\n]/).map((t=>t.trim()))));const v=[];for(const e of y)for(const n of e){if(t.query.usevalue){const e=n[t.query.usevalue.key];if(!Number.isFinite(e))continue;if(t.query.usevalue.dropBelowCutoff&&e<t.query.usevalue.dropBelowCutoff)continue}if(!(t.query.bplengthUpperLimit&&n.stop-n.start>t.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(t.query.getdata)return{items:v};if(0==v.length){const e=(0,S.createCanvas)(l*t.query.devicePixelRatio,o*t.query.devicePixelRatio),n=e.getContext("2d");return t.query.devicePixelRatio>1&&n.scale(t.query.devicePixelRatio,t.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:e.toDataURL(),height:o}}const w=Math.ceil(o/4)-1;if(h||v.length>=Nn){const e=v.length<200,n=(0,S.createCanvas)(l*t.query.devicePixelRatio,o*t.query.devicePixelRatio),r=n.getContext("2d");t.query.devicePixelRatio>1&&r.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);const s=v.length<=200?[]:null;for(const n of v){const i=p&&n.category&&p[n.category]?p[n.category].color:n.color||u;r.fillStyle=i;for(const i of n.rglst){let l=0;for(let e=0;e<i.idx;e++)l+=t.query.rglst[e].width+a;const c=t.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 t of u){const e=Math.max(c.start,t[0]),i=Math.min(c.stop,t[1]),a=l+c.scale(c.reverse?i:e),u=l+c.scale(c.reverse?e:i);r.fillRect(a,w,Math.max(1,u-a),o-2*w),En(s,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 t of f){const i=Math.max(c.start,t[0]),a=Math.min(c.stop,t[1]),u=l+c.scale(c.reverse?a:i),f=l+c.scale(c.reverse?i:a);r.fillRect(u,0,Math.max(1,f-u),o),En(s,u,f,1,n),n.strand&&e&&(r.strokeStyle="white",On(r,n.strand,u,w,f-u,o-2*w))}}}return{src:n.toDataURL(),height:o,mapisoform:s}}if(t.query.hideItemNames)for(const t of v)delete t.name;let _=null;if(m&&v.length<Sn){_=[];for(const t of v){const e={};for(const n in t)"canvas"!=n&&"rglst"!=n&&(e[n]=t[n]);_.push(e)}}const x=t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0),k=t.query.translatecoding&&x<3*l;let q;if(k){if(!t.query.genome)throw"genome missing for translating genes";if(q=e[t.query.genome],!q)throw"invalid genome"}const N=[],A=(0,S.createCanvas)(10,10);let M=A.getContext("2d");t.query.devicePixelRatio>1&&M.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);M.font="bold "+c+"px Arial";const T=v.length<qn,C=v.length<qn?[]:null;let j=!1;f&&(j=f.reverse);for(const e of t.query.rglst)e.reverse&&(j=!0);v.sort(((t,e)=>j?t.stop==e.stop?t.start-e.start:e.stop-t.stop:t.start==e.start?e.stop-t.stop:t.start-e.start));const E=v.some((t=>t.exon)),O=[0];let I=1,R=null;for(const e of v){let n=null,r=null;for(const s of e.rglst){let o=0;for(let e=0;e<s.idx;e++)o+=t.query.rglst[e].width+a;const i=t.query.rglst[s.idx],l=Math.max(e.start,i.start),c=Math.min(e.stop,i.stop);if(l<c){const t=o+i.scale(i.reverse?c:l),e=o+i.scale(i.reverse?l:c);null==n?(n=t,r=e):(n=Math.min(n,t),r=Math.max(r,e))}}if(null==n)continue;e.canvas={start:n,stop:r,stranded:null!=e.strand},e.coding&&k&&(e.willtranslate=!0,N.push(e));let s=n,o=r;if(T){const t=e.name;if(t){e.canvas.namestr=t;const n=M.measureText(t).width;e.canvas.namewidth=n,E?e.canvas.start>=n+xn?(e.canvas.namestart=e.canvas.start-xn,s=e.canvas.namestart-n,e.canvas.textalign="right"):e.canvas.stop+n+xn<=l?(e.canvas.namestart=e.canvas.stop+xn,o=e.canvas.namestart+n,e.canvas.textalign="left"):n>e.canvas.stop-e.canvas.start?e.canvas.start>l-e.canvas.stop?(e.canvas.namestart=e.canvas.start-xn,s=e.canvas.namestart-n,e.canvas.textalign="right"):(e.canvas.namestart=e.canvas.stop+xn,o=e.canvas.namestart+n,e.canvas.textalign="left"):(e.canvas.namehover=!0,e.canvas.textalign="left"):Math.min(l,e.canvas.stop)-Math.max(0,e.canvas.start)>=n+2*kn?e.canvas.namein=!0:e.canvas.start>=n+xn?(e.canvas.namestart=e.canvas.start-xn,s=e.canvas.namestart-n,e.canvas.textalign="right"):e.canvas.stop+n+xn<=l?(e.canvas.namestart=e.canvas.stop+xn,o=e.canvas.namestart+n,e.canvas.textalign="left"):e.canvas.namein=!0}}e.canvas.stop-e.canvas.start>.3*l&&(R=[]);for(let t=1;t<=I;t++)if(null==O[t]||O[t]<s){e.canvas.stack=t,O[t]=o;break}null==e.canvas.stack&&(I++,O[I]=o,e.canvas.stack=I),En(C,s,o,e.canvas.stack,e)}A.width=l*t.query.devicePixelRatio;const D=(o+i)*I-i;A.height=D*t.query.devicePixelRatio,M=A.getContext("2d"),t.query.devicePixelRatio>1&&M.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);M.font="bold "+c+"px Arial",M.textBaseline="middle",M.lineWidth=1;for(const e of v){const n=e.canvas;if(!n)continue;const r=p&&e.category&&p[e.category]?p[e.category].color:e.color||u,s=(o+i)*(n.stack-1);M.fillStyle=r,(e.exon||e.rglst.length>1)&&(M.strokeStyle=r,M.beginPath(),M.moveTo(n.start,Math.floor(s+o/2)+.5),M.lineTo(n.stop,Math.floor(s+o/2)+.5),M.stroke());for(const i of e.rglst){let l=0;for(let e=0;e<i.idx;e++)l+=t.query.rglst[e].width+a;const c=t.query.rglst[i.idx],u=[];e.utr3&&u.push(...e.utr3),e.utr5&&u.push(...e.utr5),!e.exon||e.coding&&0!=e.coding.length||u.push(...e.exon);for(const t of u){const n=Math.max(t[0],c.start),i=Math.min(t[1],c.stop);if(n<i){if(e.exon2color)for(const t of e.exon2color)if(n>=t.start&&i<=t.stop){M.fillStyle=t.color;break}const t=l+c.scale(c.reverse?i:n),a=l+c.scale(c.reverse?n:i);M.fillRect(t,s+w,Math.max(1,a-t),o-2*w),e.exon2color&&(M.fillStyle=r)}}const f=[];e.exon?e.coding&&e.coding.length>0&&f.push(...e.coding):f.push([e.start,e.stop]);let d=e.strand;n.stranded&&c.reverse&&(d="+"==e.strand?"-":"+");for(const t of f){const i=Math.max(t[0],c.start),a=Math.min(t[1],c.stop);if(i<a){if(e.exon2color)for(const t of e.exon2color)if(i>=t.start&&a<=t.stop){M.fillStyle=t.color;break}const t=l+c.scale(c.reverse?a:i),u=l+c.scale(c.reverse?i:a);if(M.fillRect(t,s,Math.max(1,u-t),o),e.exon2color&&(M.fillStyle=r),n.stranded&&!e.willtranslate)if(M.strokeStyle="white",n.namein){const e=(u-t-n.namewidth)/2;On(M,d,t,s+w,e,o-2*w),On(M,d,t+e+n.namewidth,s+w,e,o-2*w)}else On(M,d,t,s+w,u-t,o-2*w)}}if(n.stranded&&e.intron){M.strokeStyle=r;for(const t of e.intron){const e=Math.max(t[0],c.start),n=Math.min(t[1],c.stop);if(e<n){const t=l+c.scale(c.reverse?n:e);On(M,d,t,s+w,l+c.scale(c.reverse?e:n)-t,o-2*w)}}}if(R&&e.exon){for(let t=0;t<e.exon.length;t++){const r=e.exon[t];if(r[1]<=c.start||r[0]>=c.stop)continue;const s=Math.max(r[0],c.start),o=Math.min(r[1],c.stop);if(s<o){const i=l+c.scale(c.reverse?o:s),a=l+c.scale(c.reverse?s:o);R.push({chr:e.chr,start:Math.min(r[0],r[1]),stop:Math.max(r[0],r[1]),x1:i,x2:a,y:n.stack,name:"Exon "+(t+1)+"/"+e.exon.length})}}for(let t=1;t<e.exon.length;t++){const r=e.exon["+"==e.strand?t-1:t][1],s=e.exon["+"==e.strand?t:t-1][0];if(s<=c.start||r>=c.stop)continue;const o=Math.max(r,c.start),i=Math.min(s,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:e.chr,start:r,stop:s,x1:a,x2:u,y:n.stack,name:"Intron "+t+"/"+(e.exon.length-1)})}}}}if(null!=n.namestart)M.textAlign=n.textalign,M.fillStyle=r,M.fillText(n.namestr,n.namestart,s+o/2);else if(n.namehover&&!t.query.noNameHover){const t=Math.max(10,n.start+10);M.fillStyle="white",M.fillRect(t,s,n.namewidth+10,o),M.strokeStyle=r,M.strokeRect(t+1.5,s+.5,n.namewidth+10-3,o-2),M.fillStyle=r,M.textAlign="center",M.fillText(n.namestr,t+n.namewidth/2+5,s+o/2)}else n.namein&&(M.textAlign="center",M.fillStyle="white",M.fillText(n.namestr,(Math.max(0,n.start)+Math.min(l,n.stop))/2,s+o/2))}const L={height:D,mapisoform:C,mapexon:R,returngmdata:_};if(0==N.length)return L.src=A.toDataURL(),L;const $=[];M.textAlign="center",M.textBaseline="middle";for(const[e,n]of N.entries()){const e=p&&n.category&&p[n.category]?p[n.category].color:n.color||u,r=n.canvas,s=(o+i)*(r.stack-1);n.genomicseq=(await F.Kf(q,n.chr+":"+(n.start+1)+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase();const l=(0,P.nt2aa)(n);for(const e of n.rglst){const i=t.query.rglst[e.idx];let c=0;for(let n=0;n<e.idx;n++)c+=t.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 h=!1;r.stranded&&"-"==n.strand&&(h=!0);let p=0;d&&(M.font=d+"px Arial");for(const[t,e]of n.coding.entries()){let[r,a]=e;if(h){if(r>=i.stop){p+=a-r,0==t&&n.startCodonFrame&&(p-=3-n.startCodonFrame);continue}if(a<=i.start)break}else{if(a<=i.start){p+=a-r,0==t&&n.startCodonFrame&&(p-=3-n.startCodonFrame);continue}if(r>=i.stop)break}if(0==t&&n.startCodonFrame){h?a-=3-n.startCodonFrame:r+=3-n.startCodonFrame;let t=Math.max(e[0],i.start),l=Math.min(e[1],i.stop);if(h?t=Math.max(a,i.start):l=Math.min(r,i.stop),t<l){M.fillStyle=jn;const e=c+i.scale(i.reverse?l:t),n=c+i.scale(i.reverse?t:l);M.fillRect(e,s,Math.max(1,n-e),o)}}const f=Math.max(i.start,r),m=Math.min(i.stop,a);p+=h?a-m:f-r;let g=0;for(let t=0;t<m-f;t++){let e;if(p++,g++,p%3==0)e=p/3-1;else{if(t<m-f-1)continue;e=Math.floor(p/3)}let r=l[e],a=Math.ceil(p/3)%2==0?An:null;r?"M"==r?a=Tn:"*"==r&&(a=Cn):(r=4,a=Mn);let y,b=u*g;if(h){const e=m-1-t;y=c+i.scale(e)}else{const e=f+t+1-g;y=c+i.scale(e)}i.reverse&&(y-=b),g=0,y>=c&&y<=c+i.width&&(a&&(M.fillStyle=a,M.fillRect(y,s,b,o)),d&&(M.fillStyle="white",M.fillText(r,y+b/2,s+o/2)),$.push({x1:y,x2:y+b,y:n.canvas.stack,name:r+(e+1)+' <span style="font-size:.7em;color:#858585">AA residue</span>'}))}}}if(r.namehover&&!t.query.noNameHover){M.font="bold "+c+"px Arial";const t=Math.max(10,r.start+10);M.fillStyle="white",M.fillRect(t,s,r.namewidth+10,o),M.strokeStyle=e,M.strokeRect(t+1.5,s+.5,r.namewidth+10-3,o-2),M.fillStyle=e,M.fillText(r.namestr,t+r.namewidth/2+5,s+o/2)}}return L.src=A.toDataURL(),L.mapaa=$,L}(e,t))}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(bs)),ks.post(qs+"/tkbedgraphdot",function(t){return async(e,n)=>{try{const r=e.query,o=t[r.genome];if(!o)throw"unknown genome";let i=null;if(r.file)r.file=y().join(s().tpmasterdir,r.file);else{if(!r.url)throw"file or url missing";i=await F.d1(r.url,r.indexURL)}const a=await F.Jy(r.file||r.url,i,o),l=await it(r,i,a);n.send(l)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(bs)),ks.all(qs+"/tkbam",function(t){return async(e,n)=>{try{if(e.query.gdcFileUUID){if("string"!=typeof e.query.gdcFileUUID)throw"gdcFileUUID not string";!function(t){if(!t.query.gdcFilePosition)throw"gdcFileUUID is present but gdcFilePosition is missing";if("string"!=typeof t.query.gdcFilePosition)throw"gdcFilePosition is not string";if("unmapped"==t.query.gdcFilePosition)return;const e=t.query.gdcFilePosition.split(/[.:-]/);if(3!=e.length)throw"gdcFilePosition not 3 fields";const n=Number(e[1]),r=Number(e[2]);if(!Number.isInteger(n)||!Number.isInteger(r)||n>r)throw"gdcFilePosition invalid start/stop";if(t.query.stream2download)return;if(r-n>Ee)throw`Slice range exceeds ${vt(Ee)} limit. Please choose a smaller range.`}(e),e.query.__genomes=t;const r=e.get("X-Auth-Token");if(r&&(e.query.token=r),await jt(e.query.gdcFileUUID,Oe(t),e.query),e.query.stream2download)return void await async function(t,e){const{host:n,headers:r}=Oe(t.query.__genomes).getHostHeaders(t.query);r.compression=!1;const s=y().join(n.rest,"/slicing/view/",t.query.gdcFileUUID+"?region="+t.query.gdcFilePosition);e.statusCode=200;try{await Ot(v().stream(s,{method:"get",headers:r}),e)}catch(t){if("ERR_STREAM_PREMATURE_CLOSE"==t.code)return;t.stack&&console.log(t.stack),e.send({error:t.message||t})}}(e,n);e.query.file=nn(e)}if(e.query.downloadgdc)return void n.send(await rn(e));if(e.query.clientdownloadgdcslice)return void await async function(t,e){if(!t.query.gdcFileUUID||!t.query.gdcFilePosition||!t.query.file)throw"clientdownloadgdcslice: unauthorized access";const n=y().join(s().cachedir_bam,t.query.file),r=await m().promises.readFile(n);e.writeHead(200,{"Content-Type":"application/octet-stream","Content-Disposition":"attachment; filename=gdc.bam","Content-Length":r.length}),e.end(Buffer.from(r,"binary"))}(e,n);if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";if(e.query.getread)return void n.send(await async function(t,e){if(!e.query.chr)throw".chr missing";if(!e.query.qname)throw".qname missing";if(e.query.qname=decodeURIComponent(e.query.qname),!Number.isInteger(e.query.start))throw".start is not integer";if(!Number.isInteger(e.query.stop))throw".stop is not integer";const n={chr:e.query.chr,start:e.query.start,stop:e.query.stop,scale:()=>{},ntwidth:10},r=await async function(t,e){const[n,r]=await Fe(t);let s,o,i,a,l;if(t.query.unknownorder){if(!Number.isInteger(t.query.readstart)||!Number.isInteger(t.query.readstop))throw"readstart/stop not provided for read with unknown order";i=t.query.readstart,a=t.query.readstop}if(await F.UE({isbam:!0,args:["view",n,(t.query.nochr?t.query.chr.replace("chr",""):t.query.chr)+":"+e.start+"-"+e.stop],dir:r,callback:(n,r)=>{if(n.split("\t")[0]!=t.query.qname)return;const c=Ue({sam_info:n,keepallboxes:!0,keepmatepos:!0,keepunmappedread:!0},e);if(c&&(!t.query.show_unmapped||!c.discord_unmapped2)&&(t.query.start==c.segstart_original&&t.query.stop==c.segstop||t.query.paired||t.query.show_unmapped))if(t.query.show_unmapped&&t.query.getfirst){if(c.islast)return r.kill(),void(l=[c])}else if(t.query.show_unmapped&&t.query.getlast){if(c.isfirst)return r.kill(),void(l=[c])}else if(t.query.getfirst){if(c.isfirst)return r.kill(),void(l=[c])}else if(t.query.getlast){if(c.islast)return r.kill(),void(l=[c])}else if(t.query.unknownorder){if(c.segstart==i&&c.segstop==a)return r.kill(),void(l=[c])}else if(c.isfirst?s=c:c.islast&&(o=c),s&&o)return r.kill(),void(l=[s,o])}}),l){if(t.query.altseqs){const e={query_seq:l[0].seq,refseqs:t.query.refseqs,altseqs:t.query.altseqs,cigar_seq:l[0].cigarstr,start_position:l[0].segstart,ref_positions:t.query.ref_positions,refalleles:t.query.refalleles,altalleles:t.query.altalleles},n=(await(0,Q.run_rust)("align",JSON.stringify(e))).split("\n");let r;for(let t of n)t.includes("Final_output:")?r=JSON.parse(t.replace("Final_output:","")):console.log(t);l.alignments=r}return l}l=[],s&&l.push(s);o&&l.push(o);return l.length?l:null}(e,n);if(!r){if(e.query.show_unmapped)throw"mate not found";throw"read not found"}const s=[];for(const n of r)n.discord_unmapped1?s.push(await tn(n,t,e.query)):s.push(await en(n,t,e.query));r.alignments&&(s[0].alignments=r.alignments);return{lst:s}}(r,e));const o=s().debugmode?new Date:null,i=await async function(t,e){const[n,r]=await Fe(e),s={genome:t,file:n,dir:r,asPaired:e.query.asPaired,getcolorscale:e.query.getcolorscale,devicePixelRatio:e.query.devicePixelRatio?Number(e.query.devicePixelRatio):1};if(e.query.pileupheight&&(s.pileupheight=Number(e.query.pileupheight),Number.isNaN(s.pileupheight)))throw".pileupheight is not integer";e.query.drop_pcrduplicates&&(s.drop_pcrduplicates=!0);e.query.drop_supplementary_alignments&&(s.drop_supplementary_alignments=!0);if(e.query.variant){s.diff_score_plotwidth=Number(e.query.diff_score_plotwidth),e.query.max_diff_score&&(s.max_diff_score=Number(e.query.max_diff_score),s.min_diff_score=Number(e.query.min_diff_score));const t=e.query.variant.split(".");if(s.strictness=e.query.strictness,!Number.isInteger(t.length%4))throw"invalid variant, not chr.pos.ref.alt";s.alleleAlreadyUpdated=e.query.alleleAlreadyUpdated,s.alleleAlreadyUpdated&&(s.altseqs=e.query.altseqs,s.refseqs=e.query.refseqs,s.altalleles=e.query.altalleles,s.refalleles=e.query.refalleles,s.leftflankseqs=e.query.leftflankseqs,s.rightflankseqs=e.query.rightflankseqs,s.ref_positions=e.query.ref_positions);const n=t.length/4,r=[];for(let e=0;e<n;e++)r.push({chr:t[4*e],pos:Number(t[4*e+1]),ref:t[4*e+2],alt:t[4*e+3]});if(s.variant=r,e.query.alignOneGroup&&(s.alignOneGroup=e.query.alignOneGroup),Number.isNaN(s.variant.pos))throw"variant pos not integer"}else if(e.query.sv){const t=e.query.sv.split(".");if(t.length<6)throw"invalid sv, not chrA.posA.chrB.posB";if(s.sv={chrA:t[0],startA:Number(t[1]),strandA:Number(t[2]),chrB:t[3],startB:Number(t[4]),strandB:Number(t[5])},Number.isNaN(s.sv.startA))throw"sv.startA not integer";if(Number.isNaN(s.sv.startB))throw"sv.startB not integer"}if(Number.isFinite(Number(e.query.stackstart))){if(!e.query.stackstop)throw".stackstop missing";if(s.partstack={start:Number(e.query.stackstart),stop:Number(e.query.stackstop)},Number.isNaN(s.partstack.start))throw".stackstart not integer";if(Number.isNaN(s.partstack.stop))throw".stackstop not integer";if(!e.query.grouptype)throw".grouptype required for partstack";s.grouptype=e.query.grouptype}e.query.gdc||(e.query.nochr?s.nochr="string"==typeof e.query.nochr?JSON.parse(e.query.nochr):e.query.nochr:s.nochr=await F.Dp(s.file,t,s.dir));if(s.regions=e.query.regions,!Array.isArray(s.regions)||0==s.regions.length)throw"q.regions[] not non-empty array";let o=0;for(const t of s.regions){if(!t.chr)throw".chr missing from a region";if(!Number.isInteger(t.start))throw".start not integer of a region";if(!Number.isInteger(t.stop))throw".stop not integer of a region";t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start)),t.ntwidth=t.width/(t.stop-t.start),o=Math.max(o,t.ntwidth)}return s.stacksegspacing=Math.max(ke,qe*o),s.readcount_skipped=0,s}(r,e);n.send(await async function(t){await async function(t){if(t.variant){let e=0,n=0,r=0,s=t.variant[0].pos,o=t.variant[0].pos+Math.max(t.variant[0].ref.length,t.variant[0].alt.length);for(const i of t.variant){const t=Math.abs(i.pos-Math.max(i.ref.length,i.alt.length));t>e&&(e=t,n=r),s>i.pos&&(s=i.pos),o<i.pos+Math.max(i.ref.length,i.alt.length)&&(o=i.pos+Math.max(i.ref.length,i.alt.length)),r+=1}e=Math.floor(1.5*Math.max(t.variant[n].ref.length,t.variant[n].alt.length));const i={chr:t.variant[0].chr,start:s-e,stop:o+e};return await De(t,[i]),await Le(i,t),void(t.regions[0].lines=i.lines)}await De(t,t.regions);for(const e of t.regions)await Le(e,t)}(t),t.totalnumreads=t.regions.reduce(((t,e)=>t+e.lines.length),0);const e={nochr:t.nochr,count:{r:t.totalnumreads},groups:[]};t.read_limit_reached&&(e.count.read_limit_reached=t.read_limit_reached);t.canvaswidth=t.regions[t.regions.length-1].x+t.regions[t.regions.length-1].width;{const n=await async function(t){const e=[],n=[];let r=0;for(const s of t.regions){for(const t of s.lines)e.push({sam_info:t,tempscore:""});r=s.x+s.width,n.push(r)}if(0==e.length)return{groups:[{type:lt,regions:mt(t.regions),templates:e,messages:[],partstack:t.partstack,widths:n}]};if(t.variant){if(1==t.regions.length)return await async function(t,e,n){const r=t.regions[0].lines[0].split("\t")[9].length;let s=!1,o=[],i=[],a=[],l=[],c=[],u=[],f=[];if(t.alleleAlreadyUpdated)o=t.leftflankseqs,i=t.rightflankseqs,u=t.refseqs,f=t.altseqs,a=t.refalleles,l=t.altalleles,c=t.ref_positions,0!=u[0].toUpperCase().localeCompare((o[0]+a[0]+i[0]).toUpperCase())&&(console.log("Reference allele is not correct for variant 0"),s=!0);else{let e,n,s=0;for(const o of t.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(t.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 e=(await F.Kf(t.genome,o.chr+":"+o.pos+"-"+o.pos)).split("\n").slice(1).join("").toUpperCase();i=e+o.ref,u=e,o.pos-=1}else u=o.alt,i=o.ref;const f=o.pos,d=i.toUpperCase(),h=u.toUpperCase();0==s?(e=f-r,n=f+i.length+1+r):(f-r<e&&(e=f-r),f+i.length+1+r>n&&(n=f+i.length+1+r)),a.push(d),l.push(h),c.push(f),s+=1}s=0;for(const r of t.variant){const d=(await F.Kf(t.genome,r.chr+":"+e+"-"+c[s])).split("\n").slice(1).join("").toUpperCase(),h=(await F.Kf(t.genome,r.chr+":"+(c[s]+a[s].length+1)+"-"+n)).split("\n").slice(1).join("").toUpperCase(),p=d+a[s]+h,m=d+l[s]+h;console.log(r.chr+"."+c[s]+"."+a[s]+"."+l[s]),s+=1,o.push(d),i.push(h),u.push(p),f.push(m)}}const d=[];for(let t=0;t<e.length;t++){const n=e[t].sam_info.split("\t");d.push({read_sequence:n[9],start_position:Number(n[3]),cigar:n[5],flag:Number(n[1])})}const h=[];for(let t=0;t<a.length;t++)h.push({ref_position:Number(c[t]),refallele:a[t],altallele:l[t],refseq:u[t],altseq:f[t],leftflankseq:o[t],rightflankseq:i[t]});Number.isFinite(Number(t.strictness))||(t.strictness=1);const p={reads:d,alleles:h,strictness:Number(t.strictness)},m=new Date,g=await(0,Q.run_rust)("indel",JSON.stringify(p)),y=new Date;console.log("Time taken to run rust indel pipeline:",y-m,"ms");const b=g.split("\n");let v,w,_,x,k,q,N=0;for(let t of b)t.includes("Final_output:")?v=JSON.parse(JSON.parse(t.replace("Final_output:",""))):1==a.length&&t.includes("fisher_strand:")?(w=JSON.parse(t.replace("fisher_strand:","")),_=w.alternate_forward_count,x=w.alternate_reverse_count,k=w.reference_forward_count,q=w.reference_reverse_count,N=w.p_value):console.log(t);if(0==v.length)throw"No reads available for variant typing";let S=!1;1==t.variant.length&&N>60&&(S=!0);const A=pt(t);t.variant.length;let M=1;for(let n=0;n<v.length;n++){const r=v[n],s=r.read_number,o=r.categories,i=r.categories[0],a=[];if(o.length>1){for(let t=1;t<o.length;t++)a.push(o[t]);o.length-1>M&&(M=o.length-1)}if(i.includes("alt"))for(let n=0;n<t.variant.length;n++)i=="alt"+n.toString()&&A[ut+n.toString()]&&(e[s].tempscore=["alt"+n.toString()],A[ut+n.toString()].templates.push(e[s]));else"ref"==i?A[ct]&&(e[s].tempscore=["ref"],A[ct].templates.push(e[s])):"none"==i?A[ft]&&(e[s].tempscore=a,A[ft].templates.push(e[s])):"amb"==i?A[dt]&&(e[s].tempscore=a,A[dt].templates.push(e[s])):console.log("Unaccounted group, please check")}const T=[];for(const e in A){const r=A[e];if(0!=r.templates.length){if(e.includes(ut))for(let n=0;n<t.variant.length;n++)e==ut+n.toString()&&(1==t.variant.length?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting the alternative allele"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting the alternative allele"}):1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read support the alternative allele with "+l[n]+" sequence"}):r.messages.push({isheader:!0,t:r.templates.length+" reads support the alternative allele with "+l[n]+" sequence"}));else e==dt?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" ambiguous read"}):r.messages.push({isheader:!0,t:r.templates.length+" ambiguous reads"}):e==ct?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting the reference allele"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting the reference allele"}):e==ft?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting neither reference nor alternative alleles"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting neither reference nor alternative alleles"}):console.log("Unaccounted group, please check");r.widths=n,T.push(r)}}const C=[];for(let t=0;t<T.length;t++)T[t].type.includes("support_alt")&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_ref"==T[t].type&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_no"==T[t].type&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_amb"==T[t].type&&C.push(T[t]);return{groups:C,refalleleerror:s,ref_positions:c,refalleles:a,altalleles:l,max_diff_score:M,min_diff_score:0,strand_probability:N,strand_significance:S,refseqs:u,altseqs:f,leftflankseqs:o,rightflankseqs:i,alternate_forward_count:_,alternate_reverse_count:x,reference_forward_count:k,reference_reverse_count:q}}(t,e,n);console.log("Indel pipeline works only in single region. Please check!")}if(t.sv&&t.regions.length>1)return async function(t,e,n){const r=pt(e),s=[];for(let t=0;t<e.regions.length;t++){const n=e.regions[t],r=(await F.Kf(e.genome,n.chr+":"+n.start+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase(),o=[];for(const e of n.lines)o.push({sam_info:e,tempscore:"",ridx:t});const i={refseq:r,start:n.start,stop:n.stop,entries:o};0==t?(i.chr=e.sv.chrA,i.pos=e.sv.startA):1==t?(i.chr=e.sv.chrB,i.pos=e.sv.startB):console.log("More than two regions, please check"),s.push(i)}const o=new Date,i=(await(0,Q.run_rust)("sv",JSON.stringify(s))).split("\n"),a=new Date;let l,c;console.log("Time taken to run rust SV pipeline:",a-o,"ms");for(let t of i)t.includes("multi_region_templates:")?l=JSON.parse(t.replace("multi_region_templates:","")):t.includes("single_region_templates:")&&(c=JSON.parse(t.replace("single_region_templates:","")));if(!e.grouptype||"support_sv"==e.grouptype)for(const t of l)r[ht].templates.push(t);if(!e.grouptype||"support_ref"==e.grouptype)for(const t of c)r[ct].templates.push(t);const u=[];for(const t in r){const e=r[t];0!=e.templates.length&&(t==ht?1==e.templates.length?e.messages.push({isheader:!0,t:e.templates.length+" read supporting SV/fusion"}):e.messages.push({isheader:!0,t:e.templates.length+" reads supporting SV/fusion"}):t==ct&&e.messages.push({isheader:!0,t:e.templates.length+" reads supporting reference allele"}),e.widths=n,u.push(e))}return{groups:u}}(0,t,n);return{groups:[{type:lt,regions:mt(t.regions),templates:e,messages:[],partstack:t.partstack,widths:n}]}}(t);t.groups=n.groups,t.variant&&(e.ref_alleles=n.refalleles,e.alt_alleles=n.altalleles,e.allele_positions=n.ref_positions,e.strand_probability=n.strand_probability,e.alternate_forward_count=n.alternate_forward_count,e.reference_forward_count=n.reference_forward_count,e.alternate_reverse_count=n.alternate_reverse_count,e.reference_reverse_count=n.reference_reverse_count,1==n.strand_significance&&(e.strand_significance=!0),t.alleleAlreadyUpdated||(e.refseqs=n.refseqs,e.altseqs=n.altseqs,e.leftflankseqs=n.leftflankseqs,e.rightflankseqs=n.rightflankseqs,e.ref_positions=n.ref_positions,e.refalleles=n.refalleles,e.altalleles=n.altalleles)),Number.isFinite(t.max_diff_score)&&t.variant?(e.max_diff_score=t.max_diff_score,e.min_diff_score=t.min_diff_score):Number.isFinite(n.max_diff_score)&&(e.max_diff_score=n.max_diff_score,e.min_diff_score=n.min_diff_score),n.refalleleerror&&(e.refalleleerror=n.refalleleerror)}if(0==e.count.r)throw"No reads in view range.";if(t.alignOneGroup){const e=t.groups.find((e=>e.type==t.alignOneGroup));if(!e)throw"cannot find group for realignment";let n=Ze(t,e);return n=Ge(e,t,n),await async function(t,e,n){let r;if(e.variant)if("support_ref"==t.type){let s=e.leftflankseqs[0].length;r=t.partstack?await Pe(n,s,t.partstack.start,t.partstack.stop,e.refseqs[0]):await Pe(n,s,0,0,e.refseqs[0])}else if("support_no"==t.type){let s=e.leftflankseqs[0].length;r=t.partstack?await Pe(n,s,t.partstack.start,t.partstack.stop):await Pe(n,s)}else{if("support_amb"==t.type)throw"Realignment of reads in ambiguous group is not currently implemented.";if(t.type.includes("support_alt")){for(let s=0;s<e.variant.length;s++)if(t.type=="support_alt"+s.toString()){let o=e.leftflankseqs[s].length;r=t.partstack?await Pe(n,o,t.partstack.start,t.partstack.stop,e.altseqs[s]):await Pe(n,o,0,0,e.altseqs[s])}}else console.log("Unaccounted group, please check")}return{alignmentData:r}}(e,t,n)}let n=[];for(const r of t.groups){let s=Ze(t,r);s=Ge(r,t,s),await Be(r,t,s),await ze(s,t),He(r,s,t);const o={type:r.type,width:t.canvaswidth,height:r.canvasheight,stackheight:r.stackheight,stackcount:r.stacks.length,allowpartstack:r.allowpartstack,templatebox:r.returntemplatebox,count:{r:s.reduce(((t,e)=>t+e.segments.length),0)}},i=(0,S.createCanvas)(t.canvaswidth*t.devicePixelRatio,r.canvasheight*t.devicePixelRatio),a=i.getContext("2d");t.devicePixelRatio>1&&a.scale(t.devicePixelRatio,t.devicePixelRatio),a.textAlign="center",a.textBaseline="middle",o.messages=r.messages,o.messagerowheights=0;for(const e of s)Ke(a,e,r,t);Qe(a,r,t,s),t.asPaired&&(o.count.t=s.length),t.variant&&(o.diff_scores_img=await Ie(t,r,s,e.max_diff_score,e.min_diff_score),"support_alt0"==o.type?o.group_color=ie:"support_alt1"==o.type?o.group_color=ae:"support_alt2"==o.type?o.group_color=le:"support_alt3"==o.type?o.group_color=ce:"support_alt4"==o.type?o.group_color=ue:"support_alt5"==o.type?o.group_color=fe:"support_ref"==o.type&&(o.group_color=de)),o.src=i.toDataURL(),e.groups.push(o),n=[...n,...s]}t.readcount_skipped&&(e.count.skipped=t.readcount_skipped);t.getcolorscale&&(e.colorscale=function(t){const e=160,n=20,r=1,s=12,o=5,i=100,a=4,l=i+e+10,c=2*s+o+a+4*(n+r),u=(0,S.createCanvas)(t.devicePixelRatio*l,t.devicePixelRatio*c),f=u.getContext("2d");t.devicePixelRatio>1&&f.scale(t.devicePixelRatio,t.devicePixelRatio);f.fillStyle="black",f.font=s+"pt Arial",f.textAlign="center",f.fillText("Base quality",i+e/2,s);let d=2*s+o;function h(t,r,s){const o=i,a=f.createLinearGradient(o,s,o+e,s);a.addColorStop(0,r),a.addColorStop(1,t),f.fillStyle=a,f.fillRect(o,s,e,n)}return f.strokeStyle="black",f.beginPath(),f.moveTo(i,d),f.lineTo(i,d+a),f.moveTo(i+e/4,d),f.lineTo(i+e/4,d+a),f.moveTo(i+e/2,d),f.lineTo(i+e/2,d+a),f.moveTo(i+3*e/4,d),f.lineTo(i+3*e/4,d+a),f.moveTo(i+e,d),f.lineTo(i+e,d+a),f.closePath(),f.stroke(),f.fillText(40,i,d),f.fillText(30,i+e/4,d),f.fillText(20,i+e/2,d),f.fillText(10,i+3*e/4,d),f.fillText(0,i+e,d),f.textAlign="left",f.textBaseline="middle",d+=a,f.fillText("Match",0,d+n/2),h(Rt,It,d),d+=n+r,f.fillStyle="black",f.fillText("Mismatch",0,d+n/2),h(Zt,zt,d),d+=n+r,f.fillStyle="black",f.fillText("Softclip",0,d+n/2),h(Gt,Bt,d),d+=n+r,f.fillStyle="black",f.fillText("Insertion",0,d+n/2),h(Xt,Kt,d),{width:l,height:c,src:u.toDataURL()}}(t));if(!t.partstack)if(0==e.count.r);else{if(!t.pileupheight)throw"pileupheight missing";e.pileup_data=await async function(t,e){const n=(0,S.createCanvas)(t.canvaswidth*t.devicePixelRatio,t.pileupheight*t.devicePixelRatio),r=n.getContext("2d");t.devicePixelRatio>1&&r.scale(t.devicePixelRatio,t.devicePixelRatio);const s=[];let o=0;for(const[n,r]of t.regions.entries()){s[n]=await $e(t,r),Re(n,r,e,s[n]);for(const t of s[n])t&&(o=Math.max(o,t.total))}for(const[e,n]of t.regions.entries()){const i=t.pileupheight/o;for(const o of s[e]){if(!o)continue;const e=(o.position-n.start)*n.ntwidth+n.x,s=n.ntwidth>=1?e:Math.floor(e),a=Math.max(1,n.ntwidth);{r.fillStyle=oe;const e=o.total*i;r.fillRect(s,t.pileupheight-e,a,e)}let l=0;if(o.A){r.fillStyle=P.basecolor.A;const e=o.A*i;r.fillRect(s,t.pileupheight-l-e,a,e),l+=e}if(o.C){r.fillStyle=P.basecolor.C;const e=o.C*i;r.fillRect(s,t.pileupheight-l-e,a,e),l+=e}if(o.G){r.fillStyle=P.basecolor.G;const e=o.G*i;r.fillRect(s,t.pileupheight-l-e,a,e),l+=e}if(o.T){r.fillStyle=P.basecolor.T;const e=o.T*i;r.fillRect(s,t.pileupheight-l-e,a,e),l+=e}if(o.softclip){r.fillStyle=Bt;const e=o.softclip*i;r.fillRect(s,t.pileupheight-l-e,a,e)}}}return{width:t.canvaswidth,maxValue:o,src:n.toDataURL()}}(t,n)}return e}(i)),s().debugmode&&console.log("bam.js time ms",new Date-o)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(bs)),ks.get(qs+"/gdcbam",function(t){return async function(e,n){try{const r=t.hg38;if(!r)throw"hg38 missing";const s=r.datasets.GDC;if(!s)throw"hg38 GDC missing";if(St||(St=function(t){if(St)throw"The gdc queryApi has already been set.";return async function(e,n,r,s,o){const{host:i,headers:a}=t.getHostHeaders(o),l=y().join(i.rest,n.end_point),c={filters:e,case_filters:s,size:r||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(t){throw"invalid JSON from "+n.end_point}if(!Array.isArray(f.data?.hits))throw"data structure not re.data.hits[]";return f}}(s)),e.query.gdc_id){const t=await async function(t){const{gdc_id:e,filter0:n}=t,r={file_metadata:[],isCaseSample:"",numFilesSkippedByWorkflow:0},s=await At(e,r,n,t);if(!s.data.hits.length){if(r.isCaseSample)throw`No bam files available for this ${r.isCaseSample}.`;if(n){if((await At(e,r,null,t)).data.hits.length)throw"Case not in current cohort.";throw"Invalid input ID."}throw"Invalid input ID."}for(const t of s.data.hits){if(t.analysis.workflow_type==kt){r.numFilesSkippedByWorkflow++;continue}const e={};e.file_uuid=t.id,e.file_size=vt(t.file_size),e.experimental_strategy=t.experimental_strategy,e.entity_id=t.associated_entities[0].entity_submitter_id,e.case_id=t.associated_entities[0].case_id,e.sample_type=t.cases[0].samples[0].sample_type,r.file_metadata.push(e)}return r}(e.query);await async function(t,e,n){if(!t.file_metadata?.length)return;const r=e.cookies.sessionid;if(!r)return;try{await jt(t.file_metadata[0].file_uuid,n,e.query)}catch(e){"Permission denied"==e&&(t.userHasNoAccess=!0)}}(t,e,s),n.send(t)}else{const t=await async function(t,e){const n=await async function(t,e){const n=await St(null,_t,qt,t,e);return n.data.hits.map((t=>t.id))}(t,e);if(0==n.length)throw"No cases available";const r=await Tt(n,"cases.case_id",Nt,e),s={};if(!Array.isArray(r.data?.hits))throw"re.data.hits[] not array";for(const t of r.data.hits){if(t.analysis.workflow_type==kt)continue;const e=t.cases?.[0]?.submitter_id;e&&(s[e]||(s[e]=[]),s[e].push({file_uuid:t.id,sample_type:t.cases?.[0].samples?.[0].sample_type,experimental_strategy:t.experimental_strategy,file_size:vt(Number.parseFloat(t.file_size))}))}return{case2files:s,total:r.data?.pagination?.total,loaded:Nt}}(e.query.filter0,e.query);n.send(t)}}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(bs)),ks.get(qs+"/tkaicheck",(async(t,e)=>{try{e.send(await async function(t){const[e,n,r]=F.ZX(t);if(e)throw e;const s=Number(t.query.coveragemax)||100;if(!Number.isInteger(s))throw"invalid coveragemax";const o=Number(t.query.vafheight);if(!Number.isInteger(o))throw"invalid vafheight";const i=Number(t.query.coverageheight);if(!Number.isInteger(i))throw"invalid coverageheight";const a=Number(t.query.rowspace);if(!Number.isInteger(a))throw"invalid rowspace";const l=Number(t.query.dotsize)||1;if(!Number.isInteger(l))throw"invalid dotsize";if(!t.query.rglst)throw".rglst missing";"string"==typeof t.query.rglst&&(t.query.rglst=JSON.parse(t.query.rglst));const c=t.query.gtotalcutoff,u=t.query.gmafrestrict,f=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,(3*o+4*a+2*i)*t.query.devicePixelRatio),d=f.getContext("2d");let h;t.query.devicePixelRatio>1&&d.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),d.fillStyle="#f1f1f1",d.fillRect(0,0,t.query.width,o/2),d.fillRect(0,2*a+o+i,t.query.width,o/2),d.fillStyle="#FAFAD9",d.fillRect(0,o/2,t.query.width,o/2),d.fillRect(0,2*a+1.5*o+i,t.query.width,o/2),r&&(h=await F.d1(n,t.query.indexURL));let p=0;for(const e of t.query.rglst)e.x=p,p+=t.query.regionspace+e.width;const m="#786312",g="#122778",y="#858585",b="red";for(const e of t.query.rglst){const t=e.width/(e.stop-e.start);await F.UE({args:[n,e.chr+":"+e.start+"-"+e.stop],dir:h,callback:n=>{const r=n.split("\t"),f=Number.parseInt(r[1]),h=Number.parseInt(r[2]),p=Number.parseInt(r[3]),v=Number.parseInt(r[4]),w=Number.parseInt(r[5]);if(Number.isNaN(h)||Number.isNaN(p)||Number.isNaN(v)||Number.isNaN(w))return;if(c&&w<c)return;const _=Math.ceil(e.x+t*(e.reverse?e.stop-f:f-e.start)-l/2);d.fillStyle=m;const x=h/p;d.fillRect(_,o*(1-x),l,2);const k=v/w;if(u&&(k<u||k>1-u))return;d.fillRect(_,o+a+i+a+o*(1-k),l,2),d.fillStyle=g;const q=Math.abs(x-k);d.fillRect(_,2*o+4*a+2*i+o*(1-q),l,2),d.fillStyle=y;let N=(p>=s?s:p)*i/s,S=i-N;d.fillRect(_,S+o+a,l,N),d.fillStyle=y,N=(w>=s?s:w)*i/s,S=i-N,d.fillRect(_,S+3*a+2*o+i,l,N),p>=s&&(d.fillStyle=b,d.fillRect(_,o+a,l,2)),w>=s&&(d.fillStyle=b,d.fillRect(_,3*a+2*o+i,l,2))}})}return{src:f.toDataURL(),coveragemax:s}}(t))}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.get(qs+"/blat",function(t){return async(e,n)=>{try{if(e.query.serverstat){const e=[];for(const n in t){const r=t[n];r.blat&&e.push(await In(n,r))}if(0==e.length)throw"found no genome with blat";return void n.send({lst:e})}if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";if(!r.blat)throw"blat not enabled";if(!e.query.seq)throw".seq missing";n.send(await async function(t,e,n,r){const o=y().join(s().cachedir,await(0,F.tG)(">query\n"+e+"\n")),i=await Rn(t,o),a=(await(0,F.b5)(i)).trim();if(m().unlink(i,(()=>{})),m().unlink(o,(()=>{})),""==a)return{nohit:1};const l=a.split("\n"),c=[];for(const t of l){const e={},n=t.split(" ").filter((function(t){return""!=t}))[0].split("\t");e.query_match=n[0],e.query_startpos=(parseInt(n[11])+1).toString(),e.query_stoppos=n[12],e.query_strand=n[8],e.query_totallen=n[10],e.query_alignlen=Math.abs(parseInt(n[11])-parseInt(n[12])).toString(),e.ref_chr=n[13],e.ref_startpos=(parseInt(n[15])+1).toString(),e.ref_stoppos=n[16],e.ref_alignlen=Math.abs(n[16]-n[15]).toString(),e.ref_totallen=n[14],c.push(e)}return c.sort(((t,e)=>e.query_match-t.query_match)),{hits:c}}(r,e.query.seq,e.query.soft_starts,e.query.soft_stops))}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(bs)),ks.all(qs+"/mds3",function(t){return async(e,n)=>{try{if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";const s=function(t,e){const n=t.query;t.get("X-Auth-Token")&&(n.token=t.get("X-Auth-Token"));(0,F.Y5)(n,t.cookies),n.hiddenmclasslst&&(n.hiddenmclass=new Set(n.hiddenmclasslst.split(",")),delete n.hiddenmclasslst);return n}(e),o=await async function(t,e){if(t.dslabel){if(!e.datasets)throw".datasets{} missing from genome";const n=e.datasets[t.dslabel];if(!n)throw"invalid dslabel";return n}const n={queries:{}};if(t.bcffile||t.bcfurl){const[r,s,o]=(0,F.ZX)({query:{file:t.bcffile,url:t.bcfurl}});if(r)throw r;const i={};o?(i.url=s,i.indexURL=t.bcfindexURL):i.file=s,n.queries.snvindel={byrange:{_tk:i}},n.queries.snvindel.byrange.get=await pr(n,e)}return n}(s,r);!function(t,e){if(t.filter0){const n="object"==typeof t.filter0?t.filter0:JSON.parse("string"==typeof t.filter0&&t.filter0.startsWith("%")?decodeURIComponent(t.filter0):t.filter0);t.filter0=e.validate_filter0(n)}t.filterObj&&"string"==typeof t.filterObj&&(t.filterObj=JSON.parse("string"==typeof t.filterObj&&t.filterObj.startsWith("%")?decodeURIComponent(t.filterObj):t.filterObj));if(t.skewerRim){if("format"!=t.skewerRim.type)throw"unknown skewerRim.type";if(!t.skewerRim.formatKey)throw"skewerRim.formatKey missing when type=format";if(!e.queries?.snvindel?.format)throw"snvindel.format{} not found when type=format";if(!e.queries.snvindel.format[t.skewerRim.formatKey])throw"invalid skewerRim.formatKey";if(t.skewerRim.hiddenvalues=new Set,t.skewerRim.hiddenvaluelst){if(!Array.isArray(t.skewerRim.hiddenvaluelst))throw"query.skewerRim.hiddenvaluelst is not array";for(const e of t.skewerRim.hiddenvaluelst)t.skewerRim.hiddenvalues.add(e);delete t.skewerRim.hiddenvaluelst}}if(t.formatFilter){if("object"!=typeof t.formatFilter)throw"formatFilter{} not object";if(!e.queries?.snvindel?.format)throw"snvindel.format{} not found when formatFilter is used";const n={};for(const r in t.formatFilter){if(!e.queries.snvindel.format[r])throw"invalid format key from formatFilter";if(!Array.isArray(t.formatFilter[r]))throw"formatFilter[k] value is not array";n[r]=new Set(t.formatFilter[r])}t.formatFilter=n}("format"==t.skewerRim?.type||t.formatFilter)&&(t.addFormatValues=!0)}(s,o);const i=await async function(t,e){if(t.singleSampleGenomeQuantification){if(!e.queries.singleSampleGenomeQuantification)throw"not supported on this dataset";const n=e.queries.singleSampleGenomeQuantification[t.singleSampleGenomeQuantification.dataType];if(!n)throw"invalid dataType";return await n.get(t.singleSampleGenomeQuantification.sample,t.devicePixelRatio)}if(t.singleSampleGbtk){if(!e.queries.singleSampleGbtk)throw"not supported on this dataset";const n=e.queries.singleSampleGbtk[t.singleSampleGbtk.dataType];if(!n)throw"invalid dataType";return await n.get(t.singleSampleGbtk.sample)}if(t.ssm2canonicalisoform){if(!e.ssm2canonicalisoform)throw"ssm2canonicalisoform not supported on this dataset";return{isoform:await e.ssm2canonicalisoform.get(t)}}if(t.variant2samples){if(!e.variant2samples)throw"not supported by server";return{variant2samples:await e.variant2samples.get(t)}}if(t.m2csq){if(e.queries&&e.queries.snvindel&&e.queries.snvindel.m2csq)return{csq:await e.queries.snvindel.m2csq.get(t)};throw"m2csq not supported on this dataset"}if(t.forTrack){const n={};if(t.skewer){if(n.skewer=[],e.queries.snvindel){const r=await async function(t,e){if(t.isoform){if(t.atgenomic){if(!e.queries.snvindel.byrange)throw".atgenomic but missing byrange query method";return await e.queries.snvindel.byrange.get(t)}if(e.queries.snvindel.byisoform)return await e.queries.snvindel.byisoform.get(t)}if(t.rglst){if(!e.queries.snvindel.byrange)throw"q.rglst[] provided but .byrange{} is missing";return await e.queries.snvindel.byrange.get(t)}throw"insufficient query parameters for snvindel"}(t,e);n.skewer.push(...r)}if(e.queries.svfusion){const r=await async function(t,e){if(t.rglst){if(!e.queries.svfusion.byrange)throw"q.rglst provided but svfusion.byrange missing";return await e.queries.svfusion.byrange.get(t)}throw"insufficient query parameters for svfusion"}(t,e);n.skewer.push(...r)}if(e.queries.geneCnv){const r=await async function(t,e){if(t.gene){if(!e.queries.geneCnv.bygene)throw"q.gene provided but geneCnv.bygene missing";return await e.queries.geneCnv.bygene.get(t)}}(t,e);n.geneCnv=r}e.queries.cnv&&(n.cnv=await async function(t,e){if(t.rglst){if(!e.queries.cnv.byrange)throw"q.rglst provided but cnv.byrange missing";return await e.queries.cnv.byrange.get(t)}throw"insufficient query parameters for cnv"}(t,e)),function(t,e){if(e.skewer){const n=[];for(const r of e.skewer)t.rglst&&!t.rglst.find((t=>r.chr==t.chr&&r.pos>=t.start&&r.pos<=t.stop))||n.push(r);e.skewer=n}e.genecnvAtsample}(t,n),n.mclass2variantcount=function(t){const e=new Map;for(const n of t){const t=n.class||n.dt;e.set(t,1+(e.get(t)||0))}return[...e].sort(((t,e)=>e[1]-t[1]))}(n.skewer)}return function(t,e,n){const r=new Set;if(n.skewer)for(const s of n.skewer)if(s.samples){s.occurrence=s.samples.length,Nr(s,t,e),Sr(s,e);for(const t of s.samples)r.add(t.sample_id);delete s.samples}if(n.cnv)for(const t of n.cnv)if(t.samples)for(const n of t.samples)if(r.add(n.sample_id),e.cohort?.termdb?.q?.id2sampleName){const t=e.cohort.termdb.q.id2sampleName(n.sample_id);t&&(n.sample_id=t)}r.size&&(n.sampleTotalNumber=r.size)}(t,e,n),n}throw"do not know what client wants"}(s,o);n.send(i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(bs)),ks.get(qs+"/tkbampile",(async function(t,e){try{const[n,r,s]=F.ZX(t);if(n)throw n;let o=t.query.usegrade;const i=Number(t.query.allheight),a=Number(t.query.fineheight),l=Number(t.query.fineymax),c=Number(t.query.midpad),u=Number(t.query.regionspace),f=Number(t.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 t.query.rglst?JSON.parse(t.query.rglst):t.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 t of d)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));let h;s&&(h=await F.d1(r,t.query.indexURL));for(const t of d){t.items=[];let e=0;await F.UE({args:[r,t.chr+":"+t.start+"-"+t.stop],dir:h,callback:n=>{const r=n.split("\t");let s;try{s=JSON.parse(r[2])}catch(t){return void e++}const o=Number.parseInt(r[1]);t.items.push({pos:o,data:s})}})}const p=i+c+a,m=(0,S.createCanvas)(f,p),g=d.reduce(((t,e)=>t+e.items.length),0),y=m.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,p/2),void e.send({src:m.toDataURL()});let b=null;if(!o){const t=new Set;for(const e of d)for(const n of e.items)for(const e in n.data)t.add(e);if(b=[...t],b.length>0&&(o=b[0]),!o)return void e.send({src:m.toDataURL()})}let v=0;for(const t of d)for(const e of t.items)if(e.data[o]){let t=0;for(const n in e.data[o])t+=e.data[o][n];v=Math.max(v,t)}const w="#ededed";let _=0;const x=i/v,k=a/l;for(const t of d){const e=t.width/(t.stop-t.start);for(const n of t.items){const r=n.data[o];if(!r)continue;const s=t.scale(n.pos);let a=0;const u=[];for(const t in r)u.push({nt:t,v:r[t]}),a+=r[t];y.fillStyle=w;const f=x*(v-a);if(y.fillRect(_+s,f,e,x*a),u.length>1){u.sort(((t,e)=>e.v-t.v));for(let t=1;t<u.length;t++){let n=0;for(let e=0;e<t;e++)n+=u[e].v;y.fillStyle=P.basecolor[u[t].nt],y.fillRect(_+s,f+x*n,e,x*u[t].v)}}y.fillStyle=w;const d=i+c+k*(l-Math.min(a,l));if(y.fillRect(_+s,d,e,k*Math.min(a,l)),u.length>1)for(let t=1;t<u.length;t++){let n=0;for(let e=0;e<t;e++)n+=u[e].v;y.fillStyle=P.basecolor[u[t].nt],y.fillRect(_+s,d+k*(l-Math.min(l,a-n)),e,k*Math.min(l,u[t].v))}}_+=t.width+u}e.send({src:m.toDataURL(),allgrades:b,usegrade:o,allmax:v})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/dsdata",(async function(t,e){try{if(!bs[t.query.genome])throw"invalid genome";if(!t.query.dsname)throw".dsname missing";const n=bs[t.query.genome].datasets[t.query.dsname];if(!n)throw"invalid dsname";const r=[];for(const e of n.queries)if((!t.query.expressiononly||e.isgeneexpression)&&!(t.query.noexpression&&e.isgeneexpression||e.dsblocktracklst))if(e.vcffile){const n=await Is(e,t);r.push(n)}else{if(!e.makequery)throw"unknow type from one of ds.queries[]";{const s=Os(n,e,t);r.push(s)}}e.send({data:r})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/tkbigwig",(async function(t,e){try{let n,r,o,i,a=!1,l=!1;const[c,u,f]=F.ZX(t);if(c)throw c;if(u.endsWith(".gz")&&(l=!0,f&&(i=await F.d1(u,t.query.indexURL))),t.query.autoscale)a=!0;else if(t.query.percentile){if(o=t.query.percentile,!Number.isFinite(o))throw"invalid percentile"}else{if(n=t.query.minv,r=t.query.maxv,!Number.isFinite(n))throw"invalid minv";if(!Number.isFinite(r))throw"invalid maxv"}if(!Number.isFinite(t.query.barheight))throw"invalid barheight";if(!Number.isFinite(t.query.regionspace))throw"invalid regionspace";if(!Number.isFinite(t.query.width))throw"invalid width";if(!t.query.rglst)throw"region list missing";if(t.query.dotplotfactor&&!Number.isInteger(t.query.dotplotfactor))throw"dotplotfactor value should be positive integer";if(l)return await async function(t,e,n,r,s,o){if(null==n||null==r)throw"Y axis scale must be defined for bedgraph track";const i=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,t.query.barheight*t.query.devicePixelRatio),a=i.getContext("2d");t.query.devicePixelRatio>1&&a.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);let l=0;for(let e of t.query.rglst)await et(t,e,l,n,r,s,o,a),l+=e.width+t.query.regionspace;e.send({src:i.toDataURL()})}(t,e,n,r,u,i);for(const e of t.query.rglst){let n;if(s().features.bigwig_rust){const r=u+","+e.chr+","+e.start+","+e.stop+","+Math.ceil(e.width*(t.query.dotplotfactor||1));n=await(0,Q.run_rust)("bigwig",r)}else n=await rt(t,e,u);n&&(e.values=n.trim().split("\t").map(Number.parseFloat),t.query.dividefactor&&(e.values=e.values.map((e=>e/t.query.dividefactor))))}let d=!0;for(const e of t.query.rglst)e.values&&(d=!1);const h=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,t.query.barheight*t.query.devicePixelRatio),p=h.getContext("2d");if(t.query.devicePixelRatio>1&&p.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),d)return p.font="14px Arial",p.fillStyle="#858585",p.textAlign="center",p.textBaseline="middle",p.fillText(t.query.name+": no data in view range",t.query.width/2,t.query.barheight/2),void e.send({src:h.toDataURL(),nodata:!0});const m=1,g=t.query.dotplotfactor?1/t.query.dotplotfactor:1;let y=0,b=0;const v={};if(a||o){const e=[],n=[];for(const r of t.query.rglst)if(r.values)for(const t of r.values)Number.isNaN(t)||(t>=0&&e.push(t),t<=0&&n.push(t));e.length&&(e.sort(((t,e)=>t-e)),y=a?e[e.length-1]:e[Math.floor(e.length*o/100)]),n.length&&(n.sort(((t,e)=>e-t)),b=a?n[n.length-1]:n[Math.floor(n.length*o/100)]),v.minv=b,v.maxv=y}else b=n,y=r;if(t.query.barheight<10){let e=(0,tt.B8)(t.query.pcolor);const n=e.r+","+e.g+","+e.b;e=(0,tt.B8)(t.query.ncolor);const r=e.r+","+e.g+","+e.b;let s=0;for(const e of t.query.rglst){if(e.values)for(let o=0;o<e.values.length;o++){const i=e.values[o];if(Number.isNaN(i))continue;p.fillStyle=i>=y?t.query.pcolor2:i>=0?"rgba("+n+","+i/y+")":i<=b?t.query.ncolor2:"rgba("+r+","+i/b+")";const a=Math.ceil(s+(e.reverse?e.width-g*o:g*o));p.fillRect(a,0,m,t.query.barheight)}s+=e.width+t.query.regionspace}}else{const e=nt().height(t.query.barheight).min(b).max(y);let n=0;for(const r of t.query.rglst){if(r.values)for(let s=0;s<r.values.length;s++){const o=r.values[s];if(Number.isNaN(o))continue;p.fillStyle=o>0?t.query.pcolor:t.query.ncolor;const i=Math.ceil(n+(r.reverse?r.width-g*s:g*s)),a=e(o);if(o>0)p.fillRect(i,a.y,m,t.query.dotplotfactor?Math.min(2,a.h):a.h);else if(t.query.dotplotfactor){const t=Math.min(2,a.h);p.fillRect(i,a.y+a.h-t,m,t)}else p.fillRect(i,a.y,m,a.h);o>y?(p.fillStyle=t.query.pcolor2,p.fillRect(i,0,m,2)):o<b&&(p.fillStyle=t.query.ncolor2,p.fillRect(i,t.query.barheight-2,m,2))}n+=r.width+t.query.regionspace}}v.src=h.toDataURL(),e.send(v)}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/tkld",function(t){return async(e,n)=>{try{const r=t[e.query.genome];if(!r)throw"unknown genome";n.send(await async function(t,e){const[n,r,s]=F.ZX(t);if(n)throw n;let o;s&&(o=await F.d1(r,t.query.indexURL));if(!t.query.rglst)throw"rglst missing";const i=await F.Jy(r,o,e),a=t.query.connheight||50,l={rglst:[]};for(const e of t.query.rglst){const n={chr:e.chr,start:e.start,stop:e.stop,width:e.width,reverse:e.reverse,xoff:e.xoff};l.rglst.push(n);const s=[],c=new Set,u=(i?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;await F.UE({args:[r,u],dir:o,callback:t=>{const n=t.split("\t"),r=Number.parseInt(n[1]);if(r<e.start)return;const o=Number.parseInt(n[2]);if(o>e.stop)return;const i=Number.parseFloat(n[5]);s.push({start:r,stop:o,r2:i}),c.add(r),c.add(o)}}),n.img=st(e,s,c,a,t.query.devicePixelRatio||1)}return l}(e,r))}catch(t){n.send({error:t.message||t})}}}(bs)),ks.get(qs+"/tabixheader",(async function(t,e){try{const[n,r,s]=F.ZX(t);if(n)throw n;const o=s?await F.d1(r,t.query.indexURL):null,i=await F.ZD(r,o);e.send({lines:i})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.all(qs+"/snp",(async function(t,e){try{const n=t.query.genome;if(!n)throw"no genome";e.send({results:await js(t.query,bs[n])})}catch(t){return t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/isoformlst",(function(t,e){try{const n=bs[t.query.genome];if(!n)throw"invalid genome";if(!Array.isArray(t.query.lst))throw".lst missing";const r=[];for(const e of t.query.lst){if(n.genomicNameRegexp.test(e))continue;const t=n.genedb.getjsonbyisoform.all(e);r.push(t.map((t=>{const e=JSON.parse(t.genemodel);return t.isdefault&&(e.isdefault=!0),e})))}e.send({lst:r})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.post(qs+"/dbdata",(function(t,e){})),ks.get(qs+"/img",(async function(t,e){const[n,r,s]=F.ZX(t);try{if(n)throw"invalid image file";const t=await m().promises.readFile(r);e.send({src:"data:image/jpeg;base64,"+new Buffer.from(t).toString("base64"),size:j()(r)})}catch(n){e.send({error:n.message||n})}})),ks.post(qs+"/svmr",(function(t,e){if(t.query.file){const[n,r,s]=F.ZX(t);if(n)return void e.send({error:"illegal file name"});m().readFile(r,"utf8",((t,n)=>{t?e.send({error:"cannot read file"}):e.send({raw:n})}))}else e.send({error:"missing file"})})),ks.post(qs+"/study",(async function(t,e){try{if(F.lY(t.query.file))throw"invalid file path";const n=y().join(s().tpmasterdir,t.query.file.endsWith(".json")?t.query.file:t.query.file+".json"),r=JSON.parse(await F.b5(n));if(!r.genome)throw"genome missing";const o={};let i=0;for(const t of r.mutationset||[]){const e=L.Dz(r.genome);if(!e)throw"init_bulk_flag() failed";if(r.mutationset.length>1&&(e.tpsetname=t.name?t.name:"set"+ ++i),o[Math.random()]=e,t.snvindel){const n=(await F.b5(y().join(s().tpmasterdir,t.snvindel))).trim().split(/\r?\n/),r=$.parseheader(n[0],e);if(r)throw"snvindel header line error: "+r;for(let t=1;t<n.length;t++)$.parseline(t,n[t],e)}if(t.sv){const n=(await F.b5(y().join(s().tpmasterdir,t.sv))).trim().split(/\r?\n/),r=B.parseheader(n[0],e,!0);if(r)throw"sv header line error: "+r;for(let t=1;t<n.length;t++)B.parseline(t,n[t],e,!0)}if(t.fusion){const n=(await F.b5(y().join(s().tpmasterdir,t.fusion))).trim().split(/\r?\n/),r=B.parseheader(n[0],e,!1);if(r)throw"fusion header line error: "+r;for(let t=1;t<n.length;t++)B.parseline(t,n[t],e,!1)}if(t.svjson){const n=(await F.b5(y().join(s().tpmasterdir,t.svjson))).trim().split(/\r?\n/),[r,o]=G.parseheader(n[0],e);if(r)throw"svjson header line error: "+r;for(let t=1;t<n.length;t++)G.parseline(t,n[t],e,o)}if(t.cnv){const n=(await F.b5(y().join(s().tpmasterdir,t.cnv))).trim().split(/\r?\n/),r=z.parseheader(n[0],e);if(r)throw"cnv header line error: "+r;for(let t=1;t<n.length;t++)z.parseline(t,n[t],e)}if(t.itd){const n=(await F.b5(y().join(s().tpmasterdir,t.itd))).trim().split(/\r?\n/),r=U.parseheader(n[0],e);if(r)throw"itd header line error: "+r;for(let t=1;t<n.length;t++)U.parseline(t,n[t],e)}if(t.deletion){const n=(await F.b5(y().join(s().tpmasterdir,t.deletion))).trim().split(/\r?\n/),r=Z.parseheader(n[0],e);if(r)throw"deletion header line error: "+r;for(let t=1;t<n.length;t++)Z.parseline(t,n[t],e)}if(t.truncation){const n=(await F.b5(y().join(s().tpmasterdir,t.truncation))).trim().split(/\r?\n/),r=J.parseheader(n[0],e);if(r)throw"Truncation header line error: "+r;for(let t=1;t<n.length;t++)J.parseline(t,n[t],e)}}if(r.annotations){const t=r.annotations.idkey?r.annotations.idkey:"sample";r.annotations.data={};for(const e of r.annotations.files){const n=await F.b5(y().join(s().tpmasterdir,e));H.tJ(n).forEach((e=>{const n=e[t].trim();r.annotations.data[n]||(r.annotations.data[n]=[]),r.annotations.data[n].push(e)}))}}for(const t in o)W(o[t]);delete r.mutationset,e.send({cohort:r,flagset:o})}catch(t){return void e.send({error:t.message||t})}})),ks.post(qs+"/textfile",(function(t,e){if(!t.query.file)return e.send({error:"no file"});if(F.lY(t.query.file))return e.send({error:"invalid file name"});const n=y().join(s().tpmasterdir,t.query.file);if(null!=t.query.from){if(!Number.isInteger(t.query.from))return void e.send({error:"invalid value for from"});if(!Number.isInteger(t.query.to))return void e.send({error:"invalid value for to"});const r=[];_()(m().createReadStream(n)).on("end",(()=>{e.send({text:r.join("\n")})})).lines.map(String).skip(t.query.from-1).take(t.query.to).forEach((t=>{r.push(t)}))}else m().readFile(n,{encoding:"utf8"},((t,n)=>{t?e.send({error:"error reading file"}):e.send({text:n})}))})),ks.post(qs+"/urltextfile",(async function(t,e){const n=t.query.url.replace(s().URL,`http://127.0.0.1:${s().port}`);try{const t=await v()(n);switch(t.statusCode){case 200:return void e.send({text:F.cl(t.body)});case 404:return void e.send({error:"File not found: "+n});default:e.send({error:"unknown status code: "+t.status})}}catch(t){return e.send({error:"Error downloading file: "+n})}})),ks.get(qs+"/junction",(async function(t,e){try{const[n,r,o]=F.ZX(t);if(n)throw n;if(!t.query.rglst)throw"rglst[] missing";if("string"==typeof t.query.rglst&&(t.query.rglst=JSON.parse(t.query.rglst)),!Array.isArray(t.query.rglst))throw"rglst[] not an array";if(t.query.rglst.reduce(((t,e)=>e.stop-e.start+t),0)>1e6)throw"Zoom in below 1 Mb to show junctions";let i;if(t.query.isrnapeg){if(!s().features.junctionrnapeg)throw"rnapeg not supported on this server";if(o)throw"rnapeg file from url is not supported";i=await async function(t,e){try{await m().promises.stat(e)}catch(t){if("EACCES"==t.code)throw"permission denied for rnapeg file";if("ENOENT"==t.code)throw"rnapeg file not found";throw"cannot access rnapeg file ("+t.code+")"}const n=[];for(const r of t.rglst){const t=await vn({file:e,chr:r.chr,start:r.start,stop:r.stop});for(const e of t)n.push(e)}return n}(t.query,r)}else{const e=o?await F.d1(r,t.query.indexURL):null;i=await async function(t,e,n){const r=[];for(const s of t.rglst)await F.UE({args:[e,s.chr+":"+s.start+"-"+s.stop],dir:n,callback:t=>{const e=t.split("\t"),n=Number.parseInt(e[1]),o=Number.parseInt(e[2]);if(n>=s.start&&n<=s.stop||o>=s.start&&o<=s.stop){const t={chr:s.chr,start:n,stop:o,type:e[4],rawdata:[]};for(let n=5;n<e.length;n++)t.rawdata.push(Number.parseInt(e[n]));r.push(t)}}});return r}(t.query,r,e)}e.send({lst:i})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/mdsjunction",function(t){return async(e,n)=>{try{const[r,o,i]=await async function(t,e){const n=t.query;if(!n.genome)throw"genome missing";const r=e[n.genome];if(!r)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(s().tpmasterdir,n.file);else{if(!n.file2)throw"no file or url given";i.file2=y().join(s().tpmasterdir,n.file2)}else{if(!r.datasets)throw"genome is not equipped with datasets";if(!n.dslabel)throw"dslabel missing";if(o=r.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]}(e,t),a=await async function(t,e,n){if(t.junction)return await async function(t,e,n){const r=t.junction;if(!r.chr||!Number.isInteger(r.start)||!Number.isInteger(r.stop))throw"incomplete/invalid info about querying junction";let s;if(await F.UE({args:[mn(n),r.chr+":"+r.start+"-"+r.stop],dir:n.dir,callback:o=>{const i=o.split("\t"),a=Number.parseInt(i[1]),l=Number.parseInt(i[2]);if(a==r.start&&l==r.stop)if(n.file2){s=[];for(let t=5;t<i.length;t++){const e=i[t];if(!e)continue;const n=Number.parseInt(e);Number.isNaN(n)||(n<=0||s.push({i:t-5,readcount:n}))}}else{const r=JSON.parse(i[5]);s=gn(r,t,e,n)}}}),0==s.length)throw"no sample passing filters";const o={};if(n.listsamples){const t=s.map((t=>{const e={readcount:t.readcount};return t.anno?e.sample_name=t.anno.sample_name:e.i=t.i,e}));t.sort(((t,e)=>e.readcount-t.readcount)),t.length>100?(o.samples=t.slice(0,100),o.sampletotalnumber=t.length):o.samples=t}else if(n.singlejunctionsummary&&n.singlejunctionsummary.readcountboxplotpercohort){o.readcountboxplotpercohort=[];for(const t of n.singlejunctionsummary.readcountboxplotpercohort.groups){const e=new Map;for(const n of s){if(!n.anno)continue;const r=n.anno[t.key];null!=r&&(e.has(r)||e.set(r,[]),e.get(r).push(n))}if(0==e.size)continue;const n=[...e].sort(((t,e)=>e[1].length-t[1].length)),r=[];for(const[t,e]of n){let n=e[0].readcount,s=n;e.forEach((t=>{n=Math.min(n,t.readcount),s=Math.max(s,t.readcount)}));const o=yn(e,.05,.25,.5,.75,.95);r.push({label:t,samplecount:e.length,percentile:{p05:o[0],p25:o[1],p50:o[2],p75:o[3],p95:o[4]},minvalue:n,maxvalue:s})}o.readcountboxplotpercohort.push({label:t.label,boxplots:r})}}return o}(t,e,n);if(t.readcountByjBsamples)return await async function(t,e,n){if(!t.junctionAposlst)throw".junctionAposlst[] missing";let r,s=t.junctionB.start,o=t.junctionB.stop;t.junctionAposlst.forEach((t=>{s=Math.min(s,t[0]),o=Math.max(o,t[1])}));let i=[];if(await F.UE({args:[n.file||n.url,t.junctionB.chr+":"+s+"-"+o],dir:n.dir,callback:e=>{const n=e.split("\t"),s=Number.parseInt(n[1]),o=Number.parseInt(n[2]);if(s==t.junctionB.start&&o==t.junctionB.stop)r=JSON.parse(n[5]);else for(const[e,r]of t.junctionAposlst)if(e==s&&r==o){const t=JSON.parse(n[5]);t.start=s,t.stop=o,i.push(t);break}}}),!r)throw"jB not found";if(0==i.length)throw"none of jA is found";const a=gn(r,t,e,n);if(0==a.length)throw"no sample passing filters for junctionB";const l=new Set;a.forEach((t=>l.add(t.i)));const c=[];for(const e of i){const n=[];for(const r of e.samples)l.has(r.i)&&(t.readcountCutoff&&r.readcount<t.readcountCutoff||n.push(r));c.push({start:e.start,stop:e.stop,v:Math.floor(yn(n,.5))})}return{lst:c}}(t,e,n);const r={};if(t.iscustom&&t.getsamples){const t=await F.ZD(mn(n),n.dir);if(t[0]){const e=t[0].split("\t");e.length>5&&(r.sample2client=e.slice(5))}}if(!t.rglst)throw"rglst missing";if(n.viewrangeupperlimit){if(t.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=n.viewrangeupperlimit)throw"zoom in under "+common.bplen(n.viewrangeupperlimit)+" to view details"}let s=0,o=0;const i=[],a=new Set,l=new Set;for(const r of t.rglst)await F.UE({args:[mn(n),r.chr+":"+r.start+"-"+r.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 e=u[4];let n;if("known"==e)n="canonical";else{if("novel"!=e)throw"unknown rnapeg type: "+e;n=pn}if(t.infoFilter&&t.infoFilter.type&&t.infoFilter.type[n])return;const a={chr:r.chr,start:f,stop:d,info:{type:{lst:[{attrValue:n}]}}},l=[];for(let t=5;t<u.length;t++){const e=u[t];if(!e)continue;const n=Number.parseInt(e);Number.isNaN(n)||(n<=0||(l.push({readcount:n}),s=Math.max(s,n)))}if(0==l.length)return;if(o++,a.sampleCount=l.length,1==a.sampleCount)a.medianReadCount=l[0].readcount;else{const t=yn(l,.05,.25,.5,.75,.95);a.medianReadCount=t[2],a.readcountBoxplot={percentile:t}}i.push(a)}else{u[3],u[4];if(!(f>=r.start&&f<=r.stop||d>=r.start&&d<=r.stop))return;o++;const c={chr:r.chr,start:f,stop:d,info:{type:{lst:[]}}},h=JSON.parse(u[5]);if(h.sv){c.sv=h.sv;const t=c.chr+"."+c.start+"."+c.sv.mate.chr+"."+c.sv.mate.start;if(a.has(t))return;a.add(t),a.add(c.sv.mate.chr+"."+c.sv.mate.start+"."+c.chr+"."+c.start)}if(h.canonical&&c.info.type.lst.push({attrValue:"canonical"}),h.events)for(const t in h.events){const e=h.events[t];e.__ek=t,c.info.type.lst.push(e)}else h.canonical||c.info.type.lst.push({attrValue:pn});if(t.infoFilter&&t.infoFilter.type)for(const e of c.info.type.lst)if(t.infoFilter.type[e.attrValue])return;const p=gn(h,t,e,n);if(0==p.length)return;if((h.exonleft||h.exonright||h.exonleftin||h.exonrightin||h.intronleft||h.intronright||h.leftout||h.rightout)&&(c.ongene={},h.exonleft&&(c.ongene.exonleft=h.exonleft),h.exonright&&(c.ongene.exonright=h.exonright),h.exonleftin&&(c.ongene.exonleftin=h.exonleftin),h.exonrightin&&(c.ongene.exonrightin=h.exonrightin),h.intronleft&&(c.ongene.intronleft=h.intronleft),h.intronright&&(c.ongene.intronright=h.intronright),h.leftout&&(c.ongene.leftout=h.leftout),h.rightout&&(c.ongene.rightout=h.rightout)),p.forEach((t=>{l.add(t.i),s=Math.max(s,t.readcount)})),c.sampleCount=p.length,1==c.sampleCount)c.medianReadCount=p[0].readcount;else{const t=yn(p,.05,.25,.5,.75,.95);c.medianReadCount=t[2],c.readcountBoxplot={percentile:t}}i.push(c)}}});r.lst=i,r.maxreadcount=s,r.junctiontotalnumber=o,l.size;return r}(r,o,i);n.send(a)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(bs)),ks.post(qs+"/mdscnv",(function(t,e){const[n,r,o,i]=Rs(t.query);if(n)return e.send({error:n});if(!t.query.rglst)return e.send({error:"rglst missing"});if(!t.query.gain)return e.send({error:".gain missing"});if(!t.query.loss)return e.send({error:".loss missing"});if(i.viewrangeupperlimit){if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=i.viewrangeupperlimit)return e.send({error:"zoom in under "+P.bplen(i.viewrangeupperlimit)+" to view details"})}if(t.query.permanentHierarchy){const n=function(t,e){if(!e.cohort)return".cohort missing from ds";if(!e.cohort.hierarchies)return".hierarchies missing from ds.cohort";if(!e.cohort.hierarchies.lst)return".hierarchies.lst[] missing from ds.cohort";const n=e.cohort.hierarchies.lst.find((e=>e.name==t.permanentHierarchy.hierarchyname));if(!n)return"unknown hierarchy "+t.permanentHierarchy.hierarchyname;if(!n.levels)return".levels[] missing in hierarchy "+n.name;const r=n.levels[t.permanentHierarchy.levelidx];if(!r)return"level not found by array idx "+t.permanentHierarchy.levelidx;const s=r.k;return delete t.cohortHiddenAttr,t.cohortOnlyAttr={},t.cohortOnlyAttr[s]={},t.cohortOnlyAttr[s][t.permanentHierarchy.valuekey]=1,null}(t.query,o);if(n)return e.send({error:"permanentHierarchy error: "+n})}const a=[],l={count:0,samples:new Set},c={count:0,samples:new Set};for(const e of t.query.rglst){const n=new Promise(((n,r)=>{const a=(0,q.spawn)(vs,[i.file?y().join(s().tpmasterdir,i.file):i.url,e.chr+":"+e.start+"-"+e.stop],{cwd:i.usedir}),u=O().createInterface({input:a.stdout}),f=(e.stop-e.start)/e.width,d=[];for(let t=0;t<e.width;t++)d.push({positive:0,negative:0});u.on("line",(n=>{const r=n.split("\t"),s=Number.parseInt(r[1]),i=Number.parseInt(r[2]);if(t.query.bplengthUpperLimit&&i-s>t.query.bplengthUpperLimit)return;const a=JSON.parse(r[3]);if(t.query.valueCutoff&&Math.abs(a.value)<t.query.valueCutoff)return;if(a.sample&&o.cohort&&o.cohort.annotation){const e=o.cohort.annotation[a.sample];if(!e)return;if(t.query.cohortOnlyAttr&&o.cohort&&o.cohort.annotation){let n=!1;for(const r in t.query.cohortOnlyAttr){const s=e[r];if(s&&t.query.cohortOnlyAttr[r][s]){n=!0;break}}if(!n)return}if(t.query.cohortHiddenAttr&&o.cohort.attributes){let n=!1;for(const r in t.query.cohortHiddenAttr){o.cohort.attributes.lst.find((t=>t.key==r)).isNumeric;const s=e[r];if(s){if(t.query.cohortHiddenAttr[r][s]){n=!0;break}}else if(t.query.cohortHiddenAttr[r][xs]){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(e.start,s),h=Math.min(e.stop,i);let p,m;e.reverse?(p=Math.floor((e.stop-h)/f),m=Math.floor((e.stop-u)/f)):(p=Math.floor((u-e.start)/f),m=Math.floor((h-e.start)/f));for(let t=p;t<m;t++)a.value>0?d[t].positive++:a.value<0&&d[t].negative++}));const h=[];a.stderr.on("data",(t=>h.push(t))),a.on("close",(t=>{const e=h.join("");!e||gs(e)?n(d):r(e)}))}));a.push(n)}Promise.all(a).then((n=>{const r=t.query.rglst.reduce(((e,n)=>e+n.width+t.query.regionspace),0)-t.query.regionspace,s=(0,S.createCanvas)(r,t.query.gain.barheight+t.query.loss.barheight),a=s.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",r/2,t.query.gain.barheight),u.src=s.toDataURL(),void e.send(u);for(const t of n)for(const e of t)u.maxvalue=Math.max(u.maxvalue,e.positive,e.negative);const f=t.query.maxvalue||u.maxvalue;let d=0;for(const e of n){for(const n of e){if(n.positive){a.fillStyle=t.query.gain.color||"#67a9cf";const e=Math.ceil(t.query.gain.barheight*Math.min(f,n.positive)/f),r=t.query.gain.barheight-e;a.fillRect(d,r,1,e)}if(n.negative){a.fillStyle=t.query.loss.color||"#ef8a62";const e=Math.ceil(t.query.loss.barheight*Math.min(f,n.negative)/f),r=t.query.gain.barheight;a.fillRect(d,r,1,e)}d++}d+=t.query.regionspace}if(u.src=s.toDataURL(),l.samples.size||c.samples.size){const t=new Set([...l.samples,...c.samples]),[e,n]=function(t,e,n){if(!t.cohort||!t.cohort.annotation||0==n.length)return[null,null];const r=[];for(const e of n){const n=t.cohort.annotation[e];n&&r.push(n)}if(0==r.length)return[null,null];let s,o;if(t.cohort.attributes){s=[];for(const n of t.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 e of r){const r=e[n.key];null!=r?(i.has(r)||i.set(r,new Set),i.get(r).add(e[t.cohort.samplenamekey])):a++}const l=[...i];a&&l.push([xs,a]),l.sort(((t,e)=>e[1]-t[1])),o.values=[];for(const[t,r]of l){const s={name:t,sampleset:r};if(n.values&&n.values[t])for(const e in n.values[t])s[e]=n.values[t][e];e.attributeSummary&&e.attributeSummary[n.key]&&e.attributeSummary[n.key][t]&&(s.totalCount=e.attributeSummary[n.key][t]),o.values.push(s)}s.push(o)}}if(t.cohort.hierarchies){o={};for(const n of t.cohort.hierarchies.lst){const s=(0,V.Z)()((0,A.N)(r,n.levels));s.sum((t=>t.value));const i=[];s.eachBefore((r=>{const s={id:r.data.id,name:r.data.name,label:r.data.full,depth:r.depth};if(r.data.lst){s.sampleset=new Set;for(const e of r.data.lst)s.sampleset.add(e[t.cohort.samplenamekey])}r.children||(s.isleaf=1),e.hierarchySummary&&e.hierarchySummary[n.name]&&(s.totalCount=e.hierarchySummary[n.name][r.id]),i.push(s)})),o[n.name]=i}}return[s,o]}(o,i,[...t]);if(e){for(const t of e)for(const e of t.values){e.gain=0,e.loss=0;for(const t of e.sampleset)l.samples.has(t)&&e.gain++,c.samples.has(t)&&e.loss++;delete e.sampleset}u.attributeSummary=e}if(n){for(const t in n)for(const e of n[t])if(e.sampleset){e.gain=0,e.loss=0;for(const t of e.sampleset)l.samples.has(t)&&e.gain++,c.samples.has(t)&&e.loss++}u.hierarchySummary=n}}e.send(u)})).catch((t=>{e.send({error:t}),t.stack&&console.error(t.stack)}))})),ks.post(qs+"/mdssvcnv",(async function(t,e){let n,r,o,i,a,l,c,u,f;if(t.query.iscustom){if(n=bs[t.query.genome],!n)return e.send({error:"invalid genome"});if(r={},o={iscustom:1,file:t.query.file,url:t.query.url,indexURL:t.query.indexURL,allow_getallsamples:!0},t.query.checkexpressionrank){if(!t.query.checkexpressionrank.file&&!t.query.checkexpressionrank.url)return e.send({error:"no file or url for checkexpressionrank"});o.checkexpressionrank={file:t.query.checkexpressionrank.file,url:t.query.checkexpressionrank.url,indexURL:t.query.checkexpressionrank.indexURL}}if(t.query.checkvcf){let n;try{n=JSON.parse(t.query.checkvcf)}catch(t){return e.send({error:"invalid JSON for VCF object"})}if(!n.file&&!n.url)return e.send({error:"no file or url for custom VCF track"});n.type=P.mdsvcftype.vcf,o.checkvcf={info:n.info,tracks:[n]}}if(t.query.checkrnabam){if(!t.query.checkrnabam.samples)return e.send({error:"samples{} missing from checkrnabam"});let n=0;for(const e in t.query.checkrnabam.samples)n++;if(n>13)return e.send({error:"no more than 13 BAM files allowed"});const r=Us(t.query.checkrnabam);if(r)return e.send({error:r});o.checkrnabam=t.query.checkrnabam}}else{if(n=bs[t.query.genome],!n)return e.send({error:"invalid genome"});if(!n.datasets)return e.send({error:"genome is not equipped with datasets"});if(r=n.datasets[t.query.dslabel],!r)return e.send({error:"invalid dslabel"});if(t.query.getsample4disco)return function(t,e,n,r){if(t.query.iscustom)return e.send({error:"not for custom track"});if(!r.singlesamplemutationjson)return e.send({error:"singlesamplemutationjson not available for this dataset"});const o=t.query.getsample4disco,i=r.singlesamplemutationjson.samples[o];if(!i)return e.send({error:"no data"});const a=y().join(s().tpmasterdir,i);m().readFile(a,{encoding:"utf8"},((t,n)=>{if(t)return e.send({error:"error getting data for this sample"});e.send({text:n})}))}(t,e,0,r);if(t.query.gettrack4singlesample)return function(t,e,n){const r=t.query.gettrack4singlesample;if(t.query.iscustom)return e.send({error:"no server-side config available for custom track"});if(!n.sampleAssayTrack)return e.send({});return e.send({tracks:n.sampleAssayTrack.samples.get(r)})}(t,e,r);if(t.query.findsamplename)return function(t,e,n){if(t.query.iscustom)return e.send({error:"cannot search sample by name in custom track"});const r=t.query.findsamplename.toLowerCase(),s=[];if(!n.cohort.__samplelst){n.cohort.__samplelst=[];for(const t in n.cohort.annotation)n.cohort.__samplelst.push({name:t,low:t.toLowerCase()})}o(n.cohort.__samplelst);for(const t in n.queries){const e=n.queries[t];if(e.type==P.tkt.mdssvcnv&&e.groupsamplebyattr)for(const t of s){const r=n.cohort.annotation[t.name];if(!r)continue;const s=[];for(const t of e.groupsamplebyattr.attrlst){const e=r[t.k];e&&s.push({k:t.k,kvalue:e})}s.length&&(t.attributes=s,t.grouplabel=s.map((t=>t.kvalue)).join(e.groupsamplebyattr.attrnamespacer))}}if(n.cohort&&n.cohort.sampleAttribute&&n.cohort.sampleAttribute.attributes&&n.cohort.annotation)for(const t of s){const e=n.cohort.annotation[t.name];if(!e)continue;const r=[];for(const t in n.cohort.sampleAttribute.attributes){if(n.cohort.sampleAttribute.attributes[t].clientnoshow)continue;const s=e[t];null!=s&&r.push({k:t,v:s})}r.length&&(t.attr=r)}if(n.sampleAssayTrack)for(const t of s){const e=n.sampleAssayTrack.samples.get(t.name);e&&(t.num_assay_tracks=e.length)}if(n.cohort&&n.cohort.mutation_signature)for(const t in n.cohort.mutation_signature.sets){const e=n.cohort.mutation_signature.sets[t];if(e.samples)for(const t of s)e.samples.map.has(t.name)&&(t.mutation_signature=1)}if(n.singlesamplemutationjson)for(const t of s)n.singlesamplemutationjson.samples[t.name]&&(t.disco=1);return e.send({result:s});function o(t){for(const e of t){if(s.length>10)return;-1!=e.low.indexOf(r)&&(s.find((t=>t.name==e.name))||s.push(e))}}}(t,e,r);if(t.query.assaymap)return async function(t,e,n){try{if(!n.assayAvailability)throw"assay availability not enabled for this dataset";const r=new Set(t.query.skip_termids||[]),s=new Map;for(const e in n.cohort.annotation){if(t.query.key){if(n.cohort.annotation[e][t.query.key]!=t.query.value)continue}s.set(e,new Map)}for(const[t,e]of s){const s=n.assayAvailability.samples.get(t);if(s)for(const t of n.assayAvailability.assays)r.has(t.id)||s[t.id]&&e.set(t.id,"yes")}for(const t of s.keys())0==s.get(t).size&&s.delete(t);const o={};o.totalsample=s.size,o.terms=ts({sample2term:s,terms:n.assayAvailability.assays,config:{termidorder:t.query.termidorder}}),e.send(o)}catch(t){e.send({error:t.message||t})}}(t,e,r);if(!r.queries)return e.send({error:"dataset is not equipped with queries"});if(o=r.queries[t.query.querykey],!o)return e.send({error:"invalid querykey"})}if(t.query.getexpression4gene)return async function(t,e,n,r,o){try{const n=t.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 r=bs[t.query.genome],s=r.tracks.find((t=>t.__isgene)),i=(await Hs(r,s,n.chr,n.start,n.stop)).get(n.name);if(!i)throw"no gene matching with "+n.name;const a={};await Fs(new Map([[n.name,i]]),n.chr,n.start,n.stop,o,a);const l={};for(const t of a.checkrnabam)if(t.genes){const e=t.genes.find((t=>t.gene==n.name));e&&(l[t.sample]=e)}return void e.send({sample2rnabam:l})}let i;if(o.iscustom?i=o.checkexpressionrank:o.expressionrank_querykey&&(i=r.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(s().tpmasterdir,i.file):i.url,n.chr+":"+n.start+"-"+n.stop],dir:a,callback:t=>{const e=t.split("\t");let r;try{r=JSON.parse(e[3])}catch(t){reject("invalid json from expression data")}r.sample&&r.gene&&Number.isFinite(r.value)&&(delete r.outlier,r.gene.toLowerCase()==n.name.toLowerCase()&&l.push(r))}});const c=function(t,e,n){const r={};if(t&&t.cohort&&t.cohort.annotation&&e.groupsamplebyattr&&e.groupsamplebyattr.attrlst){const s=new Map;for(const r of n){const n=t.cohort.annotation[r.sample];if(!n)continue;const o=[];for(const t of e.groupsamplebyattr.attrlst)o.push(n[t.k]);const i=o.join(",");s.has(i)||s.set(i,[]),s.get(i).push(r)}for(const t of s.values()){t.sort(((t,e)=>t.value-e.value));for(const e of t)e.rank=Ys(e.value,t),r[e.sample]=e}}else{n.sort(((t,e)=>t.value-e.value));for(const t of n)t.rank=Ys(t.value,n),r[t.sample]=t}return r}(r,o,l);e.send({sample2rank:c})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}}(t,e,0,r,o);if(t.query.ifsamplehasvcf)return function(t,e,n,r,s){if(t.query.iscustom)return e.send({no:1});if(!s.vcf_querykey)return e.send({yes:1});const o=r.queries[s.vcf_querykey];if(!o)return e.send({error:"vcf query missing"});e.send(o.singlesamples?{yes:1}:{no:1})}(t,e,0,r,o);if(!t.query.rglst)return e.send({error:"rglst missing"});if(o.viewrangeupperlimit){if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=o.viewrangeupperlimit)return e.send({error:"zoom in under "+P.bplen(o.viewrangeupperlimit)+" to view details"})}t.query.hiddendt&&(i=new Set(t.query.hiddendt));if(t.query.hiddenmattr){a={};for(const e in t.query.hiddenmattr)a[e]=new Set(t.query.hiddenmattr[e])}if(t.query.filteralleleattr){l={};for(const e in t.query.filteralleleattr){const n=t.query.filteralleleattr[e];n.cutoffvalue,l[e]=n}}if(t.query.filterlocusattr){c={};for(const e in t.query.filterlocusattr){const n=t.query.filterlocusattr[e];n.cutoffvalue,c[e]=n}}if(t.query.sampleset){const e=new Set,n=new Map;for(const r of t.query.sampleset)for(const t of r.samples)e.add(t),n.set(t,r.name);e.size&&(u={set:e,sample2group:n})}if(t.query.hiddensampleattr){f={};for(const e in t.query.hiddensampleattr)f[e]=new Set(t.query.hiddensampleattr[e])}if(o.url)try{o.dir=await F.d1(o.url,o.indexURL)}catch(t){return e.send({error:"svcnv file index url error"})}const d=await function(t,e,n,r,o,i,a){if(!e.file&&!e.url)return[];const l=[];for(const c of n.query.rglst){const u=new Promise(((l,u)=>{const f=[],d=(0,q.spawn)(vs,[e.file?y().join(s().tpmasterdir,e.file):e.url,c.chr+":"+c.start+"-"+c.stop],{cwd:e.dir});O().createInterface({input:d.stdout}).on("line",(e=>{const s=e.split("\t"),l=Number.parseInt(s[1]),c=Number.parseInt(s[2]);let u;try{u=JSON.parse(s[3])}catch(t){return}if(!(null==u.dt||r&&r.has(u.dt))){if(u.dt==P.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=s[0],u.start=l,u.stop=c}else if(u.dt==P.dtfusionrna||u.dt==P.dtsv)u._chr=s[0],u._pos=l,u.chrA?(u.chrB=s[0],u.posB=l):(u.chrA=s[0],u.posA=l);else if(u.dt==P.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=s[0],u.start=l,u.stop=c}else{if(u.dt!=P.dtitd)return void console.error("unknown dt from svcnv file: "+u.dt);u.chr=s[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&&t.cohort&&t.cohort.annotation){const e=t.cohort.annotation[u.sample];if(!e)return;if(o)for(const t in o){const n=e[t];if(o[t].has(n))return}}if(i)for(const t in i){let e=u.mattr?u.mattr[t]:void 0;if(null==e&&(e=P.not_annotated),i[t].has(e))return}f.push(u)}}));const h=[];d.stderr.on("data",(t=>h.push(t))),d.on("close",(t=>{const e=h.join("");!e||gs(e)?l(f):u(e)}))}));l.push(u)}return Promise.all(l)}(r,o,t,i,f,a,u),[h,p]=await function(t,e,n,r){if(n.query.singlesample)return[];let o;if(e.iscustom?o=e.checkexpressionrank:e.expressionrank_querykey&&t.queries[e.expressionrank_querykey]&&(o=t.queries[e.expressionrank_querykey]),!o)return[];let i=o.viewrangeupperlimit;if(!i&&e.iscustom&&(i=5e6),i&&n.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=i)return[i];return Promise.resolve().then((()=>o.file?"":(0,F.d1)(o.url,o.indexURL))).then((t=>{const e=new Map,r=[];for(const i of n.query.rglst){const n=new Promise(((n,r)=>{const a=(0,q.spawn)(s().tabix,[o.file?y().join(s().tpmasterdir,o.file):o.url,i.chr+":"+i.start+"-"+i.stop],{cwd:t});O().createInterface({input:a.stdout}).on("line",(t=>{const n=t.split("\t");let r;try{r=JSON.parse(n[3])}catch(t){return}r.gene&&r.sample&&Number.isFinite(r.value)&&(e.has(r.gene)||e.set(r.gene,{chr:n[0],start:Number.parseInt(n[1]),stop:Number.parseInt(n[2]),samples:new Map}),e.get(r.gene).samples.set(r.sample,{value:r.value,ase:r.ase}))}));const l=[];a.stderr.on("data",(t=>l.push(t))),a.on("close",(t=>{const e=l.join("");!e||(0,F.sI)(e)?n():r(e)}))}));r.push(n)}return Promise.all(r).then((()=>[!1,e]))}))}(r,o,t),[g,b]=await async function(t,e,n,r,o,i,a,l,c,u){let f;n.iscustom?f=n.checkvcf:n.vcf_querykey&&e.queries[n.vcf_querykey]&&(f=e.queries[n.vcf_querykey]);if(!f)return[null,null];if(r.query.singlesample&&f.singlesamples){const n=f.singlesamples.samples[r.query.singlesample];if(n){const i={file:y().join(s().tpmasterdir,n)};try{await m().promises.stat(i.file)}catch(t){return[null,null]}const a=await Vs(i.file),[u,f,d,h]=D.e(a);if(h)throw h;return i.info=u,i.format=f,i.samples=d,i.nochr=await F.Jy(i.file,null,t),function(t,e,n,r,s,o,i){const a=[],l=[];for(const s of t.query.rglst){const c=new Promise(((l,c)=>{const u=(0,q.spawn)(vs,[n.file,(n.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+s.stop]);O().createInterface({input:u.stdout}).on("line",(s=>{const[l,c,u]=D.S(s,n);for(const n of c){if(!n.sampledata)continue;const s=n.sampledata.find((e=>e.sampleobj.name==t.query.singlesample));if(s){if(delete s.allele2readcount,n.sampledata=[s],r){let t=!1;for(const e in r){const s=n.altinfo[e];if(null==s){t=!0;break}const o=r[e];if(null!=o.cutoffvalue){if(!Number.isFinite(s)){t=!0;break}if(o.keeplowerthan){if(s>o.cutoffvalue){t=!0;break}}else if(s<o.cutoffvalue){t=!0;break}}}if(t)continue}if(!s.gtallref){if(s.__gtalleles){if(-1==s.__gtalleles.indexOf(n.alt))continue;delete s.__gtalleles}if(o){const t=[];for(const e of n.sampledata){let n=!0;for(const t in o){let r=e[t];if(null==r&&(r=P.not_annotated),o[t].has(r)){n=!1;break}}n&&t.push(e)}if(0==t.length)continue;n.sampledata=t}if(i&&e.cohort&&e.cohort.annotation){const t=[];for(const r of n.sampledata){const n=e.cohort.annotation[r.sampleobj.name];if(!n)continue;let s=!0;for(const t in i){const e=n[t];if(i[t].has(e)){s=!1;break}}s&&t.push(r)}if(0==t.length)continue;n.sampledata=t}delete n._m,delete n.vcf_ID,delete n.name,n.dt=P.dtsnvindel,a.push(n)}}}}));const f=[];u.stderr.on("data",(t=>f.push(t))),u.on("close",(t=>{const e=f.join("");!e||gs(e)?l():c(e)}))}));l.push(c)}return Promise.all(l).then((()=>[null,a]))}(r,e,i,o,0,l,c)}}let d=f.viewrangeupperlimit;!d&&n.iscustom&&(d=ys.customMdsSingleSampleVcfNoRangeLimit?0:2e6);r.query.singlesample&&(d*=5);if(d){if(r.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=d)return[d,null]}const h=[];for(const t of f.tracks){const n=Promise.resolve().then((()=>t.file?"":F.d1(t.url,t.indexURL))).then((n=>{t.dir=n;const a=[],d=[];for(const h of r.query.rglst){const p=new Promise(((d,p)=>{const m=(0,q.spawn)(vs,[t.file?y().join(s().tpmasterdir,t.file):t.url,(t.nochr?h.chr.replace("chr",""):h.chr)+":"+h.start+"-"+h.stop],{cwd:n});O().createInterface({input:m.stdout}).on("line",(n=>{if(t.type==P.mdsvcftype.vcf){const[s,d,h]=D.S(n,{nochr:t.nochr,samples:t.samples,info:f.info,format:t.format});for(const t of d)if(t.sampledata){if(o){let e=!1;for(const n in o){const r=t.altinfo[n];if(null==r){e=!0;break}const s=o[n];if(null!=s.cutoffvalue){if(!Number.isFinite(r)){e=!0;break}if(s.keeplowerthan){if(r>s.cutoffvalue){e=!0;break}}else if(r<s.cutoffvalue){e=!0;break}}else if(s.includes(r)){e=!0;break}}if(e)continue}if(i){let e=!1;for(const n in i){const r=t.info[n];if(null==r){e=!0;break}let s=r;if(Array.isArray(r)&&(s=r[0],"."==s)){e=!0;break}const o=i[n];if(null!=o.cutoffvalue){if(!Number.isFinite(s)){e=!0;break}if(o.keeplowerthan){if(s>o.cutoffvalue){e=!0;break}}else if(s<o.cutoffvalue){e=!0;break}}else if(o.includes(s)){e=!0;break}}if(e)continue}{const e=[];for(const n of t.sampledata)if(!n.gtallref){if(n.__gtalleles){if(-1==n.__gtalleles.indexOf(t.alt))continue;delete n.__gtalleles}e.push(n)}if(0==e.length)continue;t.sampledata=e}if(r.query.singlesample){let e=null;for(const n of t.sampledata)if(n.sampleobj.name==r.query.singlesample){e=n;break}if(!e)continue;t.sampledata=[e]}else if(u){const e=t.sampledata.filter((t=>u.set.has(t.sampleobj.name)));if(!e.length)continue;t.sampledata=e}if(l){const e=[];for(const n of t.sampledata){let t=!0;for(const e in l){let r=n[e];if(null==r&&(r=P.not_annotated),l[e].has(r)){t=!1;break}}t&&e.push(n)}if(0==e.length)continue;t.sampledata=e}if(c&&e.cohort&&e.cohort.annotation){const n=[];for(const r of t.sampledata){const t=e.cohort.annotation[r.sampleobj.name];if(!t)continue;let s=!0;for(const e in c){const n=t[e];if(c[e].has(n)){s=!1;break}}s&&n.push(r)}if(0==n.length)continue;t.sampledata=n}for(const e of t.sampledata)delete e.allele2readcount;delete t._m,delete t.vcf_ID,delete t.name,t.dt=P.dtsnvindel,a.push(t)}}else console.error('unknown "type" from a vcf file')}));const g=[];m.stderr.on("data",(t=>g.push(t))),m.on("close",(t=>{const e=g.join("");!e||gs(e)?d():p(e)}))}));d.push(p)}return Promise.all(d).then((()=>a))}));h.push(n)}return Promise.all(h).then((t=>{const e=[];for(const n of t)for(const t of n)if(t.dt!=P.dtsnvindel)console.error("unknown dt: "+t.dt);else{if(!t.sampledata)continue;let n=!0;for(const r of e)if(t.chr==r.chr&&t.pos==r.pos&&t.ref==r.ref&&t.alt==r.alt){for(const e of t.sampledata)r.sampledata.push(e);n=!1;break}n&&e.push(t)}return e.sort(((t,e)=>t.pos-e.pos)),[null,e]}))}(n,r,o,t,l,c,0,a,f,u),v=function(t){const e=new Map;for(const n of t)for(const t of n){if(!t.sample)continue;const n=t.sample;e.has(n)||e.set(n,[]),t._chr?e.get(n).push(t):(delete t.sample,delete t.sampletype,e.get(n).push(t))}return e}(d);if(t.query.singlesample){const n={lst:v.get(t.query.singlesample)};return g?n.vcfrangelimit=g:n.data_vcf=b,void e.send(n)}const w={samplegroups:$s(r,o,d,b,v,u),vcfrangelimit:g,data_vcf:b};t.query.getallsamples&&o.allow_getallsamples&&(w.getallsamples=!0);o.checkrnabam?await async function(t,e,n,r){if(!n.checkvcf)return;if(t.stop-t.start>=5e5)return void(r.expressionrangelimit=5e5);const s=e.tracks.find((t=>t.__isgene)),o=await Hs(e,s,t.chr,t.start,t.stop);let i,a=null;for(const t of o.values())null==a?(a=t.start,i=t.stop):(a=Math.min(a,t.start),i=Math.max(i,t.stop));await Fs(o,t.chr,a,i,n,r)}(t.query.rglst[0],n,o,w):function(t,e,n,r){if(n)return void(t.expressionrangelimit=n);if(r){t.gene2coord={};for(const[e,n]of r)t.gene2coord[e]={chr:n.chr,start:n.start,stop:n.stop};if(0==t.samplegroups.length)return;if(t.getallsamples){const e=new Set(t.samplegroups[0].samples.map((t=>t.samplename))),n=new Set;for(const[t,s]of r)for(const t of s.samples.keys())e.has(t)||n.add(t);for(const e of n)t.samplegroups[0].samples.push({samplename:e,items:[]})}for(const n of t.samplegroups){const t=new Map;for(const[s,o]of r){t.set(s,[]);for(const[r,i]of o.samples)if(n.attributes&&e.cohort&&e.cohort.annotation){const o=e.cohort.annotation[r];if(!o)continue;let a=!0;for(const t of n.attributes)if(o[t.k]!=t.kvalue){a=!1;break}a&&t.get(s).push(i)}else t.get(s).push(i)}for(const[e,n]of t)n.sort(((t,e)=>t.value-e.value));for(const e of n.samples){e.expressionrank={};for(const[n,s]of t){const t=r.get(n).samples.get(e.samplename);if(null==t)continue;const o=Ys(t.value,s);e.expressionrank[n]={rank:o};for(const r in t)e.expressionrank[n][r]=t[r]}}}}}(w,r,h,p);(function(t,e){if(t.cohort&&t.cohort.sampleAttribute&&t.cohort.sampleAttribute.attributes&&t.cohort.annotation){e.sampleannotation={};const n=[];for(const e in t.cohort.sampleAttribute.attributes){t.cohort.sampleAttribute.attributes[e].clientnoshow||n.push(e)}for(const r of e.samplegroups)for(const s of r.samples){const r=t.cohort.annotation[s.samplename];if(r){const t={};let o=!1;for(const e of n){const n=r[e];null!=n&&(o=!0,t[e]=n)}o&&(e.sampleannotation[s.samplename]=t)}}}})(r,w),e.send(w)})),ks.post(qs+"/mdsgenecount",(async function(t,e){try{const n=bs[t.query.genome];if(!n)throw"invalid genome";if(!n.datasets)throw"no datasets from genome";const r=n.datasets[t.query.dslabel];if(!r)throw"invalid dataset";if(!r.gene2mutcount)throw"not supported on this dataset";if(!t.query.samples)throw".samples missing";let s,o;s=t.query.selectedMutTypes?t.query.selectedMutTypes.join("+"):"total",o=t.query.nGenes?t.query.nGenes:15;const i=`WITH\n\tfiltered AS (\n\t\tSELECT gene, ${s} AS total FROM genecount\n\t\tWHERE sample IN (${JSON.stringify(t.query.samples).replace(/[[\]\"]/g,"").split(",").map((t=>"'"+t+"'")).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=r.gene2mutcount.db.prepare(i).all(),l=[];for(const t of a){const e=n.genedb.getCoordByGene.get(t.gene);e&&(e.gene=t.gene,e.count=t.count,delete e.name,l.push(e))}e.send({genes:l})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.post(qs+"/mds2",function(t){return async(e,n)=>{const r=e.query;try{const e=t[r.genome],s=await async function(t,e){if(!e)throw"invalid genome";if(t.dslabel){const n=e.datasets[t.dslabel];if(!n)throw"invalid dslabel";if(!n.track)throw"no mds2 track found for dataset";return n}const n={iscustom:1,track:{}};t.vcf&&(n.track.vcf=t.vcf,await F._H(n.track.vcf,e));t.ld;return n}(r,e);if(r.trigger_overlayld)return await async function(t,e,n){if(!t.ldtkname)throw".ldtkname missing";const r=e.track.ld.tracks.find((e=>e.name==t.ldtkname));if(!r)throw"ld tk not found by name: "+t.ldtkname;const s=t.m.ref+"."+t.m.alt,o=(r.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+t.m.pos+"-"+(t.m.pos+1),i=[];await F.UE({args:[r.file,o],dir:r.dir,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),o=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);r==t.m.pos&&a==s?i.push({pos:o,alleles:l,r2:c}):o==t.m.pos&&l==s&&i.push({pos:r,alleles:a,r2:c})}}),n.send({lst:i})}(r,s,n);r.hidden_mclass&&(r.hidden_mclass=new Set(r.hidden_mclass));const o={mclass2count:{}};if(r.info_fields){o.info_fields={};for(const t of r.info_fields)if(t.iscategorical)o.info_fields[t.key]={value2count:{}};else if(t.isnumerical)o.info_fields[t.key]={filteredcount:0};else{if(!t.isflag)throw"unknown info type";o.info_fields[t.key]={count_yes:0,count_no:0}}}if(r.trigger_mafcovplot&&await async function(t,e,n,r){try{if(!n.track)throw"ds.track missing";const e=n.track.vcf;if(!e)throw"ds.track.vcf missing";if(n.iscustom)e.plot_mafcov={show_samplename:1};else if(!e.plot_mafcov)throw"maf-cov plot is not supported on this track";if(!t.m)throw".m{} missing";if(!e.AD)throw"vcf.AD{} missing";const s=(e.AD.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),o=e.AD.chr2bcffile[t.m.chr];if(!o)throw"chr not in tk.AD.chr2bcffile";let i;if(await F.UE({isbcf:!0,args:["query","-r",s,"-f",Ur,o],dir:e.AD.dir,callback:n=>{const[r,s,o]=D.S(n,e.AD);for(const e of s)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(i=e)}}),!i)throw"variant not found";if(r.plotgroups=function(t,e,n){const r=[],s={name:"?",lst:[]};for(const r of t.sampledata){const o=r.AD[t.ref]||0,i=r.AD[t.alt]||0,a=o+i,l={mut:i,total:o+i,maf:0==a?0:i/a};e.plot_mafcov.show_samplename&&(l.sampleobj={name:n.cohort.termdb.q.id2sampleName(r.sampleobj.name)}),s.lst.push(l)}return r.push(s),r}(i,e,n),t.overlay_term){const e=await Yn.g5({ds:n,term1_id:t.overlay_term,term1_q:t.overlay_term_q}),s=new Map;for(const t of e.lst)s.set(t.sample,t.key1);const o=(0,$r.Z)(zr.Z),i=new Map;let a=0;for(const t of r.plotgroups)for(const e of t.lst){const t=s.get(e.sampleobj.name);if(t){const n=o(t);e.sampleobj.color=n,i.has(t)||i.set(t,{count:0,color:n,label:t}),i.get(t).count++}else a++,e.sampleobj.color=Zr}if(r.categories=[],e.CTE1&&e.CTE1.name2bin)for(const t of e.CTE1.name2bin.keys()){const e=i.get(t);e&&r.categories.push(e)}else for(const[t,e]of i)r.categories.push(e);a&&r.categories.push({count:a,color:Zr,label:"Unannotated"})}}catch(t){r.error=t.message||t,t.stack&&console.log(t.stack)}}(r,0,s,o),r.trigger_vcfbyrange&&(await Rr(r,0,s,o),r.trigger_ld)){o.__mposset=new Set;for(const t of o.vcf.rglst)if(t.variants)for(const e of t.variants)o.__mposset.add(e.pos)}if(r.trigger_ld){o.ld={};for(const t of r.trigger_ld.tracks)await Br(t,r,0,s,o);delete o.__mposset}r.trigger_ssid_onevcfm&&await async function(t,e,n,r){if(n.iscustom)throw"custom ds not allowed";const s=n.track.vcf;if(!s)throw"ds.track.vcf missing";if(!t.m)throw"q.m missing";const o=(s.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),i=s.chr2bcffile[t.m.chr];if(!i)throw"chr not in chr2bcffile";let a;if(await F.UE({isbcf:!0,args:["query",i,"-r",o,"-f",Ir+"\t%FORMAT\n"],dir:s.dir,callback:e=>{const[n,r,o]=D.S(e,s);for(const e of r)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(a=e)}}),!a)throw"variant not found";const l=[],c=[],u=[];for(const e of a.sampledata){if(!e.genotype)continue;const n=-1!=e.genotype.indexOf(t.m.ref),r=-1!=e.genotype.indexOf(t.m.alt);n?r?c.push(e.sampleobj.name):l.push(e.sampleobj.name):r&&u.push(e.sampleobj.name)}const f=Math.random().toString();r.ssid=f,r.groups={};const d=[];if(l.length){const t="Homozygous reference";r.groups[t]={size:l.length},d.push(t+"\t"+l.join(","))}if(c.length){const t="Heterozygous";r.groups[t]={size:c.length},d.push(t+"\t"+c.join(","))}if(u.length){const t="Homozygous alternative";r.groups[t]={size:u.length},d.push(t+"\t"+u.join(","))}await F.Sf(y().join(Or.cachedir_ssid,f),d.join("\n"))}(r,0,s,o),r.trigger_getvcfcsq&&await async function(t,e,n,r){const s=n.track.vcf;if(!s)throw"ds.track.vcf missing";if(!t.m)throw"q.m missing";const o=(s.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),i=s.chr2bcffile[t.m.chr];if(!i)throw"chr not in chr2bcffile";await F.UE({isbcf:!0,args:["query",i,"-r",o,"-f",Ir+"\\n"],dir:s.dir,callback:e=>{const[n,o,i]=D.S(e,s);for(const e of o)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(r.csq=e.csq)}})}(r,0,s,o),n.send(o)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(bs)),ks.post(qs+"/mdsexpressionrank",(function(t,e){let n,r,o,i=new Set;Promise.resolve().then((()=>{if(!t.query.rglst)throw"rglst missing";if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>1e7)throw"Zoom in below 10 Mb to show expression rank";if(!t.query.sample)throw"sample missing";if(t.query.iscustom){if(n=bs[t.query.genome],!n)throw"invalid genome";if(!t.query.file&&!t.query.url)throw"no file or url for expression data";r={},o={file:t.query.file,url:t.query.url,indexURL:t.query.indexURL}}else{const[e,s,i,a]=Rs(t.query);if(e)throw e;if(n=s,r=i,o=a,!o.samples)throw"total samples missing from server config";if(-1==o.samples.indexOf(t.query.sample))throw{nodata:1}}if(o.viewrangeupperlimit&&t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>o.viewrangeupperlimit)throw"zoom in under "+P.bplen(o.viewrangeupperlimit)+" to view data";if(t.query.levelkey){if(!t.query.levelvalue)throw"levelvalue is required when levelkey is used";if(!r.cohort||!r.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((e=>{const n=[];for(const a of t.query.rglst)n.push(new Promise(((n,l)=>{const c=(0,q.spawn)(vs,[o.file?y().join(s().tpmasterdir,o.file):o.url,a.chr+":"+a.start+"-"+a.stop],{cwd:e}),u=O().createInterface({input:c.stdout}),f=new Map;u.on("line",(e=>{const n=e.split("\t"),s=JSON.parse(n[3]);if(!s.gene)return;if(!s.sample)return;if(!Number.isFinite(s.value))return;const o=n[0],a=Number.parseInt(n[1]),l=Number.parseInt(n[2]);if(s.sample==t.query.sample)return f.has(s.gene)||f.set(s.gene,{chr:o,start:a,stop:l,allvalues:[]}),f.get(s.gene).thisvalue=s.value,void(s.ase&&(f.get(s.gene).ase=s.ase));if(t.query.attributes){const e=r.cohort.annotation[s.sample];if(!e)return;for(const n of t.query.attributes)if(n.k&&n.kvalue&&n.kvalue!=e[n.k])return}i.add(s.sample),f.has(s.gene)||f.set(s.gene,{chr:o,start:a,stop:l,allvalues:[]}),f.get(s.gene).allvalues.push({value:s.value})}));const d=[];c.stderr.on("data",(t=>d.push(t))),c.on("close",(t=>{const e=d.join("");e&&!gs(e)&&l({message:e}),n(f)}))})));return Promise.all(n)})).then((t=>{const n=[];for(const e of t)for(const[t,r]of e)null!=r.thisvalue&&(r.allvalues.sort(((t,e)=>t.value-e.value)),r.rank=Ys(r.thisvalue,r.allvalues),delete r.allvalues,r.gene=t,n.push(r));e.send({result:n,samplecount:i.size})})).catch((t=>{t.stack&&console.log(t),t.nodata?e.send({nodata:1}):e.send({error:t.message?t.message:t})}))})),ks.post(qs+"/mdsgeneboxplot",(t=>async(e,n)=>{try{const[r,o,i,a]=function(t,e){if(!e.query.gene)throw"gene name missing";if(!e.query.chr)throw"chr missing";if(!Number.isInteger(e.query.start))throw"start missing";if(!Number.isInteger(e.query.stop))throw"stop missing";const n=t[e.query.genome];if(!n)throw"invalid genome";let r,s,o;if(e.query.iscustom){if(!e.query.file&&!e.query.url)throw"no file or url for expression data";r={},s={file:e.query.file,url:e.query.url,indexURL:e.query.indexURL}}else{if(!n.datasets)throw"genome is not equipped with datasets";if(!e.query.dslabel)throw"dslabel missing";if(r=n.datasets[e.query.dslabel],!r)throw"invalid dslabel";if(!r.queries)throw"dataset is not equipped with queries";if(!e.query.querykey)throw"querykey missing";if(s=r.queries[e.query.querykey],!s)throw"invalid querykey"}if(e.query.svcnv)if(o={},e.query.iscustom)o.dsquery={file:e.query.svcnv.file,url:e.query.svcnv.url,indexURL:e.query.svcnv.indexURL};else{e.query.svcnv.genome=e.query.genome;const t=n.datasets[e.query.svcnv.dslabel];if(!t)throw"invalid dslabel";if(!t.queries)throw"dataset is not equipped with queries";if(!e.query.svcnv.querykey)throw"querykey missing";const r=t.queries[e.query.svcnv.querykey];if(!r)throw"invalid querykey";o.ds=t,o.dsquery=r}if(e.query.getgroup)if(e.query.sampleset);else{if(!r.cohort||!r.cohort.annotation)throw"no sample annotation for getting group";if(e.query.getgroup_unannotated){if(!s.boxplotbysamplegroup)throw"dsquery.boxplotbysamplegroup{} missing when getgroup_unannotated"}else{if(!Array.isArray(e.query.getgroup))throw"getgroup should be array";for(const t of e.query.getgroup){if(!t.k)throw"k missing from one of getgroup";if(!t.kvalue)throw"kvalue missing from one of getgroup"}}}return[n,r,s,o]}(t,e);e.query.getalllst,n.send(await async function(t,e,n,r,o){n.url&&(n.dir=await F.d1(n.url,n.indexURL));r&&r.dsquery.url&&(r.dsquery.dir=await F.d1(r.dsquery.url,r.dsquery.indexURL));const i=function(t){if(!t.query.sampleset)return;const e=new Map;for(const n of t.query.sampleset)for(const t of n.samples)e.set(t,n.name);return e}(o),a=new Map,l=[],c=[];if(await F.UE({args:[n.file?y().join(s().tpmasterdir,n.file):n.url,o.query.chr+":"+o.query.start+"-"+o.query.stop],dir:n.dir,callback:t=>{const r=t.split("\t"),s=JSON.parse(r[3]);if(s.gene&&s.gene==o.query.gene&&Number.isFinite(s.value))if(o.query.getalllst)l.push({sample:s.sample,value:s.value});else if(o.query.getgroup){if(!s.sample)return;if(i)return void(o.query.getgroup_unannotated?i.has(s.sample)||c.push(s):i.get(s.sample)==o.query.getgroup[0].full&&c.push(s));const t=e.cohort.annotation[s.sample];if(o.query.getgroup_unannotated){if(!t)return void c.push(s);for(const e of n.boxplotbysamplegroup.attributes)if(null==t[e.k])return void c.push(s);return}if(!t)return;for(const e of o.query.getgroup)if(e.kvalue!=t[e.k])return;c.push(s)}else if(n.boxplotbysamplegroup&&e.cohort&&e.cohort.annotation){if(!s.sample)return;let t;t=null==o.query.index_boxplotgroupers||0==o.query.index_boxplotgroupers?n.boxplotbysamplegroup.attributes:n.boxplotbysamplegroup.additionals[o.query.index_boxplotgroupers-1].attributes;const r=e.cohort.annotation[s.sample];if(!r)return void l.push({sample:s.sample,value:s.value});const i=r[t[0].k];if(null==i)return void l.push({sample:s.sample,value:s.value});const c=[];for(let e=1;e<t.length;e++){const n=r[t[e].k];if(null==n)break;c.push(n)}c.unshift(i);const u=c.join(", ");if(!a.has(u)){const e={samples:[],attributes:[]};for(const n of t){const t=r[n.k];if(null==t)break;const s={k:n.k,kvalue:t};n.full&&(s.full=n.full,s.fullvalue=r[n.full]),e.attributes.push(s)}a.set(u,e)}a.get(u).samples.push({sample:s.sample,value:s.value})}else if(i){if(!s.sample)return;const t=i.get(s.sample);if(!t)return void l.push({sample:s.sample,value:s.value});a.has(t)||a.set(t,{samples:[],attributes:[{full:t}]}),a.get(t).samples.push({sample:s.sample,value:s.value})}else l.push({sample:s.sample,value:s.value})}}),o.query.getgroup2boxplot){c.sort(((t,e)=>t.value-e.value));const{w1:t,w2:e,p25:n,p50:r,p75:s,out:o}=F.JC(c);return{n:c.length,min:c[0].value,max:c[c.length-1].value,w1:t,w2:e,p25:n,p50:r,p75:s,out:o}}const u=[];for(const[t,e]of a)u.push({name:t,values:e.samples,attributes:e.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 t=u[0].values;return t.sort(((t,e)=>e.value-t.value)),{lst:t,max:t[0].value,min:t[t.length-1].value}}return{nodata:1}}const f=await async function(t,e){if(!e||!t.query.svcnv.useloss&&!t.query.svcnv.usegain&&!t.query.svcnv.usesv)return;let n=t.query.start,r=t.query.stop;t.query.svcnv.usesv&&Number.isInteger(t.query.svcnv.svflank)&&(n=Math.max(0,n-t.query.svcnv.svflank),r+=t.query.svcnv.svflank);const o=new Map;return await F.UE({args:[e.dsquery.file?y().join(s().tpmasterdir,e.dsquery.file):e.dsquery.url,t.query.chr+":"+n+"-"+r],dir:e.dsquery.dir,callback:e=>{const n=e.split("\t"),r=JSON.parse(n[3]);if(r.sample)if(r.chrA||r.chrB){if(!t.query.svcnv.usesv)return;o.has(r.sample)||o.set(r.sample,{}),o.get(r.sample).sv=1}else{if(!t.query.svcnv.usegain&&!t.query.svcnv.useloss)return;if(t.query.svcnv.usesv&&t.query.svcnv.svflank){const e=Number.parseInt(n[1]),r=Number.parseInt(n[2]);if(Math.max(t.query.start,e)>Math.min(t.query.stop,r))return}if(!Number.isFinite(r.value))return;if(!t.query.svcnv.usegain&&r.value>0)return;if(!t.query.svcnv.useloss&&r.value<0)return;if(t.query.svcnv.valueCutoff&&Math.abs(r.value)<t.query.svcnv.valueCutoff)return;if(t.query.svcnv.bplengthUpperLimit&&Number.parseInt(n[2])-Number.parseInt(n[1])>t.query.svcnv.bplengthUpperLimit)return;o.has(r.sample)||o.set(r.sample,{}),r.value>0?o.get(r.sample).gain=1:r.value<0&&(o.get(r.sample).loss=1)}}}),o}(o,r);if(o.query.getgroup){if(u[0]){const t=u[0].values;if(t.sort(((t,e)=>e.value-t.value)),f)for(const e of t){const t=f.get(e.sample);if(t)for(const n in t)e[n]=t[n]}return{lst:t,max:t[0].value,min:t[t.length-1].value}}return{nodata:1}}const d=[];let h=null,p=null;for(const t of u){t.values.sort(((t,e)=>t.value-e.value));const e=t.values.length;null==h?(h=t.values[0].value,p=t.values[e-1].value):(h=Math.min(h,t.values[0].value),p=Math.max(p,t.values[e-1].value));const{w1:n,w2:r,p25:s,p50:i,p75:a,out:l}=F.JC(t.values),c=[{isall:1,w1:n,w2:r,p25:s,p50:i,p75:a,out:l}];if(f){if(o.query.svcnv.usegain){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).gain));if(e.length){const{w1:t,w2:n,p25:r,p50:s,p75:o,out:i}=F.JC(e);c.push({iscnvgain:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:s,p75:o,out:i})}}if(o.query.svcnv.useloss){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).loss));if(e.length){const{w1:t,w2:n,p25:r,p50:s,p75:o,out:i}=F.JC(e);c.push({iscnvloss:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:s,p75:o,out:i})}}if(o.query.svcnv.usesv){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).sv));if(e.length){const{w1:t,w2:n,p25:r,p50:s,p75:o,out:i}=F.JC(e);c.push({issv:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:s,p75:o,out:i})}}}d.push({name:t.name+" ("+t.values.length+")",boxplots:c,attributes:t.attributes})}return d.sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)),{groups:d,min:h,max:p}}(0,o,i,a,e))}catch(t){t.stack&&console.log(t),n.send({error:t.message||t})}})(bs)),ks.post(qs+"/mdsgenevalueonesample",(async function(t,e){const n=t.query;try{if(!n.sample)throw".sample missing";if(!n.genes)throw".genes[] missing";let r,o,i;if(t.query.iscustom){if(r=bs[n.genome],!r)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[t,e,s,a]=Rs(n);if(t)throw t;r=e,o=s,i=a}const a=i.file?null:await F.d1(i.url,i.indexURL),l={};let c=!0;for(const t of n.genes){let e;await F.UE({args:[i.file?y().join(s().tpmasterdir,i.file):i.url,t.chr+":"+t.start+"-"+t.stop],dir:a,callback:r=>{const s=r.split("\t");if(!s[3])return;const o=JSON.parse(s[3]);o.gene==t.gene&&o.sample==n.sample&&(e=o.value)}}),Number.isFinite(e)&&(l[t.gene]=e,c=!1)}c?e.send({nodata:1}):e.send({result:l})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/vcf",(async function(t,e){try{const[n,r,s]=F.ZX(t);if(n)throw n;const o=s?await F.d1(r,t.query.indexURL):null;if(!t.query.rglst)throw"rglst missing";const i=[];for(const e of t.query.rglst)await F.UE({args:[r,e.chr+":"+e.start+"-"+e.stop],dir:o,callback:t=>i.push(t)});e.send({linestr:i.join("\n")})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.get(qs+"/vcfheader",(async function(t,e){try{if(!t.query.genome)throw"genome missing";const n=bs[t.query.genome];if(!n)throw"invalid genome";const[r,s,o]=F.ZX(t);if(r)throw r;const i=o?await F.d1(s,t.query.indexURL):null;e.send({metastr:(await F.ZD(s,i)).join("\n"),nochr:await F.Jy(s,i,n)})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/translategm",(async function(t,e){try{const n=bs[t.query.genome];if(!n)throw"invalid genome";const r=t.query.gm;if(!r)throw"missing gm{}";if(!r.chr)throw"gm.chr missing";if(!r.start)throw"gm.start missing";if(!Number.isInteger(r.start))throw"gm.start not integer";if(!r.stop)throw"gm.stop missing";if(!Number.isInteger(r.stop))throw"gm.stop not integer";const s=await F.Kf(n,r.chr+":"+(r.start+1)+"-"+r.stop),o=P.fasta2gmframecheck(r,s);e.send({frame:o})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.post(qs+"/samplematrix",(function(t,e){Promise.resolve().then((()=>{const e=bs[t.query.genome];if(!e)throw"invalid genome";let n,r;if(t.query.iscustom){if(!t.query.querykey2tracks)throw"querykey2tracks{} missing for custom dataset";n={queries:{}};for(const e in t.query.querykey2tracks){const r=t.query.querykey2tracks[e];if(!r.type)throw'missing "type" for a data track';if(r.type==P.tkt.mdsvcf){const r=t.query.querykey2tracks[e];r.type=P.mdsvcftype.vcf,n.queries[e]={type:P.tkt.mdsvcf,info:r.info,tracks:[r]}}else if(r.type==P.tkt.mdssvcnv)n.queries[e]=r;else{if(r.type!=P.tkt.mdsexpressionrank)throw"unknown type of data track: "+r.type;n.queries[e]=r}}}else{if(!e.datasets)throw"genome is not equipped with datasets";if(!t.query.dslabel)throw"dslabel missing";if(n=e.datasets[t.query.dslabel],!n)throw"invalid dslabel";if(!n.queries)throw"dataset is not equipped with queries"}if(t.query.sampleset)r=new Set(t.query.sampleset);else if(t.query.limitsamplebyeitherannotation){if(!n.cohort)throw"limitsamplebyeitherannotation but no cohort in ds";if(!n.cohort.annotation)throw"limitsamplebyeitherannotation but no cohort.annotation in ds";r=new Set;for(const e in n.cohort.annotation){const s=n.cohort.annotation[e];for(const n of t.query.limitsamplebyeitherannotation)if(s[n.key]==n.value){r.add(e);break}}}const s=[];for(const e of t.query.features){let t,o=[];if(e.querykey){if(!n.queries)throw"using querykey for a feature but no ds.queries";if(t=n.queries[e.querykey],!t)throw"unknown dsquery by key "+e.querykey}else if(e.querykeylst){if(!n.queries)throw"using querykeylst for a feature but no ds.queries";for(const t of e.querykeylst){const e=n.queries[t];if(!e)throw'unknown key "'+t+'" from querykeylst';o.push(e)}if(0==o.length)throw"no valid keys in querykeylst"}else if(!e.issampleattribute)throw"unknown way to query a feature";if(e.isgenevalue){const[o,i]=Xs(e,n,t,r);if(o)throw"error with isgenevalue: "+o;s.push(i)}else if(e.iscnv){const[o,i]=Qs(e,n,t,r);if(o)throw"error with iscnv: "+o;s.push(i)}else if(e.isloh){const[o,i]=to(e,n,t,r);if(o)throw"error with isloh: "+o;s.push(i)}else if(e.isvcf){const[o,i]=oo(e,n,t,r);if(o)throw"error with isvcf: "+o;s.push(i)}else if(e.isitd){const[o,i]=eo(e,n,t,r);if(o)throw"error with isitd: "+o;s.push(i)}else if(e.issvfusion){const[o,i]=no(e,n,t,r);if(o)throw"error with issvfusion: "+o;s.push(i)}else if(e.issvcnv){const[o,i]=ro(e,n,t,r);if(o)throw"error with issvcnv: "+o;s.push(i)}else if(e.ismutation){const[t,i]=so(e,n,o,r);if(t)throw"error with ismutation: "+t;s.push(i)}else{if(!e.issampleattribute)throw"unknown type of feature";{const[t,o]=Ks(e,n,r);if(t)throw"error with issampleattribute: "+t;s.push(o)}}}return Promise.all(s)})).then((t=>{e.send({results:t})})).catch((t=>{e.send({error:"string"==typeof t?t:t.message}),t.stack&&console.error(t.stack)}))})),ks.get(qs+"/mdssamplescatterplot",(async function(t,e){try{const n=bs[t.query.genome];if(!n)throw"invalid genome";const r=n.datasets[t.query.dslabel];if(!r)throw"invalid dataset";if(!r.cohort)throw"no cohort for dataset";if(!r.cohort.annotation)throw"cohort.annotation missing for dataset";const s=r.cohort.scatterplot;if(!s)throw"scatterplot not supported for this dataset";const o=[];for(const e in r.cohort.annotation){const n=r.cohort.annotation[e];if(t.query.subsetkey&&n[t.query.subsetkey]!=t.query.subsetvalue)continue;const i=n[s.x.attribute];if(!Number.isFinite(i))continue;const a=n[s.y.attribute];Number.isFinite(a)&&o.push({sample:e,x:i,y:a,s:n})}e.send({colorbyattributes:s.colorbyattributes,colorbygeneexpression:s.colorbygeneexpression,querykey:s.querykey,dots:o,tracks:s.tracks})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/mdssamplesignature",(function(t,e){try{const n=t.query;if(!n.sample)throw".sample missing";const r=bs[n.genome];if(!r)throw"invalid genome";const s=r.datasets[n.dslabel];if(!s)throw"invalid dataset";if(!s.cohort)throw"no cohort for dataset";if(!s.cohort.mutation_signature)throw"no mutation_signature for cohort";const o=[];for(const t in s.cohort.mutation_signature.sets){const e=s.cohort.mutation_signature.sets[t];if(!e.samples)continue;const r=e.samples.map.get(n.sample);if(!r)continue;const i=[];for(const t in e.signatures)r[t]&&i.push({k:t,v:r[t]});i.length&&o.push({key:t,valuename:e.samples.valuename,annotation:i.sort(((t,e)=>e.v-t.v))})}e.send({lst:o})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/mdssurvivalplot",function(t){return async(e,n)=>{try{const r=e.query,s=t[r.genome];if(!s)throw"invalid genome";const o=s.datasets[r.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(e.query.init)return void n.send(i.init);if(!r.type)throw".type missing";const a=i.plots[r.type];if(!a)throw"unknown plot type: "+r.type;const l=function(t,e,n){if(!t.samplerule)throw".samplerule missing";if(!t.samplerule.full)throw".samplerule.full missing";const r=[];if(t.samplerule.full.byattr){const n=t.samplerule.full.key;if(!n)throw"key missing from samplerule.full{}";const s=t.samplerule.full.value;if(null==s)throw"value missing from samplerule.full{}";for(const t in e.cohort.annotation){const o=e.cohort.annotation[t];o[n]==s&&r.push({name:t,o})}}else if(t.samplerule.full.useall)for(const t in e.cohort.annotation){const n=e.cohort.annotation[t];r.push({name:t,o:n})}else{if(!t.samplerule.full.usesampleset)throw"unknown rule for samplerule.full";{const n=t.samplerule.full.sampleset;for(const t in n){const s=n[t],o=e.cohort.annotation[s];null!=o&&r.push({name:s,o})}}}const s=[];for(const t of r)Number.isFinite(t.o[n.serialtimekey])&&(t.serialtime=t.o[n.serialtimekey],t.censored=t.o[n.iscensoredkey],s.push(t));if(0==s.length)throw"no samples found for full set";return s}(r,o,a),c=await async function(t,e,n,r){if(e.samplerule.mutated_sets){const n=new Set(t.map((t=>t.name))),r=e.samplerule.mutated_sets.reduce(((e,r)=>{const s=new Set(r.samplenames);r.lst=t.filter((t=>s.has(t.name)));for(const t of r.samplenames)n.delete(t);return delete r.samplenames,e.push(r),e}),[]);return r.push({name:"No mutation (n="+n.size+")",lst:t.filter((t=>n.has(t.name))),is_notmutated:!0}),r}const s=e.samplerule.set;if(!s)return[{name:"All",lst:t}];if(s.geneexpression){if(!s.gene)throw".gene missing from samplerule.set";if(!s.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(s.start))throw".start not integer from samplerule.set";if(!Number.isInteger(s.stop))throw".start not integer from samplerule.set";if(s.bymedian)return await async function(t,e,n,r){const s=e.samplerule.set,[o,i]=await is(t,e,n),a=Math.ceil(i.length/2),l=i[a-1].genevalue;return[{name:s.gene+" "+o.datatype+" below median (n="+a+", value<"+l+")",lst:i.slice(0,a)},{name:s.gene+" "+o.datatype+" above median (n="+(i.length-a)+", value>="+l+")",lst:i.slice(a,i.length)}]}(t,e,n);if(s.byquartile)return await async function(t,e,n,r){const s=e.samplerule.set,[o,i]=await is(t,e,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:s.gene+" "+o.datatype+" from 1st quartile (n="+a+", value<"+u+")",lst:i.slice(0,a),isfirstquartile:!0},{name:s.gene+" "+o.datatype+" from 2nd quartile (n="+(l-a)+", "+u+"<=value<"+f+")",lst:i.slice(a,l)},{name:s.gene+" "+o.datatype+" from 3rd quartile (n="+(c-l)+", "+f+"<=value<"+d+")",lst:i.slice(l,c)},{name:s.gene+" "+o.datatype+" from 4th quartile (n="+(i.length-c)+", value>="+d+")",lst:i.slice(c,i.length),isfourthquartile:!0}]}(t,e,n)}if(s.mutation){if(!s.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(s.start))throw".start not integer from samplerule.set";if(!Number.isInteger(s.stop))throw".start not integer from samplerule.set";return await async function(t,e,n){const r=e.samplerule.set;if(r.samples_snvindel=new Set,r.samples_cnv=new Set,r.samples_loh=new Set,r.samples_sv=new Set,r.samples_fusion=new Set,r.samples_itd=new Set,r.cnv&&!r.snvindel&&!r.loh&&!r.sv&&!r.fusion&&!r.itd){const[r,s]=await rs(t,e,n,!0),o=[],i=[],a=[];for(const e of t)r.has(e.name)?o.push(e):s.has(e.name)?i.push(e):a.push(e);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 s=await rs(t,e,n),o=[];for(const e of t)s.find((t=>t.name==e.name))||o.push(e);const i=[];s.length&&i.push({name:"With mutation (n="+s.length+")",lst:s});o.length&&i.push({name:"No mutation (n="+o.length+")",lst:o});return i}(t,e,n)}throw"unknown rule for samplerule.set{}"}(l,r,o);let u;c.length>1&&(u=await ns(c)),await async function(t,e){if(!t.samplerule.mutated_sets)return;const n=e.find((t=>t.is_notmutated));if(!n)return;for(const t of e){if(t.is_notmutated)continue;const e=await ns([t,n]);t.pvalue=e}}(r,c),await async function(t,e){if(!t.samplerule.set)return;if(!t.samplerule.set.geneexpression)return;if(!t.samplerule.set.byquartile)return;if(4!=e.length)return;if(t.samplerule.set.against1st){for(let t=1;t<4;t++)e[t].pvalue=await ns([e[0],e[t]]);return}if(t.samplerule.set.against4th){for(let t=0;t<3;t++)e[t].pvalue=await ns([e[t],e[3]]);return}}(r,c);for(const t of c)as(t),delete t.lst;const f={samplesets:c,pvalue:u};r.samplerule.set&&r.samplerule.set.mutation&&(f.count_snvindel=r.samplerule.set.samples_snvindel.size,f.count_cnv=r.samplerule.set.samples_cnv.size,f.count_loh=r.samplerule.set.samples_loh.size,f.count_sv=r.samplerule.set.samples_sv.size,f.count_fusion=r.samplerule.set.samples_fusion.size,f.count_itd=r.samplerule.set.samples_itd.size),n.send(f)}catch(t){t.stack&&console.error(t.stack),n.send({error:t.message||t})}}}(bs)),ks.post(qs+"/fimo",function(t){return async(e,n)=>{try{const r=e.query;if(!r.m)throw"no mutation";if(!r.m.chr)throw"mutation chr missing";if(!Number.isInteger(r.m.pos))throw"mutation position is not integer";if(!r.m.ref)throw"mutation ref allele missing";if(!r.m.alt)throw"mutation alt allele missing";const s=t[r.genome];if(!s)throw"invalid genome";if(!s.fimo_motif)throw"motif finding not supported on this genome";const o=await async function(t,e){const n=t.m.pos-t.flankspan,r=t.m.pos+t.flankspan,s=await F.Kf(e,t.m.chr+":"+n+"-"+r);!function(t,e,n){if(!t.m.ref)return;if("-"==t.m.ref)return;const r=n.split("\n").slice(1).join("").toUpperCase(),s=r.substring(t.m.pos-e,t.m.pos-e+t.m.ref.length);if(s==t.m.ref.toUpperCase())return;if(common.reversecompliment(s)==t.m.ref.toUpperCase())t.m.ref=s,"-"!=t.m.alt&&(t.m.alt=common.reversecompliment(t.m.alt))}(t,n,s);const o=await Qr(t,e,s),i=new Map;for(const t of o)t.pvalue_ref=t.pvalue,delete t.pvalue,t.logpvalue_ref=t.logpvalue,delete t.logpvalue,i.has(t.name)||i.set(t.name,[]),i.get(t.name).push(t);const a=function(t,e,n,r){const s=r.split("\n"),o=s.slice(1).join("");return s[0]+"\n"+o.substr(0,t.pos-e)+("-"==t.alt?"":t.alt)+o.substr(t.pos-e+("-"==t.ref?0:t.ref.length))}(t.m,n,0,s),l=await Qr(t,e,a);for(const t of l){t.pvalue_alt=t.pvalue,delete t.pvalue,t.logpvalue_alt=t.logpvalue,delete t.logpvalue,i.has(t.name)||i.set(t.name,[]);let e=!0;for(const n of i.get(t.name))if(null!=n.logpvalue_ref&&n.strand==t.strand&&Math.abs(t.start-n.start)<=2&&Math.abs(t.stop-n.stop)<=2){n.pvalue_alt=t.pvalue_alt,n.logpvalue_alt=t.logpvalue_alt,n.logpvaluediff=t.logpvalue_alt-n.logpvalue_ref,n.logpvaluediff>0?n.gain=!0:n.loss=!0,e=!1;break}e&&i.get(t.name).push(t)}let c=0,u=0;const f=[];for(const e of i.values())for(const n of e)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!=t.minabslogp&&Math.abs(n.logpvaluediff)<t.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:r,refseq:s.split("\n").slice(1).join("")}}(r,s);n.send(o)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(bs)),ks.all(qs+"/termdb",X.TO(bs)),ks.all(qs+"/termdb-barsql",ot.TO(bs)),ks.post(qs+"/singlecell",function(t){return async(e,n)=>{try{const r=e.query,s=t[r.genome];if(!s)throw"invalid genome";if(r.getpcd)return void await async function(t,e){const n={},r=await async function(t,e){if(!t.textfile)throw".textfile missing";{const[e,n,r]=F.ZX({query:{file:t.textfile}});if(e)throw".textfile error: "+e;if(!r){if(await F.yE(n))throw"file not exist: "+t.textfile;if(await F.t7(n))throw"file not readable: "+t.textfile}t.textfile=n}let n,r,s,o,i;if(t.getpcd.category_autocolor){const e=t.getpcd.values_count&&t.getpcd.values_count<=10?zr.Z:Wr;n=$r.Z(e),s={},o={}}else if(t.getpcd.category_customcolor){const e=$r.Z(Wr);a=t.getpcd.cat_values,l=e,n=t=>{let e=!1;for(const n of a)if(n.value==t)return e=!0,n.color;if(!e)return l(t)},s={},o={},i={}}else if(t.getpcd.gene_expression){const n=t.getpcd.gene_expression;if(!n.file)throw"gene_expression.file missing";{const[t,e,r]=F.ZX({query:{file:n.file}});if(t)throw t;n.file=e}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 s=(n.nochr?n.chr.replace("chr",""):n.chr)+":"+n.start+"-"+n.stop,o=new Map;r=new Map;let i=0,a=0;if(e.numbercellwithgeneexp=0,e.numbercelltotal=0,await F.UE({args:[n.file,s],callback:t=>{const r=JSON.parse(t.split("\t")[3]);r.gene==n.genename&&Number.isFinite(r.value)&&(e.numbercellwithgeneexp++,n.autoscale&&(i=Math.min(i,r.value),a=Math.max(a,r.value)),o.set(r.sample,r.value))}}),n.autoscale){e.minexpvalue=i,e.maxexpvalue=a;const t=bt.ZP(n.color_min,n.color_max);for(const[e,n]of o){const s=tt.ZP(t((n-i)/(a-i)));r.set(e,Number.parseInt(Yr(s.r,s.g,s.b),16))}}}var a,l;return new Promise(((i,a)=>{const l=[],c=O().createInterface({input:m().createReadStream(t.textfile)});let u=!0,f=0,d=0;c.on("line",(i=>{if(u)return void(u=!1);const a=i.split(t.delimiter),c=[];for(const e of t.getpcd.coord)c.push(a[e]),f=Math.max(f,a[e]),d=Math.min(d,a[e]);if(2==t.getpcd.coord.length&&c.push("0"),n){const e=a[t.getpcd.category_index],r=n(e);if(t.hidden_types.includes(e))if(t.background_color){const e=tt.ZP(t.background_color),n=Number.parseInt(Yr(e.r,e.g,e.b),16);c.push(n)}else c.push(16777215);else c.push(Number.parseInt(r.slice(1),16));s&&(s[e]=r),o&&(o[e]=e in o?o[e]+1:1)}else if(r){e.numbercelltotal++;const n=a[t.getpcd.gene_expression.barcodecolumnidx];let s=r.get(n);if(void 0===s)if(t.getpcd.gene_expression.color_no_exp){const e=tt.ZP(t.getpcd.gene_expression.color_no_exp);s=Number.parseInt(Yr(e.r,e.g,e.b),16)}else s="2894892";c.push(s)}l.push(c.join(" "))})),c.on("close",(()=>{s&&(t.getpcd.category_customorder&&(s=function(t,e){let n={};const r=Object.keys(t).length;for(var s=1;s<=r;s++){const r=e.find((t=>{if(t.order==s)return t.value}));r&&(n[r.value]=t[r.value])}for(const r of e)r.order||(n[r.value]=t[r.value]);for(const r in t){e.find((t=>{if(t.value==JSON.stringify(r))return!0}))||(n[r]=t[r])}return n}(s,t.getpcd.cat_values)),e.category2color=s,e.categorycount=o),e.data_sphere_r=Math.max(Math.abs(f),Math.abs(d)),i(l)}))}))}(t,n),s="# .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=s+r.join("\n"),e.send(n)}(r,n);if(r.getgeneboxplot)return void await async function(t,e,n){const r=t.getgeneboxplot,s=t.getgeneboxplot.values_count&&t.getgeneboxplot.values_count<=10?$r.Z(zr.Z):$r.Z(Wr);if(!r.expfile)throw"getgeneboxplot.expfile missing";{const[t,e,n]=F.ZX({query:{file:r.expfile}});if(t)throw"getgeneboxplot.expfile error: "+t;r.expfile=e}if(!r.chr)throw"getgeneboxplot.chr missing";if(!r.start)throw"getgeneboxplot.start missing";if(!r.stop)throw"getgeneboxplot.stop missing";if(!r.genename)throw"getgeneboxplot.genename missing";const o=await Kr(r),i=(r.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop;let a=0,l=0;await F.UE({args:[r.expfile,i],callback:t=>{const e=JSON.parse(t.split("\t")[3]);if(e.gene!=r.genename)return;if(!e.sample)return;if(!Number.isFinite(e.value))return;const n=o.get(e.sample);n&&(n.expvalue=e.value,a=Math.min(a,e.value),l=Math.max(l,e.value))}});const c=new Map;for(const[t,e]of o)c.has(e.category)||c.set(e.category,[]),r.exclude_cells&&0==parseInt(e.expvalue)||c.get(e.category).push({value:e.expvalue});const u=[],f=(d=Fn.Z().domain([a,l]).ticks(20),t=>{const e=[];for(let t=1;t<d.length;t++)e.push(0);for(const n of t)for(let t=1;t<d.length;t++)if(n.value<=d[t]){e[t-1]++;break}return e});var d;for(const[t,e]of c){e.sort(((t,e)=>t.value-e.value));const n=F.JC(e);delete n.out;const r=s(t);n.category=t,n.color=r,n.numberofcells=e.length,n.density=f(e),u.push(n)}let h=[];if(t.getgeneboxplot.cat_values){const e=Object.keys(t.getgeneboxplot.cat_values).length;for(var p=1;p<=e;p++){const e=t.getgeneboxplot.cat_values.find((t=>{if(t.order==p)return t.value}));e&&h.push(u.filter((t=>t.category==e.value))[0])}for(const e of t.getgeneboxplot.cat_values)e.order||h.push(u.filter((t=>t.category==e.value))[0]);for(const e of u){t.getgeneboxplot.cat_values.find((t=>{if(t.value==e.category)return!0}))||h.push(e)}for(const e of h){const n=t.getgeneboxplot.cat_values.find((t=>{if(t.value==e.category)return t}));n&&n.color&&(e.color=n.color)}}else h=u;n.send({boxplots:h,minexpvalue:a,maxexpvalue:l})}(r,0,n);if(r.getheatmap)return void await async function(t,e,n){const r=t.getheatmap,s=[];if(!r.expfile)throw"getgeneboxplot.expfile missing";{const[t,e,n]=F.ZX({query:{file:r.expfile}});if(t)throw"getgeneboxplot.expfile error: "+t;r.expfile=e}r.gene_list.forEach((t=>{if(!t.chr)throw"getgeneboxplot.chr missing";if(!t.start)throw"getgeneboxplot.start missing";if(!t.stop)throw"getgeneboxplot.stop missing";if(!t.gene)throw"getgeneboxplot.genename missing"}));const o=await Kr(r);for(const t of r.gene_list){const e=(t.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;let n=0,i=0;const a=t.gene;await F.UE({args:[r.expfile,e],callback:e=>{const r=JSON.parse(e.split("\t")[3]);if(r.gene.toUpperCase()!==t.gene.toUpperCase())return;if(!r.sample)return;if(!Number.isFinite(r.value))return;const s=o.get(r.sample);s&&(s.expvalue=r.value,n=Math.min(n,r.value),i=Math.max(i,r.value))}});const l=new Map;for(const[t,e]of o)l.has(e.category)||l.set(e.category,[]),l.get(e.category).push({value:e.expvalue});const c=[];for(const[t,e]of l){let n=0;for(const t of e)n+=t.value;const r=e.length,s=(n/r).toFixed(3);c.push({category:t,mean:s,numberofcells:r})}s.push({genename:a,heatmap:c})}n.send({gene_heatmap:s})}(r,0,n)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(bs)),ks.post(qs+"/massSession",(async function(t,e){try{const n=t.body.__sessionFor__,{filename:r,route:o,dslabel:i,embedder:a}=n||{};let l;if(r){const e={headers:t.headers,query:n};if(l=Jr.i.getPayloadFromHeaderAuth(e,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 t.body.__sessionFor__}const c=r||function(){const t=[];for(;t.length<15;){const e=46+Math.floor(80*Math.random());(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)&&t.push(String.fromCharCode(e))}return t.join("")}(),u=JSON.stringify(t.body),f=r?Hr(n,l):s().cachedir_massSession;await m().promises.access(f).then((()=>!0)).catch((()=>!1))||m().mkdirSync(f,{recursive:!0}),await F.Sf(y().join(f,c),u),e.send({id:c})}catch(t){e.send({error:t.message||t})}})),ks.get(qs+"/massSession",(async function(t,e){try{const n=t.query.id;if(!n)throw"session id missing";const{route:r,dslabel:o,embedder:i}=t.query,a=t.query.route?Jr.i.getPayloadFromHeaderAuth(t,t.query.route):null,l=t.query.route?Hr(t.query,a):s().cachedir_massSession,c=y().join(l,n);let u;try{u=(await m().promises.stat(c)).birthtime}catch(t){throw"invalid session"}const f=await F.b5(c),d=JSON.parse(f);if(t.query.route)return void e.send({state:d});const h=new Date,p=new Date(u),g=s().features.massSessionDuration||30,b=g-Math.round((h.getTime()-p.getTime())/864e5);e.send({state:d,sessionDaysLeft:b,massSessionDuration:g})}catch(t){e.send({error:t.message||t})}})),ks.delete(qs+"/massSession",(async function(t,e){try{const n=t.query.ids;if(!n)throw"session ids[] missing";const{route:r,dslabel:o,embedder:i}=t.query,a=t.query.route?Jr.i.getPayloadFromHeaderAuth(t,t.query.route):null;if(!a)throw"missing credentials";const l=t.query.route?Hr(t.query,a):s().cachedir_massSession,c=[];for(const t of n){const e=y().join(l,t);m().unlink(e,(t=>{if(t)throw c.push(t),t}))}c.length||e.send({status:"ok"})}catch(t){e.send({error:t.message||t})}})),ks.get(qs+"/sessionIds",(async function(t,e){try{const{filename:n,route:r,dslabel:s,embedder:o}=t.query,i=Jr.i.getPayloadFromHeaderAuth(t,r);if(!i.email)throw"invalid credentials: no jwt.email";if(i.dslabel!=s||i.route!=r||i.embedder!=o)throw"invalid credentials: mismatched payload";const a=Hr(t.query,i);if(!await m().promises.access(a).then((()=>!0)).catch((()=>!1)))return void e.send({status:"ok",sessionIds:[]});const l=await m().promises.readdir(a);e.send({status:"ok",sessionIds:l})}catch(t){e.status(401),e.send({error:t.message||t})}})),ks.get(qs+"/isoformbycoord",(async function(t,e){try{const n=bs[t.query.genome];if(!n)throw"invalid genome";if(!t.query.chr)throw"chr missing";const r=Number(t.query.pos);if(!Number.isInteger(r))throw"pos must be positive integer";const o=n.tracks.find((t=>t.__isgene));o||reject("no gene track");const i=[];await F.UE({args:[y().join(s().tpmasterdir,o.file),t.query.chr+":"+r+"-"+r],callback:t=>{const e=t.split("\t")[3];if(!e)return;const r=JSON.parse(e);if(!r.isoform)return;const s={isoform:r.isoform},o=n.genedb.getjsonbyisoform.get(r.isoform);o&&(s.name=JSON.parse(o.genemodel).name,s.isdefault=o.isdefault),i.push(s)}}),e.send({lst:i})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/ase",(async function(t,e){const n=t.query,r=3e6,o=5e5;try{const t=bs[n.genome];if(!t)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=Us(n.checkrnabam);if(i)throw i;if(n.refcolor||(n.refcolor="blue"),n.altcolor||(n.altcolor="red"),!t.tracks)throw"genome.tracks[] missing";const a=t.tracks.find((t=>t.__isgene));if(!a)throw"no gene track from this genome";await async function(t,e){if(t.rnabamfile)t.rnabamfile=y().join(s().tpmasterdir,t.rnabamfile);else{if(!t.rnabamurl)throw"no file or url for rna bam";t.rnabamurl_dir=await F.d1(t.rnabamurl,t.rnabamindexURL||t.rnabamurl+".bai")}if(t.rnabam_nochr=await F.Dp(t.rnabamfile||t.rnabamurl,e,t.rnabamurl_dir),t.vcffile)t.vcffile=y().join(s().tpmasterdir,t.vcffile);else{if(!t.vcfurl)throw"no file or url for vcf";t.vcfurl_dir=await F.d1(t.vcfurl,t.vcfindexURL)}t.vcf_nochr=await F.Jy(t.vcffile||t.vcfurl,t.vcfurl_dir,e)}(n,t);const l=await Hs(t,a,n.chr,n.start,n.stop),c={};if(n.stop-n.start<r)for(const[t,e]of l){const t={file:n.rnabamfile,url:n.rnabamurl,dir:n.rnabamurl_dir,nochr:n.rnabam_nochr};let r;r=n.rnabamispairedend?await Ds(t,n.chr,e):await Ps(t,n.chr,e),e.fpkm=1e9*r/(n.rnabamtotalreads*e.exonlength)}else c.fpkmrangelimit=r;const[u,f,d,h]=function(t,e){let n=t.start,r=t.stop;for(const[t,s]of e)n=Math.min(n,s.start),r=Math.max(r,s.stop);const s=t.start,o=t.stop;return[n,r,s,o]}(n,l),p=await async function(t,e,n,r,s){const o=await Vs(t.vcffile||t.vcfurl,t.vcfurl_dir),[i,a,l,c]=D.e(o);if(c)throw c;const u={info:i,format:a,samples:l},f=await Ws(t.vcffile||t.vcfurl,(t.vcf_nochr?t.chr.replace("chr",""):t.chr)+":"+r+"-"+s,t.vcfurl_dir),d=[];for(const e of f||[]){const[n,r,s]=D.S(e,u);for(const e of r){if(!P.basecolor[e.ref]||!P.basecolor[e.alt])continue;if(!e.sampledata)continue;const n=Js(e,t.samplename,t.checkrnabam);n&&d.push(n)}}const h=[];for(const t of d)for(const[e,r]of n)if(t.pos>=r.start&&t.pos<=r.stop){h.push(t);break}return h}(n,0,l,u,f);for(const t of p)t.rnacount={nocoverage:1};let g,b;h-d>=o?c.covplotrangelimit=o:(n.rnamax?g=n.rnamax:(g=await async function(t,e,n){let r=0;return await F.UE({isbam:!0,args:["depth","-r",(t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(e+1)+"-"+(n+1),"-g","DUP",t.rnabamurl||t.rnabamfile],dir:t.rnabamurl_dir,callback:t=>{const e=t.split("\t");if(3!=e.length)return;const n=Number.parseInt(e[2]);Number.isInteger(n)&&(r=Math.max(r,n))}}),r}(n,d,h),c.rnamax=g),b=await async function(t,e,n,r,s){const o=new Map;for(const t of r)t.dnacount.ishet&&t.pos>=e&&t.pos<=n&&o.set(t.pos,t);const i=(0,S.createCanvas)(t.width*t.devicePixelRatio,(t.rnabarheight+t.barypad+t.dnabarheight)*t.devicePixelRatio),a=i.getContext("2d");t.devicePixelRatio>1&&a.scale(t.devicePixelRatio,t.devicePixelRatio);let l,c,u=!1;n-e<=t.width?(u=!0,l=1,c=t.width/(n-e),a.lineWidth=c):(c=1,l=(n-e)/t.width);return await F.UE({isbam:!0,args:["depth","-r",(t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(e+1)+"-"+(n+1),"-g","DUP",t.rnabamurl||t.rnabamfile],dir:t.rnabamurl_dir,callback:n=>{const r=n.split("\t");if(3!=r.length)return;const i=Number.parseInt(r[1])-1;if(!Number.isInteger(i))return;const f=Number.parseInt(r[2]);if(!Number.isInteger(f))return;const d=t.rnabarheight*Math.min(f,s)/s,h=u?(i-e)*c:(i-e)/l;a.strokeStyle="#ccc",a.beginPath(),a.moveTo(h+c/2,t.rnabarheight),a.lineTo(h+c/2,t.rnabarheight-d),a.stroke(),a.closePath(),f>s&&(a.strokeStyle="blue",a.beginPath(),a.moveTo(h+c/2,0),a.lineTo(h+c/2,2),a.stroke(),a.closePath());const p=o.get(i);p&&(p.rnacount.h=d)}}),{canvas:i,ctx:a,isbp:u,binpxw:c,binbpsize:l}}(n,d,h,p,g)),c.coveragesrc=await function(t,e,n,r,s,o,i,a){const l=[];for(const n of e)n.dnacount.ishet&&l.push((t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(n.pos+1)+"-"+(n.pos+1));return new Promise(((n,r)=>{const c=(0,q.spawn)(_s,["mpileup","-q",t.checkrnabam.rnapileup_q,"-Q",t.checkrnabam.rnapileup_Q,"--no-reference","-a","INFO/AD","-d",999999,"-r",l.join(","),t.rnabamurl||t.rnabamfile],{cwd:t.rnabamurl_dir});O().createInterface({input:c.stdout}).on("line",(t=>{if("#"==t[0])return;const n=Gs(t);if(!n)return;let r;n.pos>=s&&n.pos<=o&&n.DP;const i=e.find((t=>t.pos==n.pos));if(i){i.__x=r;const t=n.allele2count[i.ref]||0,e=n.allele2count[i.alt]||0;t+e>0&&(delete i.rnacount.nocoverage,i.rnacount.ref=t,i.rnacount.alt=e,i.rnacount.f=e/(t+e))}})),c.on("close",(()=>{if(!i)return void n();const{canvas:r,ctx:l,binpxw:c}=i;l.lineWidth=Math.max(3,c);let u=0;for(const n of e)n.dnacount&&(n.pos<s||n.pos>o||(n.__x=t.width*(n.pos-s)/(o-s),u=Math.max(u,n.dnacount.ref+n.dnacount.alt)));for(const n of e){if(null==n.__x)continue;n.rnacount.nocoverage||(null==n.rnacount.h&&(n.rnacount.h=t.rnabarheight*(n.rnacount.ref+n.rnacount.alt)/a),l.strokeStyle=t.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight),l.lineTo(n.__x+c/2,t.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.stroke(),l.closePath(),l.strokeStyle=t.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.lineTo(n.__x+c/2,t.rnabarheight-n.rnacount.h),l.stroke(),l.closePath());const e=t.dnabarheight*(n.dnacount.ref+n.dnacount.alt)/u;n.dnacount.ishet&&(l.strokeStyle=t.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight+t.barypad),l.lineTo(n.__x+c/2,t.rnabarheight+t.barypad+(1-n.dnacount.f)*e),l.stroke(),l.closePath(),l.strokeStyle=t.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight+t.barypad+(1-n.dnacount.f)*e),l.lineTo(n.__x+c/2,t.rnabarheight+t.barypad+e),l.stroke(),l.closePath()),delete n.__x}n(r.toDataURL())}))}))}(n,p,0,0,d,h,b,g),await async function(t,e){if(0==t.length)return;const n=[];for(const r of t)r.rnacount.nocoverage||r.rnacount.ref+r.rnacount.alt<e.checkrnabam.rna_mintotalreads||n.push(r);if(0==n.length)return;const r=await function(t){const e=y().join(s().cachedir,Math.random().toString())+".snp",n=[];for(const e of t)e.rnacount.nocoverage||null!=e.rnacount.ref&&null!=e.rnacount.alt&&n.push(e.pos+"."+e.ref+"."+e.alt+"\t\t\t\t\t\t\t\t"+e.rnacount.ref+"\t"+e.rnacount.alt);return new Promise(((t,r)=>{m().writeFile(e,n.join("\n")+"\n",(n=>{n&&r("cannot write"),t(e)}))}))}(n),o=await Bs(r);await function(t,e){return new Promise(((n,r)=>{m().readFile(e,"utf8",((e,s)=>{e&&r("cannot read binom pvalue"),s||n();for(const e of s.trim().split("\n")){const n=e.split("\t"),r=t.find((t=>n[0]==t.pos+"."+t.ref+"."+t.alt));r&&(r.rnacount.pvalue=Number.parseFloat(n[10]))}n()}))}))}(t,o),m().unlink(r,(()=>{})),m().unlink(o,(()=>{}))}(p,n),c.genes=function(t,e,n){const r=[];for(const[s,o]of e){r.push(o);const e=t.filter((t=>t.pos>=o.start&&t.pos<=o.stop));if(0==e.length){o.nosnp=1;continue}o.snps=e;const s=e.filter((t=>null!=t.rnacount.pvalue));if(0==s.length){o.nornasnp=1;continue}const i=s.reduce(((t,e)=>t+Math.abs(e.rnacount.f-.5)),0);let a=null,l=0;for(const t of s)null==a?a=t.rnacount.pvalue:a*=t.rnacount.pvalue,t.rnacount.pvalue<=n.checkrnabam.binompvaluecutoff&&l++;o.ase={markers:e.filter((t=>t.dnacount.ishet)).length,ase_markers:l,mean_delta:i/s.length,geometricmean:Math.pow(a,1/s.length)}}return r}(p,l,n);let v=0;for(const t of p)t.dnacount&&t.pos>=d&&t.pos<=h&&(v=Math.max(v,t.dnacount.ref+t.dnacount.alt));c.dnamax=v,e.send(c)}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.post(qs+"/bamnochr",(async function(t,e){const n=t.query;try{const t=bs[n.genome];if(!t)throw"invalid genome";if(n.file)n.file=y().join(s().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 r=await F.Dp(n.file||n.url,t,n.url_dir);e.send({nochr:r})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),ks.get(qs+"/gene2canonicalisoform",(function(t,e){try{if(!t.query.gene)throw".gene missing";const n=bs[t.query.genome];if(!n)throw"unknown genome";if(!n.genedb.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const r=n.genedb.get_gene2canonicalisoform.get(t.query.gene);e.send(r)}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),ks.get(qs+"/ideogram",(function(t,e){try{const n=bs[t.query.genome];if(!n)throw"invalid genome";if(!n.genedb.hasIdeogram)throw"ideogram not supported on this genome";if(!t.query.chr)throw".chr missing";const r=n.genedb.getIdeogramByChr.all(t.query.chr);if(!r.length)throw"no ideogram data for this chr";e.send(r)}catch(t){e.send({error:t.message||t})}}));F.lY,F.ZX;function ao(t){const e=t.split(/\r?\n/);if(e.length<=1||!e[0])return[null,[]];const n=e[0].split("\t"),r=[];for(let t=1;t<e.length;t++){if("#"==e[t][0])continue;const s=e[t].split("\t"),o={};for(let t=0;t<n.length;t++){const e=s[t];e&&(o[n[t]]=e)}r.push(o)}return[null,r]}async function lo(t){try{await m().promises.stat(t.tpmasterdir)}catch(e){const n="Error with "+t.tpmasterdir+": "+e.code;if("validate"==process.argv[2])throw n;return void console.log("\n!!! "+n+"\n")}if(function(){if(s().features.skip_checkDependenciesAndVersions)return void console.log("SKIPPED checkDependenciesAndVersions()");const t=["jsonlite","cmprsk","hwde","lmtest"];for(const e of t){const t=N().spawnSync(s().Rscript,["-e",`suppressPackageStartupMessages(library("${e}"))`],{encoding:"utf8"});if(t.stderr.trim())throw t.stderr}const e=10;{const t=N().execSync(s().samtools+" --version",{encoding:"utf8"}).trim().split("\n"),[n,r]=t[0].split(" ");if("samtools"!=n||!r)throw'cannot run "samtools version"';const[o,i]=r.split(".");if("1"!=o)throw"samtools not 1.*";if(Number(i)<e)throw`samtools not >= 1.${e}`}{const t=N().execSync(s().bcftools+" -v",{encoding:"utf8"}).trim().split("\n"),[n,r]=t[0].split(" ");if("bcftools"!=n||!r)throw'cannot run "bcftools version"';const[o,i]=r.split(".");if("1"!=o)throw"bcftools not 1.*";if(Number(i)<e)throw`bcftools not >= 1.${e}`}}(),null!=t.base_zindex){const e=Number.parseInt(t.base_zindex);if(Number.isNaN(e)||e<=0)throw"base_zindex must be positive integer";t.base_zindex=e}if(t.jwt){if(!t.jwt.secret)throw"jwt.secret missing";if(!t.jwt.permissioncheck)throw"jwt.permissioncheck missing"}if(!t.tpmasterdir)throw".tpmasterdir missing";if(!t.cachedir)throw".cachedir missing";if(t.cachedir_massSession=await fo("massSession"),t.cachedir_massSessionTrash=await fo("massSessionTrash"),t.cache_snpgt={dir:await fo("snpgt"),fileNameRegexp:/[^\w]/,sampleColumn:6},t.cachedir_bam=await fo("bam"),t.cachedir_genome=await fo("genome"),t.cachedir_ssid=await fo("ssid"),t.commonOverrides&&P.applyOverrides(t.commonOverrides),!t.genomes)throw".genomes[] missing";if(!Array.isArray(t.genomes))throw".genomes[] not array";for(const e of t.genomes){if(!e.name)throw".name missing from a genome: "+JSON.stringify(e);if(!e.file)throw".file missing from genome "+e.name;const n=y().join(process.cwd(),e.file),r=require(m().existsSync(n)?n:e.file),s=r.default||r;if(bs[e.name]=s,!s.genomefile)throw".genomefile missing from .js file of genome "+e.name;if("NA"==s.genomefile||(s.genomefile=y().join(t.tpmasterdir,s.genomefile)),s.genomicNameRegexp||(s.genomicNameRegexp=/[^a-zA-Z0-9.:_-]/),s.tracks||(s.tracks=[]),e.tracks)for(const t of e.tracks)s.tracks.push(t);if(e.datasets&&(s.rawdslst=e.datasets),e.snp&&(s.snp=e.snp),e.blat){if(!e.blat.host)throw".blat.host missing for "+e.name;if(!e.blat.port)throw".blat.port missing for "+e.name;s.blat=e.blat}if(e.nosnp&&delete s.snp,e.nohicenzyme&&delete s.hicenzymefragment,e.nohicdomain&&delete s.hicdomain,s.genedb&&e.no_gene2canonicalisoform&&delete s.genedb.gene2canonicalisoform,e.updateAttr)for(const t of e.updateAttr){let e=s;for(const[n,r]of t.entries())if(e)if("object"==typeof r)for(const t in r)e[t]=r[t];else{if("string"==typeof e[r]){t[n+1]&&(e[r]=t[n+1]);break}e=e[r]}}}t.defaultgenome&&bs[t.defaultgenome]&&(bs[t.defaultgenome].isdefault=!0);for(const e in bs){const n=bs[e];if(!n.majorchr)throw e+": majorchr missing";if(!n.defaultcoord)throw e+": 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 t=n.majorchr.trim().split(/[\s\t\n]+/),r={},s=[];for(let n=0;n<t.length;n+=2){const o=t[n],i=Number.parseInt(t[n+1]);if(Number.isNaN(i))throw e+" majorchr invalid chr size for "+o+" ("+t[n+1]+")";r[o]=i,s.push(o)}n.majorchr=r,n.majorchrorder=s}n.chrlookup={};for(const t in n.majorchr)n.chrlookup[t.toUpperCase()]={name:t,len:n.majorchr[t],major:!0};if(n.minorchr){if("string"==typeof n.minorchr){const t=n.minorchr.trim().split(/[\s\t\n]+/),r={};for(let n=0;n<t.length;n+=2){const s=Number.parseInt(t[n+1]);if(Number.isNaN(s))throw e+" minorchr invalid chr size for "+t[n]+" ("+t[n+1]+")";r[t[n]]=s}n.minorchr=r}for(const t in n.minorchr)n.chrlookup[t.toUpperCase()]={name:t,len:n.minorchr[t]}}if(n.genedb){if(!n.genedb.dbfile)throw e+": .genedb.dbfile missing";try{console.log("Connecting",n.genedb.dbfile),n.genedb.db=F.sE(n.genedb.dbfile)}catch(t){throw`Cannot connect genedb: ${n.genedb.dbfile}: ${t}`}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 t=(0,Kn.jj)(n.genedb.db);t.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=?")),t.has("gene2coord")&&(n.genedb.getCoordByGene=n.genedb.db.prepare("select * from gene2coord where name=?")),t.has("ideogram")?(n.genedb.hasIdeogram=!0,n.genedb.getIdeogramByChr=n.genedb.db.prepare("select * from ideogram where chromosome=?")):n.genedb.hasIdeogram=!1,t.has("gene2canonicalisoform")&&(n.genedb.get_gene2canonicalisoform=n.genedb.db.prepare("select isoform from gene2canonicalisoform where gene=?")),t.has("buildDate")&&(n.genedb.get_buildDate=n.genedb.db.prepare("select date from buildDate")),n.genedb.hasTable_refseq2ensembl=t.has("refseq2ensembl"),n.genedb.sqlTables=[...t],n.genedb.tableSize={};for(const e of t)"buildDate"!=e&&(n.genedb.tableSize[e]=n.genedb.db.prepare(`select count(*) as size from ${e}`).get().size)}if(n.termdbs)for(const t in n.termdbs)(0,Kn.JV)(n.termdbs[t],ys),console.log(`${t} initiated as ${e}-level termdb`);for(const e of n.tracks)if(e.__isgene){if(!e.file)throw"Tabix file missing for gene track: "+JSON.stringify(e);try{await F.LC(y().join(t.tpmasterdir,e.file))}catch(t){throw"Error with "+e.file+": "+t}}if(n.proteindomain){if(!n.proteindomain.dbfile)throw e+".proteindomain: missing dbfile for sqlite db";if(!n.proteindomain.statement)throw e+".proteindomain: missing statement for sqlite db";let t;try{console.log("Connecting",n.proteindomain.dbfile),t=F.sE(n.proteindomain.dbfile)}catch(t){throw"Error with "+n.proteindomain.dbfile+": "+t}n.proteindomain.getbyisoform=t.prepare(n.proteindomain.statement)}if(n.snp){if(!n.snp.bigbedfile)throw e+".snp: missing bigBed file";n.snp.bigbedfile=y().join(t.tpmasterdir,n.snp.bigbedfile),await F.Ic(n.snp.bigbedfile)}if(n.fimo_motif){if(!n.fimo_motif.db)throw e+".fimo_motif: db file missing";if(n.fimo_motif.db=y().join(t.tpmasterdir,n.fimo_motif.db),n.fimo_motif.annotationfile){const[e,r]=ao(m().readFileSync(y().join(t.tpmasterdir,n.fimo_motif.annotationfile),{encoding:"utf8"}).trim());n.fimo_motif.tf2attr={};for(const t of r)n.fimo_motif.tf2attr[t.Model.split("_")[0]]=t}}if(n.hicenzymefragment){if(!Array.isArray(n.hicenzymefragment))throw"hicenzymefragment should be an array";for(const e of n.hicenzymefragment){if(!e.enzyme)throw".enzyme missing for one element of hicenzymefragment[]";if(!e.file)throw".file missing for one element of hicenzymefragment[]";try{await F.LC(y().join(t.tpmasterdir,e.file))}catch(t){throw"Error with "+e.file+": "+t}}}if(n.hicdomain){if(!n.hicdomain.groups)throw".groups{} missing from hicdomain";for(const e in n.hicdomain.groups){const r=n.hicdomain.groups[e];if(!r.name)throw".name missing from hicdomain "+e;if(!r.sets)throw".set{} missing from hicdomain "+e;for(const n in r.sets){const s=r.sets[n];if(!s.name)throw".name missing from hicdomain "+e+" > "+n;if(!s.file)throw".file missing from hicdomain "+e+" > "+n;s.file=y().join(t.tpmasterdir,s.file);try{await F.LC(s.file)}catch(t){throw"Error with "+s.file+": "+t}}}}if(n.rawdslst){n.datasets={};for(const t of n.rawdslst){if(t.skip)continue;if(!t.name)throw"a nameless dataset from "+e;if(n.datasets[t.name])throw e+" has duplicating dataset name: "+t.name;if(!t.jsfile)throw"jsfile not available for dataset "+t.name+" of "+e;const r=y().join(process.cwd(),t.jsfile),s=require(m().existsSync(r)?r:t.jsfile),o="function"==typeof s?s(P):"function"==typeof s?.default?s.default(P):s.default||s;if(Xn(o,t),o.noHandleOnClient=t.noHandleOnClient,o.label=t.name,o.genomename=e,n.datasets[o.label]=o,o.isMds3)try{await cr(o,n,0,ks,qs)}catch(t){throw t.stack&&console.log(t.stack),"Error with mds3 dataset "+o.label+": "+t}else if(o.isMds)try{await po(o,n,t)}catch(t){throw"Error with mds dataset "+o.label+": "+t}else uo(o,n)}co(),delete n.rawdslst}}}async function co(){const t=await m().promises.readdir(s().cachedir_massSession);try{t.forEach((async t=>{const e=(await m().promises.stat(y().join(s().cachedir_massSession,t))).birthtime,n=new Date,r=new Date(e),o=s().features.massSessionDuration||30;Math.round((n.getTime()-r.getTime())/864e5)>o&&(await m().promises.copyFile(y().join(s().cachedir_massSession,t),y().join(s().cachedir_massSessionTrash,t)),await m().promises.unlink(y().join(s().cachedir_massSession,t)),console.log("File deleted: ",t,e))}))}catch(t){throw`Error: ${t}`}}function uo(t,e){if(t.dbfile)try{console.log("Connecting",t.dbfile),t.newconn=F.sE(t.dbfile)}catch(e){throw"Error with "+t.dbfile+": "+e}if(t.snvindel_attributes)for(const e of t.snvindel_attributes)if(e.lst)for(const t of e.lst)t.get=t.get.toString();else e.get=e.get.toString();if(t.cohort){if(t.cohort.levels){if(!Array.isArray(t.cohort.levels))throw"cohort.levels must be array for "+t.genomename+"."+t.label;if(0==t.cohort.levels.length)throw"levels is blank array for cohort of "+t.genomename+"."+t.label;for(const e of t.cohort.levels)if(!e.k)throw".k key missing in one of the levels, .cohort, in "+t.genomename+"."+t.label}if(t.cohort.fromdb){if(!t.cohort.fromdb.sql)throw".sql missing from ds.cohort.fromdb in "+t.genomename+"."+t.label;const e=t.newconn.prepare(t.cohort.fromdb.sql).all();delete t.cohort.fromdb,t.cohort.raw=e,console.log(e.length+" rows retrieved for "+t.label+" sample annotation")}if(t.cohort.files){let e=[];for(const n of t.cohort.files){if(!n.file)throw".file missing from one of cohort.files[] for "+t.genomename+"."+t.label;const r=m().readFileSync(y().join(s().tpmasterdir,n.file),"utf8").trim();if(!r)throw n.file+" is empty for "+t.genomename+"."+t.label;e=[...e,...H.tJ(r)]}delete t.cohort.files,t.cohort.raw?t.cohort.raw=[...t.cohort.raw,...e]:t.cohort.raw=e,console.log(e.length+" rows retrieved for "+t.label+" sample annotation")}if(t.cohort.tosampleannotation){if(!t.cohort.tosampleannotation.samplekey)throw".samplekey missing from .cohort.tosampleannotation for "+t.genomename+"."+t.label;if(!t.cohort.key4annotation)throw".cohort.key4annotation missing when .cohort.tosampleannotation is on for "+t.genomename+"."+t.label}}if(!t.queries)throw".queries missing from dataset "+t.label+", "+t.genomename;if(!Array.isArray(t.queries))throw t.label+".queries is not array";for(const n of t.queries){const r=ho(n,t,e);if(r)throw'Error parsing a query in "'+t.label+'": '+r}if(t.vcfinfofilter){const e=P.validate_vcfinfofilter(t.vcfinfofilter);if(e)throw t.label+": vcfinfofilter error: "+e}if(t.url4variant)for(const e of t.url4variant){if(!e.makelabel)throw"makelabel() missing for one item of url4variant from "+t.label;if(!e.makeurl)throw"makeurl() missing for one item of url4variant from "+t.label;e.makelabel=e.makelabel.toString(),e.makeurl=e.makeurl.toString()}}async function fo(t){const e=y().join(s().cachedir,t);try{await m().promises.stat(e)}catch(t){if("ENOENT"!=t.code)throw"error stating dir";try{await m().promises.mkdir(e)}catch(t){throw"cannot make dir"}}return e}function ho(t,e,n){if(!t.name)return".name missing";if(t.dsblocktracklst){if(!Array.isArray(t.dsblocktracklst))return"dsblocktracklst not an array in "+e.label;for(const n of t.dsblocktracklst){if(!n.type)return"missing type for a blocktrack of "+e.label;if(!n.file&&!n.url)return"neither file or url given for a blocktrack of "+e.label}}else if(t.vcffile){const e=N().execSync(vs+" -H "+y().join(s().tpmasterdir,t.vcffile),{encoding:"utf8"}).trim();if(""==e)return"no meta lines in VCF file "+t.vcffile+" of query "+t.name;const[r,o,i,a]=D.e(e.split("\n"));if(a)return"error parsing VCF meta lines of "+t.vcffile+": "+a.join("; ");t.vcf={vcfid:Math.random().toString(),info:r,format:o,samples:i},t.hlinfo&&(t.vcf.hlinfo=t.hlinfo,delete t.hlinfo),t.infopipejoin&&(t.vcf.infopipejoin=t.infopipejoin,delete t.infopipejoin);const l=N().execSync(vs+" -l "+y().join(s().tpmasterdir,t.vcffile),{encoding:"utf8"}).trim();if(""==l)return"tabix -l found no chromosomes/contigs in "+t.vcffile+" of query "+t.name;t.vcf.nochr=P.contigNameNoChr(n,l.split("\n"));let c=0;if(r)for(const t in r)c++;console.log("Parsed vcf meta from "+t.vcffile+": "+c+" INFO, "+i.length+" sample, "+(t.vcf.nochr?'no "chr"':'has "chr"'))}else{if(!t.makequery)return"do not know how to parse query: "+t.name;if(t.isgeneexpression){if(!t.config)return"config object missing for gene expression query of "+t.name;t.config.maf&&(t.config.maf.get=t.config.maf.get.toString())}}}async function po(t,e,n){if((t.isMds2||t.isMds3||t.isMds)&&Xn(t,n),t.assayAvailability){if(!t.assayAvailability.file)throw".assayAvailability.file missing";if(!t.assayAvailability.assays)throw".assayAvailability.assays[] missing";Object.freeze(t.assayAvailability.assays),t.assayAvailability.samples=new Map;for(const e of m().readFileSync(y().join(s().tpmasterdir,t.assayAvailability.file),{encoding:"utf8"}).trim().split("\n")){const[n,r]=e.split("\t");t.assayAvailability.samples.set(n,JSON.parse(r))}console.log(t.assayAvailability.samples.size+" samples with assay availability ("+t.label+")")}if(t.gene2mutcount){if(!t.gene2mutcount.dbfile)throw".gene2mutcount.dbfile missing";try{console.log("Connecting",t.gene2mutcount.dbfile),t.gene2mutcount.db=F.sE(t.gene2mutcount.dbfile),console.log("DB connected for "+t.label+": "+t.gene2mutcount.dbfile)}catch(e){throw`Error connecting db at ${t.gene2mutcount.dbfile}`}}if(t.sampleAssayTrack){if(!t.sampleAssayTrack.file)throw".file missing from sampleAssayTrack";t.sampleAssayTrack.samples=new Map;let e=0,n=new Set;for(const r of m().readFileSync(y().join(s().tpmasterdir,t.sampleAssayTrack.file),{encoding:"utf8"}).trim().split("\n")){if(!r)continue;if("#"==r[0])continue;const[s,o,i]=r.split("\t");if(!o||!i)continue;if(!t.sampleAssayTrack.samples.has(s)){if(t.cohort&&t.cohort.annotation&&!t.cohort.annotation[s]){n.add(s);continue}t.sampleAssayTrack.samples.set(s,[])}const a=JSON.parse(i);if(!P.tkt[a.type])throw"invalid type from a sample track: "+i;a.name||(a.name=s+" "+o),a.assayName=o,t.sampleAssayTrack.samples.get(s).push(a),e++}console.log(e+" assay-tracks from "+t.sampleAssayTrack.samples.size+" samples ("+t.label+")"),n.size&&console.log("Error: "+n.size+" samples with assay tracks are unannotated: "+[...n].join(" "))}if(t.singlesamplemutationjson){const e=t.singlesamplemutationjson;if(!e.file)throw".file missing from singlesamplemutationjson";e.samples={};let n=0;for(const t of m().readFileSync(y().join(s().tpmasterdir,e.file),{encoding:"utf8"}).trim().split("\n")){if(!t)continue;if("#"==t[0])continue;const[r,s]=t.split("\t");r&&s&&(n++,e.samples[r]=s)}console.log(n+" samples for disco plot")}if(t.cohort&&t.cohort.db&&t.cohort.termdb&&await Tr(t,ks,qs),t.cohort&&t.cohort.files){if(!Array.isArray(t.cohort.files))throw".cohort.files is not array";if(!t.cohort.tohash)throw".tohash() missing from cohort";if("function"!=typeof t.cohort.tohash)throw".cohort.tohash is not function";if(!t.cohort.samplenamekey)throw".samplenamekey missing";if(t.cohort.annotation={},t.cohort.mutation_signature){const e=t.cohort.mutation_signature;if(!e.sets)throw".mutation_signature.sets missing";for(const n in e.sets){const r=e.sets[n];if(r.name||(r.name=n),!r.signatures)throw".signatures{} missing from a signature set";if(r.samples){if(!r.samples.file)throw".samples.file missing from a signature set";const[e,n]=ao(m().readFileSync(y().join(s().tpmasterdir,r.samples.file),{encoding:"utf8"}).trim());r.samples.map=new Map;for(const e of n){const n=e[t.cohort.samplenamekey];if(!n)throw t.cohort.samplenamekey+" missing in file "+r.samples.file;r.samples.map.set(n,e);for(const t in r.signatures)if(e[t]){const s=Number.parseFloat(e[t]);if(Number.isNaN(s))throw"mutation signature value is not float: "+e[t]+" from sample "+n;r.samples.skipzero&&0==s?delete e[t]:e[t]=s}}}}}if(t.cohort.attributes){if(!t.cohort.attributes.lst)throw".lst[] missing for cohort.attributes";if(!Array.isArray(t.cohort.attributes.lst))return".cohort.attributes.lst is not array";for(const e of t.cohort.attributes.lst){if(!e.key)throw".key missing from one of the .cohort.attributes.lst[]";if(!e.label)throw".label missing from one of the .cohort.attributes.lst[]";if(!e.values)throw".values{} missing from "+e.label+" of .cohort.attributes.lst";for(const t in e.values)if(!e.values[t].label)throw".label missing from one value of "+e.label+" in .cohort.attributes.lst"}if(t.cohort.attributes.defaulthidden)for(const e in t.cohort.attributes.defaulthidden){const n=t.cohort.attributes.lst.find((t=>t.key==e));if(!n)throw"invalid defaulthidden key: "+e;for(const r in t.cohort.attributes.defaulthidden[e])if(!n.values[r])throw"invalid defaulthidden value "+r+" for "+e}}if(t.cohort.hierarchies){if(!t.cohort.hierarchies.lst)throw".lst[] missing from .cohort.hierarchies";if(!Array.isArray(t.cohort.hierarchies.lst))throw".cohort.hierarchies.lst is not array";for(const e of t.cohort.hierarchies.lst){if(!e.name)throw".name missing from one hierarchy";if(!e.levels)throw".levels[] missing from one hierarchy";if(!Array.isArray(e.levels))throw".levels is not array from one hierarchy";for(const t of e.levels)if(!t.k)throw".k missing from one level in hierarchy "+e.name}}if(t.cohort.sampleAttribute){if(!t.cohort.sampleAttribute.attributes)throw"attributes{} missing from cohort.sampleAttribute";for(const e in t.cohort.sampleAttribute.attributes){const n=t.cohort.sampleAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from cohort.sampleAttribute.attributes";if(n.values)for(const t in n.values){const e=n.values[t];if("object"!=typeof e)throw'value "'+t+'" not pointing to {} from sampleAttribute';e.name||(e.name=t)}if(n.showintrack&&!n.isinteger&&!n.isfloat)throw n.label+": .showintrack requires .isinteger or .isfloat"}}if(t.cohort.scatterplot){if(!t.cohort.sampleAttribute)throw".sampleAttribute missing but required for .cohort.scatterplot";const e=t.cohort.scatterplot;if(!e.querykey)throw".querykey missing from .cohort.scatterplot";{if(!t.queries)throw".cohort.scatterplot.querykey in use but ds.queries{} missing";const n=t.queries[e.querykey];if(!n)throw"unknown query by .cohort.scatterplot.querykey: "+e.querykey;if(n.type!=P.tkt.mdssvcnv)throw"type is not "+P.tkt.mdssvcnv+" of the track pointed to by .cohort.scatterplot.querykey"}if(e.colorbygeneexpression){if(!e.colorbygeneexpression.querykey)throw"querykey missing from .cohort.scatterplot.colorbygeneexpression";if(!t.queries)throw".cohort.scatterplot.colorbygeneexpression in use but ds.queries{} missing";const n=t.queries[e.colorbygeneexpression.querykey];if(!n)throw"unknown query by .cohort.scatterplot.colorbygeneexpression.querykey: "+e.colorbygeneexpression.querykey;if(!n.isgenenumeric)throw"isgenenumeric missing from the track pointed to by .cohort.scatterplot.colorbygeneexpression.querykey"}if(e.tracks,!e.x)throw".x missing from .cohort.scatterplot";if(!e.x.attribute)throw".attribute missing from .cohort.scatterplot.x";const n=t.cohort.sampleAttribute.attributes[e.x.attribute];if(!n)throw"scatterplot.x.attribute is not defined in sampleAttribute";if(!n.isfloat)throw'scatterplot.x is not "isfloat"';if(!e.y)throw".y missing from .cohort.scatterplot";if(!e.y.attribute)throw".attribute missing from .cohort.scatterplot.y";const r=t.cohort.sampleAttribute.attributes[e.y.attribute];if(!r)throw"scatterplot.y.attribute is not defined in sampleAttribute";if(!r.isfloat)throw'scatterplot.y is not "isfloat"';if(e.colorbyattributes)for(const n of e.colorbyattributes){if(!n.key)throw".key missing from one of scatterplot.colorbyattributes";const e=t.cohort.sampleAttribute.attributes[n.key];if(!e)throw"unknown attribute by key "+n.key+" from scatterplot.colorbyattributes";n.label=e.label,n.values=e.values}}for(const e of t.cohort.files){if(!e.file)throw".file missing from one of .cohort.files";const[n,r]=ao(m().readFileSync(y().join(s().tpmasterdir,e.file),{encoding:"utf8"}).trim());if(n)throw'cohort annotation file "'+e.file+'": '+n;console.log(t.label+": "+r.length+" samples loaded from annotation file "+e.file),r.forEach((e=>{for(const n in e){let r;t.cohort.sampleAttribute&&(r=t.cohort.sampleAttribute.attributes[n]),r||t.cohort.termdb&&t.cohort.termdb.termjson&&t.cohort.termdb.termjson.map&&(r=t.cohort.termdb.termjson.map.get(n)),r&&(r.isfloat?e[n]=Number.parseFloat(e[n]):r.isinteger&&(e[n]=Number.parseInt(e[n])))}t.cohort.tohash(e,t)}))}if(t.cohort.annorows=Object.values(t.cohort.annotation),console.log(t.label+": total samples from sample table: "+t.cohort.annorows.length),t.cohort.survivalplot){const e=t.cohort.survivalplot;if(!e.plots)throw".plots{} missing from survivalplot";e.init={plottypes:[]};for(const t in e.plots){const n=e.plots[t];if(!n.name)throw".name missing from survivalplot "+t;if(!n.serialtimekey)throw".serialtimekey missing from survivalplot "+t;if(!n.iscensoredkey)throw".iscensoredkey missing from survivalplot "+t;if(!n.timelabel)throw".timelabel missing from survivalplot "+t;n.key=t,e.init.plottypes.push({key:t,name:n.name,timelabel:n.timelabel})}if(e.samplegroupattrlst){e.init.samplegroupings=[];for(const n of e.samplegroupattrlst){if(!n.key)throw".key missing from an attr of samplegroupattrlst for survival";const r=t.cohort.sampleAttribute.attributes[n.key];if(!r)throw'unknown attribute key "'+n.key+'" from survival samplegroupattrlst';const s=new Map;for(const r in t.cohort.annotation){const o=t.cohort.annotation[r],i=o[n.key];if(null==i)continue;let a=!1;for(const t in e.plots)if(null!=o[e.plots[t].serialtimekey]){a=!0;break}a&&(s.has(i)?s.set(i,s.get(i)+1):s.set(i,1))}if(0==s.size)throw'no value found for "'+n.key+'" from survival samplegroupattrlst';const o=[];for(const[t,e]of s)o.push({value:t,count:e});e.init.samplegroupings.push({key:n.key,label:r.label,values:o})}}}}if(t.mutationAttribute){if(!t.mutationAttribute.attributes)throw"attributes{} missing from mutationAttribute";for(const e in t.mutationAttribute.attributes){const n=t.mutationAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from mutationAttribute.attributes";if(!n.appendto_link&&n.values)for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from mutationAttribute.attributes"}}}if(t.alleleAttribute){if(!t.alleleAttribute.attributes)throw"attributes{} missing from alleleAttribute";for(const e in t.alleleAttribute.attributes){const n=t.alleleAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from alleleAttribute.attributes";if(!n.isnumeric){if(!n.values)throw".values{} missing for non-numeric key "+e+" from alleleAttribute.attributes";for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from alleleAttribute.attributes"}}}}if(t.locusAttribute){if(!t.locusAttribute.attributes)throw"attributes{} missing from locusAttribute";for(const e in t.locusAttribute.attributes){const n=t.locusAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from locusAttribute.attributes";if(!n.isnumeric&&!n.appendto_link){if(!n.values)throw".values{} missing for non-numeric key "+e+" from locusAttribute.attributes";for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from locusAttribute.attributes"}}}}if(t.queries)for(const r in t.queries){if(n.remove_queries&&-1!=n.remove_queries.indexOf(r)){delete t.queries[r];continue}const s=t.queries[r];if(n.hide_queries&&-1!=n.hide_queries.indexOf(r)&&(s.hideforthemoment=1),s.istrack){if(!s.type)throw".type missing for track query "+r;if(s.viewrangeupperlimit&&!Number.isInteger(s.viewrangeupperlimit))throw".viewrangeupperlimit should be integer for track query "+r;if(s.type==P.tkt.mdsjunction){const n=go(s,t,e);if(n)throw r+" (mdsjunction) error: "+n}else if(s.type==P.tkt.mdscnv){const n=vo(s,t,e);if(n)throw r+" (mdscnv) error: "+n}else if(s.type==P.tkt.mdssvcnv){const n=wo(s,t,e);if(n)throw r+" (svcnv) error: "+n}else{if(s.type!=P.tkt.mdsvcf)throw"unknown track type for a query: "+s.type+" "+r;{const n=await xo(s,t,e);if(n)throw r+" (vcf) error: "+n}}mo(s,t)}else{if(!s.isgenenumeric)throw"unknown type of query from "+r;{const n=_o(s,t,e);if(n)throw r+" (genenumeric) error: "+n}}}if(t.track&&await Cr(t,e),t.annotationsampleset2matrix){if(!t.cohort)throw"ds.cohort misssing when annotationsampleset2matrix is in use";if(!t.cohort.annotation)throw"ds.cohort.annotation misssing when annotationsampleset2matrix is in use";if(!t.queries)throw"ds.queries misssing when annotationsampleset2matrix is in use";if(!t.annotationsampleset2matrix.key)throw".key STR missing in annotationsampleset2matrix";if(!t.annotationsampleset2matrix.groups)throw".groups{} missing in annotationsampleset2matrix";if("object"!=typeof t.annotationsampleset2matrix.groups)throw"ds.annotationsampleset2matrix.groups{} not an object";for(const e in t.annotationsampleset2matrix.groups){const n=t.annotationsampleset2matrix.groups[e];if(!n.groups||!Array.isArray(n.groups)||0==n.groups.length)throw".groups[] must be nonempty array in "+e;for(const r of n.groups){if(!r.name)throw".name missing from one of .groups[] in "+e;const n=r.matrixconfig;if(!n)throw".matrixconfig missing from one of .groups[] of "+e;if(!n.features)throw".features[] missing from group "+e;if(!Array.isArray(n.features))throw".features[] should be array from group "+e;if(0==n.features.length)throw".features[] zero length from group "+e;for(const r of n.features){if(t.annotationsampleset2matrix.commonfeatureattributes)for(const e in t.annotationsampleset2matrix.commonfeatureattributes)null==r[e]&&(r[e]=t.annotationsampleset2matrix.commonfeatureattributes[e]);if(!r.ismutation)return"unknown feature type from group "+e;if(!r.position)throw"position missing from feature "+JSON.stringify(r)+" from group "+e;if(!r.querykeylst)throw".querykeylst[] missing from ismutation feature from group "+e;if(!Array.isArray(r.querykeylst))throw".querykeylst[] not an array from ismutation feature from group "+e;if(0==r.querykeylst.length)throw".querykeylst[] zero length from ismutation feature from group "+e;for(const n of r.querykeylst)if(!t.queries[n])throw'unknown query key "'+n+'" from ismutation feature of group '+e}if(!n.limitsamplebyeitherannotation)throw".limitsamplebyeitherannotation[] missing from group "+e;if(!Array.isArray(n.limitsamplebyeitherannotation))throw".limitsamplebyeitherannotation[] should be array from group "+e;if(0==n.limitsamplebyeitherannotation.length)throw".limitsamplebyeitherannotation[] zero length from group "+e;for(const t of n.limitsamplebyeitherannotation){if(!t.key)throw"key missing from one of limitsamplebyeitherannotation from group "+e;if(!t.value)throw"value missing from one of limitsamplebyeitherannotation from group "+e}}}delete t.annotationsampleset2matrix.commonfeatureattributes}}function mo(t,e){if(t.groupsamplebyattr){t.groupsamplebyattr.key2group=new Map;for(const n in e.cohort.annotation)Zs(n,[],t.groupsamplebyattr.key2group,[],e,t)}}function go(t,e,n){if(t.readcountCutoff&&(!Number.isInteger(t.readcountCutoff)||t.readcountCutoff<1))return"readcountCutoff must be positive integer";let r;if(t.file){const[e,n]=io(t.file);if(e)return"tabix file error: "+e;t.file=n,r=n}else{if(!t.url)return"no file or url given for mdsjunction "+t.name;r=t.url}const s={encoding:"utf8"};const o=N().execSync(vs+" -H "+r,s).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 r=n[0].split("\t");if(r[5]){t.samples=r.slice(5),t.attributeSummary=yo(t.samples,e),t.hierarchySummary=bo(t.samples,e);for(const e in t.hierarchySummary){let n=0;for(const r in t.hierarchySummary[e])n++;console.log(n+" "+e+" hierarchy levels for "+t.name)}}}{const e=N().execSync(vs+" -l "+r,s).trim();if(!e)return"no chromosomes found";t.nochr=P.contigNameNoChr(n,e.split("\n"))}if(console.log("(mdsjunction) "+t.name+": "+(t.samples?t.samples.length:0)+" samples, "+(t.nochr?'no "chr"':'has "chr"')),!t.infoFilter)return".infoFilter{} missing";if(!t.infoFilter.lst)return".lst[] missing from .infoFilter";for(const e of t.infoFilter.lst){if(!e.key)return".key missing from one of infoFilter";if(!e.label)return".label missing from one of infoFilter";if(!e.categories)return".categories missing from one of infoFilter";for(const t in e.categories){if(!e.categories[t].label)return".label missing from one category of "+e.label;if(!e.categories[t].color)return".color missing from on category of "+e.label}if(e.hiddenCategories){for(const t in e.hiddenCategories)if(!e.categories[t])return"invalid hidden key "+t+" of "+e.label}else e.hiddenCategories={}}if(!t.singlejunctionsummary)return".singlejunctionsummary missing but is currently required from "+t.name;if(t.singlejunctionsummary.readcountboxplotpercohort){if(!t.singlejunctionsummary.readcountboxplotpercohort.groups)return".groups[] missing from query.singlejunctionsummary.readcountboxplotpercohort for "+t.name;for(const e of t.singlejunctionsummary.readcountboxplotpercohort.groups){if(!e.key)return".key missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups";if(!e.label)return".label missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups"}}}function yo(t,e){if(!(e.cohort&&e.cohort.annotation&&e.cohort.attributes&&t))return;const n={};for(const r of e.cohort.attributes.lst){const s={};for(const t in r.values)s[t]=0;for(const n of t){const t=e.cohort.annotation[n];if(!t)continue;const o=t[r.key];null!=o&&(o in s&&s[o]++)}n[r.key]=s}return n}function bo(t,e){if(!e.cohort||!e.cohort.annotation||!e.cohort.hierarchies||0==t.length)return;const n=[];for(const r of t){const t=e.cohort.annotation[r];t&&n.push(t)}const r={};for(const t of e.cohort.hierarchies.lst){const e=(0,A.N)(n,t.levels),s=(0,V.Z)()(e);s.sum((t=>t.value));const o={};s.eachBefore((t=>{o[t.id]=t.value})),r[t.name]=o}return r}function vo(t,e,n){let r;if(t.file){const[e,n]=io(t.file);if(e)return"tabix file error: "+e;r=n}else{if(!t.url)return"no file or url given for (mdscnv) "+t.name;r=t.url}const s={encoding:"utf8"};const o=N().execSync(vs+" -H "+r,s).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 r=n[0].split("\t");t.samples=r.slice(5),t.attributeSummary=yo(t.samples,e),t.hierarchySummary=bo(t.samples,e);for(const e in t.hierarchySummary){let n=0;for(const r in t.hierarchySummary[e])n++;console.log(n+" "+e+" hierarchy levels for "+t.name)}}{const e=N().execSync(vs+" -l "+r,s).trim();if(!e)return"no chromosomes found";t.nochr=P.contigNameNoChr(n,e.split("\n"))}console.log("("+t.type+") "+t.name+": "+(t.samples?t.samples.length:"no")+" samples, "+(t.nochr?'no "chr"':'has "chr"'))}function wo(t,e,n){let r;if(t.file){const[e,n]=io(t.file);if(e)return"tabix file error: "+e;r=n}else{if(!t.url)return"no file or url given for (svcnv) "+t.name;r=t.url}const s={encoding:"utf8"};const o=N().execSync(vs+" -H "+r,s).trim();if(o){const n=new Set;for(const t of o.split("\n"))for(const e of t.split(" ").slice(1))n.add(e);if(0==n.size)return"no samples from the header line";if(t.samples=[...n],e.cohort&&e.cohort.annotation){const n=new Set;for(const r of t.samples)e.cohort.annotation[r]||n.add(r);n.size&&console.log("mdssvcnv unannotated samples: "+(t.noprintunannotatedsamples?n.size:[...n].join(" ")))}}{const e=N().execSync(vs+" -l "+r,s).trim();if(!e)return"no chromosomes found";t.nochr=P.contigNameNoChr(n,e.split("\n"))}if(t.expressionrank_querykey){const n=e.queries[t.expressionrank_querykey];if(!n)return"invalid key by expressionrank_querykey";if(!n.isgenenumeric)return"query "+t.expressionrank_querykey+" not tagged as isgenenumeric"}if(t.vcf_querykey){const n=e.queries[t.vcf_querykey];if(!n)return"invalid key by vcf_querykey";if(n.type!=P.tkt.mdsvcf)return"query "+t.vcf_querykey+" not of mdsvcf type"}if(t.groupsamplebyattr){if(!t.groupsamplebyattr.attrlst)return".attrlst[] missing from groupsamplebyattr";if(0==t.groupsamplebyattr.attrlst.length)return"groupsamplebyattr.attrlst[] empty array";if(!e.cohort)return"groupsamplebyattr in use but ds.cohort missing";if(!e.cohort.annotation)return"groupsamplebyattr in use but ds.cohort.annotation missing";e.cohort.sampleAttribute||(e.cohort.sampleAttribute={}),e.cohort.sampleAttribute.attributes||(e.cohort.sampleAttribute.attributes={},console.log("cohort.sampleAttribute added when groupsamplebyattr is in use"));for(const n of t.groupsamplebyattr.attrlst){if(!n.k)return"k missing from one of groupsamplebyattr.attrlst[]";e.cohort.sampleAttribute.attributes[n.k]||(e.cohort.sampleAttribute.attributes[n.k]={label:n.label||n.k})}if(t.groupsamplebyattr.sortgroupby){if(!t.groupsamplebyattr.sortgroupby.key)return".key missing from .sortgroupby";if(!t.groupsamplebyattr.sortgroupby.order)return".order[] missing from .sortgroupby";if(!Array.isArray(t.groupsamplebyattr.sortgroupby.order))return".order must be an array"}t.groupsamplebyattr.attrnamespacer||(t.groupsamplebyattr.attrnamespacer=", ")}console.log("("+t.type+") "+t.name+": "+(t.samples?t.samples.length:"no")+" samples, "+(t.nochr?'no "chr"':'has "chr"'))}function _o(t,e,n){if(!t.datatype)return"datatype missing";if(t.viewrangeupperlimit&&Number.isNaN(t.viewrangeupperlimit))return"invalid value for viewrangeupperlimit";let r;if(!t.file)return"file missing";{const[e,n]=io(t.file);if(e)return"tabix file error: "+e;r=n}const s={cwd:null,encoding:"utf8"};{const e=N().execSync(vs+" -H "+r,s).trim();if(!e)return"no header line (#sample <sample1> ...)";const n=new Set;for(const t of e.split("\n")){const e=t.split(" ");for(let t=1;t<e.length;t++)n.add(e[t])}if(0==n.size)return"no sample names from header line";t.samples=[...n],console.log("(genenumeric) "+t.name+": "+t.samples.length+" samples")}if(t.boxplotbysamplegroup){if(!t.boxplotbysamplegroup.attributes)return"boxplotbysamplegroup.attributes missing";if(!Array.isArray(t.boxplotbysamplegroup.attributes))return"boxplotbysamplegroup.attributes should be array";for(const e of t.boxplotbysamplegroup.attributes)if(!e.k)return"k missing from one of boxplotbysamplegroup.attributes[]"}}async function xo(t,e,n){if(!t.tracks)return"tracks[] missing";if(!Array.isArray(t.tracks))return"tracks should be array";t.info={};for(const r of t.tracks){if(!r.file)return"file missing from a track (url not supported yet)";const[s,o]=io(r.file);if(s)return"tabix file error: "+s;if(r.type!=P.mdsvcftype.vcf)return"invalid track type: "+r.type;{r.cwd;const e=await F.ZD(o,r.cwd);if(0==e.length)return"no meta/header lines for "+o;const[n,s,i,a]=D.e(e);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 e in n)t.info[e]=n[e];if(r.format=s,r.samplenameconvert){if("function"!=typeof r.samplenameconvert)return".samplenameconvert must be function";for(const t of i)t.name=r.samplenameconvert(t.name)}r.samples=i}if(e.cohort&&e.cohort.annotation){const t=[];for(const n of r.samples)e.cohort.annotation[n.name]||t.push(n.name);t.length&&console.log(e.label+": VCF "+r.file+" has unannotated samples: "+t.join(","))}{const t=[];if(await F.UE({args:["-l",o],dir:r.cwd,callback:e=>{t.push(e)}}),0==t.length)return"no chr from "+o;r.nochr=P.contigNameNoChr(n,t)}console.log("("+t.type+") "+o+": "+r.samples.length+" samples, "+(r.nochr?"no chr":"has chr"))}if(t.singlesamples){if(!t.singlesamples.tablefile)return".singlesamples.tablefile missing for the VCF query";t.singlesamples.samples={};let e=0;for(const n of m().readFileSync(y().join(s().tpmasterdir,t.singlesamples.tablefile),{encoding:"utf8"}).trim().split("\n")){if(!n)continue;if("#"==n[0])continue;const r=n.split("\t");r[0]&&r[1]&&(t.singlesamples.samples[r[0]]=r[1],e++)}console.log(e+" single-sample VCF files")}}},6191:(t,e,n)=>{"use strict";n.d(e,{i:()=>y});var r=n(7147),s=n(1017),o=n.n(s),i=n(9344),a=n.n(i),l=n(8088);async function c(t,e){!function(t){for(const e in t){const n=t[e];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 t in n.embedders)n.termdb={[t]:Object.assign({type:n.type},n.embedders[t])},n.headerKey&&(n.termdb[t].headerKey=n.headerKey);delete n.type,delete n.embedders,delete n.headerKey}else if(n.type)throw`unknown legacy credentials type='${n.type}'`}}(t);const n="secrets";if("string"==typeof t[n]){const e=await r.promises.readFile(t[n],"utf8");t[n]=JSON.parse(e)}for(const e in t){const n=t[e];n["*"]&&(n["/**"]=n["*"],delete n["*"]);const r=n.headerKey||"x-ds-access-token";delete n.headerKey;for(const s in n){const o=n[s];for(const n in o){o[n]=JSON.parse(JSON.stringify(o[n]));const i=o[n],a="string"==typeof i?t.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=r);else if("forbidden"!=a.type&&"open"!=a.type)throw`unknown cred.type='${a.type}' for dsCredentials[${e}][${n}][${s}]`;a.dslabel=e,a.route=s,a.cookieId="termdb"==s&&a.headerKey||`${e}-${s}-${n}-Id`}}}}const u={termdb:["matrix"],samples:["singleSampleData","getAllSamples","scatter","convertSampleId","getAllSamplesByName"]};function f(t,e){return t.cookies?.[`${e?.cookieId}`]||t.cookies?.[`${t.query.dslabel}SessionId`]||t.headers?.["x-sjppds-sessionid"]||t.query?.["x-sjppds-sessionid"]}async function d(t,e,n,s,o,i,l=""){if(s.secret)try{const c=Date.now(),u=Math.floor(c/1e3),f={dslabel:e.dslabel,id:n,iat:u,time:c,ip:t.ip,embedder:e.embedder,route:s.route,exp:u+Math.floor(o/1e3),email:l};s.dsnames&&(f.datasets=s.dsnames.map((t=>t.id)));const d=a().sign(f,s.secret);return await r.promises.appendFile(i,`${e.dslabel}\t${n}\t${c}\t${l}\t${t.ip}\t${e.embedder}\t${s.route}\n`),d}catch(t){throw t}}function h(t,e,n,r,s){if(!r.headers.authorization||n&&t[e]?.[n])return;if(!s.secret)throw{status:"error",error:`no credentials set up for this embedder='${r.query.embedder}'`,code:403};const[o,i]=r.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,s.secret);if(n&&o.id!=n&&r.headers?.["x-sjppds-sessionid"]!=o.id)return;t[e]||(t[e]={});const i="/"!=r.path[0]||s.route.startsWith("/")?r.path:r.path.slice(1);if((0,l.isMatch)(i,s.route)||"authorizedActions"==i)return t[e][o.id]=o,o.id}catch(t){return}}async function p(t,e,n,s,o,i,a){const l=Date.now(),c=Math.random().toString()+"."+l.toString().slice(4),u=i.ip;return n[t.dslabel]||(n[t.dslabel]={}),n[t.dslabel][c]={id:c,time:l,email:o,ip:u},await r.promises.appendFile(s,`${t.dslabel}\t${c}\t${l}\t${o}\t${u}\t${t.embedder}\t${a.route}\n`),a.cookieMode&&"set-cookie"!=a.cookieMode||e.header("Set-Cookie",`${a.cookieId}=${c}; HttpOnly; SameSite=None; Secure`),c}function m(t,e,n,r,s=null){if(!n)return;if(!t.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((r||Date.now())/1e3),l=e[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(s)return{iat:f.iat,email:f.email,ip:f.ip};if(c.handlePayload)try{c.handlePayload(n,f,i)}catch(t){if("bad decrypt"==t.reason)throw`Please login again to access this feature. (${t.reason})`;throw t}if(i>f.exp)throw"Please login again to access this feature. (expired token)";const d=(n.dsnames||[t.dslabel]).filter((t=>!f.datasets?.includes(t.id))).map((t=>t.id));if(d.length)throw{error:"Missing access",linkKey:d.join(",")};return{iat:f.iat,email:f.email,ip:f.ip}}function g(t,e,n){if(!n.looseIpCheck||!t.ip?.includes(":")&&e){if(!e)throw"Server error: missing ip address in saved session";if(t.ip!=e&&t.ips?.[0]!=e&&t.connection?.remoteAddress!=e)throw"Your connection has changed, please refresh your page or sign in again."}}const y={maySetAuthRoutes:async function(t,e="",s=null){const i=s||n(334),b=i.features?.sessionTracking||"",v=o().join(i.cachedir,"dsSessions"),w=o().join(i.cachedir,"authorizedActions"),_=i.dsCredentials||{};delete i.dsCredentials;const x=i.maxSessionAge||576e5;let k;if(!_||!Object.keys(_).length)return y.getDsAuth=()=>[],y.getForbiddenRoutesForDsEmbedder=()=>[],y.userCanAccess=()=>!0,y.getRequiredCredForDsEmbedder=()=>{},void(y.getPayloadFromHeaderAuth=()=>({}));try{c(_)}catch(t){throw t}function q(t,e,n){if(!t.dslabel)return;const r=_[t.dslabel]||_["*"];if(r){if("/jwt-status"==e){const e=r[t.route]||r.termdb||r["/**"];return e&&(e[t.embedder]||e["*"])}if("/dslogin"==e){const e=r[t.route]||r["/**"];return e&&(e[t.embedder]||e["*"])}if(e.startsWith("/termdb")&&r.termdb){const e=r.termdb;return(n||u.termdb).includes(t.for)&&(e[t.embedder]||e["*"])}if(e.startsWith("/burden")&&r.burden)return r.burden[t.embedder]||r.burden["*"]}for(const n in _){if(n!=t.dslabel&&"*"!=n)continue;const r=_[n];for(const n in r){const s=r[n].routePattern||n;if(!(0,l.isMatch)(e,s))continue;const o=r[n];for(const e in o)if(e==t.embedder||"*"==e)return o[e]}}}t.use(((t,e,n)=>{if("/dslogin"==t.path||"/jwt-status"==t.path||"/dslogout"==t.path)return void n();const r=t.query,s=q(r,t.path);if(!s)return void n();let o;"jwt-only"==b&&(k={});try{const i=f(t,s);let a;if(!i){if("OPTIONS"==t.method.toUpperCase())return e.status(204),void e.send();if(a=h(k,r.dslabel,i,t,s),!a)throw o=401,"missing session cookie"}a||(a=h(k,r.dslabel,i,t,s));const l=k[r.dslabel]?.[i]||k[r.dslabel]?.[a];if(!l)throw o=401,"unestablished or expired browser session";g(t,l.ip,s);const c=Date.now();if(c-l.time>x){const{iat:e}=m(r,t.headers,s,l),n=c-e;if(n>x)throw delete k[r.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(t){console.log(t);const n=t.code||o;n&&e.status(n),e.send("object"==typeof t?t:{error:t})}}));try{k=await async function(t,e,n){const s={};for(const e in t)s[e]||(s[e]={});try{const t=await r.promises.readFile(e,"utf8"),o=+new Date;for(const e of t.split("\n")){if(!e)continue;const[t,r,i,a,l]=e.split("\t"),c=Number(i);s[t]||(s[t]={}),o-c<n&&(s[t][r]={id:r,time:c,email:a,ip:l})}return s}catch(t){return(0,r.existsSync)(e)&&console.log(t),s}}(_,v,x);const t=[];for(const e in k)for(const n in k[e]){const r=k[e][n];t.push(`${r.dslabel}\t${r.id}\t${r.time}\t${r.email}\t${r.ip}\t${r.embedder}\t${r.route}`)}await r.promises.writeFile(v,t.join("\n"))}catch(t){throw t}var N;await(N=0,new Promise((t=>setTimeout(t,N)))),t.post(e+"/dslogin",(async(t,e)=>{let n=401;try{const r=t.query,s=q(r,t.path);if(!s)throw n=400,`No login required for dataset='${r.dslabel}'`;if("/dslogin"!=s.authRoute)throw n=400,`Incorrect authorization route, use '${s.authRoute}'`;if(!t.headers.authorization)throw"missing authorization header";const[o,i]=t.headers.authorization.split(" ");if("basic"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Basic'`;if(Buffer.from(i,"base64").toString()!=s.password)throw"invalid password";const a=await p(r,e,k,v,"",t,s);n=401;const l=await d(t,r,a,s,x,v);e.send({status:"ok",jwt:l,route:s.route})}catch(t){e.status(n),e.send({error:t})}})),t.post(e+"/dslogout",(async(t,e)=>{try{const n=t.query,s=f(t,q(n,t.path));if(!s)throw"missing session cookie";const o=k[n.dslabel]?.[s];if(!o)return void e.send({status:"ok"});delete k[n.dslabel][s];t.ip;await r.promises.appendFile(v,`${n.dslabel}\t${s}\t0\t\t${o.ip}\t${o.embedder}\t${o.route}\n`),e.send({status:"ok"})}catch(t){e.status(401),e.send({error:t})}})),t.post(e+"/jwt-status",(async(t,e)=>{let n=401;try{const r=t.query,s=q(r,t.path);if(!s)return void e.send({status:"ok"});if("/jwt-status"!=s.authRoute)throw n=400,`Incorrect authorization route, use ${s.authRoute}'`;const{email:o,ip:i}=await m(r,t.headers,s);g(t,i,s);const a=await p(r,e,k,v,o,t,s);n=401;const l=await d(t,r,a,s,x,v,o);e.send({status:"ok",jwt:l,route:s.route,[s.cookieId]:a})}catch(t){console.log(t),e.status(n),e.send(t instanceof Error||"object"!=typeof t?{error:t}:t)}})),t.post(e+"/authorizedActions",(async(t,e)=>{const n=t.query;try{const s=q(n,"termdb");if(!s)return void e.send({status:"ok"});const o=f(t),i=h(k,n.dslabel,o,t,s),a=k[n.dslabel]?.[o]||k[n.dslabel]?.[i],{email:l}=a.email,c=new Date;await r.promises.appendFile(w,`${n.dslabel}\t${l}\t${c}\t${n.action}\t${JSON.stringify(n.details)}\n`),e.send({status:"ok"})}catch(t){e.status(401),e.send("object"==typeof t?t:{error:t})}})),y.getDsAuth=function(t){const e=[],n=t.query.embedder||t.get("host").split(":")[0];for(const r in _){if(r.startsWith("__"))continue;const s=_[r];for(const o in s){const i=s[o];for(const s in i){if(!(0,l.isMatch)(n,s))continue;const a=i[s],c=f({query:Object.assign({},t.query,{dslabel:r}),headers:t.headers,cookies:t.cookies},a),u=k[r]?.[c],d=u?.time||0;e.push({dslabel:r,route:o,type:a.type||"basic",insession:("basic"!=a.type||!t.path.startsWith("/genomes"))&&(("jwt"!=a.type||c)&&Date.now()-d<x)})}}}return e},y.getForbiddenRoutesForDsEmbedder=function(t,e){const n=[],r=_[t]||_["*"];if(!r)return n;for(const t in r){const s=r[t][e]||r[t]["*"];"forbidden"==s?.type&&n.push(t)}return n},y.getRequiredCredForDsEmbedder=function(t,e){const n=[];for(const r in _)if((0,l.isMatch)(t,r))for(const t in _[r])for(const s in _[r][t]){if(!(0,l.isMatch)(e,s))continue;const o=_[r][t][s];n.push({route:t,type:o.type,headerKey:o.headerKey})}return n},y.userCanAccess=function(t,e){const n=q(t.query,t.path,u.samples);if(!n)return!0;if("basic"==n.type&&t.path.startsWith("/genomes"))return!1;const r=f(t,n),s=h(k,e.label,r,t,n),o=k[e.label]?.[r]||k[e.label]?.[s],i=o?.time||0;return Date.now()-i<x},y.getPayloadFromHeaderAuth=function(t,e){if(!t.headers?.authorization)return{};const n=q(t.query,e);if(!n)return{};const[r,s]=t.headers.authorization.split(" ");if("bearer"!=r.toLowerCase())throw`unsupported authorization type='${r}', allowed: 'Bearer'`;const o=Buffer.from(s,"base64").toString();return a().verify(o,n.secret)||{}}},getJwtPayload:m,canDisplaySampleIds:(t,e)=>!!e.cohort.termdb.displaySampleIds&&y.userCanAccess(t,e),getDsAuth:()=>[],getForbiddenRoutesForDsEmbedder:()=>[],userCanAccess:()=>!0,getRequiredCredForDsEmbedder:()=>{},getPayloadFromHeaderAuth:()=>({})}},7833:(t,e,n)=>{"use strict";n.r(e);var r=n(7147),s=n.n(r),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),h=n(5558),p=n(3602),m=n(6279);const g={snvindel:f,sv:m,fusion:m,svjson:n(8423),cnv:d,itd:p,deletion:h,truncation:n(8235)};function y(t,e,n,r,s,o){for(const i of e.yesSamples){if(o&&!o.includes(i))continue;n.has(i)||n.set(i,{sample:i});const e=n.get(i);r in e||(e[r]={key:r,values:[],label:r}),s?e[r].values.some((e=>e.dt==t&&e.origin==s))||e[r].values.push({dt:parseInt(t),class:"WT",_SAMPLEID_:i,origin:s}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:parseInt(t),class:"WT",_SAMPLEID_:i})}for(const i of e.noSamples){if(o&&!o.includes(i))continue;n.has(i)||n.set(i,{sample:i});const e=n.get(i);r in e||(e[r]={key:r,values:[],label:r}),s?e[r].values.some((e=>e.dt==t&&e.origin==s))||e[r].values.push({dt:parseInt(t),class:"Blank",_SAMPLEID_:i,origin:s}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:parseInt(t),class:"Blank",_SAMPLEID_:i})}}async function b(t,e){const n=t.cohort;try{if(n.mutationFlagSet)return n.mutationFlagSet;if(!n.mutationset)return;const r={},s=t.sampleName2Id;for(const[t,o]of n.mutationset.entries()){const n=await v(t,o,e);r[Math.random()]=n;for(const t in n.data)for(const e of n.data[t])e._SAMPLENAME_=e.sample.split(";")[0].trim(),e._SAMPLEID_=s.get(e._SAMPLENAME_)||e._SAMPLENAME_}return n.mutationFlagSet=r,r}catch(t){throw t}}async function v(t,e,n){const r=u.Dz(n);if(!r)throw"init_bulk_flag() failed";r.tpsetname=e.name?e.name:"set"+t;for(const t in e){if(!(t in g))throw`unknown mutationset: ${t}`;const n=e[t].startsWith("/")?e[t]:i().join(l().tpmasterdir,e[t]);try{const e=(await s().promises.readFile(n,"utf8")).trim().split(/\r?\n/);if(g[t].parseheader(e[0],r))throw`${t} header line error: herr`;for(let n=1;n<e.length;n++)g[t].parseline(n,e[n],r)}catch(t){throw t}}return r}exports.mayGetGeneVariantData=async function(t,e){const n=this,r=t.term.name,s=await b(n,e.genome),o=new Map;if(!s)return o;let i;e?.filter?.lst.length>0&&(i=[...new Set((await(0,c.cf)(e.filter,n)).map((t=>t.id)))]);for(const t in s){const e=s[t];if(r in e.data){for(const t of e.data[r]){const e=t._SAMPLEID_;if(i&&!i.includes(e))continue;o.has(e)||o.set(e,{sample:e});const n=o.get(e);r in n||(n[r]={key:r,values:[],label:r}),n[r].values.push(t)}if(n.assayAvailability?.byDt)for(const t in n.assayAvailability.byDt){const e=n.assayAvailability.byDt[t];if(e.byOrigin)for(const n in e.byOrigin){y(t,e.byOrigin[n],o,r,n,i)}else y(t,e,o,r,!1,i)}}}return o},exports.getTermTypes=async function(t){const e=this;try{const n="string"==typeof t.ids?JSON.parse(t.ids):t.ids,r=n.map((()=>"?")).join(","),s=`SELECT id, name, type, jsondata, parent_id FROM terms WHERE id IN (${r}) OR name IN (${r})`,o=e.cohort.db.connection.prepare(s).all([...n,...n]),i={};for(const t of o)t.jsondata&&Object.assign(t,JSON.parse(t.jsondata)),i[t.id]=t;const a=n.filter((t=>!i[t])),l=await b(e,t.genome);if(l)for(const t in l){const e=l[t];if(e.data)for(const t of a)t in e.data&&!(t in i)&&(i[t]={name:t,type:"geneVariant"})}return i}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}},exports.mayGetMatchingGeneNames=async function(t,e,n,r=25){const s=await b(this,n.genome);if(s)for(const n in s){const o=s[n];for(const n in o.data){if(n.length>r)continue;if(!o.data[n]?.length)continue;const s={name:n,type:"geneVariant",isleaf:!0};n===e?t.equals.push(s):n.startsWith(e)?t.startsWith.push(s):n.includes(" "+e)?t.startsWord.push(s):n.includes(e)?t.includes.push(s):"TP53"==n&&0}}},exports.get_flagset=b},4065:(t,e,n)=>{"use strict";function r(t,e){if(t.genomicNameRegexp.test(e.input))throw"invalid character in gene name";if(e.deep){const n={};let r;{const n=t.genedb.getnamebynameorisoform.get(e.input,e.input);n&&(r=n.name)}if(!r&&t.genedb.getNameByAlias){const n=t.genedb.getNameByAlias.get(e.input);n&&(r=n.name)}if(!r&&t.genedb.get_gene2canonicalisoform&&e.input.toUpperCase().startsWith("ENSG")){const s=t.genedb.get_gene2canonicalisoform.get(e.input);if(s&&s.isoform){const e=s.isoform;n.found_isoform=e;const o=t.genedb.getnamebynameorisoform.get(e,e);if(!o)throw"cannot map enst isoform to symbol";r=o.name}}r||(r=e.input);const s=t.genedb.getjsonbyname.all(r);return n.gmlst=s.map((t=>{const e=JSON.parse(t.genemodel);return t.isdefault&&(e.isdefault=!0),e})),n}const n=e.input.toUpperCase(),r=(n.substr(0,2),t.genedb.getnameslike.all(n+"%"));if(r.length)return r.sort(),{hits:r.map((t=>t.name))};if(t.genedb.getNameByAlias){const e=t.genedb.getNameByAlias.all(n);if(e.length)return{hits:e.map((t=>t.name))}}{const n=t.genedb.getnamebynameorisoform.get(e.input,e.input);if(n)return{hits:[n.name]}}return{hits:[]}}n.d(e,{S:()=>r})},2062:(t,e,n)=>{"use strict";n.d(e,{W:()=>a,A:()=>l});var r=n(334),s=n.n(r),o=n(7147),i=n.n(o);async function a(t){l.deps||async function(){const t=`${process.cwd()}/package.json`;try{if(!i().existsSync(t))return;{const e=i().readFileSync(t,{encoding:"utf8"}),n=JSON.parse(e),r=n?.dependencies["@sjcrh/proteinpaint-server"];r&&(l.deps["@sjcrh/proteinpaint-server"].entry=r);const s=n?.dependencies["@sjcrh/proteinpaint-client"];s&&(l.deps.entry["@sjcrh/proteinpaint-client"]||(l.deps["@sjcrh/proteinpaint-client"]={}),l.deps["@sjcrh/proteinpaint-client"]=s)}}catch(t){console.log(t)}}();const e={status:"ok",genomes:{},versionInfo:l};for(const n in t){const r=t[n],s={};if(r.genedb&&(s.genedb={buildDate:r.genedb.get_buildDate?.get().date||"unknown",tables:r.genedb.tableSize}),r.termdbs){s.termdbs={};for(const t in r.termdbs){const e=r.termdbs[t];s.termdbs[t]={buildDate:e.cohort.termdb.q.get_buildDate?.get().date||"unknown"}}}Object.keys(s).length&&e.genomes&&(e.genomes[n]=s)}return e}const l={pkgver:"2.42.1-0",codedate:function(){const t=i().existsSync(s().binpath+"/server.js")&&i().statSync(s().binpath+"/server.js").mtime||new Date(0),e=i().existsSync("public/bin/proteinpaint.js")&&i().statSync("public/bin/proteinpaint.js").mtime||new Date(0);return(t>e?t:e).toDateString()}(),launchdate:new Date(Date.now()).toString().split(" ").slice(0,5).join(" "),deps:{}},c=`${s().binpath}/package.json`;if(i().existsSync(c)){const t=JSON.parse(i().readFileSync(c,{encoding:"utf8"}));l.deps["@sjcrh/proteinpaint-server"]={installed:t.version}}const u=c.replace("server","client");if(i().existsSync(u)){const t=JSON.parse(i().readFileSync(u,{encoding:"utf8"}));l.deps["@sjcrh/proteinpaint-client"]={installed:t.version}}},9157:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>c});var r=n(7147),s=n.n(r),o=(n(1017),n(334)),i=n.n(o),a=n(2081),l=n(2781);async function c(t,e,n=[]){try{await s().promises.stat(t)}catch(e){throw`${t} does not exist`}const r=[],o=[];return new Promise(((s,c)=>{const u=(0,a.spawn)(i().Rscript,[t,...n]);if(e&&e.length>0)try{const t=e.join("\n")+"\n";l.Readable.from(t).pipe(u.stdin)}catch(t){u.kill();let e=t;o.length>0&&(e+=`\nR stderr: ${o.join("").trim()}`),c(e)}u.stdout.on("data",(t=>r.push(t))),u.stderr.on("data",(t=>o.push(t))),u.on("error",(t=>c(t))),u.on("close",(t=>{if(0!==t){let e=`R process exited with non-zero status code=${t}`;r.length>0&&(e+=`\nR stdout: ${r.join("").trim()}`),o.length>0&&(e+=`\nR stderr: ${o.join("").trim()}`),c(e)}if(o.length>0){const t=o.join("").trim();c(`R process emitted standard error\nR stderr: ${t}`)}const e=r.join("").trim().split("\n");s(e)}))}))}},901:(t,e,n)=>{"use strict";n.d(e,{T:()=>s,w:()=>o});var r=n(8907);async function s(t,e,n){if(!e)return;const s=function(t,e){{const e=t.filter||t.filterObj;if(e){if(!Array.isArray(e.lst))throw"filterObj.lst is not array";return 0==e.lst.length?null:e}}if(t.tid2value){if("object"!=typeof t.tid2value)throw"q.tid2value{} not object";return o(t.tid2value,e)}}(t,n);if(!s)return;const i=[...new Set((await(0,r.cf)(s,n)).map((t=>t.id)))];let a;a=Number.isInteger(e[0])?new Set(e):new Set(e.map((t=>t.name)));const l=new Set;for(const t of i)a.has(t)&&l.add(t);return l}function o(t,e){const n={type:"tvslst",in:!0,join:"and",lst:[]};for(const r in t){const s=e.cohort.termdb.q.termjsonByOneid(r);if(!s)continue;const o=t[r];n.lst.push({type:"tvs",tvs:{term:s,values:[{key:o}]}})}return n}},1169:(t,e,n)=>{"use strict";n.d(e,{Ak:()=>m,Z5:()=>v,sV:()=>R,eG:()=>b,r8:()=>D,z7:()=>P,ws:()=>O,nD:()=>C,wm:()=>I,IK:()=>k,CN:()=>w,xq:()=>y,vK:()=>g});var r=n(2273),s=n(4048),o=n(6452),i=n.n(o),a=n(1017),l=n.n(a),c=n(4973);function u(t){const e={op:t.in?"and":"not",content:[]};if(!Array.isArray(t.lst))throw"filter.lst[] not array";for(const n of t.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 t={op:n.tvs.isnot?"!=":"in",content:{field:f(n.tvs.term.id),value:n.tvs.values.map((t=>t.key))}};e.content.push(t)}else{if(!n.tvs.ranges)throw"unknown tvs structure when converting to gdc filter";for(const t of n.tvs.ranges)t.startunbounded?e.content.push({op:t.stopinclusive?n.tvs.isnot?">":"<=":n.tvs.isnot?">=":"<",content:{field:f(n.tvs.term.id),value:t.stop}}):t.stopunbounded?e.content.push({op:t.startinclusive?n.tvs.isnot?"<":">=":n.tvs.isnot?"<=":">",content:{field:f(n.tvs.term.id),value:t.start}}):n.tvs.isnot?e.content.push({op:"or",content:[{op:"and",content:[{op:t.startinclusive?"<":"<=",content:{field:f(n.tvs.term.id),value:t.start}}]},{op:"and",content:[{op:t.stopinclusive?">":">=",content:{field:f(n.tvs.term.id),value:t.stop}}]}]}):e.content.push({op:"and",content:[{op:t.startinclusive?">=":">",content:{field:f(n.tvs.term.id),value:t.start}},{op:t.stopinclusive?"<=":"<",content:{field:f(n.tvs.term.id),value:t.stop}}]})}}return e}function f(t){const e=t.split(".");return"case"==e[0]&&(e[0]="cases"),e.join(".")}n(3345);var d=n(334),h=n.n(d);function p(...t){h().debugmode&&console.log(t.join(" "))}function m(t,e){t.convertSampleId.get=t=>{const n={};for(const r of t)n[r]=e.__gdc.map2caseid.get(r)||r;return n}}async function g(t,e){const n=["consequence.transcript.is_canonical","consequence.transcript.transcript_id"];t.get=async t=>{if(!t.ssm_id)throw".ssm_id missing";const{host:r,headers:s}=e(t),o=await i()(r.rest+"/ssms/"+t.ssm_id+"?fields="+n.join(","),{method:"GET",headers:s});let a;try{a=JSON.parse(o.body)}catch(t){throw"invalid json in response"}if(!a.data||!a.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(a.data.consequence))throw".data.consequence not array";const l=a.data.consequence.find((t=>t.transcript.is_canonical));return l?l.transcript.transcript_id:a.data.consequence[0].transcript.transcript_id}}function y(t){t.queries.snvindel.byrange.get=async e=>await t.queries.snvindel.byisoform.get(e)}function b(t,e){t.queries.geneExpression.get=async n=>{if(!Array.isArray(n.genes))throw"q.genes[] not array";const r=new Map,s=new Date,o=await v(n,t);if(0==o.length)return{gene2sample2value:r,byTermId:{}};const a=new Date;p(o.length,"cases with exp data:",a-s,"ms");const[l,c]=await async function(t,e,n,r,s){const o=[],a=new Map;for(const n of t){const t=n.gene||n.name;if("string"!=typeof t)continue;if(t.startsWith("ENSG")&&15==t.length){o.push(t),a.set(t,t);continue}const r=e.genedb.getAliasByName.all(t);if(Array.isArray(r))for(const e of r)if(e.alias.startsWith("ENSG")){o.push(e.alias),a.set(e.alias,t);break}if(o.length>100)break}try{const{host:t,headers:e}=r.getHostHeaders(s),l=await i().post(`${t.geneExp}/gene_expression/gene_selection`,{headers:e,body:JSON.stringify({case_ids:n,gene_ids:o,selection_size:o.length})}),c=JSON.parse(l.body);if(!Array.isArray(c.gene_selection))throw"re.gene_selection[] not array";const u=[];for(const t of c.gene_selection){if("string"!=typeof t.gene_id)throw".gene_id missing from one of re.gene_selection[]";u.push(t.gene_id)}return[u,a]}catch(t){throw t}}(n.genes,e,o,t,n);if(0==l.length)return{gene2sample2value:r,byTermId:{}};const u=new Date;p(l.length,"out of",n.genes.length,"genes selected for exp:",u-a,"ms");const f={};for(const t of l){const e=c.get(t);f[e]={gencodeId:t},r.set(e,new Map)}const d=await async function(t,e,n,r,s,o){const{host:a,headers:l}=o.getHostHeaders(t),c=await i().post(`${a.geneExp}/gene_expression/values`,{headers:l,body:JSON.stringify({case_ids:n,gene_ids:e,format:"tsv",tsv_units:"uqfpkm"})});if("string"!=typeof c.body)throw"response.body is not tsv text";const u=c.body.trim().split("\n");if(u.length<=1)throw"less than 1 line from tsv response.body";const f=u[0].split("\t").slice(1);if(f.length!=n.length)throw"sample column length != case_ids.length";const d={};for(const t of f){const e=o.__gdc.caseid2submitter.get(t);if(!e)throw"case submitter id unknown for a uuid";d[t]={label:e}}for(let t=1;t<u.length;t++){const e=u[t].split("\t");if(e.length!=f.length+1)throw"number of fields in gene line does not equal header";const n=e[0];if(!n)throw"ensg l[0] missing from a line";const o=r.get(n);if(!o)throw"symbol missing for "+n;for(const[t,n]of f.entries()){const r=Number(e[t+1]);if(!Number.isFinite(r))throw"non-numeric exp value from gdc";s.get(o)[n]=r}}return d}(n,l,o,c,r,t);return p("gene-case matrix built:",new Date-u,"ms"),{gene2sample2value:r,byTermId:f,bySampleId:d}}}async function v(t,e){const n={op:"and",content:[]};t.filter0&&n.content.push(t.filter0),t.filterObj&&n.content.push(u(t.filterObj)),t.filter&&n.content.push(u(t.filter));const r={size:1e4,fields:"case_id"};n.content.length&&(r.case_filters=n);try{const{host:n,headers:s}=e.getHostHeaders(t),o=await i().post(l().join(n.rest,"cases"),{headers:s,body:JSON.stringify(r)}),a=JSON.parse(o.body);if(!Array.isArray(a.data.hits))throw"re.data.hits[] not array";const c=[];for(const t of a.data.hits)if(t.id&&e.__gdc.casesWithExpData.has(t.id)&&(c.push(t.id),1e3==c.length))break;return c}catch(t){throw t.stack&&console.log(t.stack),t}}function w(t){t.queries.snvindel.byisoform.get=async e=>{const n=_(e,t),s=await async function(t,e){const n=L,r=z,{host:s,headers:o}=e.getHostHeaders(t),a=i().post(l().join(s.rest,n.endpoint),{headers:o,body:JSON.stringify(Object.assign({size:n.size,fields:n.fields.join(",")},n.filters(t)))}),c=i().post(l().join(s.rest,r.endpoint),{headers:o,body:JSON.stringify(Object.assign({size:r.size,fields:r.fields.join(",")},r.filters(t,e)))}),[u,f]=await Promise.all([a,c]);let d,h;try{d=JSON.parse(u.body),h=JSON.parse(f.body)}catch(t){throw"invalid JSON returned by GDC"}if(!d.data||!d.data.hits)throw"query1 did not return .data.hits";if(!h.data||!h.data.hits)throw"query2 did not return .data.hits[]";if(!Array.isArray(d.data.hits)||!Array.isArray(h.data.hits))throw"re.data.hits[] is not array";const p=new Map;for(const e of d.data.hits){if(!e.ssm_id)throw"ssm_id missing from a ssms hit";if(!e.consequence)throw".consequence[] missing from a ssm";if(!Number.isInteger(e.start_position))throw"hit.start_position is not integer";let n;e.csqcount=e.consequence.length,n=t.isoform?e.consequence.find((e=>e.transcript.transcript_id==t.isoform)):e.consequence.find((t=>t.transcript.is_canonical)),e.consequence=n||e.consequence[0],e.cases=[],p.set(e.ssm_id,e)}for(const t of h.data.hits){if(!t.ssm)throw".ssm{} missing from a case";if(!t.ssm.ssm_id)throw".ssm.ssm_id missing from a case";const e=p.get(t.ssm.ssm_id);if(!e)throw"ssm_id not found in ssms query";if(!t.case)throw".case{} missing from a case";e.cases.push(t.case)}return[...p.values()]}(e,t),o=[];for(const t of s){const n={ssm_id:t.ssm_id,dt:r.dtsnvindel,chr:t.chromosome,pos:t.start_position-1,ref:t.reference_allele,alt:t.tumor_allele,isoform:e.isoform,csqcount:t.csqcount};if(x(n,t.consequence),!e.hiddenmclass||!e.hiddenmclass.has(n.class)){n.samples=[];for(const r of t.cases){const t={};if(e.gdcUseCaseuuid){if(t.sample_id=r.case_id,!t.sample_id)throw"gdcUseCaseuuid=true but c.case_id undefined"}else if(t.sample_id=r.observation?.[0]?.sample?.tumor_sample_uuid,!t.sample_id)throw"gdcUseCaseuuid=false but c.observation?.[0]?.sample?.tumor_sample_uuid undefined";n.samples.push(t)}o.push(n)}}if(n){e.isoform=n;for(const t of o)t.isoform=n}return o}}function _(t,e){if(!t.isoform)return;let n;if("N"==t.isoform[0]&&e.refseq2ensembl_query){const r=e.refseq2ensembl_query.get(t.isoform);r&&(n=t.isoform,t.isoform=r.ensembl)}return n}function x(t,e){if(e&&e.transcript.consequence_type){const[n,s,o]=r.vepinfo(e.transcript.consequence_type);t.class=s,t.mname=e.transcript.aa_change}t.mname||(t.mname=t.ref+">"+t.alt),t.class||(r.basecolor[t.ref]&&r.basecolor[t.alt]?t.class=r.mclasssnv:"-"==t.ref?t.class=r.mclassinsertion:"-"==t.alt?t.class=r.mclassdeletion:t.class=r.mclassmnv)}function k(t){const e=["cnv.cnv_change","cnv.gene_level_cn","cnv.consequence.gene.symbol","case.submitter_id","case.case_id"];function n(t){const n=e.slice();if(t.twLst)for(const e of t.twLst){let t=e.term.id;t.startsWith("case.")&&(t="occurrence."+t),n.push(t)}return n.join(",")}function s(t){if(!t.gene&&"string"!=typeof t.gene)throw"p.gene does not provide non-empty string";const e={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};return t.gene&&e.filters.content.push({op:"=",content:{field:"cnv.consequence.gene.symbol",value:t.gene.split(",")}}),t.filter0&&e.case_filters.content.push(t.filter0),t.filterObj&&e.case_filters.content.push(u("string"==typeof t.filterObj?JSON.parse(t.filterObj):t.filterObj)),e}t.queries.geneCnv.bygene.get=async e=>{const{host:o,headers:a}=t.getHostHeaders(e),c=await i().post(l().join(o.rest,"cnv_occurrences"),{headers:a,body:JSON.stringify(Object.assign({size:1e5,fields:n(e)},s(e)))}),u=JSON.parse(c.body);if(!Array.isArray(u?.data?.hits))throw"geneCnv response body is not {data:hits[]}";const f={ssm_id:"geneCnvGain",dt:r.dtcnv,class:r.mclasscnvgain,samples:[]},d={ssm_id:"geneCnvLoss",dt:r.dtcnv,class:r.mclasscnvloss,samples:[]};for(const t of u.data.hits){if("object"!=typeof t.cnv)throw"hit.cnv{} not obj";if("object"!=typeof t.case)throw"hit.case{} not obj";if(!t.cnv.gene_level_cn)throw"hit.cnv.gene_level_cn is not true";let n;if("Gain"==t.cnv.cnv_change)n=f;else{if("Loss"!=t.cnv.cnv_change)throw"hit.cnv.cnv_change is not Gain/Loss";n=d}const r={sample_id:t.case.case_id};if(e.twLst)for(const n of e.twLst)S(r,t.case,n);n.samples.push(r)}const h=[];return f.samples.length&&h.push(f),d.samples.length&&h.push(d),h}}function N(t,e){if(!e)return;const n=e.split(",");for(const e of n){const n=e.split("--");if(2==n.length)return t.geneA=n[0].split("(")[0],void(t.geneB=n[1].split("(")[0])}}function S(t,e,n){const r=n.term.id.split(".");if(function e(s,o){const i=r[o];if(o==r.length-1)return void(t[n.term.id]?t[n.term.id].add(s[i]):t[n.term.id]=s[i]);const a=s[i];if(null==a)return;if(Array.isArray(a)){t[n.term.id]=new Set;for(const t of a)e(t,o+1);return}e(a,o+1)}(e,1),t[n.term.id]instanceof Set&&(t[n.term.id]=[...t[n.term.id]][0]),n.term.id in t&&"categorical"==n.term.type){const e=function(t,e){if("custom-groupset"==e.q?.type&&Array.isArray(e.q?.groupsetting?.customset?.groups))for(const n of e.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((e=>e.key==t)))return n.name}if("predefined-groupset"==e.q?.type&&Number.isInteger(e.q.groupsetting?.predefined_groupset_idx)&&e.term.groupsetting?.lst[e.q.groupsetting.predefined_groupset_idx])for(const n of e.term.groupsetting.lst[e.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((e=>e.key==t)))return n.name}}(t[n.term.id],n);e&&(t[n.term.id]=e)}}function A(t,e){const n={};for(const r of e)if(("integer"==r.term.type||"float"==r.term.type)&&r.q?.mode)if("discrete"==r.q.mode||"binary"==r.q.mode){const e={};for(const n of t){const t=n[r.term.id];Number.isFinite(t)&&("min"in e?(e.min=Math.min(t,e.min),e.max=Math.max(t,e.max)):(e.min=t,e.max=t))}const o=(0,s.gp)(r.q,(t=>e),r.term.valueConversion);for(const t of o)t.name=t.label;n[r.term.id]={bins:o};for(const e of t){const t=e[r.term.id];Number.isFinite(t)&&(e[r.term.id]=M(o,t))}}else if("continuous"!=r.q.mode)throw"mayApplyBinning: unknown numeric q.mode";return n}function M(t,e){for(const n of t)if(n.startunbounded){if(e<n.stop)return n.label;if(n.stopinclusive&&e==n.stop)return n.label}else if(n.stopunbounded){if(e>n.start)return n.label;if(n.startinclusive&&e==n.start)return n.label}else if((e>n.start||e===n.start&&n.startinclusive)&&(e<n.stop||e===n.stop&&n.stopinclusive))return n.label}function T(t){for(const e of t)if(null==e.id||""==e.id){if(!e?.term?.id)throw"tw.id and tw.term are both missing";e.id=e.term.id}else e.term||(e.term={id:e.id})}async function C(t,e,n,r){if(t.isHierCluster)return await async function(t,e,n){const r={op:"and",content:[]};t.filter0&&r.content.push(t.filter0);t.filterObj&&r.content.push(u(t.filterObj));const s=[];for(const t of e){const e=n.cohort.termdb.q.termjsonByOneid(t.term.id);e&&s.push({term:e,q:t.q})}const o=["case_id"],a=new Map;for(const t of s){const e=t.term.id.replace(/^case\./,"");o.push(e),a.set(e,t.term.id)}const{host:c,headers:f}=n.getHostHeaders(t),d=await i().post(l().join(c.rest,"cases"),{headers:f,body:JSON.stringify({size:n.__gdc.casesWithExpData.size,fields:o.join(","),case_filters:r.content.length?r:void 0})}),h=JSON.parse(d.body);if(!Array.isArray(h?.data?.hits))throw"re.data.hits[] not array";const p=[];for(const t of h.data.hits){if("string"!=typeof t.case_id)throw"h.case_id missing";if(!n.__gdc.casesWithExpData.has(t.case_id))continue;const e={sample_id:t.case_id};for(const n of s)S(e,t,n);p.push(e)}const m=A(p,s);return{byTermId:m,samples:p}}(t,e,n);if(T(e),r){if(!Array.isArray(r))throw"geneTwLst not array";t.isoforms=[];for(const e of r){if(!e?.term?.name)throw"gene tw missing .term.name";if(e.term.isoform)t.isoforms.push(e.term.isoform);else{if("object"!=typeof t.genome)throw"serverside genome obj missing, needed to map gene name to canonical isoform";if(!t.genome?.genedb?.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const n=t.genome.genedb.get_gene2canonicalisoform.get(e.term.name);if(!n?.isoform)continue;t.isoforms.push(n.isoform)}}}e.some((t=>"case.observation.sample.tumor_sample_uuid"==t.id))||e.push({term:{id:"case.observation.sample.tumor_sample_uuid"}}),e.some((t=>"case.case_id"==t.id))||e.push({term:{id:"case.case_id"}}),"samples"==t.get&&(t.ssm_id_lst||t.isoform)&&(e.some((t=>"ssm.ssm_id"==t.id))||e.push({term:{id:"ssm.ssm_id"}}),e.some((t=>"case.observation.read_depth.t_alt_count"==t.id))||e.push({term:{id:"case.observation.read_depth.t_alt_count"}}),e.some((t=>"case.observation.read_depth.t_depth"==t.id))||e.push({term:{id:"case.observation.read_depth.t_depth"}}),e.some((t=>"case.observation.read_depth.n_depth"==t.id))||e.push({term:{id:"case.observation.read_depth.n_depth"}}));const s=[];for(const t of e){const e=n.cohort.termdb.q.termjsonByOneid(t.term.id);e&&s.push({term:e,q:t.q})}const o=e.map((t=>t.term.id));t.hiddenmclass&&(o.push("ssm.consequence.transcript.consequence_type"),o.push("ssm.consequence.transcript.transcript_id"),o.push("ssm.consequence.transcript.is_canonical")),t.rglst&&(o.push("ssm.chromosome"),o.push("ssm.start_position"));const a={size:1e4,fields:o.join(",")};_(t,n),Object.assign(a,z.filters(t,n));const{host:f,headers:d}=n.getHostHeaders(t),h=await i().post(l().join(f.rest,z.endpoint),{headers:d,body:JSON.stringify(a)});let p;delete t.isoforms;try{p=JSON.parse(h.body)}catch(t){throw"invalid JSON from GDC for variant2samples query"}if(!p.data||!p.data.hits)throw"variant2samples data structure not data.hits[]";if(!Array.isArray(p.data.hits))throw"variant2samples re.data.hits is not array for query";const m=[];for(const e of p.data.hits){if(!e.case)throw"variant2samples .case{} missing from a hit";const r={};if(e.ssm&&(r.ssm_id=e.ssm.ssm_id),t.hiddenmclass){if(!Array.isArray(e.ssm?.consequence))continue;let n;n=t.isoform?e.ssm.consequence.find((e=>e.transcript.transcript_id==t.isoform)):e.ssm.consequence.find((t=>t.transcript.is_canonical));const r={};if(x(r,n||e.ssm.consequence[0]),t.hiddenmclass.has(r.class))continue}if(t.gdcUseCaseuuid){if(r.sample_id=e.case.case_id,!r.sample_id)throw"querySamples_gdcapi: case.case_id missing"}else{const t=e.case?.observation?.[0]?.sample?.tumor_sample_uuid;if(!t)throw"querySamples_gdcapi: aliquot_id missing";r.sample_id=await n.__gdc.aliquot2submitter.get(t),r.sample_URLid=e.case.case_id+"?bioId="+t}for(const t of s)S(r,e.case,t);j(e.case,r),E(r,n),m.push(r)}const g=A(m,s);if(r){const t={gene:r.map((t=>t.term.name)).join(","),twLst:s},e=await n.queries.geneCnv.bygene.get(t);for(const t of e)for(const e of t.samples)m.push(e)}const y=new Map;for(const t of m)(0,c.z9)([t],y,t.ssm_id);return{byTermId:g,samples:[...y.values()]}}function j(t,e){if(!t.observation)return;const n=t.observation[0];n&&n.read_depth&&(e.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 E(t,e){const n=t["case.project.project_id"];n&&(t.caseIsOpenAccess=e.__gdc.gdcOpenProjects?.has(n))}async function O(t,e,n,r){T(t);const s=[];for(const e of t)e.term&&"categorical"==e.term.type&&s.push({id:e.id,path:e.id.replace("case.","").replace(/\./g,"__"),type:e.term.type});const o=function(t){const e=[];for(const n of t)if(n.id)if(n.type="categorical")e.push(n.path+" {buckets { doc_count, key }}");else{if("integer"!=n.type&&"float"!=n.type)throw"unknown term type";e.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${e.join("\n")}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`;return n}(s),a=function(t,e){const n={filters:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}}]}};Z(t?.tid2value,n.filters.content,e),t&&t.ssm_id_lst&&n.filters.content.push({op:"=",content:{field:"cases.gene.ssm.ssm_id",value:t.ssm_id_lst.split(",")}});t.filter0&&n.filters.content.push(t.filter0);t.filterObj&&n.filters.content.push(u(t.filterObj));return n}(e,r),{host:l,headers:c}=r.getHostHeaders(e),f=await i().post(l.graphql,{headers:c,body:JSON.stringify({query:o,variables:a})});let d;try{d=JSON.parse(f.body)}catch(t){throw"invalid JSON from GDC for cohortTotal for query :"+o+" and filter: "+filter}const h=["data","explore","cases","aggregations"];let p=d[h[0]];for(let t=1;t<h.length;t++)if(p=p[h[t]],!p)throw`.${h[t]} missing from data structure of termid2totalsize2 for query :${o} and filter: ${filter}`;for(const t of s){if("categorical"==t.type&&!Array.isArray(p[t.path].buckets))throw h.join(".")+" not array for query :"+o+" and filter: "+filter;if(("integer"==t.type||"float"==t.type)&&"object"!=typeof p[t.path].stats)throw h.join(".")+" not object for query :"+o+" and filter: "+filter}const m=new Map;for(const t of s)if("categorical"==t.type){const e=p[t.path].buckets,n=[];for(const t of e)n.push([t.key.replace(".","__"),t.doc_count]);m.set(t.id,n)}else if("integer"==t.type||"float"==t.type){const e=p[t.path].stats.count;m.set(t.id,{total:e})}return n?[m,n]:m}function I(t){const e=["consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change"];t.queries.snvindel.m2csq.get=async n=>{const{host:r,headers:s}=t.getHostHeaders(n),o=await i()(r.rest+"/ssms/"+n.ssm_id+"?fields="+e.join(","),{method:"GET",headers:s});let a;try{a=JSON.parse(o.body)}catch(t){throw"invalid json in response"}if(!a.data||!a.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(a.data.consequence))throw".data.consequence not array";return a.data.consequence.map((t=>t.transcript))}}function R(t,e){t.queries.singleSampleMutation.get=async e=>{if(e.sample.startsWith("___")){const t=e.sample.substring(3);if(!t)throw"expecting uuid after prefix but got blank";e.case_id=t}else t.__gdc.caseid2submitter.has(e.sample)?e.case_id=e.sample:(e.case_id=t.__gdc.map2caseid.get(e.sample),e.case_id||(e.case_id=await F(e.sample,t)));return await async function(t,e,n){const s={mlst:[],dt2total:[]};{const{host:n,headers:o}=e.getHostHeaders(t),a=await i().post(l().join(n.rest,L.endpoint),{headers:o,body:JSON.stringify({size:1e4,fields:L.fields.join(","),filters:L.filters(t).filters})}),c=JSON.parse(a.body);if(!Number.isInteger(c.data?.pagination?.total))throw"re.data.pagination.total not integer";if(!Array.isArray(c.data?.hits))throw"re.data.hits[] not array";c.data.hits.length<c.data.pagination.total&&s.dt2total.push({dt:1,total:c.data.pagination.total});for(const t of c.data.hits){let e=t.consequence.find((t=>1==t.transcript.is_canonical));e||(e=t.consequence[0]);const n=e.transcript.aa_change||e.transcript.consequence_type,[o,i,a]=r.vepinfo(e.transcript.consequence_type);s.mlst.push({dt:r.dtsnvindel,mname:n,class:i,gene:e.transcript.gene.symbol,chr:t.chromosome,pos:t.start_position,ref:t.reference_allele,alt:t.tumor_allele})}}{const n=await async function(t,e){const{host:n,headers:s}=e.getHostHeaders(t),o=await i().post(l().join(n.rest,"files"),{headers:s,body:JSON.stringify({size:1e4,fields:["cases.samples.sample_type","data_type","file_id","data_format","experimental_strategy","analysis.workflow_type"].join(","),filters:function(t){if(!t.case_id)throw".case_id missing";return{op:"and",content:[{op:"in",content:{field:"cases.case_id",value:[t.case_id]}},{op:"in",content:{field:"data_type",value:["Masked Copy Number Segment","Copy Number Segment","Transcript Fusion"]}}]}}(t)})}),a=JSON.parse(o.body);if(!Array.isArray(a.data.hits))throw"re.data.hits[] not array";let c,u,f;for(const t of a.data.hits)if("BEDPE"!=t.data_format){if("TXT"==t.data_format){if("Genotyping Array"==t.experimental_strategy){const e=t.cases?.[0].samples?.[0]?.sample_type;if(!e)continue;if(e.includes("Normal"))continue;if("Masked Copy Number Segment"!=t.data_type)continue;c=t.file_id;continue}if("WGS"==t.experimental_strategy){if(!t.file_id)continue;if("Copy Number Segment"!=t.data_type)continue;u=t.file_id;continue}}}else{if("RNA-Seq"!=t.experimental_strategy)continue;if("Arriba"!=t.analysis?.workflow_type)continue;if("Transcript Fusion"!=t.data_type)continue;f=t.file_id}const d=[];if(u){const t=(await i()(l().join(n.rest,"data")+"/"+u,{method:"GET",headers:s})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t");if(7!=n.length)continue;const s=Number(n[4]),o=Number(n[5]),i=Number(n[6]);if(Number.isNaN(s)||Number.isNaN(o)||Number.isNaN(i))continue;const a={dt:r.dtcnv,chr:n[1],start:Number(n[2]),stop:Number(n[3]),value:s};!a.chr||Number.isNaN(a.start)||Number.isNaN(a.stop)||(d.push(a),s>0&&0==i&&o>0&&d.push({dt:r.dtloh,chr:a.chr,start:a.start,stop:a.stop,segmean:.5}))}}else if(c){const t=(await i()(l().join(n.rest,"data")+"/"+c,{method:"GET",headers:s})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t");if(6!=n.length)continue;if(!n[1])continue;const s={dt:r.dtcnv,chr:"chr"+n[1],start:Number(n[2]),stop:Number(n[3]),value:Number(n[5])};Number.isNaN(s.start)||Number.isNaN(s.stop)||Number.isNaN(s.value)||d.push(s)}}if(f)try{const t=(await i()(l().join(n.rest,"data")+"/"+f,{method:"GET",headers:s})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t"),s={dt:r.dtfusionrna,chrA:n[0],posA:Number(n[1]),chrB:n[3],posB:Number(n[4])};s.chrA&&s.chrB&&!Number.isNaN(s.posA)&&!Number.isNaN(s.posB)&&(N(s,n[6]),d.push(s))}}catch(t){}return d}(t,e);s.mlst.push(...n)}return s}(e,t)}}async function F(t,e){const{host:n,headers:r}=e.getHostHeaders(q),s=await i().post(`${n.rest}/cases`,{headers:r,body:JSON.stringify({size:1,fields:"case_id,submitter_id",filters:{op:"or",content:[{op:"=",content:{field:"samples.portions.analytes.aliquots.aliquot_id",value:[t]}},{op:"=",content:{field:"submitter_id",value:[t]}},{op:"=",content:{field:"samples.submitter_id",value:[t]}}]}})}),o=JSON.parse(s.body);for(const t of o.data.hits)if(t.case_id)return t.case_id;throw"cannot convert to case_id (uuid)"}function P(t,e){t.queries.singleCell.samples.get=async e=>{const n={op:"and",content:[]};e.filter0&&n.content.push(e.filter0);const r={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:["id","cases.submitter_id","cases.project.project_id","cases.samples.sample_type","cases.samples.submitter_id","cases.primary_site","cases.disease_type"].join(",")},{host:s,headers:o}=t.getHostHeaders(e),a=await i().post(l().join(s.rest,"files"),{headers:o,body:JSON.stringify(r)});let c;try{c=JSON.parse(a.body)}catch(t){throw"invalid JSON from "+api.endpoint}if(!Number.isInteger(c.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(c.data?.hits))throw"re.data.hits[] not array";const u=new Map;for(const t of c.data.hits){if(!t.id)throw"h.id (fileId) missing";const e=t.id,n=t.cases?.[0];if(!n)throw"h.cases[0] missing";const r=n.submitter_id;if(u.has(r)||u.set(r,{sample:r,primarySite:n.primary_site,diseaseType:n.disease_type,projectId:n.project?.project_id,files:[]}),!n.samples?.[0])throw"h.cases[0].samples[0] missing";u.get(r).files.push({fileId:e,sampleName:n.samples[0].submitter_id,sampleType:n.samples[0].sample_type})}return{samples:[...u.values()],fields:t.queries.singleCell.samples.fields,columnNames:t.queries.singleCell.samples.columnNames}}}function D(t,e){t.queries.singleCell.data.get=async e=>{const{host:n,headers:r}=t.getHostHeaders(e),s=(await i()(l().join(n.rest,"data",e.sample),{method:"GET",headers:r})).body.trim().split("\n"),o={name:"UMAP",cells:[],colorBy:"Cluster"},a={name:"TSNE",cells:[],colorBy:"Cluster"},c={name:"PCA",cells:[],colorBy:"Cluster"},u={id:"cluster",name:"Seurat cluster",type:"categorical",values:{}},f={[u.id]:{}};for(let t=1;t<s.length;t++){const e=s[t],n=e.split("\t"),r=n[0];if(!r)throw"cellId missing from a line: "+e;const i=n[3];if(!i)throw"seuratCluster missing from a line";u.values[i]={label:"Cluster "+i},f[u.id][r]=`Cluster ${i}`;const l=Number(n[4]),d=Number(n[5]),h=Number(n[9]),p=Number(n[10]),m=Number(n[14]),g=Number(n[15]);if(Number.isNaN(l))throw"umap1 is nan";if(Number.isNaN(d))throw"umap2 is nan";if(Number.isNaN(h))throw"tsne1 is nan";if(Number.isNaN(p))throw"tsne2 is nan";if(Number.isNaN(m))throw"pc1 is nan";if(Number.isNaN(g))throw"pc2 is nan";const y=`Cluster ${i}`;o.cells.push({cellId:r,x:l,y:d,category:y}),a.cells.push({cellId:r,x:h,y:p,category:y}),c.cells.push({cellId:r,x:m,y:g,category:y})}return{plots:[a,o,c],terms:[u],tid2cellvalue:f}}}const L={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:t=>{const e={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};let n;if(t.rglst&&(n=t.rglst[0],$(n)),t.isoform){if("string"!=typeof t.isoform)throw".isoform value not string";e.filters.content.push({op:"=",content:{field:"consequence.transcript.transcript_id",value:[t.isoform]}}),n&&(e.filters.content.push({op:">=",content:{field:"start_position",value:n.start}}),e.filters.content.push({op:"<=",content:{field:"start_position",value:n.stop}}))}else if(n)e.filters.content.push({op:"=",content:{field:"chromosome",value:n.chr}}),e.filters.content.push({op:">=",content:{field:"start_position",value:n.start}}),e.filters.content.push({op:"<=",content:{field:"start_position",value:n.stop}});else{if(!t.case_id)throw".isoform, .rglst, and .case_id are all missing";if("string"!=typeof t.case_id)throw".case_id value not string";e.filters.content.push({op:"=",content:{field:"cases.case_id",value:[t.case_id]}})}if(t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";e.case_filters.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}return t.filter0&&e.case_filters.content.push(t.filter0),t.filterObj&&e.case_filters.content.push(u(t.filterObj)),e}};function $(t){if("object"!=typeof t)throw"p.rglst[0] not object";if("string"!=typeof t.chr||!t.chr||!Number.isInteger(t.start)||!Number.isInteger(t.stop))throw"p.rglst[0] not valid {chr,start,stop}"}const z={endpoint:"/ssm_occurrences",size:1e5,fields:["ssm.ssm_id","case.case_id","case.submitter_id","case.observation.sample.tumor_sample_uuid"],filters:(t,e)=>{const n={filters:{op:"and",content:[]},case_filters:{op:"and",content:[]}};let r=!1;if(t.ssm_id_lst){if("string"!=typeof t.ssm_id_lst)throw"ssm_id_lst not string";n.filters.content.push({op:"=",content:{field:"ssm.ssm_id",value:t.ssm_id_lst.split(",")}}),r=!0}else if(t.isoform)n.filters.content.push({op:"=",content:{field:"ssms.consequence.transcript.transcript_id",value:[t.isoform]}}),r=!0;else if(t.isoforms){if(!Array.isArray(t.isoforms))throw".isoforms[] not array";n.filters.content.push({op:"in",content:{field:"ssms.consequence.transcript.transcript_id",value:t.isoforms}}),r=!0}{let e;if(t.rglst&&(e=t.rglst[0],$(e)),r)e&&(n.filters.content.push({op:">=",content:{field:"ssms.start_position",value:e.start}}),n.filters.content.push({op:"<=",content:{field:"ssms.start_position",value:e.stop}}));else{if(!e)throw".ssm_id_lst, .isoform, .isoforms, .rglst[] are all missing";n.filters.content.push({op:"=",content:{field:"ssms.chromosome",value:e.chr}}),n.filters.content.push({op:">=",content:{field:"ssms.start_position",value:e.start}}),n.filters.content.push({op:"<=",content:{field:"ssms.start_position",value:e.stop}})}}if(t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";n.case_filters.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}return t.filter0&&n.case_filters.content.push(t.filter0),t.filterObj&&n.case_filters.content.push(u(t.filterObj)),Z(t.tid2value,n.case_filters.content,e),n}};function Z(t,e,n){if(t)for(const r in t){const s=n.cohort.termdb.q.termjsonByOneid(r);if(!s)continue;const o=r.replace(/^case\./,"cases.");if("categorical"==s.type)e.push({op:"in",content:{field:o,value:[t[r]]}});else if("integer"==s.type)for(const n of t[r])e.push({op:n.op,content:{field:o,value:n.range}})}}},4973:(t,e,n)=>{"use strict";n.d(e,{z9:()=>h,dq:()=>f,uK:()=>d});var r=n(1881),s=n(1169),o=n(9064),i=n(7011);async function a(t,e){const n=[];let r=null,s=null;for(const o of e.map((e=>e[t.id]))){if(t.values?.[o]?.uncomputable)continue;const e=Number(o);Number.isFinite(e)&&(n.push(e),null===r?r=s=e:(r=Math.min(r,e),s=Math.max(s,e)))}const a=(0,o.Z)().domain([r,s]).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:r,maxvalue:s,densityMax:l.densityMax,density:l.bins,samplecount:n.length,unit:t.unit,ticks:20}}n(3345);var l=n(2273),c=n(4065),u=n(2974);const f=".";function d(t){const e=t.variant2samples;if(e){if(e.type_samples="samples",e.type_sunburst="sunburst",e.type_summary="summary",!e.variantkey)throw".variantkey missing from variant2samples";if(-1==["ssm_id"].indexOf(e.variantkey))throw"invalid value of variantkey";if(e.twLst){if(!Array.isArray(e.twLst))throw"variant2samples.twLst[] is not array";if(0==e.twLst.length)throw"variant2samples.twLst[] empty array";if(!t.cohort||!t.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.twLst is in use";for(const n of e.twLst){if(!n.id)throw"tw.id missing from one of variant2samples.twLst[]";const e=t.cohort.termdb.q.termjsonByOneid(n.id);if(!e)throw"term not found for one of variant2samples.twLst: "+n.id;if(n.term=e,!n.q)throw"tw.q{} missing for one of variant2samples.twLst: "+n.id}}if(e.sunburst_twLst){if(!Array.isArray(e.sunburst_twLst))throw".sunburst_twLst[] not array from variant2samples";if(0==e.sunburst_twLst.length)throw".sunburst_twLst[] empty array from variant2samples";if(!t.cohort||!t.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.sunburst_twLst is in use";for(const n of e.sunburst_twLst){if(!n.id)throw"tw.id missing from one of variant2samples.sunburst_twLst[]";const e=t.cohort.termdb.q.termjsonByOneid(n.id);if(!e)throw"term not found for one of variant2samples.sunburst_twLst: "+n.id;if(n.term=e,!n.q)throw"tw.q{} missing for one of variant2samples.sunburst_twLst: "+n.id}}if(e.gdcapi);else{let e=!1;if(t.queries?.snvindel?.byrange?._tk?.samples&&(e=!0),t.queries?.svfusion?.byrange?.samples&&(e=!0),!e)throw"cannot find a sample source from ds.queries{}"}e.get=async e=>await async function(t,e){!function(t,e){if("samples"==t.get){const n=e.queries?.snvindel?.byrange;n&&(n.bcffile||n.chr2bcffile)&&n._tk.format&&(t.addFormatValues=!0)}}(t,e);const n=await async function(t,e){const n=t.twLst?t.twLst.slice():[];if(e.variant2samples.gdcapi)return await(0,s.nD)(t,n,e,t.geneTwLst);if(t.ssm_id_lst)return await async function(t,e,n){const r=new Map;for(const e of t.ssm_id_lst.split(",")){const s=e.split(f);if(4!=s.length){if(6!=s.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[e,o,i,a,c,u]=s,f=decodeURIComponent(u),d=Number(e);if(d!=l.dtsv&&d!=l.dtfusionrna)throw"dt not sv/fusion";const p=Number(i);if(Number.isNaN(p))throw"position not integer";const m=Number(c);if(Number.isNaN(m))throw"pairlstIdx not integer";const g=Object.assign({},t,{rglst:[{chr:o,start:p,stop:p+1}]}),y=await n.queries.svfusion.byrange.get(g);for(const t of y)t.dt==d&&t.pos==p&&t.strand==a&&t.pairlstIdx==m&&t.mname==f&&h(t.samples,r,t.ssm_id)}}else{if(!n.queries.snvindel||!n.queries.snvindel.byrange)throw"queries.snvindel.byrange missing when id has 4 fields";const[e,o,i,a]=s,l=Number(o);if(Number.isNaN(l))throw"no integer position for snvindel from ssm id";const c=Object.assign({},t,{rglst:[{chr:e,start:l,stop:l}]}),u=await n.queries.snvindel.byrange.get(c);for(const t of u)t.pos==l&&t.ref==i&&t.alt==a&&h(t.samples,r,t.ssm_id)}}return p(r,e,n),{samples:[...r.values()]}}(t,n,e);if(t.rglst)return await m(t,n,e);if(t.geneTwLst){if("object"!=typeof t.genome)throw"serverside genome obj needed";t.rglst=[];for(const e of t.geneTwLst)if(e.term.chr&&e.term.start&&e.term.stop)t.rglst.push({chr:e.term.chr,start:e.term.start,stop:e.term.stop});else{const n=c.S(t.genome,{deep:1,input:e.term.name});if(n.gmlst){const e=n.gmlst[0];t.rglst.push({chr:e.chr,start:e.start,stop:e.stop})}}const r=await m(t,n,e);return delete t.rglst,{samples:r}}if(!e?.cohort?.termdb)throw"unable to do sql query: .cohort.termdb missing for ds";const r={ds:e,filter:t.filter||t.filterObj},o=await(0,u.gh)(r,t.twLst),i=[];for(const e in o.samples){const n=o.samples[e];n.sample_id=n.sample,delete n.sample;for(const e of t.twLst)n[e.term.id]&&(n[e.term.id]=n[e.term.id].key);i.push(n)}return{samples:i}}(t,e);if(t.get==e.variant2samples.type_samples)return!t.useIntegerSampleId&&e?.cohort?.termdb?.q?.id2sampleName&&n.samples.forEach((t=>t.sample_id=e.cohort.termdb.q.id2sampleName(t.sample_id))),n;if(t.get==e.variant2samples.type_sunburst)return n.nodes=await async function(t,e,n){const s=(0,r.N)(t,n.twLst.map((t=>({k:t.id}))));for(const t of s)delete t.lst;if(e?.cohort?.termdb?.termid2totalsize2){const t=await async function(t,e,n,r){if(0==t.length)throw"zero terms for crosstab";if(t.length>3)throw"crosstab will not work with more than 3 levels";const s=[],o=new Map;for(const e of t)o.set(e.id,new Set);const i=!r;if(r)for(const n of r){if(n.id0){if(!n.v0)continue;o.get(n.id0).add(e.cohort.termdb.useLower?n.v0.toLowerCase():n.v0)}if(n.id1&&t[1]){if(!n.v1)continue;o.get(n.id1).add(e.cohort.termdb.useLower?n.v1.toLowerCase():n.v1)}if(n.id2&&t[2]){if(!n.v2)continue;o.get(n.id2).add(e.cohort.termdb.useLower?n.v2.toLowerCase():n.v2)}}const a=t[0].id;{const r={};n.filterObj&&(r.filterObj=n.filterObj),n.filter0&&(r.filter0=n.filter0);const l=await e.cohort.termdb.termid2totalsize2.get([t[0]],r);for(const[t,n]of l.get(a)){const r=e.cohort.termdb.useLower?t.toLowerCase():t;i?(o.get(a).add(r),s.push({count:n,id0:a,v0:r})):o.get(a).has(r)&&s.push({count:n,id0:a,v0:r})}}const l=t?.[1]?.id;if(l){const r=[];for(const s of o.get(a)){const o={tid2value:{[a]:s}};n.filterObj&&(o.filterObj=n.filterObj),n.filter0&&(o.filter0=n.filter0),r.push(e.cohort.termdb.termid2totalsize2.get([t[1]],o,s))}const c=await Promise.all(r);for(const[t,n]of c)for(const[r,c]of t.get(l)){const t=e.cohort.termdb.useLower?r.toLowerCase():r;i?(o.get(l).add(t),s.push({count:c,id0:a,v0:n,id1:l,v1:t})):o.get(l).has(t)&&s.push({count:c,id0:a,v0:n,id1:l,v1:t})}}const c=t?.[2]?.id;if(c){const r=[];for(const s of o.get(a))for(const i of o.get(l)){const o={tid2value:{[a]:s,[l]:i}};n.filterObj&&(o.filterObj=n.filterObj),n.filter0&&(o.filter0=n.filter0),r.push(e.cohort.termdb.termid2totalsize2.get([t[2]],o,{v0:s,v1:i}))}const u=await Promise.all(r);for(const[t,n]of u)for(const[t,r]of v2counts.get(c)){const u=e.cohort.termdb.useLower?t.toLowerCase():t;i?(o.get(c).add(u),s.push({count:r,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:u})):o.get(c).has(u)&&s.push({count:r,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:u})}}return s}(n.twLst,e,n,s);await async function(t,e,n){for(const r of t){if(!r.id0)continue;if(!r.v0)continue;const t=n.cohort.termdb.useLower?r.v0.toLowerCase():r.v0;if(!r.id1){const n=e.find((e=>null==e.id1&&e.v0==t));n&&(r.cohortsize=n.count);continue}if(!r.v1)continue;const s=n.cohort.termdb.useLower?r.v1.toLowerCase():r.v1;if(!r.id2){const n=e.find((e=>null==e.id2&&e.v0==t&&e.v1==s));n&&(r.cohortsize=n.count);continue}if(!r.v2)continue;const o=n.cohort.termdb.useLower?r.v2.toLowerCase():r.v2;if(!r.id3){const e=crosstabL2.find((e=>e.v0==t&&e.v1==s&&e.v2==o));e&&(r.cohortsize=e.count)}}}(s,t,e)}return s}(n.samples,e,t),delete n.samples,n;if(t.get==e.variant2samples.type_summary)return n.summary=await async function(t,e,n){if(!n.twLst)throw"q.twLst[] missing for make_summary()";const r=[];for(const e of n.twLst)if(e.term)if("categorical"==e.term.type){const n=g(t,e.id);r.push({termid:e.id,numbycategory:[...n].sort(((t,e)=>e[1]-t[1]))})}else{if("integer"!=e.term.type&&"float"!=e.term.type)throw"unknown term type";{const n=await a(e.term,t);r.push({termid:e.id,density_data:n})}}if(e.cohort.termdb.termid2totalsize2){const t=await e.cohort.termdb.termid2totalsize2.get(n.twLst,n);for(const{termid:e,numbycategory:n}of r){if(!n)continue;const r=t.get(e);if(r)for(const t of n){const e=r.find((e=>e[0].toLowerCase()==t[0].toLowerCase()));e&&t.push(e[1])}}}return r}(n.samples,e,t),delete n.samples,n;throw"unknown get type"}(e,t)}}function h(t,e,n){for(const r of t){e.has(r.sample_id)||(r.ssm_id_lst=[],r.formatK2v&&(r.ssmid2format={}),e.set(r.sample_id,r));const t=e.get(r.sample_id);t.ssm_id_lst.push(n),t.ssmid2format&&(t.ssmid2format[n]=r.formatK2v)}}function p(t,e,n){if(e)for(const r of t.values())for(const t of e){const e=n.cohort.termdb.q.getSample2value(t.id,r.sample_id);e[0]&&(r[t.id]=e[0].value)}}async function m(t,e,n){const r=new Map;if(n.queries.snvindel){const e=await n.queries.snvindel.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}if(n.queries.svfusion){const e=await n.queries.svfusion.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}if(n.queries.cnv){const e=await n.queries.cnv.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}return p(r,e,n),{samples:[...r.values()]}}function g(t,e){const n=new Map;if("sample_id"in t[0]){for(const r of t){const t=r[e];t&&(n.has(t)||n.set(t,new Set),n.get(t).add(r.sample_id))}const r=new Map;for(const[t,e]of n)r.set(t,e.size);return r}if("case_uuid"in t[0]){for(const r of t){const t=r[e];t&&(n.has(t)||n.set(t,new Set),n.get(t).add(r.case_uuid))}const r=new Map;for(const[t,e]of n)r.set(t,e.size);return r}for(const e of t){const t=e[term.id];t&&n.set(t,1+(n.get(t)||0))}return n}},334:(t,e,n)=>{const r=n(7147),s=n(1017),o=process.cwd()?process.cwd()+"/serverconfig.json":"",i=s.join(__dirname,"../serverconfig.json"),a=s.join(__dirname,"../../serverconfig.json"),l=o&&r.existsSync(o)?o:r.existsSync(i)?i:r.existsSync(a)?a:"";let c;if(!l)throw"missing serverconfig.json";try{const t=r.readFileSync(l,{encoding:"utf8"});c=JSON.parse(t)}catch(t){throw`Error reading or parsing ${l}:`+t}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 t=process.argv.find((t=>t.includes("/build")));if(t)c.binpath=t.split("/build")[0]+"/server";else{if(process.argv.find((t=>t.includes(".spec.js"))))c.binpath=s.dirname(__dirname);else{const t=process.argv.find((t=>t.endsWith("/bin.js")||t.endsWith("/server.js")||t.endsWith("/proteinpaint")||t.endsWith("/proteinpaint-server")));if(t)try{const e=r.realpathSync(t);c.binpath=s.dirname(e)}catch(t){throw t}else if(r.existsSync("./server"))c.binpath=r.realpathSync("./server");else if(r.existsSync("./src"))c.binpath=r.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 t=[],e=s.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(r.existsSync(o))t.push(o);else if(r.existsSync(`${e}/${o}`))t.push(`${e}/${o}`);else{const e=s.join(c.binpath,o);r.existsSync(e)&&t.push(e)}for(const s of n){const n=`${e}/${s}`;!t.includes(n)&&r.existsSync(n)&&t.push(n)}c.routeSetters=t}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),r.existsSync("./.ssl")&&!c.ssl){c.ssl={};const t=r.readdirSync("./.ssl");for(const e of t)e.endsWith(".key")&&(c.ssl.key=process.cwd()+"/.ssl/"+e),e.endsWith(".crt")&&(c.ssl.cert=process.cwd()+"/.ssl/"+e)}"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((t=>"validate"==t))&&(c.features.stopGdcCacheAliquot=!0),!c.backend_only&&r.existsSync(s.join(process.cwd(),"./public"))){const t=s.join(c.binpath,"cards");c.cards||(c.cards={target:t,path:"cards"})}if(r.existsSync("./public/rev.txt")){const t=r.readFileSync("./public/rev.txt",{encoding:"utf8"}).trim().split(" ")[1];t&&(c.commitHash=t)}if(r.existsSync("./package.json")){const t=r.readFileSync("./package.json",{encoding:"utf8"});c.version=JSON.parse(t).version}t.exports=c},938:(t,e,n)=>{"use strict";n.d(e,{e8:()=>f,Tt:()=>p,TO:()=>u});n(1017);var r=n(3345);const s=require("partjson");var o=n.n(s),i=n(2163),a=n(1271),l=n(2974),c=n(2273);(0,i.WU)(".3r");function u(t){return async(e,n)=>{const r=e.query;for(const t of[0,1,2]){const e="term"+t,n=e+"_id";"string"==typeof r[n]?r[n]=decodeURIComponent(r[n]):"string"==typeof r[e]&&(r[e]=JSON.parse(decodeURIComponent(r[e])));const s=e+"_q";"string"==typeof r[s]&&(r[s]=JSON.parse(decodeURIComponent(r[s])))}try{const e=t[r.genome];if(!e)throw"invalid genome";const s=e.datasets[r.dslabel];if(!s)throw"invalid dslabel";if(!s.cohort)throw"ds.cohort missing";const o=s.cohort.termdb;if(!o)throw"no termdb for this dataset";const i=await f(r,s,o);r.term2_q&&await async function(t,e,n){const r=[];for(const e of t.charts){const t={};t.chartId=e.chartId,t.serieses=[];const s=e.serieses.filter((t=>!n.term1.includes(t.seriesId)));for(const e of s){const r={};r.seriesId=e.seriesId,r.data=e.data.filter((t=>!n.term2.includes(t.dataId))),r.total=r.data.reduce(((t,e)=>t+e.total),0),t.serieses.push(r)}t.total=t.serieses.reduce(((t,e)=>t+e.total),0),t.maxSeriesTotal=t.serieses.reduce(((t,e)=>t<e.total?e.total:t),0),r.push(t)}t.tests={};for(const n of r){const r={};for(const t of n.serieses)for(const e of t.data)r[e.dataId]=void 0===r[e.dataId]?e.total:r[e.dataId]+e.total;const s=[];let o=0;const i=new Map;for(const t of n.serieses)for(const e of t.data){const a=e.total,l=r[e.dataId]-e.total,c=t.total-e.total,u=n.total-r[e.dataId]-(t.total-e.total),f=t.seriesId,d=e.dataId;s.push({index:o,n1:a,n2:l,n3:c,n4:u}),i.set(o,{seriesId:f,dataId:d}),o++}const l={input:s},c=e.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 t of JSON.parse(u)){const e=i.get(t.index).seriesId,n=i.get(t.index).dataId,r=t.n1,s=t.n2,o=t.n3,a=t.n4,l=t.p_value,c="chisq"===t.fisher_chisq,u=null===l,d=t.adjusted_p_value,h=f.find((t=>t.term1comparison===e));h?h.term2tests.push({term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:r,R2C1:s,R1C2:o,R2C2:a},isChi:c,skipped:u}):f.push({term1comparison:e,term2tests:[{term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:r,R2C1:s,R1C2:o,R2C2:a},isChi:c,skipped:u}]})}t.tests[n.chartId]=f}}(i.data,s,r.hiddenValues),n.send(i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}async function f(t,e,n){if(t.ds=e,t.ssid){const[e,n]=await r.L0(t.ssid);t.sample2gt=e,t.genotype2sample=n}const s=+new Date;t.results={};const i=new Map;for(let e=0;e<=2;e++){let n=null;if(t[`term${e}_id`]){const r=t[`term${e}_id`];n={id:r,q:t[`term${e}_q`],term:{id:r}}}else t[`term${e}`]&&(n={term:t[`term${e}`],q:t[`term${e}_q`]});n&&i.set(e,n)}const a=[...i.values()],u=await(0,l.Yu)({filter:t.filter,terms:a},t.ds,t.genome),f=new Map,d=[];if(u.samples)if("geneVariant"==i.get(1)?.term?.type||"geneVariant"==i.get(2)?.term?.type)!function(t,e,n,r,s){e.push([]);let o=1;const i=t.get(1)?t.get(1).term:null,a=i?.id?i.id:i?.name;a&&n.refs.byTermId[a]?.bins?e.push(n.refs.byTermId[a]?.bins):e.push([]);const l=t.get(2)?t.get(2).term:null,u=l?.id?l.id:l?.name;u&&n.refs.byTermId[u]?.bins?e.push(n.refs.byTermId[u]?.bins):e.push([]);for(const[e,i]of Object.entries(n.samples)){const n=parseInt(e);if("geneVariant"==t.get(1)?.term?.type){const t=[],e=i[a];for(const r of e.values)if(t.some((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))){const e=t.filter((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))[0];if("object"!=typeof e.item.key1){const t=e.item.key1;e.item.key1={},e.item.key1[t]=1}e.item.key1[c.mclass[r.class].label]=e.item.key1[c.mclass[r.class].label]?e.item.key1[c.mclass[r.class].label]+1:1}else{const e={sample:o,name:s.sampleId2Name.get(n)};e.key1=c.mclass[r.class].label,e.val1=c.mclass[r.class].label;const a=s.assayAvailability?.byDt?.[r.dt]?.byOrigin;e.key0=e.val0=a?(a[r.origin]?.label||r.origin)+" "+c.dt2label[r.dt]:c.dt2label[r.dt],e.key2=i[u]?i[u].key:"",e.val2=i[u]?i[u].value:"",t.push({value:r,item:e})}for(const e of t){if("object"==typeof e.item.key1){let t="";for(const[n,r]of Object.entries(e.item.key1))t+=`${n}(${r})+`;e.item.key1=t.slice(0,-1),e.item.val1=t.slice(0,-1)}r.set(o.toString(),e.item),o++}}else if("geneVariant"==t.get(2)?.term?.type){const t=[],e=i[u],l=i[a];for(const r of e.values)if(t.some((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))){const e=t.filter((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))[0];if("object"!=typeof e.item.key2){const t=e.item.key2;e.item.key2={},e.item.key2[t]=1}e.item.key2[c.mclass[r.class].label]=e.item.key2[c.mclass[r.class].label]?e.item.key2[c.mclass[r.class].label]+1:1}else{const e={sample:o,name:s.sampleId2Name.get(n)};e.key1=l.key,e.val1=l.value;const i=s.assayAvailability?.byDt?.[r.dt]?.byOrigin;e.key0=e.val0=i?(i[r.origin]?.label||r.origin)+" "+c.dt2label[r.dt]:c.dt2label[r.dt],e.key2=c.mclass[r.class].label,e.val2=c.mclass[r.class].label,t.push({value:r,item:e})}for(const e of t){if("object"==typeof e.item.key2){let t="";for(const[n,r]of Object.entries(e.item.key2))t+=`${n}(${r})+`;e.item.key2=t.slice(0,-1),e.item.val2=t.slice(0,-1)}r.set(o.toString(),e.item),o++}}}}(i,d,u,f,e);else for(let t=0;t<=2;t++){const e=i.get(t)?.q,n=i.get(t)?i.get(t).term:null,r=n?.id?n.id:n?.name;if(r&&u.refs.byTermId[r]?.bins?d.push(u.refs.byTermId[r]?.bins):d.push([]),e?.binColored)for(const n of d[t]){const t=e.binColored;n.start==t.start&&n.stop==t.stop&&(n.color=t.color)}for(const[e,n]of Object.entries(u.samples)){let s;if(f.get(e))s=f.get(e);else if(!f.has(e)){s={sample:parseInt(e)},f.set(e,s)}if(s)if(r){const o=n[r];o?(s[`key${t}`]=1!=t?o.key:o.values?.map((t=>t.key))||[o.key],s[`val${t}`]=o.value,1===t&&(s.dedupkey1=o.values?[`${o.values.length}-value samples`]:[o.key])):f.set(e,null)}else s[`key${t}`]="",s[`val${t}`]=""}}t.results.lst=[...f.values()].filter((t=>null!==t)),t.results.bins=d;const m=+new Date,g=function(t,e,n,s){const i=[0,1,2].map((e=>{const r=function(t,e,n){const r=t["term"+n+"_id"];let s={};t[r]||r?s=e.q.termjsonByOneid(r):t[`term${n}`]&&(s=t[`term${n}`]);const o="integer"==s.type||"float"==s.type,i=s.values?Object.keys(s.values).filter((t=>s.values[t].uncomputable)).map((t=>+t)):[],a=t=>o&&!i.includes(t),l=t["term"+n+"_q"]?t["term"+n+"_q"]:{};return{term:s,isComputableVal:a,q:l}}(t,n,e);r.q.index=e;const s=t.results.bins[e];return Object.assign(r,{key:"key"+e,val:"val"+e,nval:"nval"+e,bins:s,q:r.q,orderedLabels:p(r.term,s,void 0,r.q)})}));return new(o())({data:e,seed:'{"results": {"charts": [], "refs":{}}}',template:h,"=":{prep(t){for(const e of i)if("key1"!=e.key||Array.isArray(t[e.key])||(t[e.key]=[t[e.key]]),"condition"==e.term.type){if(e.q.bar_by_grade)if(Array.isArray(t[e.key])){for(const[n,r]of t[e.key].entries())r in e.term.values&&(t[e.key][n]=e.term.values[r].label);if("key1"==e.key&&t.dedupkey1)for(const[n,r]of t.dedupkey1.entries())r in e.term.values&&(t.dedupkey1[n]=e.term.values[r].label)}else t[e.key]in e.term.values&&(t[e.key]=e.term.values[t[e.key]].label)}else"float"!=e.term.type&&"integer"!=e.term.type||e.isComputableVal(t[e.val])&&(t[e.nval]=t[e.val]);return!0},sampleCount:(t,e)=>e.self.samples?e.self.samples.size:void 0,maxSeriesTotal(t,e){let n=0;for(const t of e.self.serieses)t&&t.total>n&&(n=t.total);return n},maxAcrossCharts(t,e){let n=0;for(const t of e.self.charts)t.maxSeriesTotal>n&&(n=t.maxSeriesTotal);return n},boxplot(t,e){const n=e.self.values;if(!n||!n.length)return;n.sort(((t,e)=>t-e));const s=r.JC(n.map((t=>({value:+t}))));s.mean=e.self.sum/n.length;let o=0;for(const t of n)o+=Math.pow(t-s.mean,2);return s.sd=Math.sqrt(o/(n.length-1)),s.min=e.self.min,s.max=e.self.max,s},getAF(e,n){if(s.track&&s.track.vcf&&s.track.vcf.termdb_bygenotype&&s.track.vcf.termdb_bygenotype.getAF&&t.term2_is_genotype){if(!t.chr)throw"chr missing for getting AF";if(!t.pos)throw"pos missing for getting AF";return function(t,e,n,s,o){const i=o.track.vcf.termdb_bygenotype,a=s.has(r.EO.href)?s.get(r.EO.href):new Set,l=s.has(r.EO.halt)?s.get(r.EO.halt):new Set,c=s.has(r.EO.het)?s.get(r.EO.het):new Set;let u=0,f=0;for(const r of t){let t=!1;if(i.sex_chrs.has(e))if(i.male_samples.has(r)){if(i.chr2par&&i.chr2par[e])for(const r of i.chr2par[e])if(n>=r.start&&n<=r.stop){t=!0;break}}else t=!0;else t=!0;t?(f+=2,l.has(r)?u+=2:c.has(r)&&u++):(f++,a.has(r)||u++)}return 0==f||0==u?0:(u/f).toFixed(3)}(n.self.samples?[...n.self.samples]:[],t.chr,Number(t.pos),t.genotype2sample,s)}},filterEmptySeries(t){const e=t.serieses.filter((t=>t.total));t.serieses.splice(0,t.serieses.length,...e)},bins:()=>i.map((t=>t.bins)),q:()=>i.map(((t,e)=>{const n={};for(const e in t.q)"index"!=e&&(n[e]=t.q[e]);return n})),useColOrder:()=>i[1].orderedLabels.length>0,useRowOrder:()=>i[2].orderedLabels.length>0,sortColsRows(t){if(i[1].orderedLabels.length){const e=i[1].orderedLabels;t.cols.sort(((t,n)=>e.indexOf(t)-e.indexOf(n))),t.dedupCols&&t.dedupCols.sort(((t,n)=>e.indexOf(t)-e.indexOf(n)))}if(i[2].orderedLabels.length){const e=i[2].orderedLabels;t.rows.sort(((t,n)=>e.indexOf(t)-e.indexOf(n)))}if(t.dedupCols){const e=i[1].orderedLabels;t.dedupCols.sort(((t,n)=>{const r=`${t}`.includes("-value samples"),s=`${n}`.includes("-value samples");return r||s?r&&s?t<n?-1:1:r?1:s?-1:0:e.indexOf(t)-e.indexOf(n)}))}},sortCharts(t){if(i[0].orderedLabels.length){const e=i[0].orderedLabels;t.charts.sort(((t,n)=>e.indexOf(t.chartId)-e.indexOf(n.chartId)))}}}})}(t,t.results.lst,n,e);g.tree.results&&(g.tree.results.times={sql:m-s,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()"},h=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 p(t,e,n,r){if(n)return n.map((t=>t.label));if("condition"==t.type){if(r?.groups?.length)return r.groups.map((t=>t.name));if(t.values)return Object.keys(t.values).map(Number).sort(((t,e)=>t-e)).map((e=>t.values[e].label))}const s=Object.values(t.values||{})[0];return s&&"order"in s?Object.keys(t.values).sort(((e,n)=>"order"in t.values[e]&&"order"in t.values[n]?t.values[e].order-t.values[n].order:"order"in t.values[e]?t.values[e].order:"order"in t.values[n]?t.values[n].order:0)).map((e=>t.values[e].key)):e?.map((t=>t.name?t.name:t.label))}},4453:(t,e,n)=>{"use strict";n.d(e,{g:()=>d,y:()=>h});var r=n(1017),s=n.n(r),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(t,e){try{if(!e.cohort)throw"cohort missing from ds";const n=e.cohort.termdb.minTimeSinceDx,r=Number(t.minSampleSize);if(!Number.isFinite(n))throw"invalid minTimeSinceDx";if(!Number.isFinite(r))throw"invalid minSampleSize";t.ds=e;const s={data:{}},i=await(0,o.g5)(t);if(!i.lst.length)return s;const a={};for(const t of i.lst){const e=t.key0,n=t.val1,r=t.key1,s=t.key2;e in a||(a[e]=[]),a[e].push({time:n,event:r,series:s})}const l=t.term2_id&&i.CTE2.bins?i.CTE2.bins:[];s.refs={bins:l};const c={data:{},startTime:n};s.noEvents={},s.lowSampleSize={};for(const t in a){const e=a[t],n=new Set(e.map((t=>t.series)));for(const o of n){const n=e.filter((t=>t.series==o));n.find((t=>1===t.event))?n.length<r?s.lowSampleSize[t]=(s.lowSampleSize[t]||[]).concat([o]):c.data[t]=(c.data[t]||[]).concat(n):s.noEvents[t]=(s.noEvents[t]||[]).concat([o])}t in c.data||(s.data[t]={})}if(!Object.keys(c.data).length)return{data:{}};const u=await h(c);return Object.assign(s.data,u),s}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}async function h(t){for(let e in t.data)""===e&&(e="*",t.data[e]=t.data[""],delete t.data[""]),t.data[e]=t.data[e].map((t=>({time:t.time,event:t.event,series:""===t.series?"*":t.series})));const e=s().join(f().cachedir,Math.random().toString()+".json");await(0,i.Sf)(e,JSON.stringify(t));const n=await(0,c.default)(s().join(f().binpath,"utils/cuminc.R"),[],[e]),r=JSON.parse(n[0]);for(const t in r)"*"===t&&(r[""]=r[t],delete r[t]);for(const t in r)for(const e in r[t].estimates)"*"===e&&(r[t].estimates[""]=r[t].estimates[e],delete r[t].estimates[e]);return l().unlink(e,(()=>{})),r}},5257:(t,e,n)=>{"use strict";async function r(t,e,n="f"){if(!t)return;if("tvslst"!=t.type)throw'filter.type is not "tvslst" but: '+t.type;if(!Array.isArray(t.lst))throw"filter.lst must be an array";if(0==t.lst.length)return console.error("filter.lst[] is zero length, see if is an error");if(1==t.lst.length){if("tvslst"==t.lst[0].type)throw'only one element at a level: type should not be "tvslst"'}else if("or"!=t.join&&"and"!=t.join)throw'multiple elements at a level: filter.join must equal either "or" or "and"';"in"in t||(t.in=!0);const u=[],f=[],d=[];for(const[h,p]of t.lst.entries()){const t=n+"_"+h;let m;if("tvslst"==p.type)m=await r(p,e,t);else{if(!p.tvs)throw"filter item should have a 'tvs' or 'lst' property";if(p.tvs.term.id&&!e.cohort.termdb.q.termjsonByOneid(p.tvs.term.id))throw"invalid term id in tvs";if("categorical"==p.tvs.term.type)m=s(p.tvs,t);else if("survival"==p.tvs.term.type)m=o(p.tvs,t);else if("samplelst"==p.tvs.term.type)m=i(p.tvs,t);else if("integer"==p.tvs.term.type||"float"==p.tvs.term.type)m=l(p.tvs,t,e);else if("condition"==p.tvs.term.type)m=c(p.tvs,t);else{if("geneVariant"!=p.tvs.term.type)throw"unknown term type";m=await a(p.tvs,t,e)}}u.push(m.CTEname),f.push(...m.CTEs),d.push(...m.values)}const h="and"==t.join?"INTERSECT":"UNION",p=u.map((t=>"SELECT * FROM "+t)).join("\n"+h+"\n");return t.in?f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\t${p}\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${p}\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 s(t,e){return{CTEs:[`\n\t\t ${e} 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 ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[t.term.id,...t.values.map((t=>t.key))],CTEname:e}}function o(t,e){return{CTEs:[`\n\t\t ${e} 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${t.q?.cutoff?"AND tte >= "+t.q?.cutoff:""}\n\t\t\t\tAND exit_code ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[t.term.id,...t.values.map((t=>t.key))],CTEname:e}}function i(t,e){const n=[];for(const e in t.term.values){const r=t.term.values[e].list;n.push(...r)}return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id ${t.isnot?"NOT IN":"IN"} (${Array(n.length).fill("?").join(", ")})\n\t\t\t)`],values:[...n.map((t=>t.sampleId))],CTEname:e}}async function a(t,e,n){const r={term:t.term,q:{}},s=await n.mayGetGeneVariantData(r,{genome:n.genomename}),o=[];for(const[e,n]of s){const r=n[t.term.name].values;let s=!0;for(const e of t.values){const t=r.filter((t=>t.dt==e.dt&&(!e.origin||e.origin==t.origin)));for(const n of t)if(e.mclassExcludeLst.includes(n?.class)){s=!1;break}}s&&o.push(e)}return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${o.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[...o],CTEname:e}}function l(t,e,n){if(!t.ranges)throw".ranges{} missing";const r=[t.term.id],s=n.cohort.termdb.q.termjsonByOneid(t.term.id),o=[];let i,a=!1;for(const e of t.ranges)if("value"in e){const n=t.isnot?"!":"";o.push(`value ${n}= ?`),r.push(""+e.value)}else{a=!0;const n=[];e.startunbounded||(e.startinclusive?n.push("value >= ?"):n.push("value > ? "),r.push(e.start)),e.stopunbounded||(e.stopinclusive?n.push("value <= ?"):n.push("value < ? "),r.push(e.stop));const s=t.isnot?"NOT ":"";n.length&&o.push(s+"("+n.join(" AND ")+")")}a&&s.values&&(i=Object.keys(s.values).filter((t=>s.values[t].uncomputable)).map(Number).filter((e=>t.isnot||!t.ranges.find((t=>"value"in t&&Number(t.value)==e)))),i.length&&r.push(...i));const l=o.join(" OR ");return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_${s.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((t=>"?")).join(",")})`:""}\n\t\t\t)`],values:r,CTEname:e}}function c(t,e){let n,r;if(t.bar_by_children)n="child";else{if(!t.bar_by_grade)throw"must set the bar_by_grade or bar_by_children query parameter";n="grade"}if(t.value_by_max_grade)r="max_grade";else if(t.value_by_most_recent)r="most_recent";else{if(!t.value_by_computable_grade)throw"unknown setting of value_by_?";r="computable_grade"}const s=[],o=[];if(!t.values)throw t.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(t.term.id,...t.values.map((t=>""+t.key))),s.push(`\n\t\t\t${e} 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 ${r} = 1\n\t\t\t\tAND value ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`),{CTEs:s,values:o,CTEname:e}}n.d(e,{w:()=>r})},2826:(t,e,n)=>{"use strict";n.d(e,{iK:()=>Z,pq:()=>z,TO:()=>$});var r=n(334),s=n.n(r),o=n(394),i=(n(8088),n(6191));function a(t,e,n,r){const o=n.cohort.termdb,a={selectCohort:o.selectCohort,supportedChartTypes:o.q.getSupportedChartTypes(t.embedder),hiddenChartTypes:n.cohort.hiddenChartTypes,renamedChartTypes:n.cohort.renamedChartTypes,allowedTermTypes:l(n),termMatch2geneSet:o.termMatch2geneSet,massSessionDuration:s().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(t.dslabel,t.embedder),function(t,e){if(!e.restrictAncestries)return;t.restrictAncestries=e.restrictAncestries.map((t=>({name:t.name,tvs:t.tvs,PCcount:t.PCcount})))}(a,o),function(t,e){if(!e.cohort.scatterplots)return;t.scatterplots=e.cohort.scatterplots.plots.map((t=>({name:t.name,dimensions:t.dimensions,colorTW:t.colorTW,shapeTW:t.shapeTW})))}(a,n),function(t,e){if(!e.cohort.matrixplots)return;t.matrixplots=e.cohort.matrixplots.plots.map((t=>({name:t.name})))}(a,n),function(t,e,n){const r=e.queries;if(!r)return;t.queries={defaultCoord:r.defaultCoord||n.defaultcoord};const s=t.queries;r.defaultBlock2GeneMode&&(s.defaultBlock2GeneMode=r.defaultBlock2GeneMode);r.snvindel&&(s.snvindel={allowSNPs:r.snvindel.allowSNPs});if(r.cnv){s.cnv={};for(const t of["cnvMaxLength","cnvGainCutoff","cnvLossCutoff","absoluteValueRenderMax","gainColor","lossColor"])t in r.cnv&&(s.cnv[t]=r.cnv[t])}r.topMutatedGenes&&(s.topMutatedGenes=r.topMutatedGenes);r.topVariablyExpressedGenes&&(s.topVariablyExpressedGenes=r.topVariablyExpressedGenes);r.singleSampleMutation&&(s.singleSampleMutation={sample_id_key:r.singleSampleMutation.sample_id_key,discoSkipChrM:r.singleSampleMutation.discoSkipChrM});if(r.singleSampleGenomeQuantification){s.singleSampleGenomeQuantification={};for(const t in r.singleSampleGenomeQuantification)s.singleSampleGenomeQuantification[t]=JSON.parse(JSON.stringify(r.singleSampleGenomeQuantification[t])),delete s.singleSampleGenomeQuantification[t].folder}if(r.singleSampleGbtk){s.singleSampleGbtk={};for(const t in r.singleSampleGbtk)s.singleSampleGbtk[t]=JSON.parse(JSON.stringify(r.singleSampleGbtk[t])),delete s.singleSampleGbtk[t].folder}r.rnaseqGeneCount&&(s.rnaseqGeneCount=!0)}(a,n,r),function(t,e){if(!e.queries?.singleCell?.data)return;t.singleCell=e.queries.singleCell.data}(a,n),e.send({termdbConfig:a})}function l(t){(0,o.qN)(t);const e=new Set;for(const n of t.cohort.termdb.termtypeByCohort)n.type&&e.add(n.type);if(t.cohort.termdb.allowedTermTypes)for(const n of t.cohort.termdb.allowedTermTypes)e.add(n);return t?.queries?.defaultBlock2GeneMode&&e.add("geneVariant"),[...e]}var c=n(8907),u=n(5708),f=n(4453),d=n(1017),h=n.n(d),p=n(2974),m=n(3345),g=n(7147),y=n.n(g),b=n(9157);async function v(t,e){try{if(!e.cohort)throw"cohort missing from ds";t.ds=e;const n=[];for(const e of[0,1,2]){const r="term"+e,s=r+"_id";"string"==typeof t[s]?(t[s]=decodeURIComponent(t[s]),t[r]=t.ds.cohort.termdb.q.termjsonByOneid(t[s])):"string"==typeof t[r]&&(t[r]=JSON.parse(decodeURIComponent(t[r])));const o=r+"_q";t[r]&&n.push({term:t[r],q:t[o]})}if(t.term2){if("survival"==t.term2.type&&"survival"==t.term1.type)throw"term and overlay are both survival terms - only one could be a survival term";if("survival"!=t.term2.type&&"survival"!=t.term1.type)throw"no survival terms, either the main term OR the overlay term must be a survival term"}else if("survival"!=t.term1.type)throw"non-survival term";if(t.term0&&"survival"==t.term0.type)throw"term0 must not be a survival term";const r=function(t){if(t.term1&&"survival"==t.term1.type)return 1;if(!t.term2)throw"term1.type is not survival and term2 is missing";if("survival"!=t.term2.type)throw"both term1 and term2 are not survival type";return 2}(t),o=t[`term${r}`],i=t["term"+(1==r?2:1)],a=await(0,p.Yu)({terms:n,filter:t.filter},e,t.genome);if(a.error)throw a.error;const l=function(t,e){const n=Object.values(t.samples).filter((t=>t[e.id]));return n.sort(((t,n)=>t[e.id].value<n[e.id].value?-1:1))}(a,o),c={},u={chart:new Set,series:new Set};for(const e of l){const n=e[o.id],r=n.value;if(r<0)continue;const s=n.key;let a;if(i)if("id"in i){if(!(i.id in e))continue;a=e[i.id].key}else if("samplelst"==i.type){if(!(i.name in e))continue;a=e[i.name].key}else a=w(i,e);else a="*";u.series.add(a);const l=t.term0&&e[t.term0.id||t.term0.name]||{key:""};l.key in c||(c[l.key]=[],u.chart.add(l.key)),c[l.key].push({time:r,status:s,series:a})}const f=t.term2_id&&a.refs[t.term2.id]?.bins||[],d={keys:["chartId","seriesId","time","survival","lower","upper","nevent","ncensor","nrisk"],case:[],refs:{bins:f}};for(const t in c){const e=c[t],n=h().join(s().cachedir,Math.random().toString()+".json");await(0,m.Sf)(n,JSON.stringify(e));const r=await(0,b.default)(h().join(s().binpath,"utils/survival.R"),[],[n]),o=JSON.parse(r);for(const e of o.estimates){for(const t in e)e[t]="series"==t?"*"==e[t]?"":e[t]:Number(e[t]);d.case.push([t,e.series,e.time,e.surv,e.lower,e.upper,e.nevent,e.ncensor,e.nrisk])}o.tests&&(d.tests||(d.tests={}),d.tests[t]=o.tests),y().unlink(n,(()=>{}))}d.case.sort(((t,e)=>t[2]-e[2]));const g=function(t,e=[]){if(t){if("condition"==t.type&&t.values)return Object.keys(t.values).map(Number).sort(((t,e)=>t-e)).map((e=>t.values[e].label));if(t.values)return Object.keys(t.values).sort(((e,n)=>"order"in t.values[e]&&"order"in t.values[n]?t.values[e].order-t.values[n].order:0)).map((e=>t.values[e].label))}return e.map((t=>t.name?t.name:t.label))}(t.term2,f?f.map((t=>t.name?t.name:t.label)):[]);return d.refs.orderedKeys={chart:[...u.chart].sort(),series:[...u.series].sort(g?(t,e)=>g.indexOf(t)-g.indexOf(e):void 0)},d}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function w(t,e){const n=t.name;if("geneVariant"==t.type){if(!e[n]||!e[n].values)return"Wildtype";const t=e[n].values.filter((t=>"Blank"!=t.class));return t.find((t=>"WT"!=t.class))?`${n} Variant`:t.find((t=>"WT"==t.class))?`${n} Wildtype`:e[n].values.length>t.length?"Not tested":"Not sure"}throw`cannot get series key for term='${n}'`}var _=n(8599),x=n(3795),k=n(1575),q=n(2188);var N=n(478),S=n(1271);async function A(t,e,n,r){!function(t,e){if(!t.chr)throw"q.chr missing";if(t.start=Number(t.start),t.stop=Number(t.stop),!Number.isInteger(t.start)||!Number.isInteger(t.stop))throw"q.start/stop is not integer";if("object"!=typeof t.details)throw"q.details{} not object";if(!Array.isArray(t.details.groups))throw"q.details.groups[] not array";if(!t.details.groups[0])throw"q.details.groups[0] missing";if(t.details.groups.length>2)throw"q.details.groups[] has more than 2";for(const n of t.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(!e.queries.snvindel?.populations)throw"group type=population but this ds does not have populations";if(!e.queries.snvindel.populations.find((t=>t.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(t.details.groupTestMethods){if(!Array.isArray(t.details.groupTestMethods))throw"details.groupTestMethods[] not array";if(!Number.isInteger(t.details.groupTestMethodsIdx))throw"details.groupTestMethodsIdx not integer";if(!t.details.groupTestMethods[t.details.groupTestMethodsIdx])throw"invalid array index of details.groupTestMethodsIdx"}}(t,n);const s=await async function(t,e){const n={rglst:[{chr:t.chr,start:t.start,stop:t.stop}],addFormatValues:!0,variantFilter:t.variantFilter},[r,s]=t.details.groups;if("filter"==r.type&&"filter"==s?.type){n.filterObj=C(t,r.filter);const o=T(await e.queries.snvindel.byrange.get(n));n.filterObj=C(t,s.filter);const i=T(await e.queries.snvindel.byrange.get(n)),a=function(t,e,n){const[r,s]=n.details.groups,o=[];for(const n of t){n.groupData=[{refCount:n._refCount,altCount:n._altCount}];const t=e.find((t=>t.chr==n.chr&&t.pos==n.pos&&t.ref==n.ref&&t.alt==n.alt));t?n.groupData.push({refCount:t._refCount,altCount:t._altCount}):n.groupData.push({refCount:0,altCount:0}),o.push(n)}for(const n of e){t.find((t=>t.chr==n.chr&&t.pos==n.pos&&t.ref==n.ref&&t.alt==n.alt))||(n.groupData=[{refCount:0,altCount:0},{refCount:n._refCount,altCount:n._altCount}],o.push(n))}return o}(o.mlst,i.mlst,t);return{mlst:a,totalSampleCount_group1:M(o.mlst),totalSampleCount_group2:M(i.mlst)}}n.filterObj=C(t);const o=await e.queries.snvindel.byrange.get(n),i=T(o);"filter"==r.type?i.totalSampleCount_group1=M(o):"filter"==s?.type&&(i.totalSampleCount_group2=M(o));return i}(t,n);if(1==t.details.groups.length)j(n,s.mlst,t.details.groups[0]);else{if(2!=t.details.groups.length)throw"q.details.groups.length not 1 or 2";await async function(t,e,n){const[r,s]=e.groups;if("filter"==r.type&&"filter"==s.type)return void await async function(t,e,n){const r=e.groupTestMethods[e.groupTestMethodsIdx];if(!r)throw"details.groupTestMethodsIdx out of bound";switch(r.name){case"Allele frequency difference":return void O(t,e,n);case"Fisher's exact test":return void await F(n);default:throw"unknown value from groupTestMethods[]"}}(t,e,n.mlst);if("population"==r.type&&"filter"==s.type||"population"==s.type&&"filter"==r.type)return void await async function(t,e,n){const r=await async function(t,e,n){const r=e.groups.find((t=>"population"==t.type));if(!r)return;if(!r.adjust_race)return;const s=t.queries.snvindel.populations.find((t=>t.key==r.key));if(!s)throw"invalid group.key for population";const o=new Set;for(const t of n.mlst)for(const e of t.samples)o.add(e.sample_id);const i=new Map;let a=0;for(const e of s.sets){const n={infokey_AC:e.infokey_AC,infokey_AN:e.infokey_AN,average:0},r=await(0,c.J4)({ds:t,key:e.key});for(const t of r){if(!o.has(t.sample))continue;const e=Number(t.value);Number.isFinite(e)&&(n.average+=e,a+=e)}i.set(e.key,n)}for(const[t,e]of i)e.average/=a;n.pop2average={};for(const[t,e]of i)n.pop2average[t]=e.average;return i}(t,e,n);for(const s of n.mlst)s.groupData=I(t,e,s,r);const s=e.groupTestMethods[e.groupTestMethodsIdx];if(!s)throw"details.groupTestMethodsIdx out of bound";switch(s.name){case"Allele frequency difference":return void O(t,e,n.mlst);case"Fisher's exact test":return void await F(n.mlst);default:throw"unknown value from groupTestMethods[]"}}(t,e,n);O(t,e,n.mlst)}(n,t.details,s)}for(const t of s.mlst)delete t.samples,delete t._altCount,delete t._refCount;e.send(s)}function M(t){const e=new Set;for(const n of t)if(n.samples)for(const t of n.samples)e.add(t.sample_id);return e.size}function T(t){const e={mlst:[],skipMcountWithoutAlt:0};for(const n of t){const[t,r]=E(n);0!=t?(n._altCount=t,n._refCount=r-t,e.mlst.push(n)):e.skipMcountWithoutAlt++}return e}function C(t,e){const n=[t.filter];if(e)n.push(e);else for(const e of t.details.groups)"filter"==e.type&&n.push(e.filter);return(0,N.xH)(n)}function j(t,e,n){if("filter"!=n.type)if("info"!=n.type){if("population"!=n.type)throw"unknown type of single group";{const r=t.queries.snvindel.populations.find((t=>t.key==n.key));if(!r)throw"unknown population";for(const t of e){let e=0,n=0;for(const s of r.sets)e+=Number(t.info[s.infokey_AC]||0),n+=Number(t.info[s.infokey_AN]||0);t.nm_axis_value=e/n}}}else{if(!n.infoKey)throw"infoKey missing on single group.type=info";for(const t of e){const e=t.info[n.infoKey];if(null==e);else{const n=Number(e);Number.isNaN(n)||(t.nm_axis_value=n)}}}else for(const t of e)t.nm_axis_value=Number((t._altCount/(t._altCount+t._refCount)).toPrecision(2))}function E(t){let e=0,n=0;for(const r of t.samples){if(!r?.formatK2v?.GT)continue;const s=r.formatK2v.GT.split("/").map(Number);n+=s.length;for(const n of s)n==t.altAlleleIdx&&e++}return[e,n]}function O(t,e,n){const[r,s]=e.groups;j(t,n,r);const o=n.map((t=>t.nm_axis_value));j(t,n,s);for(const[t,e]of n.entries())e.nm_axis_value=o[t]-e.nm_axis_value}function I(t,e,n,r){const s=[];for(const o of e.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 e=t.queries.snvindel.populations.find((t=>t.key==o.key));if(!e)throw"invalid group.key for population";const i=new Map;for(const t of e.sets)i.set(t.key,{ACraw:Number(n.info[t.infokey_AC]||0),ANraw:Number(n.info[t.infokey_AN]||0)});let a=0,l=0;if(o.adjust_race)[a,l]=R(i,r);else for(const t of i.values())l+=t.ACraw,a+=t.ANraw-t.ACraw;s.push({altCount:l,refCount:a})}}else s.push({altCount:n._altCount,refCount:n._refCount});else{if(!o.key)throw"group.key missing for type=info";s.push({value:n.info[o.key]})}return s}function R(t,e){let n=0;for(const e of t.values())n+=e.ANraw;let r=0,s=0;for(const[o,i]of t)i.ANadj=n*e.get(o).average,i.ACadj=0==i.ANadj?0:i.ACraw*i.ANadj/i.ANraw,r+=i.ACadj,s+=i.ANadj;return[s-r,r]}async function F(t){for(let e=0;e<Math.ceil(t.length/200);e++){const n=[];for(let r=200*e;r<200*(e+1);r++){const e=t[r];if(!e)break;const s=e.groupData;s&&s[0]&&s[1]&&Number.isFinite(s[0].altCount)&&Number.isFinite(s[0].refCount)&&Number.isFinite(s[1].altCount)&&Number.isFinite(s[1].refCount)?(n.push({index:r,n1:Math.floor(s[0].altCount),n2:Math.floor(s[0].refCount),n3:Math.floor(s[1].altCount),n4:Math.floor(s[1].refCount)}),e.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>${s[0].altCount}</td>\n\t\t\t\t <td>${Math.floor(s[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>${s[0].refCount}</td>\n\t\t\t\t <td>${Math.floor(s[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>${(s[0].altCount/(s[0].altCount+s[0].refCount)).toFixed(3)}</td>\n\t\t\t\t <td>${(s[1].altCount/(s[1].altCount+s[1].refCount)).toFixed(3)}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>`}]):console.log(`${e.chr}.${e.pos}.${e.ref}.${e.alt}\t${JSON.stringify(s)}`)}const r=await(0,S.run_rust)("fisher",JSON.stringify({input:n}));for(const e of JSON.parse(r)){const n=t[e.index];n&&(n.p_value=e.p_value.toPrecision(2),e.p_value>0&&(n.nm_axis_value=Number((-Math.log10(e.p_value)).toPrecision(2))))}}let e=0;for(const n of t)n.p_value>0&&(e=Math.max(e,n.nm_axis_value));for(const n of t)0==n.p_value&&(n.nm_axis_value=Math.max(50,e))}var P=n(4065),D=n(3065);const L=10;function $(t){return async(e,n)=>{const r=e.query;(0,m.Y5)(r,e.cookies);try{const s=t[r.genome];if(!s)throw"invalid genome";const[o,l]=z(s,r);if(r.findterm)return await async function(t,e,n,r,s){const o={equals:[],startsWith:[],startsWord:[],includes:[]},i=decodeURIComponent(t.findterm).toUpperCase(),a=[];try{if("snp"==t.targetType){if(!r.queries?.snvindel?.allowSNPs)throw"this dataset does not support snp search";const t=await(0,D.SC)({byName:!0,lst:[i.toLowerCase()]},s);for(const e of t)a.push({type:"geneVariant",name:e.name,subtype:"snp",chr:e.chrom,start:e.chromStart,stop:e.chromEnd,alleles:e.alleles})}else{const e=(0,k.CG)({type:"geneVariant"},t.usecase).has("plot");if(r.mayGetMatchingGeneNames&&e&&await r.mayGetMatchingGeneNames(o,i,t),r.queries?.defaultBlock2GeneMode&&e)try{const t=(0,P.S)(s,{input:i});if(Array.isArray(t.hits))for(let e=0;e<7&&t.hits[e];e++)a.push({name:t.hits[e],type:"geneVariant"})}catch(t){}}const l=await n.q.findTermByName(i,L,t.cohortStr,t.treeFilter,t.usecase,o);a.push(...l.map(Z));a.forEach((t=>{"geneVariant"!=t.type&&(t.__ancestors=n.q.getAncestorIDs(t.id),t.__ancestorNames=n.q.getAncestorNames(t.id))})),e.send({lst:a})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}}(r,n,l,o,s);if(r.getterminfo)return function(t,e,n){if(!t.tid)throw"no term id";e.send({terminfo:n.q.getTermInfo(t.tid)})}(r,n,l);if(r.phewas)return r.update?await u.update_image(r,n):r.getgroup?await u.getgroup(r,n):await u.trigger(r,n,o);if(r.gettermdbconfig)return a(r,n,o,s);if(r.getcohortsamplecount)return n.send({count:o.cohort.termdb.q.getcohortsamplecount(r.cohort)});if(r.getsamplecount)return n.send(await async function(t,e,n){const r=i.i.canDisplaySampleIds(t,n);if("list"==e.getsamplecount){return await c.cf(e.filter,n,r)}return await c.B9(e,n)}(e,r,o));if(r.getsamples)return await async function(t,e,n){const r=await c.cf(t.filter,n),s=r.map((t=>n.cohort.termdb.q.id2sampleName(t)));e.send({samples:s})}(r,n,o);if(r.getcuminc)return await async function(t,e,n){const r=await(0,f.g)(t,n);e.send(r)}(r,n,o);if(r.getsurvival)return await async function(t,e,n){const r=await v(t,n);e.send(r)}(r,n,o);if(r.getregression)return await async function(t,e,n){const r=await(0,_.j)(t,n);e.send(r)}(r,n,o);if(r.validateSnps)return n.send(await(0,x.G)(r,l,o,s));if(r.getvariantfilter)return function(t,e){if(e.track)return void t.send(e.track.variant_filter);t.send(e?.queries?.snvindel?.variant_filter||{})}(n,o);if(r.getLDdata)return await async function(t,e,n){if(!t.ldtkname)throw".ldtkname missing";if(!e.queries?.ld?.tracks)throw"no ld tk";const r=e.queries.ld.tracks.find((e=>e.name==t.ldtkname));if(!r)throw"unknown ld tk";if("object"!=typeof t.m)throw"q.m{} not object";if(!t.m.chr)throw"q.m.chr missing";if(!Number.isInteger(t.m.pos))throw"q.m.pos not integer";if(!t.m.ref||!t.m.alt)throw"q.m{} invalid alleles";const s=t.m.ref+"."+t.m.alt,o=(r.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+t.m.pos+"-"+(t.m.pos+1),i=[];await(0,m.UE)({args:[r.file,o],dir:r.dir,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),o=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);r==t.m.pos&&a==s?i.push({pos:o,alleles:l,r2:c}):o==t.m.pos&&l==s&&i.push({pos:r,alleles:a,r2:c})}}),n.send({lst:i})}(r,o,n);if(r.genesetByTermId)return function(t,e,n){if(!n.termMatch2geneSet)throw"this feature is not enabled";if("string"!=typeof t.genesetByTermId||0==t.genesetByTermId.length)throw"invalid query term id";const r=n.q.getGenesetByTermId(t.genesetByTermId);e.send(r)}(r,n,l);if(r.getSampleScatter&&(r.for="scatter"),"scatter"==r.for)return await(0,q.uR)(e,r,n,o,s);if(r.getLowessCurve)return await(0,q.v8)(e,r,n);if(r.getCohortsData)return await async function(t,e,n){const r=function(t){const e=t.cohort.db.connection.prepare("select * from features").all();return{cohorts:t.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:e,cfeatures:t.cohort.db.connection.prepare("select * from cohort_features").all()}}(n);e.send(r)}(0,n,o);if("mds3queryDetails"==r.for)return function(t,e){const n={},r=e.queries||{};r.snvindel&&(n.snvindel={},r.snvindel.details&&(n.snvindel.details=r.snvindel.details),r.snvindel.populations&&(n.snvindel.populations=r.snvindel.populations));r.trackLst&&(n.trackLst=r.trackLst);if(r.ld){n.ld=JSON.parse(JSON.stringify(r.ld));for(const t of n.ld.tracks)delete t.file}t.send(n)}(n,o);if("termTypes"==r.for)return n.send(await o.getTermTypes(r));if("matrix"==r.for)return await async function(t,e,n,r,s){if(t.getPlotDataByName){if(!r.cohort?.matrixplots?.plots)throw"ds.cohort.matrixplots.plots missing for the dataset";const e=r.cohort.matrixplots.plots.find((e=>e.name===t.getPlotDataByName));if(!e)throw"invalid name of premade matrix plot";return void n.send(e.matrixConfig)}const o=await(0,p.Yu)(t,r,s);if(i.i.canDisplaySampleIds(e,r))for(const t of Object.values(o.samples))t.sampleName=r.sampleId2Name.get(t.sample);n.send(o)}(r,e,n,o,s);if("getSamplesPerFilter"==r.for)return await(0,p.fZ)(r,o,n);if("mds3variantData"==r.for)return await A(r,n,o);if(r.for,"convertSampleId"==r.for)return function(t,e,n){if(!n.convertSampleId)throw"not supported on this ds";if(!Array.isArray(t.inputs))throw"q.inputs[] not array";e.send({mapping:n.convertSampleId.get(t.inputs)})}(r,n,l);if("singleSampleData"==r.for)return async function(t,e,n,r,s){const o=i.i.canDisplaySampleIds(e,r);let a=[];if(o)try{a=s.q.getSingleSampleData(t.sampleId,t.term_ids),n.send(a)}catch(t){n.send({error:t.message||t})}else n.send({error:"Requires sign in to access the sample data"})}(r,e,n,o,l);if("getProfileFacilities"==r.for)return async function(t,e,n,r,s){const o=i.i.canDisplaySampleIds(e,r);let a=[];if(o)try{a=s.q.getProfileFacilities(),n.send(a)}catch(t){n.send({error:t.message||t})}else n.send({error:"Requires sign in to access the sample data"})}(0,e,n,o,l);if("getAllSamples"==r.for)return async function(t,e,n,r){const s=i.i.canDisplaySampleIds(e,r);let o=[];s&&(o=Object.fromEntries(r.sampleId2Name));n.send(o)}(0,e,n,o);if("getAllSamplesByName"==r.for)return async function(t,e,n,r){if(!i.i.canDisplaySampleIds(e,r))return n.send({});if(r.queries?.singleCell?.samples?.get){const t=await r.queries.singleCell.samples.get(),e={};for(const n of t.samples)e[n.sample]=r.cohort.termdb.q.sampleName2id(n.sample);return void n.send(e)}{let e=r.sampleName2Id;if(t.filter){t.ds=r;const n=await(0,c.cf)(t.filter,t.ds,!0);e=new Map;for(const t of n)e.set(t.name,t.id)}n.send(Object.fromEntries(e))}}(r,e,n,o);if("DEanalysis"==r.for)return await async function(t,e,n){if(!n.queries?.rnaseqGeneCount)throw"not enabled by this dataset";const r=await n.queries.rnaseqGeneCount.get(t);e.send(r)}(r,n,o);throw"termdb: doesn't know what to do"}catch(t){n.send({error:t.message||t}),t.stack?console.log(t.stack):console.log(t)}}}function z(t,e){{const n=t.datasets[e.dslabel];if(n){if(n?.cohort?.termdb)return[n,n.cohort.termdb];throw".cohort.termdb not found on this dataset"}}if(!t.termdbs)throw"invalid dslabel";const n=t.termdbs[e.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 Z(t){return JSON.parse(JSON.stringify(t))}},2974:(t,e,n)=>{"use strict";n.d(e,{Yu:()=>f,fZ:()=>d,gh:()=>h,te:()=>p});var r=n(1017),s=n.n(r),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(t,e,n){try{return function(t,e,n){if(!e.cohort)throw"cohort missing from ds";if(!t.terms)throw"missing 'terms' parameter";t.ds=e,t.genome=n;for(const e of t.terms)e.term.name||(e.term=t.ds.cohort.termdb.q.termjsonByOneid(e.term.id)),e.q||console.log("do something??");if(t.currentGeneNames&&!Array.isArray(t.currentGeneNames))throw"currentGeneNames[] is not array";t.filter0&&"string"==typeof t.filter0&&(t.filter0=JSON.parse(t.filter0))}(t,e,n),await async function(t){const[e,n]=function(t){const e=[],n=[];for(const r of t){const t=r.term.type;"snplst"==t||"snplocus"==t||"geneVariant"==t?n.push(r):e.push(r)}return[e,n]}(t.terms),[r,s]=await async function(t,e){if(!e.length)return[{},{}];if(t.ds?.cohort?.db)return await h(t,e);if(t.ds?.variant2samples?.get)return await async function(t,e){const n={filter0:t.filter0,filterObj:t.filter,genome:t.genome,get:"samples",twLst:e,gdcUseCaseuuid:!0,isHierCluster:t.isHierCluster};t.rglst&&(n.rglst=t.rglst);if(t.currentGeneNames){n.geneTwLst=[];for(const e of t.currentGeneNames)n.geneTwLst.push({term:{name:e,type:"geneVariant"}})}const r=await t.ds.variant2samples.get(n),s={};for(const t of r.samples){const n={sample:t.sample_id};for(const r of e){const e=t[r.term.id];Array.isArray(e)&&null!=e[0]&&null!=e[0]?n[r.term.id]={key:e[0],value:e[0]}:null!=e&&null!=e&&(n[r.term.id]={key:e,value:e})}s[t.sample_id]=n}return[s,r.byTermId||{}]}(t,e);throw"unknown method for dictionary terms"}(t,e);if(e.length&&!Object.keys(r).length)return{samples:r,refs:{byTermId:s,bySampleId:{}}};const i=await async function(t,e){if(!e.find((t=>"snplst"==t.term.type||"snplocus"==t.term.type)))return;if(!t.filter)return;return new Set((await(0,o.cf)(t.filter,t.ds)).map((t=>t.id)))}(t,n);for(const o of n)if("geneVariant"==o.term.type){t.ds.cohort?.termdb?.getGeneAlias&&(s[o.term.name]=t.ds.cohort?.termdb?.getGeneAlias(t,o));const n=await t.ds.mayGetGeneVariantData(o,t);for(const[t,s]of n.entries())o.term.name in s&&(e.length||t in r||(r[t]={sample:t}),r[t]&&(r[t][o.term.name]=s[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 t=new Map;await(0,u._)(o,t,!0);for(const[e,n]of t){if(i&&!i.has(e))continue;e in r||(r[e]={sample:e});const t={};for(const[e,r]of n.id2value)t[e]=r.value;r[e][o.term.id]=t}}}const a={};for(const e in r)t.ds.cohort?.termdb?.q?.id2sampleName?a[e]={label:t.ds.cohort.termdb.q.id2sampleName(Number(e))}:t.ds.__gdc?.caseid2submitter&&(a[e]={label:t.ds.__gdc.caseid2submitter.get(e)});return{samples:r,refs:{byTermId:s,bySampleId:a}}}(t)}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}async function d(t,e,n){t.ds=e;const r={};for(const e in t.filters){const n=t.filters[e],s=(await(0,o.cf)(n,t.ds)).map((t=>t.id));r[e]=Array.from(new Set(s))}n.send(r)}async function h(t,e){const n={},r={},s={},a=await(0,i.w)(t.filter,t.ds),l=a?a.values.slice():[],c=await Promise.all(e.map((async(e,n)=>{const i=await(0,o.Bi)(t,l,n,a,e);if(i.bins&&(r[e.term.id]={bins:i.bins}),i.events&&(r[e.term.id]={events:i.events}),e.term.values){const t=Object.values(e.term.values);t.find((t=>"order"in t))&&(r[e.term.id]={keyOrder:t.sort(((t,e)=>t.order-e.order)).map((t=>t.key))})}return"id"in e.term&&(s[e.term.id]=e),i}))).catch(console.error);l.push(...e.map((t=>t.term.id||t.term.name)));const u=`WITH\n\t\t${a?a.filters+",":""}\n\t\t${c.map((t=>t.sql)).join(",\n")}\n\t\t${c.map((t=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${t.tablename}\n\t\t\t${a?`WHERE sample IN ${a.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,f=t.ds.cohort.db.connection.prepare(u).all(l),d=await async function(t){if(!t.currentGeneNames)return;const e=new Set;for(const n of t.currentGeneNames){const r={term:{name:n,type:"geneVariant"}},s=await t.ds.mayGetGeneVariantData(r,t);for(const t of s.keys())e.add(t)}return e}(t);for(const{sample:t,term_id:e,key:r,value:o}of f){if(d&&!d.has(t))continue;n[t]||(n[t]={sample:t});s[e];if(n[t][e]){if(!n[t][e].values){const r=n[t][e];n[t][e]={values:[r]}}n[t][e].values.push({key:r,value:o})}else n[t][e]={key:r,value:o}}return[n,r]}async function p(t){if(t.cohort.matrixplots){if(!Array.isArray(t.cohort.matrixplots.plots))throw"cohort.matrixplots.plots is not array";for(const e of t.cohort.matrixplots.plots){if(!e.name)throw".name missing from one of matrixplots.plots[]";if(!e.file)throw"unknown data source of one of matrixplots.plots[]";{const t=await c.b5(s().join(l().tpmasterdir,e.file));e.matrixConfig=JSON.parse(t),e.getConfig&&(e.matrixConfig=e.getConfig(e.matrixConfig))}}}}},5708:(t,e,n)=>{"use strict";n.r(e),n.d(e,{do_precompute:()=>y,getgroup:()=>N,trigger:()=>g,update_image:()=>x});var r=n(7147),s=n.n(r),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),h=n(334),p=n.n(h),m=n(9157);async function g(t,e,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(!t.ssid)throw"ssid missing";const r={};let s;t.filter&&(s=new Set(await l.cf(t.filter,n)));const[o,c]=await a.L0(t.ssid,s);r.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,h=c.has(a.EO.halt)?c.get(a.EO.halt).size:0,g=function(t,e,n,r,s,o){const i=[];let a;if(e.cohort.termdb.selectCohort&&t){const e=t.lst.find((t=>"cohortFilter"==t.tag));e&&(a=e.tvs.values.map((t=>t.key)).sort().join(","))}for(const t of e.cohort.termdb.q.getcategory2vcfsample()){if(a&&t.subcohort!=a)continue;const l=u.iK(e.cohort.termdb.q.termjsonByOneid(t.term_id));for(const e of t.categories){const[a,c,u]=q(n,e.group1lst);let f,d,h;e.group2lst?[f,d,h]=q(n,e.group2lst):(f=r-a,d=o-c,h=s-u),a+f+c+d+u+h!=0&&i.push({term:l,group_name:t.group_name,parent_name:t.parent_name,group1label:e.group1label,group2label:e.group2label,table:[u,h,a,f,c,d]})}}return i}(t.filter,n,o,f,d,h);r.testcount=g.length;{const t=[];for(let e=0;e<g.length;e++)t.push(e+"\t"+g[e].table.join("\t"));const e=await(0,m.default)(i().join(p().binpath,"utils/fisher.2x3.R"),t);let n=0;for(const t of e)g[n++].pvalue=Number(t.split("\t")[7])}r.maxlogp=function(t){let e=0;for(const n of t)0==n.pvalue?n.logp=100:n.logp=-Math.log10(n.pvalue),e=Math.max(e,n.logp);return e}(g);const y=function(t){const e=new Map;for(const n of t)e.has(n.group_name)||e.set(n.group_name,[]),e.get(n.group_name).push(n);const n=[];for(const[t,r]of e)n.push({group_name:t,categories:r});return n}(g);r.tmpfile=await function(t){const e=[];for(const n of t)for(const t of n.categories)e.push(n.group_name+"\t"+t.logp+"\t"+t.pvalue+"\t"+JSON.stringify(t));return a.tG(e.join("\n"))}(y),k(y,r,t);{const t=.05;r.hoverdots=g.filter((e=>e.pvalue<=t))}e.send(r)}async function y(t){if(!t.cohort)throw"ds.cohort missing";if(!t.cohort.termdb)throw"cohort.termdb missing";if(!t.cohort.termdb.phewas)throw"not allowed on this dataset";t.cohort.termdb.selectCohort?await async function(t){const e=await async function(t){if(!t.cohort.termdb.phewas.precompute_subcohort2totalsamples)return;for(const e in t.cohort.termdb.phewas.precompute_subcohort2totalsamples){const n=t.cohort.termdb.phewas.precompute_subcohort2totalsamples[e];if(n.termtype)for(const e in n.termtype)n.termtype[e].samples=await l.cf(n.termtype[e].filter,t)}return t.cohort.termdb.phewas.precompute_subcohort2totalsamples}(t),n=function(t){const e=new Map,n=t.cohort.db.connection.prepare("SELECT * FROM subcohort_terms");for(const{term_id:t,cohort:r}of n.all())e.has(t)||e.set(t,new Set),e.get(t).add(r);return e}(t),r=s().createWriteStream("category2vcfsample"),o=[];for(const{group_name:s,term:i}of t.cohort.termdb.q.getAlltermsbyorder()){if(!i.type)continue;if(!n.has(i.id)){o.push(i.id);continue}let a="";{const e=t.cohort.termdb.q.getTermParent(i.id);e&&(a=e.name)}const c=v(i,t,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,t);else{if("condition"!=i.type)throw"unknown term type";c=t.cohort.termdb.phewas.comparison_groups?_(o.lst,t):w(o.lst,i,t)}c=b({categories:c,q:n,subcohortTermtype2samples:e,term:i});for(const t of c)console.log(t.group1lst.length+(t.group2lst?"/"+t.group2lst.length:"")+"\t"+t.group1label+"\t"+i.name+"\t"+n.cohortname);r.write(n.cohortname+"\t"+s+"\t"+i.id+"\t"+a+"\t"+(n.term1_q?JSON.stringify(n.term1_q):"{}")+"\t"+JSON.stringify(c)+"\n")}}r.end((()=>{console.log('Phewas precompute result written to file "category2vcfsample".'),o.length&&(console.log(o.length+" empty terms:"),console.log(o.join("\n")))}))}(t):await async function(t){const[e]=await async function(t){let e=null;if(t.cohort.termdb.phewas.samplefilter4termtype&&t.cohort.termdb.phewas.samplefilter4termtype.condition){const n=await l.cf(t.cohort.termdb.phewas.samplefilter4termtype.condition.filter,t);if(t.track&&t.track.vcf&&t.track.vcf.sample2arrayidx){e=[];for(const r of n)t.track.vcf.sample2arrayidx.has(r)&&e.push(r)}else e=n}return[e]}(t),n=[];for(const{group_name:r,term:s}of t.cohort.termdb.q.getAlltermsbyorder()){if(!s.type)continue;let o="";{const e=t.cohort.termdb.q.getTermParent(s.id);e&&(o=e.name)}const i=v(s,t);for(const a of i){const i=await l.g5(a);let c;if("categorical"==s.type||"integer"==s.type||"float"==s.type)c=w(i.lst,s,t);else{if("condition"!=s.type)throw"unknown term type";c=t.cohort.termdb.phewas.comparison_groups?_(i.lst,t):w(i.lst,s,t)}c=b({categories:c,q:a,term:s,condition_samplelst:e});for(const t of c)console.log(t.group1lst.length+(t.group2lst?"/"+t.group2lst.length:"")+"\t"+t.group1label+"\t"+s.name);n.push(r+"\t"+s.id+"\t"+o+"\t"+(a.term1_q?JSON.stringify(a.term1_q):"{}")+"\t"+JSON.stringify(c))}}s().writeFileSync("category2vcfsample",n.join("\n")),console.log('Phewas precompute result written to file "category2vcfsample".')}(t)}function b(t){const{categories:e,q:n,term:r,subcohortTermtype2samples:s,condition_samplelst:o}=t;if(s&&s[n.cohortname]&&s[n.cohortname].termtype&&s[n.cohortname].termtype[r.type]){const t=s[n.cohortname].termtype[r.type].samples;for(const n of e)if(n.group2lst)n.group2lst=n.group2lst.filter((e=>-1!=t.indexOf(e)));else if(n.copycontrolfrom1stgroup){n.group2lst=[];for(const t of e[0].group2lst)n.group2lst.push(t)}else{const e=new Set(n.group1lst);n.group2lst=t.filter((t=>!e.has(t)))}return e}if(o&&"condition"==r.type){for(const t of e)if(t.group2lst)t.group2lst=t.group2lst.filter((t=>-1!=o.indexOf(t)));else if(t.copycontrolfrom1stgroup){t.group2lst=[];for(const n of e[0].group2lst)t.group2lst.push(n)}else{const e=new Set(t.group1lst);t.group2lst=o.filter((t=>!e.has(t)))}return e}if(!r.values)return e;const i=new Set;for(const t in r.values)r.values[t].uncomputable&&i.add(r.values[t].label);if(0==i.size)return e;const a=[];for(const t of e)i.has(t.group1label)?console.log("skip "+t.group1label+", "+r.id):a.push(t);for(let t=0;t<a.length;t++){const e=a[t];e.group2lst=[];for(let n=0;n<a.length;n++)n!=t&&e.group2lst.push(...a[n].group1lst)}return a}function v(t,e,n){const r=[];if(e.cohort.termdb.selectCohort){if(!n)throw"term2cohort is required when cohort selection is enabled";for(const s of e.cohort.termdb.selectCohort.values){const o=s.keys.sort().join(",");if(!n.get(t.id).has(o))continue;const i={type:"tvslst",in:!0,join:"",lst:[{type:"tvs",tvs:{term:e.cohort.termdb.selectCohort.term,values:s.keys.map((t=>({key:t})))}}]};if("categorical"==t.type)r.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:e,term1_id:t.id});else if("float"==t.type||"integer"==t.type)r.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:e,term1_id:t.id,term1_q:t.bins.default});else{if("condition"!=t.type)throw"unknown term type";r.push({cohortname:o,filter:JSON.parse(JSON.stringify(i)),ds:e,term1_id:t.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}}}else if("categorical"==t.type)r.push({ds:e,term1_id:t.id});else if("float"==t.type||"integer"==t.type)r.push({ds:e,term1_id:t.id,term1_q:t.bins.default});else{if("condition"!=t.type)throw"unknown term type";r.push({ds:e,term1_id:t.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}return r}function w(t,e,n){const r=new Map;for(const s of t){if(n.track&&n.track.vcf&&n.track.vcf.sample2arrayidx&&!n.track.vcf.sample2arrayidx.has(s.sample))continue;const t=s.key1;if(!r.has(t)){let n=t;e.values&&(n=e.values[t]?e.values[t].label:t),r.set(t,{group1label:n,group2label:"All others",group1lst:[]})}r.get(t).group1lst.push(s.sample)}return[...r.values()]}function _(t,e){const n=[];for(const r of e.cohort.termdb.phewas.comparison_groups){const s=[],o=[];for(const n of t){if(e.track&&e.track.vcf&&e.track.vcf.sample2arrayidx&&!e.track.vcf.sample2arrayidx.has(n.sample))continue;const t=Number(n.key1);r.group1grades.has(t)?s.push(n.sample):r.group2grades&&r.group2grades.has(t)&&o.push(n.sample)}0!=s.length?n.push({group1label:r.group1label,group2label:r.group2label,group1lst:s,group2lst:o.length?o:void 0,copycontrolfrom1stgroup:r.copycontrolfrom1stgroup}):console.log("Empty group1: "+r.group1label)}return n}async function x(t,e){const n=await a.b5(i().join(p().cachedir,t.file)),r=[];for(const t of n.trim().split("\n")){const[e,n]=t.split("\t",2),s=Number(n);0!=r.length&&r[r.length-1].group_name==e||r.push({group_name:e,categories:[]}),r[r.length-1].categories.push({logp:s})}const s={maxlogp:Number(t.max)};k(r,s,t),e.send(s)}function k(t,e,n){const r=Number(n.intendwidth),s=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),h=Number(n.devicePixelRatio),p=r/t.reduce(((t,e)=>t+e.categories.length),0),m=(0,c.createCanvas)(10,10),g=m.getContext("2d");let y=0;for(const e of t){const t=e.categories.length*p;e.width=Math.max(t,o)+2*a,e.dotshiftx=t>o?p:o/e.categories.length,y+=e.width}const b=l+y+u;m.width=b*h;const v=f+s+d;m.height=v*h,h>1&&g.scale(h,h),y=0,g.fillStyle="#FDFEE2";for(const[e,n]of t.entries())e%2==0&&g.fillRect(y,f,n.width,s),y+=n.width;y=0,g.fillStyle="black",e.grouplabels=[];for(const n of t){e.grouplabels.push({name:n.group_name,x:y+n.width/2,y:f+s+2*i});let t=0;for(const r of n.categories){const o=0==e.maxlogp?0:r.logp>=e.maxlogp?s:s*r.logp/e.maxlogp;g.beginPath(),g.arc(y+a+t,f+s-o,i,0,2*Math.PI),g.fill(),r.x=y+a+t,t+=n.dotshiftx}y+=n.width}e.canvaswidth=b,e.canvasheight=v,e.toppad=f,e.bottompad=d,e.axisheight=s,e.dotradius=i,e.groupnamefontsize=o,e.src=m.toDataURL()}function q(t,e){const n=new Map;for(const r of e){const e=t.get(r);e&&n.set(e,1+(n.get(e)||0))}return[n.get(a.EO.het)||0,n.get(a.EO.halt)||0,n.get(a.EO.href)||0]}async function N(t,e){if(!t.file)throw"file missing";return new Promise(((n,r)=>{const o=[],a=d().createInterface({input:s().createReadStream(i().join(p().cachedir,t.file))});a.on("line",(e=>{if(!e.startsWith(t.getgroup+"\t"))return;const n=e.split("\t"),r=JSON.parse(n[3]);r.pvalue=Number(n[2]),o.push(r)})),a.on("close",(()=>{e.send({categories:o}),n()}))}))}},8599:(t,e,n)=>{"use strict";n.d(e,{_:()=>j,j:()=>x});var r=n(1017),s=n.n(r),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),h=n.n(d),p=n(3345),m=n(1271),g=n(4453);const y=["linear","logistic","cox"],b=1;let v,w;const _={NodeJS:{},"regression.R":{}};async function x(t,e){try{!function(t,e){if(!e.cohort)throw"cohort missing from ds";if(t.ds=e,!t.regressionType)throw"regressionType missing";if(!y.includes(t.regressionType))throw"unknown regressionType";if(!t.outcome)throw"missing 'outcome' parameter";if(!("id"in t.outcome))throw"outcome.id missing";if(!t.outcome.q)throw"outcome.q missing";if(t.outcome.q.computableValuesOnly=!0,t.outcome.term=e.cohort.termdb.q.termjsonByOneid(t.outcome.id),!t.outcome.term)throw"invalid outcome term: "+t.outcome.id;if(!t.independent)throw"independent[] missing";if(!Array.isArray(t.independent)||0==t.independent.length)throw"q.independent is not non-empty array";for(const n of t.independent){if(!n.q)throw`missing q for independent term '${n.id}'`;if(k(n,t,e),"snplst"!=n.type&&"snplocus"!=n.type){if(n.q.computableValuesOnly=!0,!n.id)throw".id missing for an independent term";if(n.term=e.cohort.termdb.q.termjsonByOneid(n.id),!n.term)throw`invalid independent term='${n.id}'`}else{if(!n.q.cacheid)throw"q.cacheid missing";if(h().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 e of t.independent){e.interactions||(e.interactions=[]);for(const n of e.interactions)if(!t.independent.find((t=>t.id==n)))throw"interacting term id missing from independent[]: "+n}}(t,e),v=(new Date).getTime();const n=await async function(t,e,n){const[r,s]=function(t){const e=[],n=[];for(const r of t)"snplst"==r.type||"snplocus"==r.type?n.push(r):e.push(r);return[e,n]}(e),a=await async function(t,e){const n=new Map,r=await(0,i.w)(t.filter,t.ds),s=r?r.values.slice():[],a=await Promise.all(e.map((async(e,n)=>await(0,o.Bi)(t,s,n,r,e)))).catch(console.error);s.push(...e.map((t=>t.id)));const l=`WITH\n\t\t${r?r.filters+",":""}\n\t\t${a.map((t=>t.sql)).join(",\n")}\n\t\t${a.map((t=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${t.tablename}\n\t\t\t${r?`WHERE sample IN ${r.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,c=t.ds.cohort.db.connection.prepare(l).all(s),u=[],f=t.ds.cohort.termdb.ageEndOffset;if(!f)throw"missing age end offset";for(const e of c)if("cox"==t.regressionType&&e.term_id==t.outcome.id){const n=e.key,{age_start:r,age_end:s}=JSON.parse(e.value);if(-1==n)continue;const o={age_start:r,age_end:"age"==t.outcome.q.timeScale?s+f:s};u.push({sample:e.sample,key:n,value:o,term_id:e.term_id})}else u.push(e);for(const{sample:t,term_id:r,key:s,value:o}of u){const i=e.find((t=>t.id==r));if(n.has(t)||n.set(t,{sample:t,id2value:new Map}),n.get(t).id2value.has(r))throw`duplicate '${r}' entry for sample='${t}'`;n.get(t).id2value.set(r,{key:i.q.scale?s/i.q.scale:s,value:i.q.scale?o/i.q.scale:o})}const d=new Set;for(const t of n.values())for(const n of e)if(!t.id2value.has(n.id)){d.add(t.sample);break}for(const t of d)n.delete(t);return n}(t,r);for(const t of s){if(C(t,a,n),"snplst"!=t.type&&"snplocus"!=t.type)throw"unknown type of independent non-dictionary term";await j(t,a)}return[...a.values()]}(t,[t.outcome,...t.independent],e);w=(new Date).getTime(),_.NodeJS.getSampleData=(w-v)/1e3+" sec",v=(new Date).getTime();const r=function(t,e){const n={id:t.outcome.id,name:t.outcome.term.name,rtype:"numeric"};"logistic"==t.regressionType&&(n.categories={ref:t.outcome.refGrp,nonref:S(t.outcome)});"cox"==t.regressionType&&(n.timeToEvent={timeId:t.outcome.id+"_time",eventId:t.outcome.id+"_event",timeScale:t.outcome.q.timeScale},"age"==n.timeToEvent.timeScale&&(n.timeToEvent.agestartId=t.outcome.id+"_agestart",n.timeToEvent.ageendId=t.outcome.id+"_ageend"));const r=[];for(const e of t.independent)"snplst"==e.type||"snplocus"==e.type?N(e,r,t):q(e,r,t);const s=[];for(const o of e){const{sample:e,id2value:i}=o;if(!i.has(t.outcome.id)){o.noOutcome=!0;continue}const a=i.get(t.outcome.id);let l=!1;for(const e of t.independent)if("snplocus"!=e.type)if("snplst"==e.type){for(const t of e.highAFsnps.keys())if(!i.get(t)){l=!0;break}}else{if(!i.get(e.id)){l=!0;break}}if(l)continue;const c={};if("linear"==t.regressionType&&(c[n.id]=a.value),"logistic"==t.regressionType&&(c[n.id]=a.key===t.outcome.refGrp?0:1),"cox"==t.regressionType){c[n.timeToEvent.eventId]=a.key;const{age_start:e,age_end:r}=a.value;c[n.timeToEvent.timeId]=r-e,"age"==t.outcome.q.timeScale&&(c[n.timeToEvent.agestartId]=e,c[n.timeToEvent.ageendId]=r)}for(const t of r){const e=i.get(t.id);c[t.id]=e?"numeric"===t.rtype?e.value:e.key:null}s.push(c)}const o={regressionType:t.regressionType,binpath:h().binpath,data:s,outcome:n,independent:r};return o}(t,n);w=(new Date).getTime(),_.NodeJS.makeRinput=(w-v)/1e3+" sec",function(t){const e=t.regressionType,n=t.outcome;if(t.data.length<b)throw"too few samples to fit model";let r=t.independent.length;if("cox"==e)if("time"==n.timeToEvent.timeScale)r+=2;else{if("age"!=n.timeToEvent.timeScale)throw"unknown cox regression time scale";r+=4}else r+=1;if(t.data.find((t=>Object.keys(t).length!=r)))throw"unequal number of variables in data entries";if("logistic"==e){if([...new Set(t.data.map((t=>t[n.id])))].find((t=>![0,1].includes(t))))throw"non-0/1 outcome values found"}if("cox"==e){if([...new Set(t.data.map((t=>t[n.timeToEvent.eventId])))].find((t=>![0,1].includes(t))))throw"non-0/1 outcome event values found"}for(const e of t.independent)if("numeric"==e.rtype){if(e.refGrp)throw`reference group given for '${e.id}'`}else{if("factor"!=e.rtype)throw`variable rtype='${e.rtype}' not recognized`;{if(!e.refGrp)throw`reference group not given for '${e.id}'`;if("snplst"==e.type||"snplocus"==e.type)continue;const n=new Set(t.data.map((t=>t[e.id])));if(n.size<2)throw`fewer than 2 categories in data of variable='${e.id}'`;if(!n.has(e.refGrp))throw`reference group missing in data of variable='${e.id}'`}}}(r);const[s,a]=function(t){const e={},n={};if(e.outcome=t.outcome.id,n[t.outcome.id]="outcome",t.outcome.timeToEvent){const r=t.outcome.timeToEvent;e.outcome_time=r.timeId,n[r.timeId]="outcome_time",e.outcome_event=r.eventId,n[r.eventId]="outcome_event","age"==r.timeScale&&(e.outcome_agestart=r.agestartId,e.outcome_ageend=r.ageendId,n[r.agestartId]="outcome_agestart",n[r.ageendId]="outcome_ageend")}for(const[r,s]of t.independent.entries())e["id"+r+"_"]=s.id,n[s.id]="id"+r+"_";if(t.outcome.id=n[t.outcome.id],t.outcome.timeToEvent){const e=t.outcome.timeToEvent;e.timeId=n[e.timeId],e.eventId=n[e.eventId],"age"==e.timeScale&&(e.agestartId=n[e.agestartId],e.ageendId=n[e.ageendId])}for(const e of t.independent)if(e.id=n[e.id],e.interactions&&e.interactions.length>0)for(const[t,r]of e.interactions.entries())e.interactions[t]=n[r];for(const e of t.data)for(const t in e)e[n[t]]=e[t],delete e[t];return[e,n]}(r),l={resultLst:[]};return await Promise.all([A(r,s,t,l),M(t,n,r,l)]),console.log("benchmark:",_),l}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function k(t,e,n){if(!t.q.restrictAncestry)return;if(!("name"in t.q.restrictAncestry))throw".name missing from tw.q.restrictAncestry";if(!n.cohort.termdb.restrictAncestries)throw"ds.cohort.termdb.restrictAncestries missing";const r=n.cohort.termdb.restrictAncestries.find((e=>e.name==t.q.restrictAncestry.name));if(!r)throw"unknown ancestry for restriction: "+t.q.restrictAncestry.name;if(r.pcs)t.q.restrictAncestry.pcs=r.pcs;else{if(!r.PCBySubcohort)throw"unknown way of accessing pcs from ds.cohort.termdb.restrictAncestries: "+t.q.restrictAncestry.name;{if(!e.filter)throw"q.filter missing while trying to access subcohort for PCBySubcohort";const n=O(e.filter,"cohortFilter");if(!n)throw"tvs by tag=cohortFilter missing from q.filter.lst[] while trying to access subcohort for PCBySubcohort";const s=n.tvs.values.map((t=>t.key)).sort().join(","),o=r.PCBySubcohort[s];if(!o)throw"unknown key for PCBySubcohort: "+s;if(!o.pcs)throw"pcs Map() missing from PCBySubcohort[]: "+s;t.q.restrictAncestry.pcs=o.pcs}}}function q(t,e,n){const r={id:t.id,name:t.term.name,type:"spline"==t.q.mode?"spline":"other",rtype:"continuous"==t.q.mode||"spline"==t.q.mode?"numeric":"factor"};if(t.interactions.length>0){r.interactions=[];for(const e of t.interactions){const t=n.independent.find((t=>t.id==e));if("snplst"==t.type)for(const e of t.highAFsnps.keys())r.interactions.push(e);else{if("snplocus"==t.type)continue;r.interactions.push(e)}}}"factor"===r.rtype&&(r.refGrp=t.refGrp),"spline"==t.q.mode&&(r.spline={knots:t.q.knots.map((t=>Number(t.value)))},n.independent.find((t=>"snplocus"==t.type))||(r.spline.plotfile=s().join(h().cachedir,Math.random().toString()+".png"))),e.push(r)}function N(t,e,n){for(const r of t.highAFsnps.keys()){const s={id:r,name:r,type:t.type};3==t.q.geneticModel?(s.rtype="factor",s.refGrp=t.q.snp2refGrp[r]):s.rtype="numeric";for(const e of n.independent)e.interactions.includes(t.id)&&(s.interactions||(s.interactions=[]),s.interactions.push(e.id));e.push(s)}if(t.q.restrictAncestry)for(const n of t.q.restrictAncestry.pcs.keys())e.push({id:n,name:n,type:"float",rtype:"numeric"})}function S(t){if("condition"==t.term.type){for(const e of t.q.groups)if(e.name!=t.refGrp)return e;throw"nonref group not found for logistic outcome"}if("predefined-groupset"==t.q.type){if(!t.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!Number.isInteger(t.q.groupsetting.predefined_groupset_idx))throw'outcome.q.predefined_groupset_idx not integer when q.type is "predefined-groupset"';if(!t.term.groupsetting)throw"outcome.term.groupsetting missing";const e=t.term.groupsetting.lst[t.q.groupsetting.predefined_groupset_idx];if(!e)throw"groupset not found by outcome.q.predefined_groupset_idx";const n=e.groups.find((e=>e.name!=t.refGrp));if(!n)throw"non-ref group not found for predefined-groupset";return n.name}if("custom-groupset"==t.q.type){if(!t.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!t.q.groupsetting.customset)throw"outcome.q.customset missing";const e=t.q.groupsetting.customset.groups.find((e=>e.name!=t.refGrp));if(!e)throw"non-ref group not found for custom-groupset";return e.name}if("values"==t.q.type){if(!t.term.values)throw"outcome.term.values{} missing";for(const e in t.term.values){const n=t.term.values[e];if(n.label!=t.refGrp)return n.label}throw"unknown nonref group from outcome.term.values"}if("custom-bin"==t.q.type){const e=t.q.lst.find((e=>e.label!=t.refGrp));if(!e)throw"non-ref bin is not found for custom-bin";return e.label}if("regular-bin"==t.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(t,e,n,r){v=(new Date).getTime();const o=s().join(h().cachedir,Math.random().toString()+".json");await p.Sf(o,JSON.stringify(t));const i=await(0,a.default)(s().join(h().binpath,"utils","regression.R"),[],[o]);c().unlink(o,(()=>{})),await async function(t,e,n,r,s){if(1!=e.length)throw"expected 1 json line in R output";const o=JSON.parse(e[0]),i=o.data;_["regression.R"]=o.benchmark;for(const e of i){const o={data:{sampleSize:e.data.sampleSize,eventCnt:e.data.eventCnt?e.data.eventCnt:null}};if(e.id){const t=n[e.id];o.id=t;const s=r.independent.find((t=>"snplocus"==t.type));if(!s)throw"snplocus term missing";o.AFstr=s.snpid2AFstr.get(t),o.data.headerRow=T(t,s)}const i=e.data;if(i.residuals&&(o.data.residuals=i.residuals,o.data.residuals.label="linear"==t.regressionType?"Residuals":"Deviance residuals"),"cox"==t.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"==t.regressionType?null:i.coefficients.rows.shift(),terms:{},interactions:[]};for(const t of i.coefficients.rows)if(-1!=t[0].indexOf(":")){const e={},[r,s]=t.shift().split(":"),[i,a]=t.shift().split(":");e.term1=n[r],e.category1=i,e.term2=n[s],e.category2=a,e.lst=t,o.data.coefficients.interactions.push(e)}else{const e=t.shift(),r=t.shift(),s=n[e];o.data.coefficients.terms[s]||(o.data.coefficients.terms[s]={}),r?(o.data.coefficients.terms[s].categories||(o.data.coefficients.terms[s].categories={}),o.data.coefficients.terms[s].categories[r]=t):o.data.coefficients.terms[s].fields=t}o.data.coefficients.label="Coefficients",o.data.type3={header:i.type3.header,terms:{},interactions:[]},"cox"!=t.regressionType&&(o.data.type3.intercept=i.type3.rows.shift());for(const t of i.type3.rows)if(-1!=t[0].indexOf(":")){const e={},[r,s]=t.shift().split(":");e.term1=n[r],e.term2=n[s],e.lst=t,o.data.type3.interactions.push(e)}else{const e=n[t.shift()];o.data.type3.terms[e]||(o.data.type3.terms[e]=t)}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 t=i.totalSnpEffect.rows[0].slice(0,4),e=i.totalSnpEffect.rows[0][4].split(";"),r=e.findIndex((t=>!t.includes(":"))),s=e.splice(r,1)[0];o.data.totalSnpEffect.snp=n[s];const a=[];for(const t of e){if(!t.includes(":"))throw"expected interaction";const[e,r]=t.split(":");a.push({term1:n[e],term2:n[r]})}o.data.totalSnpEffect.interactions=a,o.data.totalSnpEffect.lst=t,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 e of t.independent)if(e.spline&&e.spline.plotfile){o.data.splinePlots||(o.data.splinePlots=[]);const t=e.spline.plotfile,n=await c().promises.readFile(t);o.data.splinePlots.push({src:"data:image/png;base64,"+new Buffer.from(n).toString("base64"),size:f()(t)}),c().unlink(t,(t=>{if(t)throw t}))}i.warnings&&(o.data.warnings=i.warnings);const a=r.independent.find((t=>"snplst"==t.type));if(a){if(a.lowAFsnps&&a.lowAFsnps.size){o.data.warnings||(o.data.warnings=[]);for(const t of a.lowAFsnps.keys())o.data.warnings.push(`${t}: effect allele frequency below cutoff, excluded from analysis`)}if(a.monomorphicLst&&a.monomorphicLst.length){o.data.warnings||(o.data.warnings=[]);for(const t of a.monomorphicLst)o.data.warnings.push(`${t}: monomorphic, excluded from analysis`)}}s.resultLst.push(o)}}(t,i,e,n,r),w=(new Date).getTime(),_.NodeJS.runRegression=(w-v)/1e3+" sec"}async function M(t,e,n,r){const o=t.independent.find((t=>"snplocus"==t.type));if(o){if(v=(new Date).getTime(),function(t,e){for(const n of t.monomorphicLst){const r=t.snpgt2count.get(n),s=[];for(const[t,e]of r)s.push(t+"="+e);const o={id:n,data:{headerRow:T(n,t)}};e.resultLst.push(o)}}(o,r),o.lowAFsnps.size)if("linear"==t.regressionType)await async function(t,e,n,r){const o=[],i=new Map;for(const[r,s]of t.lowAFsnps){let t=0,a=null,l=null;const c=[],u=[];for(const{sample:r,noOutcome:o}of e){if(o)continue;const e=n.data[t++].outcome;if(!Number.isFinite(e))continue;const i=s.samples.get(r);if(!i)continue;null==a?a=l=e:(a=Math.min(a,e),l=Math.max(l,e));const[f,d]=i.split("/");f==s.effAle||d==s.effAle?c.push(e):u.push(e)}o.push({group1_id:r+"_hasEffAllele",group1_values:c,group2_id:r+"_noEffAllele",group2_values:u}),i.set(r,{minv:a,maxv:l})}const l=s().join(h().cachedir,Math.random().toString()+".json");await p.Sf(l,JSON.stringify(o));const u=await(0,a.default)(s().join(h().binpath,"utils/wilcoxon.R"),[],[l]);c().unlink(l,(()=>{}));const f=JSON.parse(u);for(const e of f){const n=e.group1_id.replace("_hasEffAllele",""),s=e.group1_values,o=e.group2_values;let a;a=null==e.pvalue||"null"==e.pvalue?"NA":e.pvalue.toPrecision(4);const{minv:l,maxv:c}=i.get(n),u=p.JC(s.sort(((t,e)=>t-e)).map((t=>({value:t}))));u.label=`Carry ${0==t.q.alleleType?"minor":"alternative"} allele, n=${s.length}`;const f=p.JC(o.sort(((t,e)=>t-e)).map((t=>({value:t}))));f.label=`No ${0==t.q.alleleType?"minor":"alternative"} allele, n=${o.length}`;const d={id:n,AFstr:t.snpid2AFstr.get(n),data:{headerRow:T(n,t),wilcoxon:{pvalue:a,boxplots:{minv:l,maxv:c,hasEff:u,noEff:f}}}};r.resultLst.push(d)}}(o,e,n,r);else if("logistic"==t.regressionType)await async function(t,e,n,r){const s=[];let o=0;const i=new Map;for(const[r,a]of t.lowAFsnps){let t=0,l=0,c=0,u=0,f=0;for(const{sample:r,noOutcome:s}of e){if(s)continue;const e=n.data[f++],o="outcome"in e?e.outcome:e.outcome_event;if(0!=o&&1!=o)throw"outcome is not 0 or 1";const i=a.samples.get(r);if(!i)continue;const[d,h]=i.split("/"),p=a.effAle==d||a.effAle==h;0==o?p?l++:t++:p?u++:c++}i.set(o,r);const d={index:o,n1:u,n2:l,n3:c,n4:t};s.push(d),o++}const a=await(0,m.run_rust)("fisher",JSON.stringify({input:s}));for(const e of JSON.parse(a)){const n=i.get(e.index),{effAle:s}=t.lowAFsnps.get(n),o=e.p_value,a="chisq"===e.fisher_chisq,l={id:n,AFstr:t.snpid2AFstr.get(n),data:{headerRow:T(n,t),fisher:{isChi:a,pvalue:Number(o.toFixed(4)),rows:[["","Carry "+s+" allele","No "+s+" allele"],["Have event",e.n1,e.n3],["No event",e.n2,e.n4]]}}};r.resultLst.push(l)}}(o,e,n,r);else{if("cox"!=t.regressionType)throw"unknown regression type";await async function(t,e,n,r){const s={data:{}},o=new Set;for(const[r,i]of t.lowAFsnps){const t=[];let a=0;for(const{sample:r,noOutcome:s}of e){if(s)continue;const e=n.data[a++];if(0!==e.outcome_event&&1!==e.outcome_event)throw"d.outcome_event is not 0/1";if(!Number.isFinite(e.outcome_time))throw"d.outcome_time is not numeric";const o={time:e.outcome_time,event:e.outcome_event},l=i.samples.get(r);if(!l)continue;const[c,u]=l.split("/");o.series=i.effAle==c||i.effAle==u?"1":"2",t.push(o)}new Set(t.map((t=>t.series))).size<2?o.add(r):s.data[r]=t}const i=await(0,g.y)(s);let a;for(const[e,n]of t.lowAFsnps){if(o.has(e)){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[e].tests?.length)throw"must have a single test";const t=Number(i[e].tests[0].pvalue);if(!Number.isFinite(t))throw"invalid pvalue";a={pvalue:Number(t.toFixed(4)),ci_data:{[e]:i[e]}}}const n={id:e,AFstr:t.snpid2AFstr.get(e),data:{headerRow:T(e,t),cuminc:a}};r.resultLst.push(n)}}(o,e,n,r)}w=(new Date).getTime(),_.NodeJS.snplocusPostprocess=(w-v)/1e3+" sec"}}function T(t,e){const n=e.snpgt2count.get(t);if(!n)return{k:"Error",v:"Variant not found"};const r=[];for(const[t,e]of n)r.push(t+"="+e);const s={snpid:t,gtcounts:r};return e.monomorphicLst.includes(t)?s.monomorphic=!0:(s.effAle=e.highAFsnps.has(t)?e.highAFsnps.get(t).effAle:e.lowAFsnps.get(t).effAle,s.af=e.snpid2AFstr.get(t)),{k:"Variant:",v:s}}function C(t,e,n){if(t.q.restrictAncestry)for(const[n,r]of t.q.restrictAncestry.pcs)for(const[t,s]of r)e.has(t)&&e.get(t).id2value.set(n,{key:s,value:s})}async function j(t,e,n){const r=(await p.b5(s().join(h().cache_snpgt.dir,t.q.cacheid))).split("\n"),o=r[0].split("\t").slice(h().cache_snpgt.sampleColumn).map(Number);if(n)for(const t of o)e.set(t,{id2value:new Map});const i=o.map((t=>e.has(t))),a=new Map;for(let e=1;e<r.length;e++){const n=r[e].split("\t"),s=n[0],l={refAle:n[3],altAles:n[4].split(","),samples:new Map};t.q.snp2effAle?l.effAle=t.q.snp2effAle[s]:l.effAle=l.altAles[0],a.set(s,l);for(const[t,e]of o.entries()){if(!i[t])continue;const r=n[t+h().cache_snpgt.sampleColumn];r&&a.get(s).samples.set(e,r)}}"snplst"!=t.type||n||function(t,e,n,r){if(0==e.q.missingGenotype){for(const e of t.values()){let t;if(e.refAle!=e.effAle)t=e.refAle;else for(const n of e.altAles)if(n!=e.effAle){t=n;break}if(!t)throw"not finding a non-effect allele";for(const[s,o]of n.entries())r[s]&&(e.samples.has(o)||e.samples.set(o,t+"/"+t))}return}if(1==e.q.missingGenotype){const e=new Set;for(const{samples:s}of t.values())for(const[t,o]of n.entries())r[t]&&(s.has(o)||e.add(o));for(const{samples:n}of t.values())for(const t of e)n.delete(t);return}throw"invalid missingGenotype value"}(a,t,o,i),t.snpgt2count=new Map;for(const[e,n]of a){const r=new Map;for(const[t,e]of n.samples)r.set(e,1+(r.get(e)||0));t.snpgt2count.set(e,r)}!function(t,e){t.lowAFsnps=new Map,t.highAFsnps=new Map,t.monomorphicLst=[],t.snpid2AFstr=new Map;for(const[n,r]of e){if(1==t.snpgt2count.get(n).size){t.monomorphicLst.push(n);continue}const e=r.samples.size;let s=0;for(const[t,e]of r.samples){const[t,n]=e.split("/");s+=(t==r.effAle?1:0)+(n==r.effAle?1:0)}const o=s/(2*e);t.snpid2AFstr.set(n,(100*o).toFixed(1)+"%"),o<t.q.AFcutoff/100?t.lowAFsnps.set(n,r):t.highAFsnps.set(n,r)}}(t,a);for(const[n,r]of t.highAFsnps)for(const[s,o]of r.samples){const[i,a]=o.split("/"),l=E(t,r.effAle,i,a);e.get(s).id2value.set(n,{key:l,value:l})}}function E(t,e,n,r){switch(t.q.geneticModel){case 0:return(n==e?1:0)+(r==e?1:0);case 1:return n==e||r==e?1:0;case 2:return n==e&&r==e?1:0;case 3:return n+"/"+r;default:throw"unknown geneticModel option"}}function O(t,e){if(t.tag===e)return t;if("tvslst"===t.type)for(const n of t.lst){const t=O(n,e);if(t)return t}}},2188:(t,e,n)=>{"use strict";n.d(e,{uR:()=>g,v8:()=>k,wz:()=>m});var r=n(2974),s=n(1017),o=n.n(s),i=n(3345),a=n(334),l=n.n(a),c=n(2273),u=n(8907),f=n(5257),d=n(6191),h=n(9157);const p="#F5F5DC";async function m(t){if(t.cohort.scatterplots){if(!Array.isArray(t.cohort.scatterplots.plots))throw"cohort.scatterplots.plots is not array";for(const e of t.cohort.scatterplots.plots){if(!e.name)throw".name missing from one of scatterplots.plots[]";if(!e.file)throw"unknown data source of one of scatterplots.plots[]";{const n=(await(0,i.b5)(o().join(l().tpmasterdir,e.file))).trim().split("\n"),r=n[0].split("\t");e.filterableSamples=[];const s=[];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=t.cohort.termdb.q.sampleName2id(i[0]);if(null==d){if(r[3]){f.info={};for(let t=3;t<r.length;t++)f.info[r[t]]=i[t]}s.push(f)}else c++,f.sampleId=d,e.filterableSamples.push(f)}s.length&&(e.referenceSamples=s),console.log(e.filterableSamples.length,`scatterplot lines from ${e.name} of ${t.label},`,e.referenceSamples?e.referenceSamples.length+" reference cases":"",a?a+" lines with invalid X/Y values":"")}}}}async function g(t,e,n,s,o){try{let i,a;if(2==e.coordTWs.length)i=[],a=await async function(t,e,n){e.ds=n;const r=[];if(2!=e.coordTWs.length)return r;const s=await(0,f.w)(e.filter,e.ds);let o="";s&&(o+=(0,u.ig)(`WITH ${s.filters}`,s.values.slice()));const i=e.coordTWs[0].term,a=e.coordTWs[1].term;let l;e.divideByTW&&"continuous"==e.divideByTW.q.mode&&(l=e.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}'`,s&&(o+=` AND ax.sample IN ${s.CTEname}`);const c=e.ds.cohort.db.connection.prepare(o).all(),h=d.i.canDisplaySampleIds(t,n);for(const{sampleId:t,x:s,y:o,z:i}of c){const a={sampleId:t,x:s,y:o,z:i};h&&(a.sample=n.sampleId2Name.get(t));const l=x(e.coordTWs[0].term,s)&&x(e.coordTWs[1].term,o)&&x(e.divideByTW?.term,i);a&&l&&r.push(a)}return r}(t,e,s);else{if(!e.plotName)throw"Neither plot name or coordinates where provided";if(!s.cohort.scatterplots||!s.cohort.scatterplots.plots)throw"not supported";const t=s.cohort.scatterplots.plots.find((t=>t.name==e.plotName));if(!t)throw`plot not found with plotName ${e.plotName}`;const n=await async function(t,e,n){if(n.filterableSamples){let t=[],e=[];return n.referenceSamples&&(e=r(n.referenceSamples)),n.filterableSamples&&(t=r(n.filterableSamples)),[e,t]}if(n.gdcapi)throw"gdcapi not implemented yet";throw"do not know how to load data from this plot";function r(t){const e=[];for(const n of JSON.parse(JSON.stringify(t)))e.push(n);return e}}(0,0,t);i=n[0],a=n[1]}const l=[];e.coordTWs&&l.push(...e.coordTWs),e.colorTW&&l.push(e.colorTW),e.shapeTW&&l.push(e.shapeTW),e.divideByTW&&l.push(e.divideByTW),e.scaleDotTW&&l.push(e.scaleDotTW);const h=await(0,r.Yu)({filter:e.filter,terms:l},s,o);if(h.error)throw h.error;const m=await async function(t,e,n,r){const s={};for(const o of e){const e=n.samples[o.sampleId.toString()];if(!e)continue;let i=!1;if(r.colorTW&&!y(e,r.colorTW)||r.shapeTW&&!y(e,r.shapeTW))continue;let a="Default";if(r.divideByTW&&"continuous"!=r.divideByTW.q.mode)if(o.z=0,"geneVariant"==r.divideByTW.term.type)a=v(!0,e,r.divideByTW),null==a&&(a=v(!1,e,r.divideByTW),i=!0);else{const t=r.divideByTW.term.id||r.divideByTW.term.name,n=e[t]?.key;if(null==n)continue;a=r.divideByTW.term.values?.[n]?.label||n}if(!s[a]){const e=t.map((t=>({...t,category:"Ref",shape:"Ref",z:0})));s[a]={samples:e,colorMap:{},shapeMap:{},isLast:i}}if(r.divideByTW||(o.z=0),r.scaleDotTW){const t=e?.[r.scaleDotTW.id]?.key;if(!t||!x(r.scaleDotTW.term,t))continue;o.scale=t}else o.scale=1;o.cat_info={},o.hidden={},r.colorTW?"continuous"===r.colorTW?.q?.mode?e&&(o.category=e[r.colorTW.term.id||r.colorTW.term.name].value):b(e,o,r.colorTW,s[a].colorMap,"category"):o.category="Default",r.shapeTW?b(e,o,r.shapeTW,s[a].shapeMap,"shape"):o.shape="Ref",s[a].samples.push(o)}let o=0;for(const[t,e]of Object.entries(s))o=Math.max(o,Object.keys(e.colorMap).length);const i=(0,c.getColors)(o);for(const[o,a]of Object.entries(s)){if(r.colorTW&&"continuous"!==r.colorTW.q.mode){let t=20;const e=c.schemeCategory20,s=Object.entries(a.colorMap);for(const[o,a]of s){let s;if(r.colorTW.term.values?.[o])s=r.colorTW.term.values?.[o];else for(const t in r.colorTW.term.values)r.colorTW.term.values?.[t].label==o&&(s=r.colorTW.term.values?.[t]);if(s&&"color"in s)a.color=s.color;else if(n.refs?.byTermId[r.colorTW.term.id]?.bins){const s=n.refs.byTermId[r.colorTW.term.id].bins.find((t=>t.name===o));s?a.color=s.color:(a.color=e[t],t--)}else"geneVariant"!=r.colorTW.term.type&&(a.color=i(o))}}let s=1;for(const[t,e]of Object.entries(a.shapeMap))"shape"in e||(e.shape=s),s++;a.colorLegend=r.colorTW?_(a.colorMap,r.colorTW,n.refs):[["Default",{sampleCount:e.length,color:"blue"}]],a.colorLegend.push(["Ref",{sampleCount:t.length,color:r.colorTW?.term.values?.Ref?r.colorTW.term.values?.Ref.color:p}]),a.shapeLegend=_(a.shapeMap,r.shapeTW,n.refs),a.shapeLegend.push(["Ref",{sampleCount:t.length,shape:0}])}return s}(i,a,h,e);n.send(m)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}function y(t,e){const n=t?.[e?.term?.id||e?.term?.name]?.key,r=void 0!==n;return r||console.log(JSON.stringify(t)+" missing value for the term "+JSON.stringify(e)),r}function b(t,e,n,r,s){let o=null;"geneVariant"==n.term.type?function(t,e,n,r,s){if("geneVariant"==n.term.type){const o=t?.[n.term.name]?.values;e.cat_info[s]=[];for(const t of o){const n=c.mclass[t.class],o=w(t);let i;e.cat_info[s].push(t),null==r[o]?(i={color:n.color,sampleCount:1,hasOrigin:"origin"in t},r[o]=i):(i=r[o],i.sampleCount=i.sampleCount+1,i.hasOrigin=i.hasOrigin||"origin"in t)}e[s]=v(!0,t,n)||v(!1,t,n),e[s]||(e[s]=w(o[0])),e.hidden[s]=!!n.q.hiddenValues&&e[s]in n.q.hiddenValues}}(t,e,n,r,s):(o=t?.[n.id||n.term.name]?.key,n.term.values?.[o]?.label?(o=n.term.values?.[o]?.label,e.hidden[s]=!!n.q.hiddenValues&&o in n.q.hiddenValues):e.hidden[s]=!!n.q.hiddenValues&&t?.[n.id]?.key in n.q.hiddenValues,o&&(e[s]=o.toString(),null==r[o]?r[o]={sampleCount:1}:r[o].sampleCount++))}function v(t,e,n){const r=e?.[n.term.name]?.values;for(const[e,s]of Object.entries(c.dt2label)){const s=r.find((t=>{const r=w(t),s=!(n.q.hiddenValues&&r in n.q.hiddenValues);return t.dt==e&&s}));if(!s)continue;const o="WT"==s.class||"Blank"==s.class;if(t&&o)continue;return w(s)}}function w(t){const e=t.dt,n=c.mclass[t.class],r=c.morigin[t.origin]?.label,s=r?`${r[0]} ${c.dt2label[e]}`:c.dt2label[e];return`${n.label}, ${s}`}function _(t,e,n){let r=[];if(!e||0==t.size)return r;if("geneVariant"==e.term.type)r=Object.entries(t),r.sort(((t,e)=>t[0]<e[0]?-1:t[0]>e[0]?1:0));else if(n?.byTermId[e.term.id]?.bins){const s=n.byTermId[e.term.id].bins;for(const e of s)t[e.name]&&r.push([e.name,t[e.name]]);for(const[e,n]of Object.entries(t))r.some((t=>t[0]===e))||r.push([e,n])}else r=Object.entries(t),r.sort(((t,n)=>{let r,s;for(const o in e.term.values){const i=e.term.values[o];(i.label&&t[0]==i.label||o==t[0])&&(r=i),(i.label&&n[0]==i.label||o==n[0])&&(s=i)}return r&&"order"in r?r?.order<s?.order?-1:1:t[1].sampleCount>n[1].sampleCount?-1:1}));return r}function x(t,e){if(!t)return!0;return!t.values?.[e]?.uncomputable}async function k(t,e,n){const r=e.coords,s=o().join(l().cachedir,Math.random().toString()+".json");await(0,i.Sf)(s,JSON.stringify(r));let a=await(0,h.default)(o().join(l().binpath,"utils/lowess.R"),[],[s]);a=JSON.parse(a);const c=[];for(const[t,e]of Object.entries(a.x))c.push([e,a.y[t]]);return n.send(c)}},394:(t,e,n)=>{"use strict";n.d(e,{JV:()=>l,jj:()=>c,qN:()=>u});var r=n(334),s=n.n(r),o=n(3345),i=n(1575),a=n(6191);function l(t){if(!t.cohort)throw"ds.cohort missing";if(!t.cohort.db)throw"ds.cohort.db missing";if(!t.cohort.termdb)throw"ds.cohort.termdb missing";const e=t.cohort.db.file_fullpath||t.cohort.db.file;if(!e)throw"both file and file_fullpath missing";let n;try{console.log("Connecting",e),n=(0,o.sE)(e),console.log(`DB connected for ${t.label}: ${e}`)}catch(t){throw`Cannot connect db ${e}: ${t.message||t}`}t.cohort.db.connection=n;const r=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 t of l)r.has(t)||console.log(`${t} table missing!!!!!!!!!!!!!!!!!!!!`);if(!r.has("terms"))throw"terms table missing";if(!r.has("ancestry"))throw"ancestry table missing";if(t.cohort.termdb.selectCohort&&!r.has("subcohort_terms"))throw"subcohort_terms table is missing while termdb.selectCohort is enabled";t.cohort.termdb.q={};const f=t.cohort.termdb.q;if(r.has("buildDate")&&(f.get_buildDate=n.prepare("select date from buildDate")),r.has("term2genes")){t.cohort.termdb.termMatch2geneSet=!0;const e=n.prepare("SELECT genes FROM term2genes WHERE id=?"),r=new Map;f.getGenesetByTermId=t=>{if(r.has(t))return r.get(t);const n=e.get(t);if(n&&n.genes){const e=JSON.parse(n.genes);return r.set(t,e),e}}}if(r.has("sampleidmap")){const e=new Map,r=new Map,s=n.prepare("SELECT * FROM sampleidmap");let o=0;for(const{id:t,name:n}of s.all())e.set(t,n),r.set(n,t),o++;if(f.id2sampleName=t=>e.get(t),f.sampleName2id=t=>r.get(t),t.cohort.termdb.selectCohort){const t=n.prepare("SELECT cohort,sample_count from cohorts").all(),e={};for(const n of t)e[n.cohort]=n.sample_count;f.getcohortsamplecount=t=>t?e[t]||0:o}else f.getcohortsamplecount=()=>o}if(r.has("category2vcfsample")){const t=n.prepare("SELECT * FROM category2vcfsample");let e;f.getcategory2vcfsample=()=>{if(e)return e;e=t.all();for(const t of e)t.q=JSON.parse(t.q),t.categories=JSON.parse(t.categories);return e}}if(r.has("alltermsbyorder")){const t=n.prepare("SELECT * FROM alltermsbyorder");let e;f.getAlltermsbyorder=()=>{if(e)return e;const n=t.all();e=[];for(const t of n){const n=f.termjsonByOneid(t.id);n&&e.push({group_name:t.group_name,term:n})}return e}}{const t=n.prepare("SELECT name, jsondata FROM terms WHERE id=?"),e=new Map;f.termjsonByOneid=n=>{if(e.has(n))return e.get(n);const r=t.get(n);if(r){const t=JSON.parse(r.jsondata);return t.id=n,t.name=r.name||t.name,e.set(n,t),t}}}{const t=n.prepare("select id from terms where parent_id=?"),e=new Map;f.termIsLeaf=n=>{if(e.has(n))return e.get(n);let r=!0;const s=t.get(n);return s&&s.id&&(r=!1),e.set(n,r),r}}{const t=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"),e=new Map;f.getRootTerms=(n="")=>{const r=n;if(e.has(r))return e.get(r);const s=t.all(n).map((t=>{const e=JSON.parse(t.jsondata);return e.id=t.id,e.name=t.name||e.name,e.included_types=t.included_types?t.included_types.split(","):["TO-DO-PLACEHOLDER"],e.child_types=t.child_types?t.child_types.split(","):[],e}));return e.set(r,s),s}}{const t=n.prepare("SELECT parent_id FROM terms WHERE id=?");{const e=new Map;f.termHasParent=n=>{if(e.has(n))return e.get(n);let r=!1;const s=t.get(n);return s&&s.parent_id&&(r=!0),e.set(n,r),r}}{const e=new Map;f.getTermParentId=n=>{if(e.has(n))return e.get(n);let r;const s=t.get(n);return s&&s.parent_id&&(r=s.parent_id),e.set(n,r),r}}{const t=new Map;f.getTermParent=e=>{if(t.has(e))return t.get(e);const n=f.getTermParentId(e);let r;return n&&(r=f.termjsonByOneid(n)),t.set(e,r),r}}}{const t=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"),e=new Map;f.getTermChildren=(n,r="")=>{const s=n+";;"+r;if(e.has(s))return e.get(s);const o=t.all([r,n]);let i;return o&&(i=o.map((t=>{const e=JSON.parse(t.jsondata);return e.id=t.id,e.name=t.name||e.name,e.included_types=t.included_types?t.included_types.split(","):[],e.child_types=t.child_types?t.child_types.split(","):[],e}))),e.set(s,i),i}}{const t=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=(e,n=10,r="",s=null,o=null,a=null)=>{const l=t.all([r,"%"+e+"%"]);if(l){const t=a||{equals:[],startsWith:[],startsWord:[],includes:[]};for(const n of l){if(!n.jsondata)continue;const r=n.name.toLowerCase(),s=JSON.parse(n.jsondata);s.id=n.id,s.name=n.name||s.name,s.included_types=n.included_types?n.included_types.split(","):[],o&&!(0,i.CG)(s,o).has("plot")||(r===e?t.equals.push(s):r.startsWith(e)?t.startsWith.push(s):r.includes(" "+e)?t.startsWord.push(s):t.includes.push(s))}return[...t.equals,...t.startsWith,...t.startsWord,...t.includes].slice(0,n)}}}{const t=n.prepare("SELECT MAX(value) AS v FROM anno_integer WHERE term_id=?"),e=n.prepare("SELECT MAX(value) AS v FROM anno_float WHERE term_id=?"),r=new Map;f.findTermMaxvalue=(n,s)=>{if(r.has(n))return r.get(n);const o=(s?t:e).get(n);return o?(r.set(n,o.v),o.v):void 0}}{const t={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=e=>{const n=f.termjsonByOneid(e);if(!n)return;const r=t[n.type];if(!r)return;const s=r.all(e);if(!s||0==s.length)return;const o=new Map;for(const t of s)o.set(t.sample,t.value);return o}}{const t=n.prepare("SELECT ancestor_id FROM ancestry WHERE term_id=?"),e=new Map;f.getAncestorIDs=n=>{if(e.has(n))return e.get(n);const r=t.all(n).map((t=>t.ancestor_id));return e.set(n,r),r}}{const t=n.prepare("SELECT t.name FROM ancestry as a, terms as t WHERE a.term_id=? AND t.id=a.ancestor_id"),e=new Map;f.getAncestorNames=n=>{if(e.has(n))return e.get(n);const r=t.all(n).map((t=>t.name));return e.set(n,r),r}}{const t={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=?")},e={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=?")},r={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,s=null)=>{const o=f.termjsonByOneid(n);return s?"string"==typeof s?r[o.type].all(n,s):e[o.type].all(n,s):t[o.type].all(n)}}if(r.has("termhtmldef")){const t=n.prepare("SELECT jsonhtml FROM termhtmldef WHERE id=?"),e=new Map;f.getTermInfo=n=>{if(e.has(n))return e.get(n);const r=t.get(n);if(r){const t=JSON.parse(r.jsonhtml);return t.id=n,e.set(n,t),t}}}f.getSupportedChartTypes=e=>{u(t);s().dsCredentials?.[t.label];const n={},r={};for(const o of t.cohort.termdb.termtypeByCohort)if(o.type){if(!(o.cohort in n)){n[o.cohort]=new Set(["regression","summary"]),t.cohort.scatterplots&&n[o.cohort].add("sampleScatter"),r[o.cohort]=0,t.cohort.allowedChartTypes?.includes("matrix")&&n[o.cohort].add("matrix");const s=a.i.getForbiddenRoutesForDsEmbedder(t.label,e);s.includes("termdb")||s.includes("*")||(n[o.cohort].add("dataDownload"),n[o.cohort].add("sampleView"),t.queries?.singleCell&&n[o.cohort].add("singleCellPlot"))}s().features?.draftChartTypes&&n[o.cohort].add(...s().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||(r[o.cohort]+=o.samplecount)}for(const t in r)r[t]>1&&n[t].add("sampleScatter");for(const t in n)n[t]=[...n[t]];if(t.cohort.allowedChartTypes)for(const e in n)n[e]=n[e].filter((e=>t.cohort.allowedChartTypes.includes(e)));if(t.queries){if(t.queries.snvindel||t.queries.trackLst)for(const t in n)n[t].push("genomeBrowser");if(t.queries.geneExpression)for(const t in n)n[t].push("hierCluster");if(t.queries.rnaseqGeneCount)for(const t in n)n[t].push("DEanalysis")}return n},f.getSingleSampleData=function(t,e=[]){const r=e.length?`and term_id in (${e.map((t=>"?")).join(",")})`:"",s=`select term_id, value, jsondata from ( select term_id, value \n\t\tfrom anno_categorical \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, \n\t\tvalue from anno_float \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, value \n\t\tfrom anno_integer \n\t\twhere sample=? ${r}\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=? ${r}\n\t\tunion all \n\t\tselect term_id, (tte || ' ' || exit_code) as value \n\t\tfrom survival \n\t\twhere sample=? ${r}) join terms on terms.id = term_id`;return n.prepare(s).all([t,...e,t,...e,t,...e,t,...e,t,...e])},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(t){const e=t.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();return new Set(e.map((t=>t.name)))}function u(t){if(t.cohort.termdb.termtypeByCohort){if(!Array.isArray(t.cohort.termdb.termtypeByCohort))throw"termtypeByCohort is not array"}else{if(!t.cohort?.db?.connection)throw"termtypeByCohort[] not set but cohort.db.connection missing";t.cohort.termdb.termtypeByCohort=t.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:(t,e,n)=>{"use strict";n.d(e,{G:()=>g,u:()=>y});var r=n(7147),s=n.n(r),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",h="%POS\t%ID\t%REF\t%ALT\t%INFO[\t%TGT]\n",p="./.",m=1e3;async function g(t,e,n,r){try{if(t.sumSamples)return await async function(t,e,n,r){if(!t.cacheid)throw"cacheid missing";if(u().cache_snpgt.fileNameRegexp.test(t.cacheid))throw"invalid cacheid";let s,o;if(n.track){if(s=n.track.vcf,!s)throw"ds.track.vcf missing"}else s=n.queries.snvindel.byrange._tk;if(t.filter){const e=new Set((await l.cf(t.filter,n)).map((t=>t.id)));if(0==e.size)throw"no samples from filter";o=s.samples.map((t=>e.has(t.name)))}else o=s.samples.map((t=>!0));const c=(await a.b5(i().join(u().cache_snpgt.dir,t.cacheid))).split("\n"),f=new Set,d=[];for(let t=1;t<c.length;t++){const e=c[t].split("\t"),n=e[0],r=e[3],i={},a={};for(let t=u().cache_snpgt.sampleColumn;t<e.length;t++){const n=e[t];if(!n)continue;if(!o[t-u().cache_snpgt.sampleColumn])continue;f.add(s.samples[t-u().cache_snpgt.sampleColumn].name),a[n]=1+(a[n]||0);const r=n.split("/");for(const t of r)i[t]=1+(i[t]||0)}const l=[];for(const t in i)l.push({allele:t,count:i[t],isRef:t==r});d.push({snpid:n,alleles:l,gt2count:a})}return{numOfSampleWithAnyValidGT:f.size,snps:d}}(t,0,n);if(t.snptext)return await async function(t,e,n){if(!n.snp)throw"snp not supported by genome";if(!t.snptext)throw".snptext missing";const r=function(t){const e=[];for(const n of t.trim().split("\n")){const[t,r]=n.trim().split(/[\s\t]/);if(t&&t.startsWith("rs")){if(e.find((e=>e.rsid==t)))continue;const n={rsid:t,snpid:t};r&&(n.effectAllele=r),e.push(n)}else e.push({rsid:t,snpid:t,invalid:"INVALID RSID"})}return e}(t.snptext);if(!r.length)throw"no snps";await async function(t,e){for(const n of t)if(!n.invalid)if(n.chr&&"string"==typeof n.chr){const t=e.chrlookup[n.chr.toUpperCase()];if(!t){n.invalid=!0;continue}if(!Number.isInteger(n.pos)){n.invalid=!0;continue}if(n.pos<=0||n.pos>=t.len){n.invalid=!0;continue}}else if(n.rsid){const t=await a.mr(e.snp.bigbedfile,n.rsid),r=[];for(const n of t){const t=n.split("\t"),s=e.chrlookup[t[0].toUpperCase()];s&&s.major&&r.push(t)}if(0==r.length){n.invalid=!0;continue}const s=r[0];n.chr=s[0],n.pos=Number.parseInt(s[1]),n.dbsnpRef=s[4],n.dbsnpAlts=s[6].split(",").filter(Boolean)}else n.invalid=!0;if(!t.find((t=>!t.invalid)))throw"no valid variants"}(r,n);const o=await async function(t,e,n){let r;if(n.track){if(r=n.track.vcf,!r)throw"ds.track.vcf missing"}else r=n.queries.snvindel.byrange._tk;const o=new Set,l=[];for(const t of e){if(t.invalid)continue;let e;if(r.chr2files){if(e=r.chr2files?.[t.chr].file,!e)throw"chr not in chr2files"}else if(r.chr2bcffile){if(e=r.chr2bcffile[t.chr],!e)throw"chr not in chr2bcffile"}else e=r.file||r.url;o.add(e);const n=(r.nochr?t.chr.replace("chr",""):t.chr)+"\t"+(t.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:r.dir,callback:t=>{const n=t.split("\t"),s=(r.nochr?"chr":"")+n[0],o=n[1],i=n[2],a=n[3].split(","),l=e.find((t=>{if(t.chr==s&&t.pos===o-1&&t.dbsnpRef==i&&t.dbsnpAlts.some((t=>a.includes(t))))return t}));if(l){l.referenceAllele=i,l.altAlleles=a,l.gtlst=[];for(let t=4;t<n.length;t++)l.gtlst.push(n[t]==p?"":n[t])}}}),s().unlink(c,(()=>{})),s().unlink(f,(()=>{}));const h=["snpid\tchr\tpos\tref\talt\teff\t"+r.samples.map((t=>t.name)).join("\t")];for(const t of e)t.invalid||t.gtlst&&(h.push(t.snpid+"\t"+t.chr+"\t"+t.pos+"\t"+t.referenceAllele+"\t"+t.altAlleles.join(",")+"\t"+(t.effectAllele||"")+"\t"+t.gtlst.join("\t")),delete t.gtlst);const m=t.genome+"_"+t.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random());return await a.Sf(i().join(u().cache_snpgt.dir,m),h.join("\n")),m}(t,r,e);return{snps:r,cacheid:o}}(t,n,r);if(t.chr)return await async function(t,e,n){const r=Number(t.start),s=Number(t.stop);if(!Number.isInteger(r)||!Number.isInteger(s))throw"start/stop are not integers";if(r>s||r<0)throw"invalid start/stop coordinate";let o,l;if(e.track){if(o=e.track.vcf,!o)throw"ds.track.vcf missing";if(l=o.chr2bcffile[t.chr],!l)throw"chr not in chr2bcffile"}else if(o=e.queries.snvindel.byrange._tk,l=o.chr2files?o.chr2files?.[t.chr].file:o.file||o.url,!l)throw"no bcf file";const c=(o.nochr?t.chr.replace("chr",""):t.chr)+":"+r+"-"+s,d=["query",l,"-r",c,"-f",h];t.variant_filter&&y(t.variant_filter,d);const g={snps:[]},b=["snpid\tchr\tpos\tref\talt\teff\t"+o.samples.map((t=>t.name)).join("\t")];return await a.UE({isbcf:!0,args:d,dir:o.dir,callback:(e,n)=>{if(g.snps.length>=m)return n.kill(),void(g.reachedVariantLimit=!0);const r=e.split("\t"),s=Number(r[0])-1,i=r[1],a=r[2],l=r[3].split(","),c=i&&"."!=i?i:s+"."+a+"."+l.join(","),u={snpid:c,chr:t.chr,pos:s};(0,f.H)(o,a,l,u,r[4],r[1]);for(const t of u.mlst)t.vcf_id&&(t.mname=t.vcf_id);g.snps.push(u);const d=[c,t.chr,s,a,l.join(","),""];for(let t=5;t<r.length;t++)d.push(r[t]==p?"":r[t]);b.push(d.join("\t"))}}),g.cacheid=t.genome+"_"+t.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random()),await a.Sf(i().join(u().cache_snpgt.dir,g.cacheid),b.join("\n")),g}(t,n);throw"unknown how to validate"}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function y(t,e){const n=[];for(const e of t.lst)if(e.tvs.values){const t=e.tvs.isnot?"!=":"=";for(const r of e.tvs.values){const s=isNaN(r.key)?`"${r.key}"`:Number(r.key);n.push(`INFO/${e.tvs.term.id}${t}${s}`)}}else{if(!e.tvs.ranges)throw`unknown tvs spec for info_field: type=${e.type}, term.id=${e.tvs.term.id}`;for(const t of e.tvs.ranges)"start"in t&&n.push(`INFO/${e.tvs.term.id} ${t.startinclusive?">=":">"} ${t.start}`),"stop"in t&&n.push(`INFO/${e.tvs.term.id} ${t.stopinclusive?"<=":"<"} ${t.stop}`)}0!=n.length&&e.push("-i",n.join(" && "))}},8907:(t,e,n)=>{"use strict";n.d(e,{yT:()=>M,YG:()=>C,g5:()=>S,J4:()=>N,B9:()=>k,cf:()=>x,tt:()=>q,Bi:()=>A,ig:()=>j});var r={};n.r(r),n.d(r,{binary:()=>f,continuous:()=>l,cubicSpline:()=>c,discrete:()=>u});var s={};n.r(s),n.d(s,{groupset:()=>p,values:()=>d});var o={};n.r(o),n.d(o,{binary:()=>g,cox:()=>b,cuminc:()=>y,discrete:()=>m});var i=n(4048),a=n(5257);const l={getCTE(t,e,n,r,s,o,i){s.push(e.id);const a=M(e,r);return s.push(...a.values),{sql:`${t} 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_${e.type}\n\t\t\t\tWHERE term_id=? ${a.clause}\n\t\t\t)`,tablename:t}}},c=l,u={getCTE(t,e,n,r,s,o,i){s.push(e.id);const a=C(r,e,n,o,i),l=[],c=new Map;r.bin_size;for(const t of a)!("name"in t)&&t.label&&(t.name=t.label),c.set(t.name,t),l.push(`SELECT '${t.name}' AS name,\n\t\t\t\t${null==t.start?0:t.start} AS start,\n\t\t\t\t${null==t.stop?0:t.stop} AS stop,\n\t\t\t\t0 AS unannotated,\n\t\t\t\t${t.startunbounded?1:0} AS startunbounded,\n\t\t\t\t${t.stopunbounded?1:0} AS stopunbounded,\n\t\t\t\t${t.startinclusive?1:0} AS startinclusive,\n\t\t\t\t${t.stopinclusive?1:0} AS stopinclusive`);const u=[];if(e.values)for(const t in e.values){const n=e.values[t].uncomputable;if(r.computableValuesOnly&&n)continue;if(!r.computableValuesOnly&&!n)continue;u.push(t);const s=e.values[t];l.push(`SELECT '${s.label}' AS name,\n\t ${t} 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(s.label,{is_unannotated:!0,value:t,label:s.label})}const f="bin_defs_"+o,d=M(e,r,"a");s.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${t} 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_${e.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:t,name2bin:c,bins:a}}},f=u,d={getCTE(t,e,n,r,s){s.push(e.id);const o=M(e,r);return s.push(...o.values),{sql:`${t} 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:t}}};let h=0;const p={async getCTE(t,e,n,r,s,o){if(!o.groups)throw`.groups[] missing from a group-set, term.id='${e.id}'`;const i=[],a=[];for(const t of o.groups)if("values"==t.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 (${t.values.map((t=>"?")).join(",")})\n\t\t\t\t`),s.push(t.name,e.id,...t.values.map((t=>t.key.toString())));else{if("filter"!=t.type)throw`unsupported groupset type='${t.type}'`;if(!("activeCohort"in r.groupsetting)||!t.filter4activeCohort)throw`activeCohort error: cannot construct filter statement for group name='${t.name}', term.id=${e.id}`;{const o=t.filter4activeCohort[r.groupsetting.activeCohort],l=await getFilterCTEs(o,n,"xf"+h++);if(!l)throw`unable to construct a group='${t.name}' filter for term.id='${e.id}'`;a.push(l.filters),s.push(...l.values.slice(),t.name,t.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${t} AS (\n\t\t\t\t${i.join("\nUNION ALL\n")}\n\t\t\t)`,tablename:t}}},m={getCTE(t,e,n,r,s){if(r.breaks&&r.breaks.length>0)return w(t,e,r,s);{const[n,o]=v(r);s.push(e.id);const i=M(e,r);return s.push(...i.values),{sql:`${t} 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:t}}}},g={getCTE(t,e,n,r,s){if(1!=r.breaks?.length)throw"binary mode requires one break";return w(t,e,r,s)}},y={getCTE(t,e,n,r,s){if(1!=r.breaks?.length)throw"cuminc mode requires one break";return s.push(e.id,r.breaks[0]),{sql:`${t} 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:t}}},b={getCTE(t,e,n,r,s){if(1!=r.breaks?.length)throw"cox mode requires one break";s.push(e.id,r.breaks[0]);const o=Object.keys(e.values).map(Number),i=Math.max(...o);return{sql:`${t} 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:t,events:[{event:1,label:`Event (grade ${r.breaks[0]===i?r.breaks[0]:`${r.breaks[0]}-${i}`})`},{event:0,label:"Censored/death"},{event:-1,label:"Event before entry into the cohort"}]}}};function v(t){const e=t.bar_by_children?"child":t.bar_by_grade?"grade":"";if(!e)throw"must set the bar_by_grade or bar_by_children query parameter";const n=t.value_by_max_grade?"max_grade":t.value_by_most_recent?"most_recent":t.value_by_computable_grade?"computable_grade":"";if(!n)throw"must set a valid value_by_*";return[e,n]}function w(t,e,n,r){const[s,o]=v(n);if("grade"!=s)throw"breaks must be used on grade values";const i=[];for(const t 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 (${t.values.map((t=>"?")).join(",")})\n\t\t`),r.push(t.name,e.id,...t.values.map((t=>t.toString())));return{sql:`${t} AS (\n\t\t\t${i.join("\nUNION ALL\n")}\n\t\t)`,tablename:t}}const _={getCTE(t,e,n){let r,s,o="";for(const[t,i]of e.q.groups.entries())"in"in i||(i.in=!0),r=i.values.map((t=>t.sampleId)),s=r.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 (${s})\n\t\t\t`,t!=e.q.groups.length-1&&(o+="UNION ALL "),n.push(i.name,i.name,...r);return{sql:`${t} AS (${o})`,tablename:t}}};n(334),n(3345);async function x(t,e,n=!1){const r=await(0,a.w)(t,e),s=e.cohort.db.connection.prepare(r?`WITH ${r.filters} SELECT sample as id, name FROM ${r.CTEname} join sampleidmap on sample = sampleidmap.id`:"SELECT id, name FROM sampleidmap");let o;if(o=r?s.all(r.values):s.all(),n)return o;for(const t of o)delete t.name;return o}async function k(t,e){if(!t.filter)throw"filter missing";let n;if("object"==typeof t.filter)n=t.filter;else{if("string"!=typeof t.filter)throw"q.filter not obj or str";n=JSON.parse(t.filter)}const r=await(0,a.w)(n,e),s=`WITH ${r.filters}\n\t\tSELECT 'FILTERED_COHORT' as subcohort, count(distinct sample) as samplecount \n\t\tFROM ${r.CTEname}`;return e.cohort.db.connection.prepare(s).all(r.values)}async function q(t){const e=t.ds.cohort.termdb.q.termjsonByOneid(t.term_id);if("integer"!=e.type&&"float"!=e.type)throw"term is not numeric";if(!e.values)return[];const n=await(0,a.w)(t.filter,t.ds),r=n?n.values.slice():[];r.push(t.term_id);const s=[];for(const t in e.values)s.push("?"),r.push(Number(t));const o=`\n\t\t${n?"WITH "+n.filters:""}\n\t\tSELECT count(sample) AS samplecount,value\n\t\tFROM anno_${e.type}\n\t\tWHERE term_id=?\n\t\t${n?"AND sample IN "+n.CTEname:""}\n\t\tAND value IN (${s.join(",")})\n\t\tGROUP BY value`;return t.ds.cohort.db.connection.prepare(o).all(r)}async function N(t){if(!t.key)throw".key missing";if(!t.ds)throw".ds{} missing";const e=await(0,a.w)(t.filter,t.ds),n=e?e.values.slice():[],r=t.ds.cohort.termdb.q.termjsonByOneid(t.key);n.push(t.key);const s=`\n\t\t${e?"WITH "+e.filters:""}\n\t\tSELECT sample, value\n\t\tFROM anno_${r.type}\n\t\tWHERE term_id=?\n\t\t${e?" AND sample IN "+e.CTEname:""}`;return t.ds.cohort.db.connection.prepare(s).all(n)}async function S(t,e={}){"string"==typeof t.filter&&(t.filter=JSON.parse(decodeURIComponent(t.filter)));const n=Object.assign({withCTEs:!0,columnas:"t1.sample AS sample",groupby:""},e),r=await(0,a.w)(t.filter,t.ds),s=r?r.values.slice():[],o=await A(t,s,0,r),i=await A(t,s,1,r),l=await A(t,s,2,r),c=[o,i,l].map(((t,e)=>`\n\t\tSELECT sample, key, value, ${e} as termNum\n\t\tFROM ${t.tablename}\n\t\t${r?"WHERE sample IN "+r.CTEname:""}\n\t`)).join("\nUNION ALL\n"),u=`WITH\n\t\t${r?r.filters+",":""}\n\t\t${o.sql},\n\t\t${i.sql},\n\t\t${l.sql}\n\t\t${c}`;try{const e=t.ds.cohort.db.connection.prepare(u).all(s),a=new Map;for(const t of e){a.has(t.sample)||a.set(t.sample,{sample:t.sample});const e=a.get(t.sample),n=`key${t.termNum}`;n in e||(e[n]=[]),e[n].push(t)}const c=[],f=new Map;for(const e of a.values())if("key1"in e){if(t.term0_q&&t.term0_id){if(!("key0"in e))continue}else e.key0=[{key:"",value:""}];if(t.term2_q&&(t.term2_id||"samplelst"===t.term2.type)){if(!("key2"in e))continue}else e.key2=[{key:"",value:""}];e.rows=[];for(const t of e.key0)for(const n of e.key1)for(const r of e.key2)e.rows.push({sample:e.sample,key0:t.key,val0:t.value,key1:n.key,val1:n.value,key2:r.key,val2:r.value});for(const t of e.rows)if(n.groupby){if(!f.has(t[n.groupby])){const e=Object.assign({samplecount:0},t);c.push(e),f.set(t[n.groupby],e)}f.get(t[n.groupby]).samplecount++}else c.push(t)}return n.withCTEs?{lst:c,CTE0:o,CTE1:i,CTE2:l,filter:r}:c}catch(t){throw console.log("error in sql:\n",j(u,s)),t}}async function A(t,e,n,i,a=null){const l=a&&a.term||t[`term${n}`],c=l?l.id:t["term"+n+"_id"];if("samplelst"!=l?.type)if(a||1!=n){if(!c){const t="samplekey_"+n;return{tablename:t,sql:`${t} AS (\nSELECT null AS sample, '' as key, '' as value\n)`}}}else if(!c)throw"missing term1 id";const u=l&&l.type?l:t.ds.cohort.termdb.q.termjsonByOneid(c);if(!u)throw`no term found by id='${c}'`;let f=a&&a.q||t["term"+n+"_q"]||{};"string"==typeof f&&(f=JSON.parse(decodeURIComponent(f)));const d="samplekey_"+n;let h;if("categorical"==u.type){const n=T(u,f);h=await s[n?"groupset":"values"].getCTE(d,u,t.ds,f,e,n)}else if("integer"==u.type||"float"==u.type){const s="spline"==f.mode?"cubicSpline":f.mode||"discrete";h=await r[s].getCTE(d,u,t.ds,f,e,n,i)}else if("condition"==u.type){const n=f.mode||"discrete";h=await o[n].getCTE(d,u,t.ds,f,e)}else if("survival"==u.type)h=function(t,e,n,r,s){return r.push(e.id),{sql:`${t} 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${s?"AND s.sample IN "+s.CTEname:""}\n\t\t)`,tablename:t}}(d,u,0,e,i);else{if("samplelst"!=u.type)throw"unknown term type";h=await _.getCTE(d,a||{term:u,q:f},e)}return h}function M(t,e,n=""){if(!t.values||!e.computableValuesOnly)return{values:[],clause:""};const r=Object.keys(t.values).filter((e=>t.values[e].uncomputable)),s=n?`${n}.value`:"value";return{values:r,clause:r.length?`AND ${s} NOT IN (${r.map((()=>"?")).join(",")})`:""}}function T(t,e){if(e.groupsetting&&!e.groupsetting.disabled&&e.groupsetting.inuse){if(Number.isInteger(e.groupsetting.predefined_groupset_idx)){if(e.groupsetting.predefined_groupset_idx<0)throw"q.predefined_groupset_idx out of bound";if(!t.groupsetting)throw"term.groupsetting missing when q.predefined_groupset_idx in use";if(!t.groupsetting.lst)throw"term.groupsetting.lst missing when q.predefined_groupset_idx in use";const n=t.groupsetting.lst[e.groupsetting.predefined_groupset_idx];if(!n)throw"q.predefined_groupset_idx out of bound";return n}if(e.groupsetting.customset)return e.groupsetting.customset;throw"do not know how to get groupset"}}function C(t,e,n,r,s){if("continuous"!=t.mode&&"spline"!=t.mode)return i.gp(t,(t=>function(t,e,n,r=[]){const s=[];n&&s.push(...n.values);s.push(e.id);const o=e.values?Object.keys(e.values).filter((t=>e.values[t].uncomputable)):[],i=[],a=[],l=[];let c;for(const t of r)c="pct_"+t,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)`),s.push(t),a.push(c),l.push(`${c}.value AS ${"p"+t}`);const u=`WITH\n\t\t${n?n.filters+", ":""} \n\t\tvals AS (\n\t\t\tSELECT value\n\t\t\tFROM anno_${e.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=t.cohort.db.connection.prepare(u).all(s),d=f.length?f[0]:{};return d.max=f[0].vmax,d.min=f[0].vmin,d}(n,e,s,t)))}function j(t,e){const n=e.slice();let r;return t.split("").map((t=>{if("?"==t){r=t;const e=n.shift();return"string"==typeof e?`'${e}'`:e}return"\t"==t?"":"\n"!=t&&" "!=t||r!==t?(r=t,t):""})).join("")}},3345:(t,e,n)=>{"use strict";n.d(e,{Dp:()=>Q,JC:()=>ot,d1:()=>j,fk:()=>lt,sE:()=>W,Ic:()=>F,yE:()=>$,t7:()=>z,ZX:()=>E,EO:()=>Y,Kf:()=>H,ZD:()=>Z,UE:()=>U,lY:()=>I,_H:()=>P,L0:()=>K,Y5:()=>st,z5:()=>tt,mr:()=>et,b5:()=>J,cl:()=>X,Jy:()=>L,sI:()=>nt,aS:()=>rt,LC:()=>D,Sf:()=>B,tG:()=>G});var r=n(7147),s=n.n(r),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 h=n.n(d);const p=require("better-sqlite3");var m=n.n(p),g=n(334),y=n.n(g);n(2781);const b=require("minimatch");var v=n.n(b),w=n(6113),_=n.n(w),x=n(6452),k=n.n(x);const q=y(),{tabix:N,samtools:S,bcftools:A,bigBedToBed:M,bigBedNamedItems:T,bigBedInfo:C}=q;async function j(t,e){if(!t)throw".gz file URL missing";if("string"!=typeof t)throw".gz file URL not string";if(e&&"string"!=typeof e)throw"index URL not string";const[n,r,o]=R(t);if(n)throw".gz file URL error: "+n;const a=i().join(q.cachedir,r,o);try{await s().promises.stat(a)}catch(n){if("ENOENT"!=n.code)throw"stating gz url dir: "+n.code;try{await s().promises.mkdir(a,{recursive:!0})}catch(n){throw"url dir: cannot mkdir"}}if(!e)return a;{const[t,r,o]=R(e);if(t)throw"indexl url error: "+t;const l=i().join(a,i().basename(o));try{return await s().promises.stat(l),a}catch(n){if("ENOENT"==n.code)return await async function(t,e){try{const o=await h()(t);if(200!=o.status)throw"index file not accessible from url with status code "+o.status;await(n=o.body,r=e,new Promise(((t,e)=>{const o=s().createWriteStream(r);n.pipe(o),n.on("end",(()=>t()))})))}catch(t){throw"cannot download from url"}var n,r}(e,l),a;throw"stating indexl url file: "+n.code}}}function E(t,e=!0){let n=null,r=!1;if(t.query.file){if(n=t.query.file,I(n,e,!1))return["illegal file path"];n=i().join(q.tpmasterdir,n)}else if(t.query.url){if(n=t.query.url,n.includes(" "))return["url must not contain whitespace"];if(n.includes('"')||n.includes("'"))return["url must not contain single or double quotes"];r=!0}return n?[null,n,r]:["file unspecified"]}const O=Object.freeze([".bam",".bai",".gz",".tbi",".csi",".bw",".bb"]);function I(t,e=!1,n=!0){if("/"==t[0])return!0;if(t.includes('"')||t.includes("'"))return!0;if(t.includes("|")||t.includes("&"))return!0;if(t.includes(" "))return!0;if(-1!=t.indexOf(".."))return!0;if(t.match(/(\<script|script\>)/i))return!0;if(e&&q.whiteListPaths){let e=!0;for(const n of q.whiteListPaths){if(t.startsWith(n)||"!"!=n[0]&&v()(t,n)){e=!1;break}if("!"==n[0]&&!v()(t,n)){e=!0;break}}if(e)return!0}if(n)for(const e of O)if(e===i().extname(t).toLowerCase())return!0;return!1}function R(t){const e=t.split("://");return 2!=e.length?["improper url"]:e[0].length<3?["protocol string length too short"]:e[1].length<5?["body string length too short"]:[null,e[0],e[1]]}async function F(t){try{await s().promises.stat(t)}catch(e){const n=q.debugmode?`file='${t}'`:"";if("EACCES"==e.code)throw`Permission denied ${n}`;if("ENOENT"==e.code)throw`No such file or directory ${n}`;if("EPERM"==e.code)throw`Operation not permitted ${n}`;throw`cannot access file (' + e.code + ') ${n}`}}async function P(t,e,n){let r;if(t.file)t.file.startsWith(q.tpmasterdir)||(t.file=i().join(q.tpmasterdir,t.file)),r=t.file,await D(t.file);else{if(!t.url)throw"no file or url given for vcf file";r=t.url,t.dir=await utils.cache_index(t.url,t.indexURL)}const[s,o,l,c]=n?await(u=r,d=t.dir,new Promise(((t,e)=>{const n=(0,a.spawn)(A,["view","-h",u],{cwd:d}),r=[];n.stdout.on("data",(t=>r.push(t))),n.on("close",(()=>{t(f.e(r.join("").trim().split("\n")))}))}))):await async function(t,e){return f.e(await Z(t,e))}(r,t.dir);var u,d;if(c)throw console.log(c.join("\n")),"got above errors parsing vcf";t.info=s,t.format=o,t.samples=l,await L(r,t.dir,e)&&(t.nochr=!0)}async function D(t){if(!t.endsWith(".gz"))throw"tabix file not ending with .gz";if(await $(t))throw t+" file not exist";if(await z(t))throw".gz file not readable";const e=t+".tbi";if(await $(e)){const e=t+".csi";if(await $(e))throw"neither .tbi .csi index file exist for "+t;if(await z(e))throw".csi index file not readable"}else if(await z(e))throw".tbi index file not readable"}async function L(t,e,n){const r=[];return await U({args:["-l",t],dir:e,callback:t=>{r.push(t)}}),u.contigNameNoChr(n,r)}function $(t){return new Promise(((e,n)=>{s().access(t,s().constants.F_OK,(t=>{t&&e(!0),e(!1)}))}))}function z(t){return new Promise(((e,n)=>{s().access(t,s().constants.R_OK,(t=>{t&&e(!0),e(!1)}))}))}async function Z(t,e){const n=[];return await U({args:["-H",t],dir:e,callback:t=>{n.push(t)}}),n}function U({args:t,dir:e,callback:n,isbcf:r,isbam:s}){if(!t)throw"args is missing";if(!Array.isArray(t))throw"args[] is not array";if(0==t.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)(r?A:s?S:N,t,{cwd:e}),u=c().createInterface({input:l.stdout}),f=[];u.on("line",(t=>n(t,l))),l.stderr.on("data",(t=>f.push(t))),l.on("close",(()=>{const t=f.join("").trim();t&&!nt(t)&&i(t),o()}))}))}function B(t,e){return new Promise(((n,r)=>{s().writeFile(t,e,(t=>{t&&r("cannot write"),n()}))}))}async function G(t){const e=Math.random().toString();return await B(i().join(q.cachedir,e),t),e}function J(t){return new Promise(((e,n)=>{s().readFile(t,{encoding:"utf8"},((r,s)=>{r&&n("cannot read file: "+t),e(s)}))}))}async function H(t,e){if("NA"==t.genomefile){const t=e.split(/[:-]/),n=[];for(let e=Number(t[1]);e<=Number(t[2]);e++)n.push("N");return`>${e}\n${n.join("")}`}const n=[];return await U({isbam:!0,args:["faidx",t.genomefile,e],callback:t=>n.push(t)}),n.join("\n")}function W(t,e={}){const n="/"==t[0]?t:i().join(q.tpmasterdir,t);try{return new(m())(n,Object.assign({readonly:!0,fileMustExist:!0},e))}catch(t){throw`error connecting to ${n}: ${t}`}}const V=new Set(["Homozygous reference","Homozygous alternative","Heterozygous"]),Y={href:"Homozygous reference",halt:"Homozygous alternative",het:"Heterozygous"};async function K(t,e){const n=await J(i().join(q.cachedir_ssid,t)),r=new Map,s=new Map;for(const t of n.trim().split("\n")){if(!t)continue;const[n,o]=t.split("\t");if(!o)continue;if(!V.has(n))throw"unknown hardcoded genotype label: "+n;const i=o.split(",").map((t=>Number(t))),a=e?i.filter((t=>e.has(t))):i;for(const t of a)r.set(t,n);s.set(n,new Set(a))}return[r,s]}function X(t){return t.replace(/\<script|\bon[\w]{1,38}\b[\ \t\n]*\=/gi," _")}async function Q(t,e,n){const r=[];if(await U({isbam:!0,args:["view","-H",t],dir:n,callback:t=>r.push(t)}),0==r.length)throw"cannot list bam header lines";const s=[];for(const t of r){if(!t.startsWith("@SQ"))continue;const e=t.split("\t")[1];e||reject("2nd field missing from @SQ line");const n=e.split(":");"SN"!=n[0]&&reject('@SQ line 2nd field is not "SN" but '+n[0]),n[1]||reject("@SQ line no value for SN"),s.push(n[1])}return u.contigNameNoChr(e,s)}function tt(t,e,n,r){return new Promise(((s,o)=>{const i=(0,a.spawn)(M,[`-chrom=${e}`,`-start=${n}`,`-end=${r}`,t,"stdout"]),l=[],c=[];i.stdout.on("data",(t=>l.push(t))),i.stderr.on("data",(t=>c.push(t))),i.on("close",(t=>{0!==t&&o(`bigBed query exited with non-zero status and this standard error:\n${c.join("")}`),c.length>0&&o(c.join(""));const e=l.join("").trim();s(e?e.split("\n"):[])}))}))}function et(t,e){return new Promise(((n,r)=>{const s=(0,a.spawn)(T,[t,e,"stdout"]),o=[],i=[];s.stdout.on("data",(t=>o.push(t))),s.stderr.on("data",(t=>i.push(t))),s.on("close",(t=>{0!==t&&r(`bigBed query exited with non-zero status and this standard error:\n${i.join("")}`),i.length>0&&r(i.join(""));const e=o.join("").trim();n(e?e.split("\n"):[])}))}))}function nt(t){return t.startsWith("[E::idx_test_and_fetch]")}async function rt(t){return new Promise(((e,n)=>{const r=(0,a.spawn)(C,[t]),s=[],o=[];r.stdout.on("data",(t=>s.push(t))),r.stderr.on("data",(t=>o.push(t))),r.on("close",(t=>{const n=o.join("");n&&(n.includes("is not a big bed file")||n.includes("Couldn't open"),e(!1));s.join("").trim().startsWith("version")&&e(!0)}))}))}function st(t,e){if(e.sessionid){if("sessionid"in t)throw"q.sessionid already exists so cannot copy from cookies.sessionid";t.sessionid=e.sessionid}}function ot(t){const e=t.length;if(e<5)return{out:t};const n=t[Math.floor(e/2)].value,r=t[Math.floor(e/4)].value,s=t[Math.floor(3*e/4)].value,o=t[Math.floor(.05*e)].value,i=t[Math.floor(.95*e)].value,a=(t[Math.floor(.01*e)].value,s-r);let l,c;if(0==a)l=0,c=0;else{const n=t.findIndex((t=>t.value>r-1.5*a));l=t[-1==n?0:n].value;const o=t.findIndex((t=>t.value>s+1.5*a));c=t[-1==o?e-1:o-1].value}const u=t.filter((t=>t.value<r-1.5*a||t.value>s+1.5*a));return{w1:l,w2:c,p05:o,p25:r,p50:n,p75:s,p95:i,iqr:a,out:u}}const it=q.features?.extApiCache||{},at=i().join(q.cachedir,"extApiResponse");if(q.features?.extApiCache){s().existsSync(at)||s().mkdirSync(at,{recursive:!0});for(const t in it){const e=i().join(at,it[t]);s().existsSync(e)||s().mkdirSync(e,{recursive:!0})}}async function lt(t,e={},n={}){let r;for(const e in it)t.includes(e)&&(r=i().join(at,it[e]));if(!t.includes(":/"))throw`cannot use cachedFetch wuth a relative URL: ${t}`;const o=r&&_().createHash("sha1").update(`${t} ${JSON.stringify(e.body)}`).digest("hex"),a=r&&i().join(r,o);let l;if(a&&s().existsSync(a))try{const t=s().readFileSync(a)?.toString("utf-8").trim();l=JSON.parse(t)}catch(t){throw console.log(t),t}else try{const r={"content-type":"application/json",accept:"application/json"};if(e.headers)for(const t in e.headers)r[t.toLowerCase()]=e.headers[t].toLowerCase();const o=e.method?.toLowerCase()||"get",i=n.client||k(),c=await i[o](t,{headers:r,body:"get"==o?void 0:r["content-type"].includes("json")?JSON.stringify(e.body||{}):e.body});if(a){const t="string"==typeof c.body?c.body:r.accept.includes("json")?JSON.stringify(c.body):e.response;s().writeFileSync(a,t,{encoding:"utf8"})}l="string"==typeof c.body&&r.accept.includes("json")?JSON.parse(c.body):c.body}catch(t){throw t}return n.metaKey&&(l[n.metaKey]={id:o,cacheFile:a}),{body:l}}},3625:(t,e,n)=>{"use strict";n.d(e,{H:()=>a});var r=n(9380),s=n(4298),o=n(736),i=n(2273);function a(t,e,n,a,l,c,u){const f=(0,r.w)(l);for(const e in t.info){if("A"==t.info[e].Number&&e in f&&(f[e]=f[e].split(",")),t.info[e].separator&&e in f){const n=f[e].split(t.info[e].separator);n.length>1&&(f[e]=n)}if("Float"==t.info[e].Type||"Integer"==t.info[e].Type)if(Array.isArray(f[e])){const t=f[e].map(Number);f[e]=t}else f[e]=Number(f[e])}a.mlst=n.map((t=>{const[n,r,s]=function(t,e,n){for(;e.length>1&&n.length>1&&e[e.length-1]==n[n.length-1];)e=e.substring(0,e.length-1),n=n.substring(0,n.length-1);for(;e.length>1&&n.length>1&&e[0]==n[0];)e=e.substring(1),n=n.substring(1),t++;return[t,e,n]}(a.pos,e,t),i={allele_original:t,ref:r,alt:s,pos:n,type:(0,o.P)(r,s)};return c&&"."!=c&&(i.vcf_id=c),i})),t.info?.CSQ&&f.CSQ&&(0,s.A)(f.CSQ,t.info.CSQ.csqheader,a);const d={};u&&(d.usegm={isoform:u});for(const[n,r]of a.mlst.entries()){(0,i.vcfcopymclass)(r,d),delete r.csq,r.mname||(r.mname="."!=c?c:a.pos+":"+e+">"+r.allele_original),r.altAlleleIdx=n+1,r.info={};for(const e in f)"A"==t.info?.[e]?.Number?r.info[e]=f[e][n]:r.info[e]=f[e]}}},126:(t,e,n)=>{var r={"./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 s(t){var e=o(t);return n(e)}function o(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}s.keys=function(){return Object.keys(r)},s.resolve=o,t.exports=s,s.id=126},1271:t=>{"use strict";t.exports=require("@sjcrh/proteinpaint-rust")},6718:t=>{"use strict";t.exports=require("canvas")},6452:t=>{"use strict";t.exports=require("got")},7219:t=>{"use strict";t.exports=require("image-size")},9344:t=>{"use strict";t.exports=require("jsonwebtoken")},8088:t=>{"use strict";t.exports=require("micromatch")},6464:t=>{"use strict";t.exports=require("util")},2081:t=>{"use strict";t.exports=require("child_process")},6113:t=>{"use strict";t.exports=require("crypto")},7147:t=>{"use strict";t.exports=require("fs")},1017:t=>{"use strict";t.exports=require("path")},4521:t=>{"use strict";t.exports=require("readline")},2781:t=>{"use strict";t.exports=require("stream")},9263:(t,e,n)=>{"use strict";function r(t,e){return null==t||null==e?NaN:t<e?-1:t>e?1:t>=e?0:NaN}n.d(e,{Z:()=>r})},5519:(t,e,n)=>{"use strict";n.d(e,{Nw:()=>l,ZP:()=>u,ZR:()=>c,ml:()=>a});var r=n(9263),s=n(3292),o=n(3745);const i=(0,s.Z)(r.Z),a=i.right,l=i.left,c=(0,s.Z)(o.Z).center,u=a},3292:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(9263),s=n(788);function o(t){let e,n,o;function a(t,r,s=0,o=t.length){if(s<o){if(0!==e(r,r))return o;do{const e=s+o>>>1;n(t[e],r)<0?s=e+1:o=e}while(s<o)}return s}return 2!==t.length?(e=r.Z,n=(e,n)=>(0,r.Z)(t(e),n),o=(e,n)=>t(e)-n):(e=t===r.Z||t===s.Z?t:i,n=t,o=t),{left:a,center:function(t,e,n=0,r=t.length){const s=a(t,e,n,r-1);return s>n&&o(t[s-1],e)>-o(t[s],e)?s-1:s},right:function(t,r,s=0,o=t.length){if(s<o){if(0!==e(r,r))return o;do{const e=s+o>>>1;n(t[e],r)<=0?s=e+1:o=e}while(s<o)}return s}}}function i(){return 0}},1045:(t,e,n)=>{"use strict";function r(t,e){if(!((e=+e)>=0))throw new RangeError("invalid r");let n=t.length;if(!((n=Math.floor(n))>=0))throw new RangeError("invalid length");if(!n||!e)return t;const r=c(e),s=t.slice();return r(t,s,0,n,1),r(s,t,0,n,1),r(t,s,0,n,1),t}n.d(e,{TX:()=>o,u8:()=>s,yv:()=>r});const s=i(c),o=i((function(t){const e=c(t);return(t,n,r,s,o)=>{e(t,n,(r<<=2)+0,(s<<=2)+0,o<<=2),e(t,n,r+1,s+1,o),e(t,n,r+2,s+2,o),e(t,n,r+3,s+3,o)}}));function i(t){return function(e,n,r=n){if(!((n=+n)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:s,width:o,height:i}=e;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((i=Math.floor(void 0!==i?i:s.length/o))>=0))throw new RangeError("invalid height");if(!o||!i||!n&&!r)return e;const c=n&&t(n),u=r&&t(r),f=s.slice();return c&&u?(a(c,f,s,o,i),a(c,s,f,o,i),a(c,f,s,o,i),l(u,s,f,o,i),l(u,f,s,o,i),l(u,s,f,o,i)):c?(a(c,s,f,o,i),a(c,f,s,o,i),a(c,s,f,o,i)):u&&(l(u,s,f,o,i),l(u,f,s,o,i),l(u,s,f,o,i)),e}}function a(t,e,n,r,s){for(let o=0,i=r*s;o<i;)t(e,n,o,o+=r,1)}function l(t,e,n,r,s){for(let o=0,i=r*s;o<r;++o)t(e,n,o,o+i,r)}function c(t){const e=Math.floor(t);if(e===t)return function(t){const e=2*t+1;return(n,r,s,o,i)=>{if(!((o-=i)>=s))return;let a=t*r[s];const l=i*t;for(let t=s,e=s+l;t<e;t+=i)a+=r[Math.min(o,t)];for(let t=s,c=o;t<=c;t+=i)a+=r[Math.min(o,t+l)],n[t]=a/e,a-=r[Math.max(s,t-l)]}}(t);const n=t-e,r=2*t+1;return(t,s,o,i,a)=>{if(!((i-=a)>=o))return;let l=e*s[o];const c=a*e,u=c+a;for(let t=o,e=o+c;t<e;t+=a)l+=s[Math.min(i,t)];for(let e=o,f=i;e<=f;e+=a)l+=s[Math.min(i,e+c)],t[e]=(l+n*(s[Math.max(o,e-u)]+s[Math.min(i,e+u)]))/r,l-=s[Math.max(o,e-c)]}}},879:(t,e,n)=>{"use strict";function r(t,e){let n=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&++n;else{let r=-1;for(let s of t)null!=(s=e(s,++r,t))&&(s=+s)>=s&&++n}return n}n.d(e,{Z:()=>r})},788:(t,e,n)=>{"use strict";function r(t,e){return null==t||null==e?NaN:e<t?-1:e>t?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},2038:(t,e,n)=>{"use strict";function r(t,e){let n,r;if(void 0===e)for(const e of t)null!=e&&(void 0===n?e>=e&&(n=r=e):(n>e&&(n=e),r<e&&(r=e)));else{let s=-1;for(let o of t)null!=(o=e(o,++s,t))&&(void 0===n?o>=o&&(n=r=o):(n>o&&(n=o),r<o&&(r=o)))}return[n,r]}n.d(e,{Z:()=>r})},9343:(t,e,n)=>{"use strict";n.d(e,{Kd:()=>o,dU:()=>r,e3:()=>s});class r{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const e=this._partials;let n=0;for(let r=0;r<this._n&&r<32;r++){const s=e[r],o=t+s,i=Math.abs(t)<Math.abs(s)?t-(o-s):s-(o-t);i&&(e[n++]=i),t=o}return e[n]=t,this._n=n+1,this}valueOf(){const t=this._partials;let e,n,r,s=this._n,o=0;if(s>0){for(o=t[--s];s>0&&(e=o,n=t[--s],o=e+n,r=n-(o-e),!r););s>0&&(r<0&&t[s-1]<0||r>0&&t[s-1]>0)&&(n=2*r,e=o+n,n==e-o&&(o=e))}return o}}function s(t,e){const n=new r;if(void 0===e)for(let e of t)(e=+e)&&n.add(e);else{let r=-1;for(let s of t)(s=+e(s,++r,t))&&n.add(s)}return+n}function o(t,e){const n=new r;let s=-1;return Float64Array.from(t,void 0===e?t=>n.add(+t||0):r=>n.add(+e(r,++s,t)||0))}},2942:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(9263);function s(t,e=r.Z){let n,s=!1;if(1===e.length){let o;for(const i of t){const t=e(i);(s?(0,r.Z)(t,o)>0:0===(0,r.Z)(t,t))&&(n=i,o=t,s=!0)}}else for(const r of t)(s?e(r,n)>0:0===e(r,r))&&(n=r,s=!0);return n}},9060:(t,e,n)=>{"use strict";n.r(e),n.d(e,{Adder:()=>y.dU,InternMap:()=>b.L,InternSet:()=>b.H,ascending:()=>s.Z,bin:()=>L,bisect:()=>r.ZP,bisectCenter:()=>r.ZR,bisectLeft:()=>r.Nw,bisectRight:()=>r.ml,bisector:()=>o.Z,blur:()=>i.yv,blur2:()=>i.u8,blurImage:()=>i.TX,count:()=>a.Z,cross:()=>f,cumsum:()=>d,descending:()=>h.Z,deviation:()=>m,difference:()=>_t,disjoint:()=>xt,every:()=>mt,extent:()=>g.Z,fcumsum:()=>y.Kd,filter:()=>yt,flatGroup:()=>k,flatRollup:()=>q,fsum:()=>y.e3,greatest:()=>it.Z,greatestIndex:()=>at,group:()=>w,groupSort:()=>E,groups:()=>_,histogram:()=>L,index:()=>A,indexes:()=>M,intersection:()=>kt,least:()=>st,leastIndex:()=>ot,map:()=>bt,max:()=>U.Z,maxIndex:()=>B.Z,mean:()=>G,median:()=>J,medianIndex:()=>H,merge:()=>W.Z,min:()=>V.Z,minIndex:()=>Y.Z,mode:()=>K,nice:()=>P,pairs:()=>X,permute:()=>tt.Z,quantile:()=>$.ZP,quantileIndex:()=>$.Cr,quantileSorted:()=>$.s7,quickselect:()=>et.Z,range:()=>nt.Z,rank:()=>rt,reduce:()=>vt,reverse:()=>wt,rollup:()=>N,rollups:()=>S,scan:()=>lt,shuffle:()=>ct,shuffler:()=>ut,some:()=>gt,sort:()=>j.ZP,subset:()=>At,sum:()=>ft,superset:()=>Nt,thresholdFreedmanDiaconis:()=>z,thresholdScott:()=>Z,thresholdSturges:()=>D.Z,tickIncrement:()=>F.G9,tickStep:()=>F.ly,ticks:()=>F.ZP,transpose:()=>dt,union:()=>Mt,variance:()=>p,zip:()=>pt});var r=n(5519),s=n(9263),o=n(3292),i=n(1045),a=n(879);function l(t){return 0|t.length}function c(t){return!(t>0)}function u(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function f(...t){const e="function"==typeof t[t.length-1]&&function(t){return e=>t(...e)}(t.pop()),n=(t=t.map(u)).map(l),r=t.length-1,s=new Array(r+1).fill(0),o=[];if(r<0||n.some(c))return o;for(;;){o.push(s.map(((e,n)=>t[n][e])));let i=r;for(;++s[i]===n[i];){if(0===i)return e?o.map(e):o;s[i--]=0}}}function d(t,e){var n=0,r=0;return Float64Array.from(t,void 0===e?t=>n+=+t||0:s=>n+=+e(s,r++,t)||0)}var h=n(788);function p(t,e){let n,r=0,s=0,o=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(n=e-s,s+=n/++r,o+=n*(e-s));else{let i=-1;for(let a of t)null!=(a=e(a,++i,t))&&(a=+a)>=a&&(n=a-s,s+=n/++r,o+=n*(a-s))}if(r>1)return o/(r-1)}function m(t,e){const n=p(t,e);return n?Math.sqrt(n):n}var g=n(2038),y=n(9343),b=n(8828);function v(t){return t}function w(t,...e){return C(t,v,v,e)}function _(t,...e){return C(t,Array.from,v,e)}function x(t,e){for(let n=1,r=e.length;n<r;++n)t=t.flatMap((t=>t.pop().map((([e,n])=>[...t,e,n]))));return t}function k(t,...e){return x(_(t,...e),e)}function q(t,e,...n){return x(S(t,e,...n),n)}function N(t,e,...n){return C(t,v,e,n)}function S(t,e,...n){return C(t,Array.from,e,n)}function A(t,...e){return C(t,v,T,e)}function M(t,...e){return C(t,Array.from,T,e)}function T(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function C(t,e,n,r){return function t(s,o){if(o>=r.length)return n(s);const i=new b.L,a=r[o++];let l=-1;for(const t of s){const e=a(t,++l,s),n=i.get(e);n?n.push(t):i.set(e,[t])}for(const[e,n]of i)i.set(e,t(n,o));return e(i)}(t,0)}var j=n(3897);function E(t,e,n){return(2!==e.length?(0,j.ZP)(N(t,e,n),(([t,e],[n,r])=>(0,s.Z)(e,r)||(0,s.Z)(t,n))):(0,j.ZP)(w(t,n),(([t,n],[r,o])=>e(n,o)||(0,s.Z)(t,r)))).map((([t])=>t))}var O=Array.prototype,I=O.slice;O.map;function R(t){return()=>t}var F=n(6106);function P(t,e,n){let r;for(;;){const s=(0,F.G9)(t,e,n);if(s===r||0===s||!isFinite(s))return[t,e];s>0?(t=Math.floor(t/s)*s,e=Math.ceil(e/s)*s):s<0&&(t=Math.ceil(t*s)/s,e=Math.floor(e*s)/s),r=s}}var D=n(2327);function L(){var t=v,e=g.Z,n=D.Z;function s(s){Array.isArray(s)||(s=Array.from(s));var o,i,a,l=s.length,c=new Array(l);for(o=0;o<l;++o)c[o]=t(s[o],o,s);var u=e(c),f=u[0],d=u[1],h=n(c,f,d);if(!Array.isArray(h)){const t=d,n=+h;if(e===g.Z&&([f,d]=P(f,d,n)),(h=(0,F.ZP)(f,d,n))[0]<=f&&(a=(0,F.G9)(f,d,n)),h[h.length-1]>=d)if(t>=d&&e===g.Z){const t=(0,F.G9)(f,d,n);isFinite(t)&&(t>0?d=(Math.floor(d/t)+1)*t:t<0&&(d=(Math.ceil(d*-t)+1)/-t))}else h.pop()}for(var p=h.length;h[0]<=f;)h.shift(),--p;for(;h[p-1]>d;)h.pop(),--p;var m,y=new Array(p+1);for(o=0;o<=p;++o)(m=y[o]=[]).x0=o>0?h[o-1]:f,m.x1=o<p?h[o]:d;if(isFinite(a)){if(a>0)for(o=0;o<l;++o)null!=(i=c[o])&&f<=i&&i<=d&&y[Math.min(p,Math.floor((i-f)/a))].push(s[o]);else if(a<0)for(o=0;o<l;++o)if(null!=(i=c[o])&&f<=i&&i<=d){const t=Math.floor((f-i)*a);y[Math.min(p,t+(h[t]<=i))].push(s[o])}}else for(o=0;o<l;++o)null!=(i=c[o])&&f<=i&&i<=d&&y[(0,r.ZP)(h,i,0,p)].push(s[o]);return y}return s.value=function(e){return arguments.length?(t="function"==typeof e?e:R(e),s):t},s.domain=function(t){return arguments.length?(e="function"==typeof t?t:R([t[0],t[1]]),s):e},s.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?R(I.call(t)):R(t),s):n},s}var $=n(1177);function z(t,e,n){return Math.ceil((n-e)/(2*((0,$.ZP)(t,.75)-(0,$.ZP)(t,.25))*Math.pow((0,a.Z)(t),-1/3)))}function Z(t,e,n){return Math.ceil((n-e)*Math.cbrt((0,a.Z)(t))/(3.49*m(t)))}var U=n(8319),B=n(5374);function G(t,e){let n=0,r=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(++n,r+=e);else{let s=-1;for(let o of t)null!=(o=e(o,++s,t))&&(o=+o)>=o&&(++n,r+=o)}if(n)return r/n}function J(t,e){return(0,$.ZP)(t,.5,e)}function H(t,e){return(0,$.Cr)(t,.5,e)}var W=n(1740),V=n(816),Y=n(2980);function K(t,e){const n=new b.L;if(void 0===e)for(let e of t)null!=e&&e>=e&&n.set(e,(n.get(e)||0)+1);else{let r=-1;for(let s of t)null!=(s=e(s,++r,t))&&s>=s&&n.set(s,(n.get(s)||0)+1)}let r,s=0;for(const[t,e]of n)e>s&&(s=e,r=t);return r}function X(t,e=Q){const n=[];let r,s=!1;for(const o of t)s&&n.push(e(r,o)),r=o,s=!0;return n}function Q(t,e){return[t,e]}var tt=n(362),et=n(551),nt=n(1265);function rt(t,e=s.Z){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let n=Array.from(t);const r=new Float64Array(n.length);2!==e.length&&(n=n.map(e),e=s.Z);const o=(t,r)=>e(n[t],n[r]);let i,a;return Uint32Array.from(n,((t,e)=>e)).sort(e===s.Z?(t,e)=>(0,j.Wv)(n[t],n[e]):(0,j.di)(o)).forEach(((t,e)=>{const n=o(t,void 0===i?t:i);n>=0?((void 0===i||n>0)&&(i=t,a=e),r[t]=a):r[t]=NaN})),r}function st(t,e=s.Z){let n,r=!1;if(1===e.length){let o;for(const i of t){const t=e(i);(r?(0,s.Z)(t,o)<0:0===(0,s.Z)(t,t))&&(n=i,o=t,r=!0)}}else for(const s of t)(r?e(s,n)<0:0===e(s,s))&&(n=s,r=!0);return n}function ot(t,e=s.Z){if(1===e.length)return(0,Y.Z)(t,e);let n,r=-1,o=-1;for(const s of t)++o,(r<0?0===e(s,s):e(s,n)<0)&&(n=s,r=o);return r}var it=n(2942);function at(t,e=s.Z){if(1===e.length)return(0,B.Z)(t,e);let n,r=-1,o=-1;for(const s of t)++o,(r<0?0===e(s,s):e(s,n)>0)&&(n=s,r=o);return r}function lt(t,e){const n=ot(t,e);return n<0?void 0:n}const ct=ut(Math.random);function ut(t){return function(e,n=0,r=e.length){let s=r-(n=+n);for(;s;){const r=t()*s--|0,o=e[s+n];e[s+n]=e[r+n],e[r+n]=o}return e}}function ft(t,e){let n=0;if(void 0===e)for(let e of t)(e=+e)&&(n+=e);else{let r=-1;for(let s of t)(s=+e(s,++r,t))&&(n+=s)}return n}function dt(t){if(!(s=t.length))return[];for(var e=-1,n=(0,V.Z)(t,ht),r=new Array(n);++e<n;)for(var s,o=-1,i=r[e]=new Array(s);++o<s;)i[o]=t[o][e];return r}function ht(t){return t.length}function pt(){return dt(arguments)}function mt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(!e(r,++n,t))return!1;return!0}function gt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(e(r,++n,t))return!0;return!1}function yt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");const n=[];let r=-1;for(const s of t)e(s,++r,t)&&n.push(s);return n}function bt(t,e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof e)throw new TypeError("mapper is not a function");return Array.from(t,((n,r)=>e(n,r,t)))}function vt(t,e,n){if("function"!=typeof e)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let s,o,i=-1;if(arguments.length<3){if(({done:s,value:n}=r.next()),s)return;++i}for(;({done:s,value:o}=r.next()),!s;)n=e(n,o,++i,t);return n}function wt(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()}function _t(t,...e){t=new b.H(t);for(const n of e)for(const e of n)t.delete(e);return t}function xt(t,e){const n=e[Symbol.iterator](),r=new b.H;for(const e of t){if(r.has(e))return!1;let t,s;for(;({value:t,done:s}=n.next())&&!s;){if(Object.is(e,t))return!1;r.add(t)}}return!0}function kt(t,...e){t=new b.H(t),e=e.map(qt);t:for(const n of t)for(const r of e)if(!r.has(n)){t.delete(n);continue t}return t}function qt(t){return t instanceof b.H?t:new b.H(t)}function Nt(t,e){const n=t[Symbol.iterator](),r=new Set;for(const t of e){const e=St(t);if(r.has(e))continue;let s,o;for(;({value:s,done:o}=n.next());){if(o)return!1;const t=St(s);if(r.add(t),Object.is(e,t))break}}return!0}function St(t){return null!==t&&"object"==typeof t?t.valueOf():t}function At(t,e){return Nt(e,t)}function Mt(...t){const e=new b.H;for(const n of t)for(const t of n)e.add(t);return e}},8319:(t,e,n)=>{"use strict";function r(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n<e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let s of t)null!=(s=e(s,++r,t))&&(n<s||void 0===n&&s>=s)&&(n=s)}return n}n.d(e,{Z:()=>r})},5374:(t,e,n)=>{"use strict";function r(t,e){let n,r=-1,s=-1;if(void 0===e)for(const e of t)++s,null!=e&&(n<e||void 0===n&&e>=e)&&(n=e,r=s);else for(let o of t)null!=(o=e(o,++s,t))&&(n<o||void 0===n&&o>=o)&&(n=o,r=s);return r}n.d(e,{Z:()=>r})},1740:(t,e,n)=>{"use strict";function r(t){return Array.from(function*(t){for(const e of t)yield*e}(t))}n.d(e,{Z:()=>r})},816:(t,e,n)=>{"use strict";function r(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n>e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let s of t)null!=(s=e(s,++r,t))&&(n>s||void 0===n&&s>=s)&&(n=s)}return n}n.d(e,{Z:()=>r})},2980:(t,e,n)=>{"use strict";function r(t,e){let n,r=-1,s=-1;if(void 0===e)for(const e of t)++s,null!=e&&(n>e||void 0===n&&e>=e)&&(n=e,r=s);else for(let o of t)null!=(o=e(o,++s,t))&&(n>o||void 0===n&&o>=o)&&(n=o,r=s);return r}n.d(e,{Z:()=>r})},3745:(t,e,n)=>{"use strict";function r(t){return null===t?NaN:+t}function*s(t,e){if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(yield e);else{let n=-1;for(let r of t)null!=(r=e(r,++n,t))&&(r=+r)>=r&&(yield r)}}n.d(e,{K:()=>s,Z:()=>r})},362:(t,e,n)=>{"use strict";function r(t,e){return Array.from(e,(e=>t[e]))}n.d(e,{Z:()=>r})},1177:(t,e,n)=>{"use strict";n.d(e,{Cr:()=>h,ZP:()=>f,s7:()=>d});var r=n(8319),s=n(5374),o=n(816),i=n(2980),a=n(551),l=n(3745),c=n(3897),u=n(2942);function f(t,e,n){if(s=(t=Float64Array.from((0,l.K)(t,n))).length){if((e=+e)<=0||s<2)return(0,o.Z)(t);if(e>=1)return(0,r.Z)(t);var s,i=(s-1)*e,c=Math.floor(i),u=(0,r.Z)((0,a.Z)(t,c).subarray(0,c+1));return u+((0,o.Z)(t.subarray(c+1))-u)*(i-c)}}function d(t,e,n=l.Z){if(r=t.length){if((e=+e)<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,s=(r-1)*e,o=Math.floor(s),i=+n(t[o],o,t);return i+(+n(t[o+1],o+1,t)-i)*(s-o)}}function h(t,e,n){if(r=(t=Float64Array.from((0,l.K)(t,n))).length){if((e=+e)<=0||r<2)return(0,i.Z)(t);if(e>=1)return(0,s.Z)(t);var r,o=Math.floor((r-1)*e),f=(0,a.Z)(Uint32Array.from(t,((t,e)=>e)),o,0,r-1,((e,n)=>(0,c.Wv)(t[e],t[n])));return(0,u.Z)(f.subarray(0,o+1),(e=>t[e]))}}},551:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(3897);function s(t,e,n=0,i=t.length-1,a){for(a=void 0===a?r.Wv:(0,r.di)(a);i>n;){if(i-n>600){const r=i-n+1,o=e-n+1,l=Math.log(r),c=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*c*(r-c)/r)*(o-r/2<0?-1:1);s(t,e,Math.max(n,Math.floor(e-o*c/r+u)),Math.min(i,Math.floor(e+(r-o)*c/r+u)),a)}const r=t[e];let l=n,c=i;for(o(t,n,e),a(t[i],r)>0&&o(t,n,i);l<c;){for(o(t,l,c),++l,--c;a(t[l],r)<0;)++l;for(;a(t[c],r)>0;)--c}0===a(t[n],r)?o(t,n,c):(++c,o(t,c,i)),c<=e&&(n=c+1),e<=c&&(i=c-1)}return t}function o(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}},1265:(t,e,n)=>{"use strict";function r(t,e,n){t=+t,e=+e,n=(s=arguments.length)<2?(e=t,t=0,1):s<3?1:+n;for(var r=-1,s=0|Math.max(0,Math.ceil((e-t)/n)),o=new Array(s);++r<s;)o[r]=t+r*n;return o}n.d(e,{Z:()=>r})},3897:(t,e,n)=>{"use strict";n.d(e,{Wv:()=>a,ZP:()=>o,di:()=>i});var r=n(9263),s=n(362);function o(t,...e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[n]=e;if(n&&2!==n.length||e.length>1){const r=Uint32Array.from(t,((t,e)=>e));return e.length>1?(e=e.map((e=>t.map(e))),r.sort(((t,n)=>{for(const r of e){const e=a(r[t],r[n]);if(e)return e}}))):(n=t.map(n),r.sort(((t,e)=>a(n[t],n[e])))),(0,s.Z)(t,r)}return t.sort(i(n))}function i(t=r.Z){if(t===r.Z)return a;if("function"!=typeof t)throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||0===r?r:(0===t(n,n))-(0===t(e,e))}}function a(t,e){return(null==t||!(t>=t))-(null==e||!(e>=e))||(t<e?-1:t>e?1:0)}},2327:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(879);function s(t){return Math.ceil(Math.log((0,r.Z)(t))/Math.LN2)+1}},6106:(t,e,n)=>{"use strict";n.d(e,{G9:()=>a,ZP:()=>i,ly:()=>l});var r=Math.sqrt(50),s=Math.sqrt(10),o=Math.sqrt(2);function i(t,e,n){var r,s,o,i,l=-1;if(n=+n,(t=+t)===(e=+e)&&n>0)return[t];if((r=e<t)&&(s=t,t=e,e=s),0===(i=a(t,e,n))||!isFinite(i))return[];if(i>0){let n=Math.round(t/i),r=Math.round(e/i);for(n*i<t&&++n,r*i>e&&--r,o=new Array(s=r-n+1);++l<s;)o[l]=(n+l)*i}else{i=-i;let n=Math.round(t*i),r=Math.round(e*i);for(n/i<t&&++n,r/i>e&&--r,o=new Array(s=r-n+1);++l<s;)o[l]=(n+l)/i}return r&&o.reverse(),o}function a(t,e,n){var i=(e-t)/Math.max(0,n),a=Math.floor(Math.log(i)/Math.LN10),l=i/Math.pow(10,a);return a>=0?(l>=r?10:l>=s?5:l>=o?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=r?10:l>=s?5:l>=o?2:1)}function l(t,e,n){var i=Math.abs(e-t)/Math.max(0,n),a=Math.pow(10,Math.floor(Math.log(i)/Math.LN10)),l=i/a;return l>=r?a*=10:l>=s?a*=5:l>=o&&(a*=2),e<t?-a:a}},1495:(t,e,n)=>{"use strict";n.d(e,{B8:()=>q,Il:()=>s,J5:()=>i,SU:()=>k,Ss:()=>N,Ym:()=>O,ZP:()=>w,xV:()=>o});var r=n(3456);function s(){}var o=.7,i=1/o,a="\\s*([+-]?\\d+)\\s*",l="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",c="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",u=/^#([0-9a-f]{3,8})$/,f=new RegExp(`^rgb\\(${a},${a},${a}\\)$`),d=new RegExp(`^rgb\\(${c},${c},${c}\\)$`),h=new RegExp(`^rgba\\(${a},${a},${a},${l}\\)$`),p=new RegExp(`^rgba\\(${c},${c},${c},${l}\\)$`),m=new RegExp(`^hsl\\(${l},${c},${c}\\)$`),g=new RegExp(`^hsla\\(${l},${c},${c},${l}\\)$`),y={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 b(){return this.rgb().formatHex()}function v(){return this.rgb().formatRgb()}function w(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=u.exec(t))?(n=e[1].length,e=parseInt(e[1],16),6===n?_(e):3===n?new N(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?x(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?x(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=f.exec(t))?new N(e[1],e[2],e[3],1):(e=d.exec(t))?new N(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=h.exec(t))?x(e[1],e[2],e[3],e[4]):(e=p.exec(t))?x(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=m.exec(t))?j(e[1],e[2]/100,e[3]/100,1):(e=g.exec(t))?j(e[1],e[2]/100,e[3]/100,e[4]):y.hasOwnProperty(t)?_(y[t]):"transparent"===t?new N(NaN,NaN,NaN,0):null}function _(t){return new N(t>>16&255,t>>8&255,255&t,1)}function x(t,e,n,r){return r<=0&&(t=e=n=NaN),new N(t,e,n,r)}function k(t){return t instanceof s||(t=w(t)),t?new N((t=t.rgb()).r,t.g,t.b,t.opacity):new N}function q(t,e,n,r){return 1===arguments.length?k(t):new N(t,e,n,null==r?1:r)}function N(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function S(){return`#${C(this.r)}${C(this.g)}${C(this.b)}`}function A(){const t=M(this.opacity);return`${1===t?"rgb(":"rgba("}${T(this.r)}, ${T(this.g)}, ${T(this.b)}${1===t?")":`, ${t})`}`}function M(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function T(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function C(t){return((t=T(t))<16?"0":"")+t.toString(16)}function j(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new I(t,e,n,r)}function E(t){if(t instanceof I)return new I(t.h,t.s,t.l,t.opacity);if(t instanceof s||(t=w(t)),!t)return new I;if(t instanceof I)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,o=Math.min(e,n,r),i=Math.max(e,n,r),a=NaN,l=i-o,c=(i+o)/2;return l?(a=e===i?(n-r)/l+6*(n<r):n===i?(r-e)/l+2:(e-n)/l+4,l/=c<.5?i+o:2-i-o,a*=60):l=c>0&&c<1?0:a,new I(a,l,c,t.opacity)}function O(t,e,n,r){return 1===arguments.length?E(t):new I(t,e,n,null==r?1:r)}function I(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function R(t){return(t=(t||0)%360)<0?t+360:t}function F(t){return Math.max(0,Math.min(1,t||0))}function P(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}(0,r.Z)(s,w,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:b,formatHex:b,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return E(this).formatHsl()},formatRgb:v,toString:v}),(0,r.Z)(N,q,(0,r.l)(s,{brighter(t){return t=null==t?i:Math.pow(i,t),new N(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?o:Math.pow(o,t),new N(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new N(T(this.r),T(this.g),T(this.b),M(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`#${C(this.r)}${C(this.g)}${C(this.b)}${C(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:A,toString:A})),(0,r.Z)(I,O,(0,r.l)(s,{brighter(t){return t=null==t?i:Math.pow(i,t),new I(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?o:Math.pow(o,t),new I(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,s=2*n-r;return new N(P(t>=240?t-240:t+120,s,r),P(t,s,r),P(t<120?t+240:t-120,s,r),this.opacity)},clamp(){return new I(R(this.h),F(this.s),F(this.l),M(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 t=M(this.opacity);return`${1===t?"hsl(":"hsla("}${R(this.h)}, ${100*F(this.s)}%, ${100*F(this.l)}%${1===t?")":`, ${t})`}`}}))},3456:(t,e,n)=>{"use strict";function r(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function s(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}n.d(e,{Z:()=>r,l:()=>s})},4476:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r={},s={},o=34,i=10,a=13;function l(t){return new Function("d","return {"+t.map((function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'})).join(",")+"}")}function c(t){var e=Object.create(null),n=[];return t.forEach((function(t){for(var r in t)r in e||n.push(e[r]=r)})),n}function u(t,e){var n=t+"",r=n.length;return r<e?new Array(e-r+1).join(0)+n:n}function f(t){var e,n=t.getUTCHours(),r=t.getUTCMinutes(),s=t.getUTCSeconds(),o=t.getUTCMilliseconds();return isNaN(t)?"Invalid Date":((e=t.getUTCFullYear())<0?"-"+u(-e,6):e>9999?"+"+u(e,6):u(e,4))+"-"+u(t.getUTCMonth()+1,2)+"-"+u(t.getUTCDate(),2)+(o?"T"+u(n,2)+":"+u(r,2)+":"+u(s,2)+"."+u(o,3)+"Z":s?"T"+u(n,2)+":"+u(r,2)+":"+u(s,2)+"Z":r||n?"T"+u(n,2)+":"+u(r,2)+"Z":"")}function d(t){var e=new RegExp('["'+t+"\n\r]"),n=t.charCodeAt(0);function u(t,e){var l,c=[],u=t.length,f=0,d=0,h=u<=0,p=!1;function m(){if(h)return s;if(p)return p=!1,r;var e,l,c=f;if(t.charCodeAt(c)===o){for(;f++<u&&t.charCodeAt(f)!==o||t.charCodeAt(++f)===o;);return(e=f)>=u?h=!0:(l=t.charCodeAt(f++))===i?p=!0:l===a&&(p=!0,t.charCodeAt(f)===i&&++f),t.slice(c+1,e-1).replace(/""/g,'"')}for(;f<u;){if((l=t.charCodeAt(e=f++))===i)p=!0;else if(l===a)p=!0,t.charCodeAt(f)===i&&++f;else if(l!==n)continue;return t.slice(c,e)}return h=!0,t.slice(c,u)}for(t.charCodeAt(u-1)===i&&--u,t.charCodeAt(u-1)===a&&--u;(l=m())!==s;){for(var g=[];l!==r&&l!==s;)g.push(l),l=m();e&&null==(g=e(g,d++))||c.push(g)}return c}function d(e,n){return e.map((function(e){return n.map((function(t){return p(e[t])})).join(t)}))}function h(e){return e.map(p).join(t)}function p(t){return null==t?"":t instanceof Date?f(t):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t}return{parse:function(t,e){var n,r,s=u(t,(function(t,s){if(n)return n(t,s-1);r=t,n=e?function(t,e){var n=l(t);return function(r,s){return e(n(r),s,t)}}(t,e):l(t)}));return s.columns=r||[],s},parseRows:u,format:function(e,n){return null==n&&(n=c(e)),[n.map(p).join(t)].concat(d(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=c(t)),d(t,e).join("\n")},formatRows:function(t){return t.map(h).join("\n")},formatRow:h,formatValue:p}}},5026:(t,e,n)=>{"use strict";n.d(e,{E0:()=>o,Hf:()=>c,n5:()=>l,sS:()=>u,tJ:()=>s,uH:()=>a,vP:()=>i});var r=(0,n(4476).Z)("\t"),s=r.parse,o=r.parseRows,i=r.format,a=r.formatBody,l=r.formatRows,c=r.formatRow,u=r.formatValue},2163:(t,e,n)=>{"use strict";n.d(e,{WU:()=>s,ZP:()=>a,jH:()=>o});var r,s,o,i=n(2107);function a(t){return r=(0,i.Z)(t),s=r.format,o=r.formatPrefix,r}a({thousands:",",grouping:[3],currency:["$",""]})},2313:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(4218);function s(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},4218:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function s(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{V:()=>s,Z:()=>r})},7259:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,v:()=>o});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function s(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new o({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function o(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}s.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}},2107:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(2313);var s=n(7259);var o,i=n(4218);function a(t,e){var n=(0,i.V)(t,e);if(!n)return t+"";var r=n[0],s=n[1];return s<0?"0."+new Array(-s).join("0")+r:r.length>s+1?r.slice(0,s+1)+"."+r.slice(s+1):r+new Array(s-r.length+2).join("0")}const l={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:i.Z,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>a(100*t,e),r:a,s:function(t,e){var n=(0,i.V)(t,e);if(!n)return t+"";var r=n[0],s=n[1],a=s-(o=3*Math.max(-8,Math.min(8,Math.floor(s/3))))+1,l=r.length;return a===l?r:a>l?r+new Array(a-l+1).join("0"):a>0?r.slice(0,a)+"."+r.slice(a):"0."+new Array(1-a).join("0")+(0,i.V)(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function c(t){return t}var u=Array.prototype.map,f=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function d(t){var e,n,i=void 0===t.grouping||void 0===t.thousands?c:(e=u.call(t.grouping,Number),n=t.thousands+"",function(t,r){for(var s=t.length,o=[],i=0,a=e[0],l=0;s>0&&a>0&&(l+a+1>r&&(a=Math.max(1,r-l)),o.push(t.substring(s-=a,s+a)),!((l+=a+1)>r));)a=e[i=(i+1)%e.length];return o.reverse().join(n)}),a=void 0===t.currency?"":t.currency[0]+"",d=void 0===t.currency?"":t.currency[1]+"",h=void 0===t.decimal?".":t.decimal+"",p=void 0===t.numerals?c:function(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}(u.call(t.numerals,String)),m=void 0===t.percent?"%":t.percent+"",g=void 0===t.minus?"−":t.minus+"",y=void 0===t.nan?"NaN":t.nan+"";function b(t){var e=(t=(0,s.Z)(t)).fill,n=t.align,r=t.sign,c=t.symbol,u=t.zero,b=t.width,v=t.comma,w=t.precision,_=t.trim,x=t.type;"n"===x?(v=!0,x="g"):l[x]||(void 0===w&&(w=12),_=!0,x="g"),(u||"0"===e&&"="===n)&&(u=!0,e="0",n="=");var k="$"===c?a:"#"===c&&/[boxX]/.test(x)?"0"+x.toLowerCase():"",q="$"===c?d:/[%p]/.test(x)?m:"",N=l[x],S=/[defgprs%]/.test(x);function A(t){var s,a,l,c=k,d=q;if("c"===x)d=N(t)+d,t="";else{var m=(t=+t)<0||1/t<0;if(t=isNaN(t)?y:N(Math.abs(t),w),_&&(t=function(t){t:for(var e,n=t.length,r=1,s=-1;r<n;++r)switch(t[r]){case".":s=e=r;break;case"0":0===s&&(s=r),e=r;break;default:if(!+t[r])break t;s>0&&(s=0)}return s>0?t.slice(0,s)+t.slice(e+1):t}(t)),m&&0==+t&&"+"!==r&&(m=!1),c=(m?"("===r?r:g:"-"===r||"("===r?"":r)+c,d=("s"===x?f[8+o/3]:"")+d+(m&&"("===r?")":""),S)for(s=-1,a=t.length;++s<a;)if(48>(l=t.charCodeAt(s))||l>57){d=(46===l?h+t.slice(s+1):t.slice(s))+d,t=t.slice(0,s);break}}v&&!u&&(t=i(t,1/0));var A=c.length+t.length+d.length,M=A<b?new Array(b-A+1).join(e):"";switch(v&&u&&(t=i(M+t,M.length?b-d.length:1/0),M=""),n){case"<":t=c+t+d+M;break;case"=":t=c+M+t+d;break;case"^":t=M.slice(0,A=M.length>>1)+c+t+d+M.slice(A);break;default:t=M+c+t+d}return p(t)}return w=void 0===w?6:/[gprs]/.test(x)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w)),A.toString=function(){return t+""},A}return{format:b,formatPrefix:function(t,e){var n=b(((t=(0,s.Z)(t)).type="f",t)),o=3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3))),i=Math.pow(10,-o),a=f[8+o/3];return function(t){return n(i*t)+a}}}}},9680:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(2313);function s(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},3150:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(2313);function s(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},3621:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(2313);function s(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},9466:(t,e,n)=>{"use strict";function r(t){return null==t?null:s(t)}function s(t){if("function"!=typeof t)throw new Error;return t}n.d(e,{C:()=>s,j:()=>r})},5220:(t,e,n)=>{"use strict";function r(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function s(t,e){t instanceof Map?(t=[void 0,t],void 0===e&&(e=i)):void 0===e&&(e=o);for(var n,r,s,a,u,f=new c(t),d=[f];n=d.pop();)if((s=e(n.data))&&(u=(s=Array.from(s)).length))for(n.children=s,a=u-1;a>=0;--a)d.push(r=s[a]=new c(s[a])),r.parent=n,r.depth=n.depth+1;return f.eachBefore(l)}function o(t){return t.children}function i(t){return Array.isArray(t)?t[1]:null}function a(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function l(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function c(t){this.data=t,this.depth=this.height=0,this.parent=null}n.d(e,{NB:()=>c,le:()=>l,ZP:()=>s}),c.prototype=s.prototype={constructor:c,count:function(){return this.eachAfter(r)},each:function(t,e){let n=-1;for(const r of this)t.call(e,r,++n,this);return this},eachAfter:function(t,e){for(var n,r,s,o=this,i=[o],a=[],l=-1;o=i.pop();)if(a.push(o),n=o.children)for(r=0,s=n.length;r<s;++r)i.push(n[r]);for(;o=a.pop();)t.call(e,o,++l,this);return this},eachBefore:function(t,e){for(var n,r,s=this,o=[s],i=-1;s=o.pop();)if(t.call(e,s,++i,this),n=s.children)for(r=n.length-1;r>=0;--r)o.push(n[r]);return this},find:function(t,e){let n=-1;for(const r of this)if(t.call(e,r,++n,this))return r},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,s=r&&r.length;--s>=0;)n+=r[s].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),s=null;t=n.pop(),e=r.pop();for(;t===e;)s=t,t=n.pop(),e=r.pop();return s}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var s=r.length;t!==n;)r.splice(s,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return s(this).eachBefore(a)},[Symbol.iterator]:function*(){var t,e,n,r,s=this,o=[s];do{for(t=o.reverse(),o=[];s=t.pop();)if(yield s,e=s.children)for(n=0,r=e.length;n<r;++n)o.push(e[n])}while(o.length)}}},4766:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(9466),s=n(5220),o={depth:-1},i={},a={};function l(t){return t.id}function c(t){return t.parentId}function u(){var t,e=l,n=c;function u(r){var l,c,u,h,p,m,g,y,b=Array.from(r),v=e,w=n,_=new Map;if(null!=t){const e=b.map(((e,n)=>function(t){t=`${t}`;let e=t.length;d(t,e-1)&&!d(t,e-2)&&(t=t.slice(0,-1));return"/"===t[0]?t:`/${t}`}(t(e,n,r)))),n=e.map(f),s=new Set(e).add("");for(const t of n)s.has(t)||(s.add(t),e.push(t),n.push(f(t)),b.push(a));v=(t,n)=>e[n],w=(t,e)=>n[e]}for(u=0,l=b.length;u<l;++u)c=b[u],m=b[u]=new s.NB(c),null!=(g=v(c,u,r))&&(g+="")&&(y=m.id=g,_.set(y,_.has(y)?i:m)),null!=(g=w(c,u,r))&&(g+="")&&(m.parent=g);for(u=0;u<l;++u)if(g=(m=b[u]).parent){if(!(p=_.get(g)))throw new Error("missing: "+g);if(p===i)throw new Error("ambiguous: "+g);p.children?p.children.push(m):p.children=[m],m.parent=p}else{if(h)throw new Error("multiple roots");h=m}if(!h)throw new Error("no root");if(null!=t){for(;h.data===a&&1===h.children.length;)h=h.children[0],--l;for(let t=b.length-1;t>=0&&(m=b[t]).data===a;--t)m.data=null}if(h.parent=o,h.eachBefore((function(t){t.depth=t.parent.depth+1,--l})).eachBefore(s.le),h.parent=null,l>0)throw new Error("cycle");return h}return u.id=function(t){return arguments.length?(e=(0,r.j)(t),u):e},u.parentId=function(t){return arguments.length?(n=(0,r.j)(t),u):n},u.path=function(e){return arguments.length?(t=(0,r.j)(e),u):t},u}function f(t){let e=t.length;if(e<2)return"";for(;--e>1&&!d(t,e););return t.slice(0,e)}function d(t,e){if("/"===t[e]){let n=0;for(;e>0&&"\\"===t[--e];)++n;if(0==(1&n))return!0}return!1}},4321:(t,e,n)=>{"use strict";n.d(e,{M:()=>i,Z:()=>o});var r=n(2303),s=n(5003);function o(t,e){return((0,s.v)(e)?s.Z:i)(t,e)}function i(t,e){var n,s=e?e.length:0,o=t?Math.min(s,t.length):0,i=new Array(o),a=new Array(s);for(n=0;n<o;++n)i[n]=(0,r.Z)(t[n],e[n]);for(;n<s;++n)a[n]=e[n];return function(t){for(n=0;n<o;++n)a[n]=i[n](t);return a}}},5409:(t,e,n)=>{"use strict";function r(t,e,n,r,s){var o=t*t,i=o*t;return((1-3*t+3*o-i)*e+(4-6*o+3*i)*n+(1+3*t+3*o-3*i)*r+i*s)/6}function s(t){var e=t.length-1;return function(n){var s=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),o=t[s],i=t[s+1],a=s>0?t[s-1]:2*o-i,l=s<e-1?t[s+2]:2*i-o;return r((n-s/e)*e,a,o,i,l)}}n.d(e,{Z:()=>s,t:()=>r})},7855:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(5409);function s(t){var e=t.length;return function(n){var s=Math.floor(((n%=1)<0?++n:n)*e),o=t[(s+e-1)%e],i=t[s%e],a=t[(s+1)%e],l=t[(s+2)%e];return(0,r.t)((n-s/e)*e,o,i,a,l)}}},8190:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,wx:()=>o,yi:()=>i});var r=n(8486);function s(t,e){return function(n){return t+n*e}}function o(t,e){var n=e-t;return n?s(t,n>180||n<-180?n-360*Math.round(n/360):n):(0,r.Z)(isNaN(t)?e:t)}function i(t){return 1==(t=+t)?a:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):(0,r.Z)(isNaN(e)?n:e)}}function a(t,e){var n=e-t;return n?s(t,n):(0,r.Z)(isNaN(t)?e:t)}},8486:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=t=>()=>t},6261:(t,e,n)=>{"use strict";function r(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}n.d(e,{Z:()=>r})},8403:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}n.d(e,{Z:()=>r})},5003:(t,e,n)=>{"use strict";function r(t,e){e||(e=[]);var n,r=t?Math.min(e.length,t.length):0,s=e.slice();return function(o){for(n=0;n<r;++n)s[n]=t[n]*(1-o)+e[n]*o;return s}}function s(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}n.d(e,{Z:()=>r,v:()=>s})},8765:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(2303);function s(t,e){var n,s={},o={};for(n in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)n in t?s[n]=(0,r.Z)(t[n],e[n]):o[n]=e[n];return function(t){for(n in s)o[n]=s[n](t);return o}}},9444:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(2303);function s(t,e){void 0===e&&(e=t,t=r.Z);for(var n=0,s=e.length-1,o=e[0],i=new Array(s<0?0:s);n<s;)i[n]=t(o,o=e[++n]);return function(t){var e=Math.max(0,Math.min(s-1,Math.floor(t*=s)));return i[e](t-e)}}},490:(t,e,n)=>{"use strict";n.d(e,{YD:()=>u,ZP:()=>a,hD:()=>c});var r=n(1495),s=n(5409),o=n(7855),i=n(8190);const a=function t(e){var n=(0,i.yi)(e);function s(t,e){var s=n((t=(0,r.B8)(t)).r,(e=(0,r.B8)(e)).r),o=n(t.g,e.g),a=n(t.b,e.b),l=(0,i.ZP)(t.opacity,e.opacity);return function(e){return t.r=s(e),t.g=o(e),t.b=a(e),t.opacity=l(e),t+""}}return s.gamma=t,s}(1);function l(t){return function(e){var n,s,o=e.length,i=new Array(o),a=new Array(o),l=new Array(o);for(n=0;n<o;++n)s=(0,r.B8)(e[n]),i[n]=s.r||0,a[n]=s.g||0,l[n]=s.b||0;return i=t(i),a=t(a),l=t(l),s.opacity=1,function(t){return s.r=i(t),s.g=a(t),s.b=l(t),s+""}}}var c=l(s.Z),u=l(o.Z)},5250:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}n.d(e,{Z:()=>r})},9009:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(8403),s=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,o=new RegExp(s.source,"g");function i(t,e){var n,i,a,l=s.lastIndex=o.lastIndex=0,c=-1,u=[],f=[];for(t+="",e+="";(n=s.exec(t))&&(i=o.exec(e));)(a=i.index)>l&&(a=e.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,r.Z)(n,i)})),l=o.lastIndex;return l<e.length&&(a=e.slice(l),u[c]?u[c]+=a:u[++c]=a),u.length<2?f[0]?function(t){return function(e){return t(e)+""}}(f[0].x):function(t){return function(){return t}}(e):(e=f.length,function(t){for(var n,r=0;r<e;++r)u[(n=f[r]).i]=n.x(t);return u.join("")})}},2303:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(1495),s=n(490),o=n(4321),i=n(6261),a=n(8403),l=n(8765),c=n(9009),u=n(8486),f=n(5003);function d(t,e){var n,d=typeof e;return null==e||"boolean"===d?(0,u.Z)(e):("number"===d?a.Z:"string"===d?(n=(0,r.ZP)(e))?(e=n,s.ZP):c.Z:e instanceof r.ZP?s.ZP:e instanceof Date?i.Z:(0,f.v)(e)?f.Z:Array.isArray(e)?o.M:"function"!=typeof e.valueOf&&"function"!=typeof e.toString||isNaN(e)?l.Z:a.Z)(t,e)}},7763:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(4090).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf")},4090:(t,e,n)=>{"use strict";function r(t){for(var e=t.length/6|0,n=new Array(e),r=0;r<e;)n[r]="#"+t.slice(6*r,6*++r);return n}n.d(e,{Z:()=>r})},1303:(t,e,n)=>{"use strict";n.d(e,{JG:()=>h,ZP:()=>m,yR:()=>c,l4:()=>p});var r=n(5519),s=n(2303),o=n(8403),i=n(5250);var a=n(9120),l=[0,1];function c(t){return t}function u(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:(n=isNaN(e)?NaN:.5,function(){return n});var n}function f(t,e,n){var r=t[0],s=t[1],o=e[0],i=e[1];return s<r?(r=u(s,r),o=n(i,o)):(r=u(r,s),o=n(o,i)),function(t){return o(r(t))}}function d(t,e,n){var s=Math.min(t.length,e.length)-1,o=new Array(s),i=new Array(s),a=-1;for(t[s]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++a<s;)o[a]=u(t[a],t[a+1]),i[a]=n(e[a],e[a+1]);return function(e){var n=(0,r.ZP)(t,e,1,s)-1;return i[n](o[n](e))}}function h(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function p(){var t,e,n,r,u,h,p=l,m=l,g=s.Z,y=c;function b(){var t,e,n,s=Math.min(p.length,m.length);return y!==c&&(t=p[0],e=p[s-1],t>e&&(n=t,t=e,e=n),y=function(n){return Math.max(t,Math.min(e,n))}),r=s>2?d:f,u=h=null,v}function v(e){return null==e||isNaN(e=+e)?n:(u||(u=r(p.map(t),m,g)))(t(y(e)))}return v.invert=function(n){return y(e((h||(h=r(m,p.map(t),o.Z)))(n)))},v.domain=function(t){return arguments.length?(p=Array.from(t,a.Z),b()):p.slice()},v.range=function(t){return arguments.length?(m=Array.from(t),b()):m.slice()},v.rangeRound=function(t){return m=Array.from(t),g=i.Z,b()},v.clamp=function(t){return arguments.length?(y=!!t||c,b()):y!==c},v.interpolate=function(t){return arguments.length?(g=t,b()):g},v.unknown=function(t){return arguments.length?(n=t,v):n},function(n,r){return t=n,e=r,b()}}function m(){return p()(c,c)}},4635:(t,e,n)=>{"use strict";n.r(e),n.d(e,{scaleBand:()=>i,scaleDiverging:()=>_t,scaleDivergingLog:()=>xt,scaleDivergingPow:()=>qt,scaleDivergingSqrt:()=>Nt,scaleDivergingSymlog:()=>kt,scaleIdentity:()=>f,scaleImplicit:()=>o.O,scaleLinear:()=>c.Z,scaleLog:()=>q,scaleOrdinal:()=>o.Z,scalePoint:()=>l,scalePow:()=>O,scaleQuantile:()=>$,scaleQuantize:()=>z,scaleRadial:()=>F,scaleSequential:()=>ht,scaleSequentialLog:()=>pt,scaleSequentialPow:()=>gt,scaleSequentialQuantile:()=>bt,scaleSequentialSqrt:()=>yt,scaleSequentialSymlog:()=>mt,scaleSqrt:()=>I,scaleSymlog:()=>M,scaleThreshold:()=>Z,scaleTime:()=>et,scaleUtc:()=>lt,tickFormat:()=>St.Z});var r=n(1265),s=n(2998),o=n(5540);function i(){var t,e,n=(0,o.Z)().unknown(void 0),a=n.domain,l=n.range,c=0,u=1,f=!1,d=0,h=0,p=.5;function m(){var n=a().length,s=u<c,o=s?u:c,i=s?c:u;t=(i-o)/Math.max(1,n-d+2*h),f&&(t=Math.floor(t)),o+=(i-o-t*(n-d))*p,e=t*(1-d),f&&(o=Math.round(o),e=Math.round(e));var m=(0,r.Z)(n).map((function(e){return o+t*e}));return l(s?m.reverse():m)}return delete n.unknown,n.domain=function(t){return arguments.length?(a(t),m()):a()},n.range=function(t){return arguments.length?([c,u]=t,c=+c,u=+u,m()):[c,u]},n.rangeRound=function(t){return[c,u]=t,c=+c,u=+u,f=!0,m()},n.bandwidth=function(){return e},n.step=function(){return t},n.round=function(t){return arguments.length?(f=!!t,m()):f},n.padding=function(t){return arguments.length?(d=Math.min(1,h=+t),m()):d},n.paddingInner=function(t){return arguments.length?(d=Math.min(1,t),m()):d},n.paddingOuter=function(t){return arguments.length?(h=+t,m()):h},n.align=function(t){return arguments.length?(p=Math.max(0,Math.min(1,t)),m()):p},n.copy=function(){return i(a(),[c,u]).round(f).paddingInner(d).paddingOuter(h).align(p)},s.o.apply(m(),arguments)}function a(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return a(e())},t}function l(){return a(i.apply(null,arguments).paddingInner(1))}var c=n(9064),u=n(9120);function f(t){var e;function n(t){return null==t||isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=Array.from(e,u.Z),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return f(t).unknown(e)},t=arguments.length?Array.from(t,u.Z):[0,1],(0,c.Q)(n)}var d=n(6106),h=n(7259),p=n(2163);function m(t,e){var n,r=0,s=(t=t.slice()).length-1,o=t[r],i=t[s];return i<o&&(n=r,r=s,s=n,n=o,o=i,i=n),t[r]=e.floor(o),t[s]=e.ceil(i),t}var g=n(1303);function y(t){return Math.log(t)}function b(t){return Math.exp(t)}function v(t){return-Math.log(-t)}function w(t){return-Math.exp(-t)}function _(t){return isFinite(t)?+("1e"+t):t<0?0:t}function x(t){return(e,n)=>-t(-e,n)}function k(t){const e=t(y,b),n=e.domain;let r,s,o=10;function i(){return r=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}(o),s=function(t){return 10===t?_:t===Math.E?Math.exp:e=>Math.pow(t,e)}(o),n()[0]<0?(r=x(r),s=x(s),t(v,w)):t(y,b),e}return e.base=function(t){return arguments.length?(o=+t,i()):o},e.domain=function(t){return arguments.length?(n(t),i()):n()},e.ticks=t=>{const e=n();let i=e[0],a=e[e.length-1];const l=a<i;l&&([i,a]=[a,i]);let c,u,f=r(i),h=r(a);const p=null==t?10:+t;let m=[];if(!(o%1)&&h-f<p){if(f=Math.floor(f),h=Math.ceil(h),i>0){for(;f<=h;++f)for(c=1;c<o;++c)if(u=f<0?c/s(-f):c*s(f),!(u<i)){if(u>a)break;m.push(u)}}else for(;f<=h;++f)for(c=o-1;c>=1;--c)if(u=f>0?c/s(-f):c*s(f),!(u<i)){if(u>a)break;m.push(u)}2*m.length<p&&(m=(0,d.ZP)(i,a,p))}else m=(0,d.ZP)(f,h,Math.min(h-f,p)).map(s);return l?m.reverse():m},e.tickFormat=(t,n)=>{if(null==t&&(t=10),null==n&&(n=10===o?"s":","),"function"!=typeof n&&(o%1||null!=(n=(0,h.Z)(n)).precision||(n.trim=!0),n=(0,p.WU)(n)),t===1/0)return n;const i=Math.max(1,o*t/e.ticks().length);return t=>{let e=t/s(Math.round(r(t)));return e*o<o-.5&&(e*=o),e<=i?n(t):""}},e.nice=()=>n(m(n(),{floor:t=>s(Math.floor(r(t))),ceil:t=>s(Math.ceil(r(t)))})),e}function q(){const t=k((0,g.l4)()).domain([1,10]);return t.copy=()=>(0,g.JG)(t,q()).base(t.base()),s.o.apply(t,arguments),t}function N(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function S(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function A(t){var e=1,n=t(N(e),S(e));return n.constant=function(n){return arguments.length?t(N(e=+n),S(e)):e},(0,c.Q)(n)}function M(){var t=A((0,g.l4)());return t.copy=function(){return(0,g.JG)(t,M()).constant(t.constant())},s.o.apply(t,arguments)}function T(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function C(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function j(t){return t<0?-t*t:t*t}function E(t){var e=t(g.yR,g.yR),n=1;return e.exponent=function(e){return arguments.length?1===(n=+e)?t(g.yR,g.yR):.5===n?t(C,j):t(T(n),T(1/n)):n},(0,c.Q)(e)}function O(){var t=E((0,g.l4)());return t.copy=function(){return(0,g.JG)(t,O()).exponent(t.exponent())},s.o.apply(t,arguments),t}function I(){return O.apply(null,arguments).exponent(.5)}function R(t){return Math.sign(t)*t*t}function F(){var t,e=(0,g.ZP)(),n=[0,1],r=!1;function o(n){var s=function(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}(e(n));return isNaN(s)?t:r?Math.round(s):s}return o.invert=function(t){return e.invert(R(t))},o.domain=function(t){return arguments.length?(e.domain(t),o):e.domain()},o.range=function(t){return arguments.length?(e.range((n=Array.from(t,u.Z)).map(R)),o):n.slice()},o.rangeRound=function(t){return o.range(t).round(!0)},o.round=function(t){return arguments.length?(r=!!t,o):r},o.clamp=function(t){return arguments.length?(e.clamp(t),o):e.clamp()},o.unknown=function(e){return arguments.length?(t=e,o):t},o.copy=function(){return F(e.domain(),n).round(r).clamp(e.clamp()).unknown(t)},s.o.apply(o,arguments),(0,c.Q)(o)}var P=n(1177),D=n(5519),L=n(9263);function $(){var t,e=[],n=[],r=[];function o(){var t=0,s=Math.max(1,n.length);for(r=new Array(s-1);++t<s;)r[t-1]=(0,P.s7)(e,t/s);return i}function i(e){return null==e||isNaN(e=+e)?t:n[(0,D.ZP)(r,e)]}return i.invertExtent=function(t){var s=n.indexOf(t);return s<0?[NaN,NaN]:[s>0?r[s-1]:e[0],s<r.length?r[s]:e[e.length-1]]},i.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(L.Z),o()},i.range=function(t){return arguments.length?(n=Array.from(t),o()):n.slice()},i.unknown=function(e){return arguments.length?(t=e,i):t},i.quantiles=function(){return r.slice()},i.copy=function(){return $().domain(e).range(n).unknown(t)},s.o.apply(i,arguments)}function z(){var t,e=0,n=1,r=1,o=[.5],i=[0,1];function a(e){return null!=e&&e<=e?i[(0,D.ZP)(o,e,0,r)]:t}function l(){var t=-1;for(o=new Array(r);++t<r;)o[t]=((t+1)*n-(t-r)*e)/(r+1);return a}return a.domain=function(t){return arguments.length?([e,n]=t,e=+e,n=+n,l()):[e,n]},a.range=function(t){return arguments.length?(r=(i=Array.from(t)).length-1,l()):i.slice()},a.invertExtent=function(t){var s=i.indexOf(t);return s<0?[NaN,NaN]:s<1?[e,o[0]]:s>=r?[o[r-1],n]:[o[s-1],o[s]]},a.unknown=function(e){return arguments.length?(t=e,a):a},a.thresholds=function(){return o.slice()},a.copy=function(){return z().domain([e,n]).range(i).unknown(t)},s.o.apply((0,c.Q)(a),arguments)}function Z(){var t,e=[.5],n=[0,1],r=1;function o(s){return null!=s&&s<=s?n[(0,D.ZP)(e,s,0,r)]:t}return o.domain=function(t){return arguments.length?(e=Array.from(t),r=Math.min(e.length,n.length-1),o):e.slice()},o.range=function(t){return arguments.length?(n=Array.from(t),r=Math.min(e.length,n.length-1),o):n.slice()},o.invertExtent=function(t){var r=n.indexOf(t);return[e[r-1],e[r]]},o.unknown=function(e){return arguments.length?(t=e,o):t},o.copy=function(){return Z().domain(e).range(n).unknown(t)},s.o.apply(o,arguments)}var U=n(7150),B=n(2311),G=n(7905),J=n(6018),H=n(8467),W=n(6596),V=n(2991),Y=n(1343),K=n(1852);function X(t){return new Date(t)}function Q(t){return t instanceof Date?+t:+new Date(+t)}function tt(t,e,n,r,s,o,i,a,l,c){var u=(0,g.ZP)(),f=u.invert,d=u.domain,h=c(".%L"),p=c(":%S"),y=c("%I:%M"),b=c("%I %p"),v=c("%a %d"),w=c("%b %d"),_=c("%B"),x=c("%Y");function k(t){return(l(t)<t?h:a(t)<t?p:i(t)<t?y:o(t)<t?b:r(t)<t?s(t)<t?v:w:n(t)<t?_:x)(t)}return u.invert=function(t){return new Date(f(t))},u.domain=function(t){return arguments.length?d(Array.from(t,Q)):d().map(X)},u.ticks=function(e){var n=d();return t(n[0],n[n.length-1],null==e?10:e)},u.tickFormat=function(t,e){return null==e?k:c(e)},u.nice=function(t){var n=d();return t&&"function"==typeof t.range||(t=e(n[0],n[n.length-1],null==t?10:t)),t?d(m(n,t)):u},u.copy=function(){return(0,g.JG)(u,tt(t,e,n,r,s,o,i,a,l,c))},u}function et(){return s.o.apply(tt(U.jK,U._g,B.Z,G.Z,J.OM,H.Z,W.Z,V.Z,Y.Z,K.i$).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}var nt=n(4552),rt=n(7351),st=n(1887),ot=n(7445),it=n(8927),at=n(8593);function lt(){return s.o.apply(tt(U.WG,U.jo,nt.Z,rt.Z,st.Ox,ot.Z,it.Z,at.Z,Y.Z,K.g0).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}var ct=n(2303),ut=n(5250);function ft(){var t,e,n,r,s,o=0,i=1,a=g.yR,l=!1;function c(e){return null==e||isNaN(e=+e)?s:a(0===n?.5:(e=(r(e)-t)*n,l?Math.max(0,Math.min(1,e)):e))}function u(t){return function(e){var n,r;return arguments.length?([n,r]=e,a=t(n,r),c):[a(0),a(1)]}}return c.domain=function(s){return arguments.length?([o,i]=s,t=r(o=+o),e=r(i=+i),n=t===e?0:1/(e-t),c):[o,i]},c.clamp=function(t){return arguments.length?(l=!!t,c):l},c.interpolator=function(t){return arguments.length?(a=t,c):a},c.range=u(ct.Z),c.rangeRound=u(ut.Z),c.unknown=function(t){return arguments.length?(s=t,c):s},function(s){return r=s,t=s(o),e=s(i),n=t===e?0:1/(e-t),c}}function dt(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function ht(){var t=(0,c.Q)(ft()(g.yR));return t.copy=function(){return dt(t,ht())},s.O.apply(t,arguments)}function pt(){var t=k(ft()).domain([1,10]);return t.copy=function(){return dt(t,pt()).base(t.base())},s.O.apply(t,arguments)}function mt(){var t=A(ft());return t.copy=function(){return dt(t,mt()).constant(t.constant())},s.O.apply(t,arguments)}function gt(){var t=E(ft());return t.copy=function(){return dt(t,gt()).exponent(t.exponent())},s.O.apply(t,arguments)}function yt(){return gt.apply(null,arguments).exponent(.5)}function bt(){var t=[],e=g.yR;function n(n){if(null!=n&&!isNaN(n=+n))return e(((0,D.ZP)(t,n,1)-1)/(t.length-1))}return n.domain=function(e){if(!arguments.length)return t.slice();t=[];for(let n of e)null==n||isNaN(n=+n)||t.push(n);return t.sort(L.Z),n},n.interpolator=function(t){return arguments.length?(e=t,n):e},n.range=function(){return t.map(((n,r)=>e(r/(t.length-1))))},n.quantiles=function(e){return Array.from({length:e+1},((n,r)=>(0,P.ZP)(t,r/e)))},n.copy=function(){return bt(e).domain(t)},s.O.apply(n,arguments)}var vt=n(9444);function wt(){var t,e,n,r,s,o,i,a=0,l=.5,c=1,u=1,f=g.yR,d=!1;function h(t){return isNaN(t=+t)?i:(t=.5+((t=+o(t))-e)*(u*t<u*e?r:s),f(d?Math.max(0,Math.min(1,t)):t))}function p(t){return function(e){var n,r,s;return arguments.length?([n,r,s]=e,f=(0,vt.Z)(t,[n,r,s]),h):[f(0),f(.5),f(1)]}}return h.domain=function(i){return arguments.length?([a,l,c]=i,t=o(a=+a),e=o(l=+l),n=o(c=+c),r=t===e?0:.5/(e-t),s=e===n?0:.5/(n-e),u=e<t?-1:1,h):[a,l,c]},h.clamp=function(t){return arguments.length?(d=!!t,h):d},h.interpolator=function(t){return arguments.length?(f=t,h):f},h.range=p(ct.Z),h.rangeRound=p(ut.Z),h.unknown=function(t){return arguments.length?(i=t,h):i},function(i){return o=i,t=i(a),e=i(l),n=i(c),r=t===e?0:.5/(e-t),s=e===n?0:.5/(n-e),u=e<t?-1:1,h}}function _t(){var t=(0,c.Q)(wt()(g.yR));return t.copy=function(){return dt(t,_t())},s.O.apply(t,arguments)}function xt(){var t=k(wt()).domain([.1,1,10]);return t.copy=function(){return dt(t,xt()).base(t.base())},s.O.apply(t,arguments)}function kt(){var t=A(wt());return t.copy=function(){return dt(t,kt()).constant(t.constant())},s.O.apply(t,arguments)}function qt(){var t=E(wt());return t.copy=function(){return dt(t,qt()).exponent(t.exponent())},s.O.apply(t,arguments)}function Nt(){return qt.apply(null,arguments).exponent(.5)}var St=n(8902)},2998:(t,e,n)=>{"use strict";function r(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t)}return this}function s(t,e){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof e?this.interpolator(e):this.range(e)}return this}n.d(e,{O:()=>s,o:()=>r})},9064:(t,e,n)=>{"use strict";n.d(e,{Q:()=>a,Z:()=>l});var r=n(6106),s=n(1303),o=n(2998),i=n(8902);function a(t){var e=t.domain;return t.ticks=function(t){var n=e();return(0,r.ZP)(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return(0,i.Z)(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var s,o,i=e(),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,r.G9)(c,u,n))===s)return i[a]=c,i[l]=u,e(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}s=o}return t},t}function l(){var t=(0,s.ZP)();return t.copy=function(){return(0,s.JG)(t,l())},o.o.apply(t,arguments),a(t)}},9120:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{Z:()=>r})},5540:(t,e,n)=>{"use strict";n.d(e,{O:()=>o,Z:()=>i});var r=n(8828),s=n(2998);const o=Symbol("implicit");function i(){var t=new r.L,e=[],n=[],a=o;function l(r){let s=t.get(r);if(void 0===s){if(a!==o)return a;t.set(r,s=e.push(r)-1)}return n[s%n.length]}return l.domain=function(n){if(!arguments.length)return e.slice();e=[],t=new r.L;for(const r of n)t.has(r)||t.set(r,e.push(r)-1);return l},l.range=function(t){return arguments.length?(n=Array.from(t),l):n.slice()},l.unknown=function(t){return arguments.length?(a=t,l):a},l.copy=function(){return i(e,n).unknown(a)},s.o.apply(l,arguments),l}},8902:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=n(6106),s=n(7259),o=n(3150),i=n(2163),a=n(3621),l=n(9680);function c(t,e,n,c){var u,f=(0,r.ly)(t,e,n);switch((c=(0,s.Z)(null==c?",f":c)).type){case"s":var d=Math.max(Math.abs(t),Math.abs(e));return null!=c.precision||isNaN(u=(0,o.Z)(f,d))||(c.precision=u),(0,i.jH)(c,d);case"":case"e":case"g":case"p":case"r":null!=c.precision||isNaN(u=(0,a.Z)(f,Math.max(Math.abs(t),Math.abs(e))))||(c.precision=u-("e"===c.type));break;case"f":case"%":null!=c.precision||isNaN(u=(0,l.Z)(f))||(c.precision=u-2*("%"===c.type))}return(0,i.WU)(c)}},1852:(t,e,n)=>{"use strict";n.d(e,{Z1:()=>o,ZP:()=>c,g0:()=>i,i$:()=>s,wp:()=>a});var r,s,o,i,a,l=n(3015);function c(t){return r=(0,l.Z)(t),s=r.format,o=r.parse,i=r.utcFormat,a=r.utcParse,r}c({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})},3015:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(1887),s=n(7445),o=n(6018),i=n(8467),a=n(2311),l=n(4552);function c(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function u(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function f(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function d(t){var e=t.dateTime,n=t.date,a=t.time,l=t.periods,d=t.days,p=t.shortDays,m=t.months,g=t.shortMonths,y=v(l),b=w(l),X=v(d),bt=w(d),Ct=v(p),jt=w(p),Et=v(m),Ot=w(m),It=v(g),Rt=w(g),Ft={a:function(t){return p[t.getDay()]},A:function(t){return d[t.getDay()]},b:function(t){return g[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:null,d:z,e:z,f:J,g:rt,G:ot,H:Z,I:U,j:B,L:G,m:H,M:W,p:function(t){return l[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:Mt,s:Tt,S:V,u:Y,U:K,V:Q,w:tt,W:et,x:null,X:null,y:nt,Y:st,Z:it,"%":At},Pt={a:function(t){return p[t.getUTCDay()]},A:function(t){return d[t.getUTCDay()]},b:function(t){return g[t.getUTCMonth()]},B:function(t){return m[t.getUTCMonth()]},c:null,d:at,e:at,f:dt,g:kt,G:Nt,H:lt,I:ct,j:ut,L:ft,m:ht,M:pt,p:function(t){return l[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:Mt,s:Tt,S:mt,u:gt,U:yt,V:vt,w:wt,W:_t,x:null,X:null,y:xt,Y:qt,Z:St,"%":At},Dt={a:function(t,e,n){var r=Ct.exec(e.slice(n));return r?(t.w=jt.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(t,e,n){var r=X.exec(e.slice(n));return r?(t.w=bt.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(t,e,n){var r=It.exec(e.slice(n));return r?(t.m=Rt.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(t,e,n){var r=Et.exec(e.slice(n));return r?(t.m=Ot.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(t,n,r){return zt(t,e,n,r)},d:j,e:j,f:P,g:A,G:S,H:O,I:O,j:E,L:F,m:C,M:I,p:function(t,e,n){var r=y.exec(e.slice(n));return r?(t.p=b.get(r[0].toLowerCase()),n+r[0].length):-1},q:T,Q:L,s:$,S:R,u:x,U:k,V:q,w:_,W:N,x:function(t,e,r){return zt(t,n,e,r)},X:function(t,e,n){return zt(t,a,e,n)},y:A,Y:S,Z:M,"%":D};function Lt(t,e){return function(n){var r,s,o,i=[],a=-1,l=0,c=t.length;for(n instanceof Date||(n=new Date(+n));++a<c;)37===t.charCodeAt(a)&&(i.push(t.slice(l,a)),null!=(s=h[r=t.charAt(++a)])?r=t.charAt(++a):s="e"===r?" ":"0",(o=e[r])&&(r=o(n,s)),i.push(r),l=a+1);return i.push(t.slice(l,a)),i.join("")}}function $t(t,e){return function(n){var a,l,d=f(1900,void 0,1);if(zt(d,t,n+="",0)!=n.length)return null;if("Q"in d)return new Date(d.Q);if("s"in d)return new Date(1e3*d.s+("L"in d?d.L:0));if(e&&!("Z"in d)&&(d.Z=0),"p"in d&&(d.H=d.H%12+12*d.p),void 0===d.m&&(d.m="q"in d?d.q:0),"V"in d){if(d.V<1||d.V>53)return null;"w"in d||(d.w=1),"Z"in d?(l=(a=u(f(d.y,0,1))).getUTCDay(),a=l>4||0===l?r.l6.ceil(a):(0,r.l6)(a),a=s.Z.offset(a,7*(d.V-1)),d.y=a.getUTCFullYear(),d.m=a.getUTCMonth(),d.d=a.getUTCDate()+(d.w+6)%7):(l=(a=c(f(d.y,0,1))).getDay(),a=l>4||0===l?o.wA.ceil(a):(0,o.wA)(a),a=i.Z.offset(a,7*(d.V-1)),d.y=a.getFullYear(),d.m=a.getMonth(),d.d=a.getDate()+(d.w+6)%7)}else("W"in d||"U"in d)&&("w"in d||(d.w="u"in d?d.u%7:"W"in d?1:0),l="Z"in d?u(f(d.y,0,1)).getUTCDay():c(f(d.y,0,1)).getDay(),d.m=0,d.d="W"in d?(d.w+6)%7+7*d.W-(l+5)%7:d.w+7*d.U-(l+6)%7);return"Z"in d?(d.H+=d.Z/100|0,d.M+=d.Z%100,u(d)):c(d)}}function zt(t,e,n,r){for(var s,o,i=0,a=e.length,l=n.length;i<a;){if(r>=l)return-1;if(37===(s=e.charCodeAt(i++))){if(s=e.charAt(i++),!(o=Dt[s in h?e.charAt(i++):s])||(r=o(t,n,r))<0)return-1}else if(s!=n.charCodeAt(r++))return-1}return r}return Ft.x=Lt(n,Ft),Ft.X=Lt(a,Ft),Ft.c=Lt(e,Ft),Pt.x=Lt(n,Pt),Pt.X=Lt(a,Pt),Pt.c=Lt(e,Pt),{format:function(t){var e=Lt(t+="",Ft);return e.toString=function(){return t},e},parse:function(t){var e=$t(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=Lt(t+="",Pt);return e.toString=function(){return t},e},utcParse:function(t){var e=$t(t+="",!0);return e.toString=function(){return t},e}}}var h={"-":"",_:" ",0:"0"},p=/^\s*\d+/,m=/^%/,g=/[\\^$*+?|[\]().{}]/g;function y(t,e,n){var r=t<0?"-":"",s=(r?-t:t)+"",o=s.length;return r+(o<n?new Array(n-o+1).join(e)+s:s)}function b(t){return t.replace(g,"\\$&")}function v(t){return new RegExp("^(?:"+t.map(b).join("|")+")","i")}function w(t){return new Map(t.map(((t,e)=>[t.toLowerCase(),e])))}function _(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function x(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function k(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function q(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function N(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function S(t,e,n){var r=p.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function A(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function M(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function T(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function C(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function j(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function E(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function O(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function I(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function R(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function F(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function P(t,e,n){var r=p.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function D(t,e,n){var r=m.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function L(t,e,n){var r=p.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function $(t,e,n){var r=p.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function z(t,e){return y(t.getDate(),e,2)}function Z(t,e){return y(t.getHours(),e,2)}function U(t,e){return y(t.getHours()%12||12,e,2)}function B(t,e){return y(1+i.Z.count((0,a.Z)(t),t),e,3)}function G(t,e){return y(t.getMilliseconds(),e,3)}function J(t,e){return G(t,e)+"000"}function H(t,e){return y(t.getMonth()+1,e,2)}function W(t,e){return y(t.getMinutes(),e,2)}function V(t,e){return y(t.getSeconds(),e,2)}function Y(t){var e=t.getDay();return 0===e?7:e}function K(t,e){return y(o.OM.count((0,a.Z)(t)-1,t),e,2)}function X(t){var e=t.getDay();return e>=4||0===e?(0,o.bL)(t):o.bL.ceil(t)}function Q(t,e){return t=X(t),y(o.bL.count((0,a.Z)(t),t)+(4===(0,a.Z)(t).getDay()),e,2)}function tt(t){return t.getDay()}function et(t,e){return y(o.wA.count((0,a.Z)(t)-1,t),e,2)}function nt(t,e){return y(t.getFullYear()%100,e,2)}function rt(t,e){return y((t=X(t)).getFullYear()%100,e,2)}function st(t,e){return y(t.getFullYear()%1e4,e,4)}function ot(t,e){var n=t.getDay();return y((t=n>=4||0===n?(0,o.bL)(t):o.bL.ceil(t)).getFullYear()%1e4,e,4)}function it(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+y(e/60|0,"0",2)+y(e%60,"0",2)}function at(t,e){return y(t.getUTCDate(),e,2)}function lt(t,e){return y(t.getUTCHours(),e,2)}function ct(t,e){return y(t.getUTCHours()%12||12,e,2)}function ut(t,e){return y(1+s.Z.count((0,l.Z)(t),t),e,3)}function ft(t,e){return y(t.getUTCMilliseconds(),e,3)}function dt(t,e){return ft(t,e)+"000"}function ht(t,e){return y(t.getUTCMonth()+1,e,2)}function pt(t,e){return y(t.getUTCMinutes(),e,2)}function mt(t,e){return y(t.getUTCSeconds(),e,2)}function gt(t){var e=t.getUTCDay();return 0===e?7:e}function yt(t,e){return y(r.Ox.count((0,l.Z)(t)-1,t),e,2)}function bt(t){var e=t.getUTCDay();return e>=4||0===e?(0,r.hB)(t):r.hB.ceil(t)}function vt(t,e){return t=bt(t),y(r.hB.count((0,l.Z)(t),t)+(4===(0,l.Z)(t).getUTCDay()),e,2)}function wt(t){return t.getUTCDay()}function _t(t,e){return y(r.l6.count((0,l.Z)(t)-1,t),e,2)}function xt(t,e){return y(t.getUTCFullYear()%100,e,2)}function kt(t,e){return y((t=bt(t)).getUTCFullYear()%100,e,2)}function qt(t,e){return y(t.getUTCFullYear()%1e4,e,4)}function Nt(t,e){var n=t.getUTCDay();return y((t=n>=4||0===n?(0,r.hB)(t):r.hB.ceil(t)).getUTCFullYear()%1e4,e,4)}function St(){return"+0000"}function At(){return"%"}function Mt(t){return+t}function Tt(t){return Math.floor(+t/1e3)}},8467:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,a:()=>a});var r=n(3606),s=n(9123),o=(0,r.Z)((t=>t.setHours(0,0,0,0)),((t,e)=>t.setDate(t.getDate()+e)),((t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*s.yB)/s.UD),(t=>t.getDate()-1));const i=o;var a=o.range},9123:(t,e,n)=>{"use strict";n.d(e,{UD:()=>i,Y2:()=>o,Ym:()=>r,iM:()=>a,jz:()=>l,qz:()=>c,yB:()=>s});const r=1e3,s=60*r,o=60*s,i=24*o,a=7*i,l=30*i,c=365*i},6596:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,i:()=>a});var r=n(3606),s=n(9123),o=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*s.Ym-t.getMinutes()*s.yB)}),(function(t,e){t.setTime(+t+e*s.Y2)}),(function(t,e){return(e-t)/s.Y2}),(function(t){return t.getHours()}));const i=o;var a=o.range},3606:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=new Date,s=new Date;function o(t,e,n,i){function a(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return a.floor=function(e){return t(e=new Date(+e)),e},a.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},a.round=function(t){var e=a(t),n=a.ceil(t);return t-e<n-t?e:n},a.offset=function(t,n){return e(t=new Date(+t),null==n?1:Math.floor(n)),t},a.range=function(n,r,s){var o,i=[];if(n=a.ceil(n),s=null==s?1:Math.floor(s),!(n<r&&s>0))return i;do{i.push(o=new Date(+n)),e(n,s),t(n)}while(o<n&&n<r);return i},a.filter=function(n){return o((function(e){if(e>=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(a.count=function(e,o){return r.setTime(+e),s.setTime(+o),t(r),t(s),Math.floor(n(r,s))},a.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?a.filter(i?function(e){return i(e)%t==0}:function(e){return a.count(0,e)%t==0}):a:null}),a}},8383:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,m:()=>i});var r=n(3606),s=(0,r.Z)((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));s.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?(0,r.Z)((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):s:null};const o=s;var i=s.range},2991:(t,e,n)=>{"use strict";n.d(e,{L:()=>a,Z:()=>i});var r=n(3606),s=n(9123),o=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*s.Ym)}),(function(t,e){t.setTime(+t+e*s.yB)}),(function(t,e){return(e-t)/s.yB}),(function(t){return t.getMinutes()}));const i=o;var a=o.range},7905:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,e:()=>o});var r=(0,n(3606).Z)((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const s=r;var o=r.range},1343:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,m:()=>a});var r=n(3606),s=n(9123),o=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*s.Ym)}),(function(t,e){return(e-t)/s.Ym}),(function(t){return t.getUTCSeconds()}));const i=o;var a=o.range},7150:(t,e,n)=>{"use strict";n.d(e,{WG:()=>_,_g:()=>q,jK:()=>k,jo:()=>x});var r=n(3292),s=n(6106),o=n(9123),i=n(8383),a=n(1343),l=n(2991),c=n(6596),u=n(8467),f=n(6018),d=n(7905),h=n(2311),p=n(8593),m=n(8927),g=n(7445),y=n(1887),b=n(7351),v=n(4552);function w(t,e,n,l,c,u){const f=[[a.Z,1,o.Ym],[a.Z,5,5*o.Ym],[a.Z,15,15*o.Ym],[a.Z,30,30*o.Ym],[u,1,o.yB],[u,5,5*o.yB],[u,15,15*o.yB],[u,30,30*o.yB],[c,1,o.Y2],[c,3,3*o.Y2],[c,6,6*o.Y2],[c,12,12*o.Y2],[l,1,o.UD],[l,2,2*o.UD],[n,1,o.iM],[e,1,o.jz],[e,3,3*o.jz],[t,1,o.qz]];function d(e,n,a){const l=Math.abs(n-e)/a,c=(0,r.Z)((([,,t])=>t)).right(f,l);if(c===f.length)return t.every((0,s.ly)(e/o.qz,n/o.qz,a));if(0===c)return i.Z.every(Math.max((0,s.ly)(e,n,a),1));const[u,d]=f[l/f[c-1][2]<f[c][2]/l?c-1:c];return u.every(d)}return[function(t,e,n){const r=e<t;r&&([t,e]=[e,t]);const s=n&&"function"==typeof n.range?n:d(t,e,n),o=s?s.range(t,+e+1):[];return r?o.reverse():o},d]}const[_,x]=w(v.Z,b.Z,y.Ox,g.Z,m.Z,p.Z),[k,q]=w(h.Z,d.Z,f.OM,u.Z,c.Z,l.Z)},7445:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,y:()=>a});var r=n(3606),s=n(9123),o=(0,r.Z)((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/s.UD}),(function(t){return t.getUTCDate()-1}));const i=o;var a=o.range},8927:(t,e,n)=>{"use strict";n.d(e,{X:()=>a,Z:()=>i});var r=n(3606),s=n(9123),o=(0,r.Z)((function(t){t.setUTCMinutes(0,0,0)}),(function(t,e){t.setTime(+t+e*s.Y2)}),(function(t,e){return(e-t)/s.Y2}),(function(t){return t.getUTCHours()}));const i=o;var a=o.range},8593:(t,e,n)=>{"use strict";n.d(e,{N:()=>a,Z:()=>i});var r=n(3606),s=n(9123),o=(0,r.Z)((function(t){t.setUTCSeconds(0,0)}),(function(t,e){t.setTime(+t+e*s.yB)}),(function(t,e){return(e-t)/s.yB}),(function(t){return t.getUTCMinutes()}));const i=o;var a=o.range},7351:(t,e,n)=>{"use strict";n.d(e,{K:()=>o,Z:()=>s});var r=(0,n(3606).Z)((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e)}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()}));const s=r;var o=r.range},1887:(t,e,n)=>{"use strict";n.d(e,{$3:()=>p,DK:()=>m,J1:()=>l,Ox:()=>i,QQ:()=>f,Q_:()=>v,SU:()=>h,b3:()=>c,fz:()=>b,g4:()=>d,hB:()=>u,l6:()=>a,uy:()=>g,xj:()=>y});var r=n(3606),s=n(9123);function o(t){return(0,r.Z)((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/s.iM}))}var i=o(0),a=o(1),l=o(2),c=o(3),u=o(4),f=o(5),d=o(6),h=i.range,p=a.range,m=l.range,g=c.range,y=u.range,b=f.range,v=d.range},4552:(t,e,n)=>{"use strict";n.d(e,{D:()=>i,Z:()=>o});var r=n(3606),s=(0,r.Z)((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));s.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const o=s;var i=s.range},6018:(t,e,n)=>{"use strict";n.d(e,{$t:()=>y,EY:()=>d,Ff:()=>v,Ld:()=>g,OM:()=>i,aU:()=>m,b$:()=>b,bJ:()=>p,bL:()=>u,mC:()=>f,sy:()=>l,vm:()=>h,wA:()=>a,zg:()=>c});var r=n(3606),s=n(9123);function o(t){return(0,r.Z)((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*s.yB)/s.iM}))}var i=o(0),a=o(1),l=o(2),c=o(3),u=o(4),f=o(5),d=o(6),h=i.range,p=a.range,m=l.range,g=c.range,y=u.range,b=f.range,v=d.range},2311:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,g:()=>i});var r=n(3606),s=(0,r.Z)((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));s.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const o=s;var i=s.range},3016:(t,e,n)=>{"use strict";n.r(e),n.d(e,{Adder:()=>r.Adder,Delaunay:()=>Qs,FormatSpecifier:()=>ta.v,InternMap:()=>r.InternMap,InternSet:()=>r.InternSet,Node:()=>ld.NB,Voronoi:()=>Hs,ZoomTransform:()=>Rb,active:()=>gn,arc:()=>eg,area:()=>cg,areaRadial:()=>bg,ascending:()=>r.ascending,autoType:()=>bo,axisBottom:()=>b,axisLeft:()=>v,axisRight:()=>y,axisTop:()=>g,bin:()=>r.bin,bisect:()=>r.bisect,bisectCenter:()=>r.bisectCenter,bisectLeft:()=>r.bisectLeft,bisectRight:()=>r.bisectRight,bisector:()=>r.bisector,blob:()=>ai,blur:()=>r.blur,blur2:()=>r.blur2,blurImage:()=>r.blurImage,brush:()=>Gn,brushSelection:()=>Zn,brushX:()=>Un,brushY:()=>Bn,buffer:()=>ci,chord:()=>nr,chordDirected:()=>sr,chordTranspose:()=>rr,cluster:()=>ad,color:()=>$e.ZP,contourDensity:()=>_s,contours:()=>ms,count:()=>r.count,create:()=>Cm,creator:()=>Nt,cross:()=>r.cross,csv:()=>pi,csvFormat:()=>fo,csvFormatBody:()=>ho,csvFormatRow:()=>mo,csvFormatRows:()=>po,csvFormatValue:()=>go,csvParse:()=>co,csvParseRows:()=>uo,cubehelix:()=>ns,cumsum:()=>r.cumsum,curveBasis:()=>ly,curveBasisClosed:()=>uy,curveBasisOpen:()=>dy,curveBumpX:()=>xg,curveBumpY:()=>kg,curveBundle:()=>py,curveCardinal:()=>yy,curveCardinalClosed:()=>vy,curveCardinalOpen:()=>_y,curveCatmullRom:()=>qy,curveCatmullRomClosed:()=>Sy,curveCatmullRomOpen:()=>My,curveLinear:()=>og,curveLinearClosed:()=>Cy,curveMonotoneX:()=>Dy,curveMonotoneY:()=>Ly,curveNatural:()=>Zy,curveStep:()=>By,curveStepAfter:()=>Jy,curveStepBefore:()=>Gy,descending:()=>r.descending,deviation:()=>r.deviation,difference:()=>r.difference,disjoint:()=>r.disjoint,dispatch:()=>N,drag:()=>io,dragDisable:()=>Bt,dragEnable:()=>Gt,dsv:()=>hi,dsvFormat:()=>ao.Z,easeBack:()=>ei,easeBackIn:()=>Qo,easeBackInOut:()=>ei,easeBackOut:()=>ti,easeBounce:()=>Yo,easeBounceIn:()=>Vo,easeBounceInOut:()=>Ko,easeBounceOut:()=>Yo,easeCircle:()=>Do,easeCircleIn:()=>Fo,easeCircleInOut:()=>Do,easeCircleOut:()=>Po,easeCubic:()=>dn,easeCubicIn:()=>un,easeCubicInOut:()=>dn,easeCubicOut:()=>fn,easeElastic:()=>si,easeElasticIn:()=>ri,easeElasticInOut:()=>oi,easeElasticOut:()=>si,easeExp:()=>Ro,easeExpIn:()=>Oo,easeExpInOut:()=>Ro,easeExpOut:()=>Io,easeLinear:()=>wo,easePoly:()=>So,easePolyIn:()=>qo,easePolyInOut:()=>So,easePolyOut:()=>No,easeQuad:()=>ko,easeQuadIn:()=>_o,easeQuadInOut:()=>ko,easeQuadOut:()=>xo,easeSin:()=>jo,easeSinIn:()=>To,easeSinInOut:()=>jo,easeSinOut:()=>Co,every:()=>r.every,extent:()=>r.extent,fcumsum:()=>r.fcumsum,filter:()=>r.filter,flatGroup:()=>r.flatGroup,flatRollup:()=>r.flatRollup,forceCenter:()=>ki,forceCollide:()=>Fi,forceLink:()=>Li,forceManyBody:()=>Wi,forceRadial:()=>Vi,forceSimulation:()=>Hi,forceX:()=>Yi,forceY:()=>Ki,format:()=>Xi.WU,formatDefaultLocale:()=>Xi.ZP,formatLocale:()=>Qi.Z,formatPrefix:()=>Xi.jH,formatSpecifier:()=>ta.Z,fsum:()=>r.fsum,geoAlbers:()=>xf,geoAlbersUsa:()=>kf,geoArea:()=>ol,geoAzimuthalEqualArea:()=>Af,geoAzimuthalEqualAreaRaw:()=>Sf,geoAzimuthalEquidistant:()=>Tf,geoAzimuthalEquidistantRaw:()=>Mf,geoBounds:()=>$l,geoCentroid:()=>Xl,geoCircle:()=>cc,geoClipAntimeridian:()=>_c,geoClipCircle:()=>xc,geoClipExtent:()=>Cc,geoClipRectangle:()=>Tc,geoConicConformal:()=>Rf,geoConicConformalRaw:()=>If,geoConicEqualArea:()=>_f,geoConicEqualAreaRaw:()=>wf,geoConicEquidistant:()=>Lf,geoConicEquidistantRaw:()=>Df,geoContains:()=>Hc,geoDistance:()=>Dc,geoEqualEarth:()=>Jf,geoEqualEarthRaw:()=>Gf,geoEquirectangular:()=>Pf,geoEquirectangularRaw:()=>Ff,geoGnomonic:()=>Wf,geoGnomonicRaw:()=>Hf,geoGraticule:()=>Kc,geoGraticule10:()=>Xc,geoIdentity:()=>Vf,geoInterpolate:()=>Qc,geoLength:()=>Rc,geoMercator:()=>jf,geoMercatorRaw:()=>Cf,geoNaturalEarth1:()=>Kf,geoNaturalEarth1Raw:()=>Yf,geoOrthographic:()=>Qf,geoOrthographicRaw:()=>Xf,geoPath:()=>nf,geoProjection:()=>yf,geoProjectionMutator:()=>bf,geoRotation:()=>ic,geoStereographic:()=>ed,geoStereographicRaw:()=>td,geoStream:()=>Ra,geoTransform:()=>rf,geoTransverseMercator:()=>rd,geoTransverseMercatorRaw:()=>nd,gray:()=>Fr,greatest:()=>r.greatest,greatestIndex:()=>r.greatestIndex,group:()=>r.group,groupSort:()=>r.groupSort,groups:()=>r.groups,hcl:()=>Gr,hierarchy:()=>ld.ZP,histogram:()=>r.histogram,hsl:()=>$e.Ym,html:()=>_i,image:()=>gi,index:()=>r.index,indexes:()=>r.indexes,interpolate:()=>Jt.Z,interpolateArray:()=>eh.Z,interpolateBasis:()=>nh.Z,interpolateBasisClosed:()=>rh.Z,interpolateBlues:()=>rm,interpolateBrBG:()=>mp,interpolateBuGn:()=>Op,interpolateBuPu:()=>Rp,interpolateCividis:()=>pm,interpolateCool:()=>ym,interpolateCubehelix:()=>_h,interpolateCubehelixDefault:()=>mm,interpolateCubehelixLong:()=>xh,interpolateDate:()=>sh.Z,interpolateDiscrete:()=>oh,interpolateGnBu:()=>Pp,interpolateGreens:()=>om,interpolateGreys:()=>am,interpolateHcl:()=>bh,interpolateHclLong:()=>vh,interpolateHsl:()=>ph,interpolateHslLong:()=>mh,interpolateHue:()=>ah,interpolateInferno:()=>Mm,interpolateLab:()=>gh,interpolateMagma:()=>Am,interpolateNumber:()=>Ce.Z,interpolateNumberArray:()=>lh.Z,interpolateObject:()=>ch.Z,interpolateOrRd:()=>Lp,interpolateOranges:()=>hm,interpolatePRGn:()=>yp,interpolatePiYG:()=>vp,interpolatePlasma:()=>Tm,interpolatePuBu:()=>Up,interpolatePuBuGn:()=>zp,interpolatePuOr:()=>_p,interpolatePuRd:()=>Gp,interpolatePurples:()=>cm,interpolateRainbow:()=>vm,interpolateRdBu:()=>kp,interpolateRdGy:()=>Np,interpolateRdPu:()=>Hp,interpolateRdYlBu:()=>Ap,interpolateRdYlGn:()=>Tp,interpolateReds:()=>fm,interpolateRgb:()=>ze.ZP,interpolateRgbBasis:()=>ze.hD,interpolateRgbBasisClosed:()=>ze.YD,interpolateRound:()=>uh.Z,interpolateSinebow:()=>km,interpolateSpectral:()=>jp,interpolateString:()=>Ze.Z,interpolateTransformCss:()=>Re,interpolateTransformSvg:()=>Fe,interpolateTurbo:()=>qm,interpolateViridis:()=>Sm,interpolateWarm:()=>gm,interpolateYlGn:()=>Kp,interpolateYlGnBu:()=>Vp,interpolateYlOrBr:()=>Qp,interpolateYlOrRd:()=>em,interpolateZoom:()=>dh,interrupt:()=>Me,intersection:()=>r.intersection,interval:()=>Eb,isoFormat:()=>Tb,isoParse:()=>jb,json:()=>bi,lab:()=>Pr,lch:()=>Br,least:()=>r.least,leastIndex:()=>r.leastIndex,line:()=>lg,lineRadial:()=>yg,link:()=>Ag,linkHorizontal:()=>Mg,linkRadial:()=>Cg,linkVertical:()=>Tg,local:()=>Em,map:()=>r.map,matcher:()=>j,max:()=>r.max,maxIndex:()=>r.maxIndex,mean:()=>r.mean,median:()=>r.median,medianIndex:()=>r.medianIndex,merge:()=>r.merge,min:()=>r.min,minIndex:()=>r.minIndex,mode:()=>r.mode,namespace:()=>J,namespaces:()=>G,nice:()=>r.nice,now:()=>ie,pack:()=>Ed,packEnclose:()=>gd,packSiblings:()=>Cd,pairs:()=>r.pairs,partition:()=>Dd,path:()=>dr,permute:()=>r.permute,pie:()=>dg,piecewise:()=>kh.Z,pointRadial:()=>vg,pointer:()=>Wt,pointers:()=>Im,polygonArea:()=>Nh,polygonCentroid:()=>Sh,polygonContains:()=>jh,polygonHull:()=>Ch,polygonLength:()=>Eh,precisionFixed:()=>ea.Z,precisionPrefix:()=>na.Z,precisionRound:()=>ra.Z,quadtree:()=>Mi,quantile:()=>r.quantile,quantileIndex:()=>r.quantileIndex,quantileSorted:()=>r.quantileSorted,quantize:()=>qh,quickselect:()=>r.quickselect,radialArea:()=>bg,radialLine:()=>yg,randomBates:()=>Lh,randomBernoulli:()=>Zh,randomBeta:()=>Gh,randomBinomial:()=>Jh,randomCauchy:()=>Wh,randomExponential:()=>$h,randomGamma:()=>Bh,randomGeometric:()=>Uh,randomInt:()=>Rh,randomIrwinHall:()=>Dh,randomLcg:()=>tp,randomLogNormal:()=>Ph,randomLogistic:()=>Vh,randomNormal:()=>Fh,randomPareto:()=>zh,randomPoisson:()=>Yh,randomUniform:()=>Ih,randomWeibull:()=>Hh,range:()=>r.range,rank:()=>r.rank,reduce:()=>r.reduce,reverse:()=>r.reverse,rgb:()=>$e.B8,ribbon:()=>kr,ribbonArrow:()=>qr,rollup:()=>r.rollup,rollups:()=>r.rollups,scaleBand:()=>ep.scaleBand,scaleDiverging:()=>ep.scaleDiverging,scaleDivergingLog:()=>ep.scaleDivergingLog,scaleDivergingPow:()=>ep.scaleDivergingPow,scaleDivergingSqrt:()=>ep.scaleDivergingSqrt,scaleDivergingSymlog:()=>ep.scaleDivergingSymlog,scaleIdentity:()=>ep.scaleIdentity,scaleImplicit:()=>ep.scaleImplicit,scaleLinear:()=>ep.scaleLinear,scaleLog:()=>ep.scaleLog,scaleOrdinal:()=>ep.scaleOrdinal,scalePoint:()=>ep.scalePoint,scalePow:()=>ep.scalePow,scaleQuantile:()=>ep.scaleQuantile,scaleQuantize:()=>ep.scaleQuantize,scaleRadial:()=>ep.scaleRadial,scaleSequential:()=>ep.scaleSequential,scaleSequentialLog:()=>ep.scaleSequentialLog,scaleSequentialPow:()=>ep.scaleSequentialPow,scaleSequentialQuantile:()=>ep.scaleSequentialQuantile,scaleSequentialSqrt:()=>ep.scaleSequentialSqrt,scaleSequentialSymlog:()=>ep.scaleSequentialSymlog,scaleSqrt:()=>ep.scaleSqrt,scaleSymlog:()=>ep.scaleSymlog,scaleThreshold:()=>ep.scaleThreshold,scaleTime:()=>ep.scaleTime,scaleUtc:()=>ep.scaleUtc,scan:()=>r.scan,schemeAccent:()=>sp,schemeBlues:()=>nm,schemeBrBG:()=>pp,schemeBuGn:()=>Ep,schemeBuPu:()=>Ip,schemeCategory10:()=>np.Z,schemeDark2:()=>op,schemeGnBu:()=>Fp,schemeGreens:()=>sm,schemeGreys:()=>im,schemeOrRd:()=>Dp,schemeOranges:()=>dm,schemePRGn:()=>gp,schemePaired:()=>ip,schemePastel1:()=>ap,schemePastel2:()=>lp,schemePiYG:()=>bp,schemePuBu:()=>Zp,schemePuBuGn:()=>$p,schemePuOr:()=>wp,schemePuRd:()=>Bp,schemePurples:()=>lm,schemeRdBu:()=>xp,schemeRdGy:()=>qp,schemeRdPu:()=>Jp,schemeRdYlBu:()=>Sp,schemeRdYlGn:()=>Mp,schemeReds:()=>um,schemeSet1:()=>cp,schemeSet2:()=>up,schemeSet3:()=>fp,schemeSpectral:()=>Cp,schemeTableau10:()=>dp,schemeYlGn:()=>Yp,schemeYlGnBu:()=>Wp,schemeYlOrBr:()=>Xp,schemeYlOrRd:()=>tm,select:()=>Lt,selectAll:()=>Rm,selection:()=>Dt,selector:()=>A,selectorAll:()=>C,shuffle:()=>r.shuffle,shuffler:()=>r.shuffler,some:()=>r.some,sort:()=>r.sort,stack:()=>Ky,stackOffsetDiverging:()=>Qy,stackOffsetExpand:()=>Xy,stackOffsetNone:()=>Hy,stackOffsetSilhouette:()=>tb,stackOffsetWiggle:()=>eb,stackOrderAppearance:()=>nb,stackOrderAscending:()=>sb,stackOrderDescending:()=>ib,stackOrderInsideOut:()=>ab,stackOrderNone:()=>Wy,stackOrderReverse:()=>lb,stratify:()=>Ld.Z,style:()=>rt,subset:()=>r.subset,sum:()=>r.sum,superset:()=>r.superset,svg:()=>xi,symbol:()=>sy,symbolAsterisk:()=>Eg,symbolCircle:()=>Og,symbolCross:()=>Ig,symbolDiamond:()=>Pg,symbolDiamond2:()=>Dg,symbolPlus:()=>Lg,symbolSquare:()=>$g,symbolSquare2:()=>zg,symbolStar:()=>Gg,symbolTriangle:()=>Hg,symbolTriangle2:()=>Vg,symbolWye:()=>ty,symbolX:()=>ey,symbols:()=>ny,symbolsFill:()=>ny,symbolsStroke:()=>ry,text:()=>fi,thresholdFreedmanDiaconis:()=>r.thresholdFreedmanDiaconis,thresholdScott:()=>r.thresholdScott,thresholdSturges:()=>r.thresholdSturges,tickFormat:()=>ep.tickFormat,tickIncrement:()=>r.tickIncrement,tickStep:()=>r.tickStep,ticks:()=>r.ticks,timeDay:()=>pb.Z,timeDays:()=>pb.a,timeFormat:()=>Nb.i$,timeFormatDefaultLocale:()=>Nb.ZP,timeFormatLocale:()=>Sb.Z,timeFriday:()=>mb.mC,timeFridays:()=>mb.b$,timeHour:()=>hb.Z,timeHours:()=>hb.i,timeInterval:()=>cb.Z,timeMillisecond:()=>ub.Z,timeMilliseconds:()=>ub.m,timeMinute:()=>db.Z,timeMinutes:()=>db.L,timeMonday:()=>mb.wA,timeMondays:()=>mb.bJ,timeMonth:()=>gb.Z,timeMonths:()=>gb.e,timeParse:()=>Nb.Z1,timeSaturday:()=>mb.EY,timeSaturdays:()=>mb.Ff,timeSecond:()=>fb.Z,timeSeconds:()=>fb.m,timeSunday:()=>mb.OM,timeSundays:()=>mb.vm,timeThursday:()=>mb.bL,timeThursdays:()=>mb.$t,timeTickInterval:()=>qb._g,timeTicks:()=>qb.jK,timeTuesday:()=>mb.sy,timeTuesdays:()=>mb.aU,timeWednesday:()=>mb.zg,timeWednesdays:()=>mb.Ld,timeWeek:()=>mb.OM,timeWeeks:()=>mb.vm,timeYear:()=>yb.Z,timeYears:()=>yb.g,timeout:()=>pe,timer:()=>ce,timerFlush:()=>ue,transition:()=>an,transpose:()=>r.transpose,tree:()=>Jd,treemap:()=>Kd,treemapBinary:()=>Xd,treemapDice:()=>Pd,treemapResquarify:()=>th,treemapSlice:()=>Hd,treemapSliceDice:()=>Qd,treemapSquarify:()=>Yd,tsv:()=>mi,tsvFormat:()=>yo.vP,tsvFormatBody:()=>yo.uH,tsvFormatRow:()=>yo.Hf,tsvFormatRows:()=>yo.n5,tsvFormatValue:()=>yo.sS,tsvParse:()=>yo.tJ,tsvParseRows:()=>yo.E0,union:()=>r.union,utcDay:()=>wb.Z,utcDays:()=>wb.y,utcFormat:()=>Nb.g0,utcFriday:()=>_b.QQ,utcFridays:()=>_b.fz,utcHour:()=>vb.Z,utcHours:()=>vb.X,utcMillisecond:()=>ub.Z,utcMilliseconds:()=>ub.m,utcMinute:()=>bb.Z,utcMinutes:()=>bb.N,utcMonday:()=>_b.l6,utcMondays:()=>_b.$3,utcMonth:()=>xb.Z,utcMonths:()=>xb.K,utcParse:()=>Nb.wp,utcSaturday:()=>_b.g4,utcSaturdays:()=>_b.Q_,utcSecond:()=>fb.Z,utcSeconds:()=>fb.m,utcSunday:()=>_b.Ox,utcSundays:()=>_b.SU,utcThursday:()=>_b.hB,utcThursdays:()=>_b.xj,utcTickInterval:()=>qb.jo,utcTicks:()=>qb.WG,utcTuesday:()=>_b.J1,utcTuesdays:()=>_b.DK,utcWednesday:()=>_b.b3,utcWednesdays:()=>_b.uy,utcWeek:()=>_b.Ox,utcWeeks:()=>_b.SU,utcYear:()=>kb.Z,utcYears:()=>kb.D,variance:()=>r.variance,window:()=>Q,xml:()=>wi,zip:()=>r.zip,zoom:()=>Jb,zoomIdentity:()=>Fb,zoomTransform:()=>Pb});var r=n(9060);function s(t){return t}var o=1,i=2,a=3,l=4,c=1e-6;function u(t){return"translate("+t+",0)"}function f(t){return"translate(0,"+t+")"}function d(t){return e=>+t(e)}function h(t,e){return e=Math.max(0,t.bandwidth()-2*e)/2,t.round()&&(e=Math.round(e)),n=>+t(n)+e}function p(){return!this.__axis}function m(t,e){var n=[],r=null,m=null,g=6,y=6,b=3,v="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,w=t===o||t===l?-1:1,_=t===l||t===i?"x":"y",x=t===o||t===a?u:f;function k(u){var f=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,k=null==m?e.tickFormat?e.tickFormat.apply(e,n):s:m,q=Math.max(g,0)+b,N=e.range(),S=+N[0]+v,A=+N[N.length-1]+v,M=(e.bandwidth?h:d)(e.copy(),v),T=u.selection?u.selection():u,C=T.selectAll(".domain").data([null]),j=T.selectAll(".tick").data(f,e).order(),E=j.exit(),O=j.enter().append("g").attr("class","tick"),I=j.select("line"),R=j.select("text");C=C.merge(C.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),j=j.merge(O),I=I.merge(O.append("line").attr("stroke","currentColor").attr(_+"2",w*g)),R=R.merge(O.append("text").attr("fill","currentColor").attr(_,w*q).attr("dy",t===o?"0em":t===a?"0.71em":"0.32em")),u!==T&&(C=C.transition(u),j=j.transition(u),I=I.transition(u),R=R.transition(u),E=E.transition(u).attr("opacity",c).attr("transform",(function(t){return isFinite(t=M(t))?x(t+v):this.getAttribute("transform")})),O.attr("opacity",c).attr("transform",(function(t){var e=this.parentNode.__axis;return x((e&&isFinite(e=e(t))?e:M(t))+v)}))),E.remove(),C.attr("d",t===l||t===i?y?"M"+w*y+","+S+"H"+v+"V"+A+"H"+w*y:"M"+v+","+S+"V"+A:y?"M"+S+","+w*y+"V"+v+"H"+A+"V"+w*y:"M"+S+","+v+"H"+A),j.attr("opacity",1).attr("transform",(function(t){return x(M(t)+v)})),I.attr(_+"2",w*g),R.attr(_,w*q).text(k),T.filter(p).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===i?"start":t===l?"end":"middle"),T.each((function(){this.__axis=M}))}return k.scale=function(t){return arguments.length?(e=t,k):e},k.ticks=function(){return n=Array.from(arguments),k},k.tickArguments=function(t){return arguments.length?(n=null==t?[]:Array.from(t),k):n.slice()},k.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),k):r&&r.slice()},k.tickFormat=function(t){return arguments.length?(m=t,k):m},k.tickSize=function(t){return arguments.length?(g=y=+t,k):g},k.tickSizeInner=function(t){return arguments.length?(g=+t,k):g},k.tickSizeOuter=function(t){return arguments.length?(y=+t,k):y},k.tickPadding=function(t){return arguments.length?(b=+t,k):b},k.offset=function(t){return arguments.length?(v=+t,k):v},k}function g(t){return m(o,t)}function y(t){return m(i,t)}function b(t){return m(a,t)}function v(t){return m(l,t)}var w={value:()=>{}};function _(){for(var t,e=0,n=arguments.length,r={};e<n;++e){if(!(t=arguments[e]+"")||t in r||/[\s.]/.test(t))throw new Error("illegal type: "+t);r[t]=[]}return new x(r)}function x(t){this._=t}function k(t,e){for(var n,r=0,s=t.length;r<s;++r)if((n=t[r]).name===e)return n.value}function q(t,e,n){for(var r=0,s=t.length;r<s;++r)if(t[r].name===e){t[r]=w,t=t.slice(0,r).concat(t.slice(r+1));break}return null!=n&&t.push({name:e,value:n}),t}x.prototype=_.prototype={constructor:x,on:function(t,e){var n,r,s=this._,o=(r=s,(t+"").trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");if(n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}}))),i=-1,a=o.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++i<a;)if(n=(t=o[i]).type)s[n]=q(s[n],t.name,e);else if(null==e)for(n in s)s[n]=q(s[n],t.name,null);return this}for(;++i<a;)if((n=(t=o[i]).type)&&(n=k(s[n],t.name)))return n},copy:function(){var t={},e=this._;for(var n in e)t[n]=e[n].slice();return new x(t)},call:function(t,e){if((n=arguments.length-2)>0)for(var n,r,s=new Array(n),o=0;o<n;++o)s[o]=arguments[o+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(o=0,n=(r=this._[t]).length;o<n;++o)r[o].value.apply(e,s)},apply:function(t,e,n){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var r=this._[t],s=0,o=r.length;s<o;++s)r[s].value.apply(e,n)}};const N=_;function S(){}function A(t){return null==t?S:function(){return this.querySelector(t)}}function M(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function T(){return[]}function C(t){return null==t?T:function(){return this.querySelectorAll(t)}}function j(t){return function(){return this.matches(t)}}function E(t){return function(e){return e.matches(t)}}var O=Array.prototype.find;function I(){return this.firstElementChild}var R=Array.prototype.filter;function F(){return Array.from(this.children)}function P(t){return new Array(t.length)}function D(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}function L(t,e,n,r,s,o){for(var i,a=0,l=e.length,c=o.length;a<c;++a)(i=e[a])?(i.__data__=o[a],r[a]=i):n[a]=new D(t,o[a]);for(;a<l;++a)(i=e[a])&&(s[a]=i)}function $(t,e,n,r,s,o,i){var a,l,c,u=new Map,f=e.length,d=o.length,h=new Array(f);for(a=0;a<f;++a)(l=e[a])&&(h[a]=c=i.call(l,l.__data__,a,e)+"",u.has(c)?s[a]=l:u.set(c,l));for(a=0;a<d;++a)c=i.call(t,o[a],a,o)+"",(l=u.get(c))?(r[a]=l,l.__data__=o[a],u.delete(c)):n[a]=new D(t,o[a]);for(a=0;a<f;++a)(l=e[a])&&u.get(h[a])===l&&(s[a]=l)}function z(t){return t.__data__}function Z(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function U(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}D.prototype={constructor:D,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var B="http://www.w3.org/1999/xhtml";const G={svg:"http://www.w3.org/2000/svg",xhtml:B,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function J(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),G.hasOwnProperty(e)?{space:G[e],local:t}:t}function H(t){return function(){this.removeAttribute(t)}}function W(t){return function(){this.removeAttributeNS(t.space,t.local)}}function V(t,e){return function(){this.setAttribute(t,e)}}function Y(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function K(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function X(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function Q(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function tt(t){return function(){this.style.removeProperty(t)}}function et(t,e,n){return function(){this.style.setProperty(t,e,n)}}function nt(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function rt(t,e){return t.style.getPropertyValue(e)||Q(t).getComputedStyle(t,null).getPropertyValue(e)}function st(t){return function(){delete this[t]}}function ot(t,e){return function(){this[t]=e}}function it(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function at(t){return t.trim().split(/^|\s+/)}function lt(t){return t.classList||new ct(t)}function ct(t){this._node=t,this._names=at(t.getAttribute("class")||"")}function ut(t,e){for(var n=lt(t),r=-1,s=e.length;++r<s;)n.add(e[r])}function ft(t,e){for(var n=lt(t),r=-1,s=e.length;++r<s;)n.remove(e[r])}function dt(t){return function(){ut(this,t)}}function ht(t){return function(){ft(this,t)}}function pt(t,e){return function(){(e.apply(this,arguments)?ut:ft)(this,t)}}function mt(){this.textContent=""}function gt(t){return function(){this.textContent=t}}function yt(t){return function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}}function bt(){this.innerHTML=""}function vt(t){return function(){this.innerHTML=t}}function wt(t){return function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}}function _t(){this.nextSibling&&this.parentNode.appendChild(this)}function xt(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function kt(t){return function(){var e=this.ownerDocument,n=this.namespaceURI;return n===B&&e.documentElement.namespaceURI===B?e.createElement(t):e.createElementNS(n,t)}}function qt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Nt(t){var e=J(t);return(e.local?qt:kt)(e)}function St(){return null}function At(){var t=this.parentNode;t&&t.removeChild(this)}function Mt(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function Tt(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function Ct(t){return function(){var e=this.__on;if(e){for(var n,r=0,s=-1,o=e.length;r<o;++r)n=e[r],t.type&&n.type!==t.type||n.name!==t.name?e[++s]=n:this.removeEventListener(n.type,n.listener,n.options);++s?e.length=s:delete this.__on}}}function jt(t,e,n){return function(){var r,s=this.__on,o=function(t){return function(e){t.call(this,e,this.__data__)}}(e);if(s)for(var i=0,a=s.length;i<a;++i)if((r=s[i]).type===t.type&&r.name===t.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=o,r.options=n),void(r.value=e);this.addEventListener(t.type,o,n),r={type:t.type,name:t.name,value:e,listener:o,options:n},s?s.push(r):this.__on=[r]}}function Et(t,e,n){var r=Q(t),s=r.CustomEvent;"function"==typeof s?s=new s(e,n):(s=r.document.createEvent("Event"),n?(s.initEvent(e,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(e,!1,!1)),t.dispatchEvent(s)}function Ot(t,e){return function(){return Et(this,t,e)}}function It(t,e){return function(){return Et(this,t,e.apply(this,arguments))}}ct.prototype={add:function(t){this._names.indexOf(t)<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Rt=[null];function Ft(t,e){this._groups=t,this._parents=e}function Pt(){return new Ft([[document.documentElement]],Rt)}Ft.prototype=Pt.prototype={constructor:Ft,select:function(t){"function"!=typeof t&&(t=A(t));for(var e=this._groups,n=e.length,r=new Array(n),s=0;s<n;++s)for(var o,i,a=e[s],l=a.length,c=r[s]=new Array(l),u=0;u<l;++u)(o=a[u])&&(i=t.call(o,o.__data__,u,a))&&("__data__"in o&&(i.__data__=o.__data__),c[u]=i);return new Ft(r,this._parents)},selectAll:function(t){t="function"==typeof t?function(t){return function(){return M(t.apply(this,arguments))}}(t):C(t);for(var e=this._groups,n=e.length,r=[],s=[],o=0;o<n;++o)for(var i,a=e[o],l=a.length,c=0;c<l;++c)(i=a[c])&&(r.push(t.call(i,i.__data__,c,a)),s.push(i));return new Ft(r,s)},selectChild:function(t){return this.select(null==t?I:function(t){return function(){return O.call(this.children,t)}}("function"==typeof t?t:E(t)))},selectChildren:function(t){return this.selectAll(null==t?F:function(t){return function(){return R.call(this.children,t)}}("function"==typeof t?t:E(t)))},filter:function(t){"function"!=typeof t&&(t=j(t));for(var e=this._groups,n=e.length,r=new Array(n),s=0;s<n;++s)for(var o,i=e[s],a=i.length,l=r[s]=[],c=0;c<a;++c)(o=i[c])&&t.call(o,o.__data__,c,i)&&l.push(o);return new Ft(r,this._parents)},data:function(t,e){if(!arguments.length)return Array.from(this,z);var n=e?$:L,r=this._parents,s=this._groups;"function"!=typeof t&&(t=function(t){return function(){return t}}(t));for(var o=s.length,i=new Array(o),a=new Array(o),l=new Array(o),c=0;c<o;++c){var u=r[c],f=s[c],d=f.length,h=Z(t.call(u,u&&u.__data__,c,r)),p=h.length,m=a[c]=new Array(p),g=i[c]=new Array(p);n(u,f,m,g,l[c]=new Array(d),h,e);for(var y,b,v=0,w=0;v<p;++v)if(y=m[v]){for(v>=w&&(w=v+1);!(b=g[w])&&++w<p;);y._next=b||null}}return(i=new Ft(i,r))._enter=a,i._exit=l,i},enter:function(){return new Ft(this._enter||this._groups.map(P),this._parents)},exit:function(){return new Ft(this._exit||this._groups.map(P),this._parents)},join:function(t,e,n){var r=this.enter(),s=this,o=this.exit();return"function"==typeof t?(r=t(r))&&(r=r.selection()):r=r.append(t+""),null!=e&&(s=e(s))&&(s=s.selection()),null==n?o.remove():n(o),r&&s?r.merge(s).order():s},merge:function(t){for(var e=t.selection?t.selection():t,n=this._groups,r=e._groups,s=n.length,o=r.length,i=Math.min(s,o),a=new Array(s),l=0;l<i;++l)for(var c,u=n[l],f=r[l],d=u.length,h=a[l]=new Array(d),p=0;p<d;++p)(c=u[p]||f[p])&&(h[p]=c);for(;l<s;++l)a[l]=n[l];return new Ft(a,this._parents)},selection:function(){return this},order:function(){for(var t=this._groups,e=-1,n=t.length;++e<n;)for(var r,s=t[e],o=s.length-1,i=s[o];--o>=0;)(r=s[o])&&(i&&4^r.compareDocumentPosition(i)&&i.parentNode.insertBefore(r,i),i=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=U);for(var n=this._groups,r=n.length,s=new Array(r),o=0;o<r;++o){for(var i,a=n[o],l=a.length,c=s[o]=new Array(l),u=0;u<l;++u)(i=a[u])&&(c[u]=i);c.sort(e)}return new Ft(s,this._parents).order()},call:function(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r=t[e],s=0,o=r.length;s<o;++s){var i=r[s];if(i)return i}return null},size:function(){let t=0;for(const e of this)++t;return t},empty:function(){return!this.node()},each:function(t){for(var e=this._groups,n=0,r=e.length;n<r;++n)for(var s,o=e[n],i=0,a=o.length;i<a;++i)(s=o[i])&&t.call(s,s.__data__,i,o);return this},attr:function(t,e){var n=J(t);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==e?n.local?W:H:"function"==typeof e?n.local?X:K:n.local?Y:V)(n,e))},style:function(t,e,n){return arguments.length>1?this.each((null==e?tt:"function"==typeof e?nt:et)(t,e,null==n?"":n)):rt(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?st:"function"==typeof e?it:ot)(t,e)):this.node()[t]},classed:function(t,e){var n=at(t+"");if(arguments.length<2){for(var r=lt(this.node()),s=-1,o=n.length;++s<o;)if(!r.contains(n[s]))return!1;return!0}return this.each(("function"==typeof e?pt:e?dt:ht)(n,e))},text:function(t){return arguments.length?this.each(null==t?mt:("function"==typeof t?yt:gt)(t)):this.node().textContent},html:function(t){return arguments.length?this.each(null==t?bt:("function"==typeof t?wt:vt)(t)):this.node().innerHTML},raise:function(){return this.each(_t)},lower:function(){return this.each(xt)},append:function(t){var e="function"==typeof t?t:Nt(t);return this.select((function(){return this.appendChild(e.apply(this,arguments))}))},insert:function(t,e){var n="function"==typeof t?t:Nt(t),r=null==e?St:"function"==typeof e?e:A(e);return this.select((function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(At)},clone:function(t){return this.select(t?Tt:Mt)},datum:function(t){return arguments.length?this.property("__data__",t):this.node().__data__},on:function(t,e,n){var r,s,o=function(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}(t+""),i=o.length;if(!(arguments.length<2)){for(a=e?jt:Ct,r=0;r<i;++r)this.each(a(o[r],e,n));return this}var a=this.node().__on;if(a)for(var l,c=0,u=a.length;c<u;++c)for(r=0,l=a[c];r<i;++r)if((s=o[r]).type===l.type&&s.name===l.name)return l.value},dispatch:function(t,e){return this.each(("function"==typeof e?It:Ot)(t,e))},[Symbol.iterator]:function*(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r,s=t[e],o=0,i=s.length;o<i;++o)(r=s[o])&&(yield r)}};const Dt=Pt;function Lt(t){return"string"==typeof t?new Ft([[document.querySelector(t)]],[document.documentElement]):new Ft([[t]],Rt)}const $t={passive:!1},zt={capture:!0,passive:!1};function Zt(t){t.stopImmediatePropagation()}function Ut(t){t.preventDefault(),t.stopImmediatePropagation()}function Bt(t){var e=t.document.documentElement,n=Lt(t).on("dragstart.drag",Ut,zt);"onselectstart"in e?n.on("selectstart.drag",Ut,zt):(e.__noselect=e.style.MozUserSelect,e.style.MozUserSelect="none")}function Gt(t,e){var n=t.document.documentElement,r=Lt(t).on("dragstart.drag",null);e&&(r.on("click.drag",Ut,zt),setTimeout((function(){r.on("click.drag",null)}),0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}var Jt=n(2303);function Ht(t){let e;for(;e=t.sourceEvent;)t=e;return t}function Wt(t,e){if(t=Ht(t),void 0===e&&(e=t.currentTarget),e){var n=e.ownerSVGElement||e;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=t.clientX,r.y=t.clientY,[(r=r.matrixTransform(e.getScreenCTM().inverse())).x,r.y]}if(e.getBoundingClientRect){var s=e.getBoundingClientRect();return[t.clientX-s.left-e.clientLeft,t.clientY-s.top-e.clientTop]}}return[t.pageX,t.pageY]}var Vt,Yt,Kt=0,Xt=0,Qt=0,te=1e3,ee=0,ne=0,re=0,se="object"==typeof performance&&performance.now?performance:Date,oe="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function ie(){return ne||(oe(ae),ne=se.now()+re)}function ae(){ne=0}function le(){this._call=this._time=this._next=null}function ce(t,e,n){var r=new le;return r.restart(t,e,n),r}function ue(){ie(),++Kt;for(var t,e=Vt;e;)(t=ne-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Kt}function fe(){ne=(ee=se.now())+re,Kt=Xt=0;try{ue()}finally{Kt=0,function(){var t,e,n=Vt,r=1/0;for(;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:Vt=e);Yt=t,he(r)}(),ne=0}}function de(){var t=se.now(),e=t-ee;e>te&&(re-=e,ee=t)}function he(t){Kt||(Xt&&(Xt=clearTimeout(Xt)),t-ne>24?(t<1/0&&(Xt=setTimeout(fe,t-se.now()-re)),Qt&&(Qt=clearInterval(Qt))):(Qt||(ee=se.now(),Qt=setInterval(de,te)),Kt=1,oe(fe)))}function pe(t,e,n){var r=new le;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e)}),e,n),r}le.prototype=ce.prototype={constructor:le,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?ie():+n)+(null==e?0:+e),this._next||Yt===this||(Yt?Yt._next=this:Vt=this,Yt=this),this._call=t,this._time=n,he()},stop:function(){this._call&&(this._call=null,this._time=1/0,he())}};var me=N("start","end","cancel","interrupt"),ge=[],ye=0,be=1,ve=2,we=3,_e=4,xe=5,ke=6;function qe(t,e,n,r,s,o){var i=t.__transition;if(i){if(n in i)return}else t.__transition={};!function(t,e,n){var r,s=t.__transition;function o(t){n.state=be,n.timer.restart(i,n.delay,n.time),n.delay<=t&&i(t-n.delay)}function i(o){var c,u,f,d;if(n.state!==be)return l();for(c in s)if((d=s[c]).name===n.name){if(d.state===we)return pe(i);d.state===_e?(d.state=ke,d.timer.stop(),d.on.call("interrupt",t,t.__data__,d.index,d.group),delete s[c]):+c<e&&(d.state=ke,d.timer.stop(),d.on.call("cancel",t,t.__data__,d.index,d.group),delete s[c])}if(pe((function(){n.state===we&&(n.state=_e,n.timer.restart(a,n.delay,n.time),a(o))})),n.state=ve,n.on.call("start",t,t.__data__,n.index,n.group),n.state===ve){for(n.state=we,r=new Array(f=n.tween.length),c=0,u=-1;c<f;++c)(d=n.tween[c].value.call(t,t.__data__,n.index,n.group))&&(r[++u]=d);r.length=u+1}}function a(e){for(var s=e<n.duration?n.ease.call(null,e/n.duration):(n.timer.restart(l),n.state=xe,1),o=-1,i=r.length;++o<i;)r[o].call(t,s);n.state===xe&&(n.on.call("end",t,t.__data__,n.index,n.group),l())}function l(){for(var r in n.state=ke,n.timer.stop(),delete s[e],s)return;delete t.__transition}s[e]=n,n.timer=ce(o,0,n.time)}(t,n,{name:e,index:r,group:s,on:me,tween:ge,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:ye})}function Ne(t,e){var n=Ae(t,e);if(n.state>ye)throw new Error("too late; already scheduled");return n}function Se(t,e){var n=Ae(t,e);if(n.state>we)throw new Error("too late; already running");return n}function Ae(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function Me(t,e){var n,r,s,o=t.__transition,i=!0;if(o){for(s in e=null==e?null:e+"",o)(n=o[s]).name===e?(r=n.state>ve&&n.state<xe,n.state=ke,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete o[s]):i=!1;i&&delete t.__transition}}var Te,Ce=n(8403),je=180/Math.PI,Ee={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Oe(t,e,n,r,s,o){var i,a,l;return(i=Math.sqrt(t*t+e*e))&&(t/=i,e/=i),(l=t*n+e*r)&&(n-=t*l,r-=e*l),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,l/=a),t*r<e*n&&(t=-t,e=-e,l=-l,i=-i),{translateX:s,translateY:o,rotate:Math.atan2(e,t)*je,skewX:Math.atan(l)*je,scaleX:i,scaleY:a}}function Ie(t,e,n,r){function s(t){return t.length?t.pop()+" ":""}return function(o,i){var a=[],l=[];return o=t(o),i=t(i),function(t,r,s,o,i,a){if(t!==s||r!==o){var l=i.push("translate(",null,e,null,n);a.push({i:l-4,x:(0,Ce.Z)(t,s)},{i:l-2,x:(0,Ce.Z)(r,o)})}else(s||o)&&i.push("translate("+s+e+o+n)}(o.translateX,o.translateY,i.translateX,i.translateY,a,l),function(t,e,n,o){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),o.push({i:n.push(s(n)+"rotate(",null,r)-2,x:(0,Ce.Z)(t,e)})):e&&n.push(s(n)+"rotate("+e+r)}(o.rotate,i.rotate,a,l),function(t,e,n,o){t!==e?o.push({i:n.push(s(n)+"skewX(",null,r)-2,x:(0,Ce.Z)(t,e)}):e&&n.push(s(n)+"skewX("+e+r)}(o.skewX,i.skewX,a,l),function(t,e,n,r,o,i){if(t!==n||e!==r){var a=o.push(s(o)+"scale(",null,",",null,")");i.push({i:a-4,x:(0,Ce.Z)(t,n)},{i:a-2,x:(0,Ce.Z)(e,r)})}else 1===n&&1===r||o.push(s(o)+"scale("+n+","+r+")")}(o.scaleX,o.scaleY,i.scaleX,i.scaleY,a,l),o=i=null,function(t){for(var e,n=-1,r=l.length;++n<r;)a[(e=l[n]).i]=e.x(t);return a.join("")}}}var Re=Ie((function(t){const e=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(t+"");return e.isIdentity?Ee:Oe(e.a,e.b,e.c,e.d,e.e,e.f)}),"px, ","px)","deg)"),Fe=Ie((function(t){return null==t?Ee:(Te||(Te=document.createElementNS("http://www.w3.org/2000/svg","g")),Te.setAttribute("transform",t),(t=Te.transform.baseVal.consolidate())?Oe((t=t.matrix).a,t.b,t.c,t.d,t.e,t.f):Ee)}),", ",")",")");function Pe(t,e){var n,r;return function(){var s=Se(this,t),o=s.tween;if(o!==n)for(var i=0,a=(r=n=o).length;i<a;++i)if(r[i].name===e){(r=r.slice()).splice(i,1);break}s.tween=r}}function De(t,e,n){var r,s;if("function"!=typeof n)throw new Error;return function(){var o=Se(this,t),i=o.tween;if(i!==r){s=(r=i).slice();for(var a={name:e,value:n},l=0,c=s.length;l<c;++l)if(s[l].name===e){s[l]=a;break}l===c&&s.push(a)}o.tween=s}}function Le(t,e,n){var r=t._id;return t.each((function(){var t=Se(this,r);(t.value||(t.value={}))[e]=n.apply(this,arguments)})),function(t){return Ae(t,r).value[e]}}var $e=n(1495),ze=n(490),Ze=n(9009);function Ue(t,e){var n;return("number"==typeof e?Ce.Z:e instanceof $e.ZP?ze.ZP:(n=(0,$e.ZP)(e))?(e=n,ze.ZP):Ze.Z)(t,e)}function Be(t){return function(){this.removeAttribute(t)}}function Ge(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Je(t,e,n){var r,s,o=n+"";return function(){var i=this.getAttribute(t);return i===o?null:i===r?s:s=e(r=i,n)}}function He(t,e,n){var r,s,o=n+"";return function(){var i=this.getAttributeNS(t.space,t.local);return i===o?null:i===r?s:s=e(r=i,n)}}function We(t,e,n){var r,s,o;return function(){var i,a,l=n(this);if(null!=l)return(i=this.getAttribute(t))===(a=l+"")?null:i===r&&a===s?o:(s=a,o=e(r=i,l));this.removeAttribute(t)}}function Ve(t,e,n){var r,s,o;return function(){var i,a,l=n(this);if(null!=l)return(i=this.getAttributeNS(t.space,t.local))===(a=l+"")?null:i===r&&a===s?o:(s=a,o=e(r=i,l));this.removeAttributeNS(t.space,t.local)}}function Ye(t,e){var n,r;function s(){var s=e.apply(this,arguments);return s!==r&&(n=(r=s)&&function(t,e){return function(n){this.setAttributeNS(t.space,t.local,e.call(this,n))}}(t,s)),n}return s._value=e,s}function Ke(t,e){var n,r;function s(){var s=e.apply(this,arguments);return s!==r&&(n=(r=s)&&function(t,e){return function(n){this.setAttribute(t,e.call(this,n))}}(t,s)),n}return s._value=e,s}function Xe(t,e){return function(){Ne(this,t).delay=+e.apply(this,arguments)}}function Qe(t,e){return e=+e,function(){Ne(this,t).delay=e}}function tn(t,e){return function(){Se(this,t).duration=+e.apply(this,arguments)}}function en(t,e){return e=+e,function(){Se(this,t).duration=e}}var nn=Dt.prototype.constructor;function rn(t){return function(){this.style.removeProperty(t)}}var sn=0;function on(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function an(t){return Dt().transition(t)}function ln(){return++sn}var cn=Dt.prototype;function un(t){return t*t*t}function fn(t){return--t*t*t+1}function dn(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}on.prototype=an.prototype={constructor:on,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=A(t));for(var r=this._groups,s=r.length,o=new Array(s),i=0;i<s;++i)for(var a,l,c=r[i],u=c.length,f=o[i]=new Array(u),d=0;d<u;++d)(a=c[d])&&(l=t.call(a,a.__data__,d,c))&&("__data__"in a&&(l.__data__=a.__data__),f[d]=l,qe(f[d],e,n,d,f,Ae(a,n)));return new on(o,this._parents,e,n)},selectAll:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=C(t));for(var r=this._groups,s=r.length,o=[],i=[],a=0;a<s;++a)for(var l,c=r[a],u=c.length,f=0;f<u;++f)if(l=c[f]){for(var d,h=t.call(l,l.__data__,f,c),p=Ae(l,n),m=0,g=h.length;m<g;++m)(d=h[m])&&qe(d,e,n,m,h,p);o.push(h),i.push(l)}return new on(o,i,e,n)},selectChild:cn.selectChild,selectChildren:cn.selectChildren,filter:function(t){"function"!=typeof t&&(t=j(t));for(var e=this._groups,n=e.length,r=new Array(n),s=0;s<n;++s)for(var o,i=e[s],a=i.length,l=r[s]=[],c=0;c<a;++c)(o=i[c])&&t.call(o,o.__data__,c,i)&&l.push(o);return new on(r,this._parents,this._name,this._id)},merge:function(t){if(t._id!==this._id)throw new Error;for(var e=this._groups,n=t._groups,r=e.length,s=n.length,o=Math.min(r,s),i=new Array(r),a=0;a<o;++a)for(var l,c=e[a],u=n[a],f=c.length,d=i[a]=new Array(f),h=0;h<f;++h)(l=c[h]||u[h])&&(d[h]=l);for(;a<r;++a)i[a]=e[a];return new on(i,this._parents,this._name,this._id)},selection:function(){return new nn(this._groups,this._parents)},transition:function(){for(var t=this._name,e=this._id,n=ln(),r=this._groups,s=r.length,o=0;o<s;++o)for(var i,a=r[o],l=a.length,c=0;c<l;++c)if(i=a[c]){var u=Ae(i,e);qe(i,t,n,c,a,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new on(r,this._parents,t,n)},call:cn.call,nodes:cn.nodes,node:cn.node,size:cn.size,empty:cn.empty,each:cn.each,on:function(t,e){var n=this._id;return arguments.length<2?Ae(this.node(),n).on.on(t):this.each(function(t,e,n){var r,s,o=function(t){return(t+"").trim().split(/^|\s+/).every((function(t){var e=t.indexOf(".");return e>=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?Ne:Se;return function(){var i=o(this,t),a=i.on;a!==r&&(s=(r=a).copy()).on(e,n),i.on=s}}(n,t,e))},attr:function(t,e){var n=J(t),r="transform"===n?Fe:Ue;return this.attrTween(t,"function"==typeof e?(n.local?Ve:We)(n,r,Le(this,"attr."+t,e)):null==e?(n.local?Ge:Be)(n):(n.local?He:Je)(n,r,e))},attrTween:function(t,e){var n="attr."+t;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==e)return this.tween(n,null);if("function"!=typeof e)throw new Error;var r=J(t);return this.tween(n,(r.local?Ye:Ke)(r,e))},style:function(t,e,n){var r="transform"==(t+="")?Re:Ue;return null==e?this.styleTween(t,function(t,e){var n,r,s;return function(){var o=rt(this,t),i=(this.style.removeProperty(t),rt(this,t));return o===i?null:o===n&&i===r?s:s=e(n=o,r=i)}}(t,r)).on("end.style."+t,rn(t)):"function"==typeof e?this.styleTween(t,function(t,e,n){var r,s,o;return function(){var i=rt(this,t),a=n(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=rt(this,t)),i===l?null:i===r&&l===s?o:(s=l,o=e(r=i,a))}}(t,r,Le(this,"style."+t,e))).each(function(t,e){var n,r,s,o,i="style."+e,a="end."+i;return function(){var l=Se(this,t),c=l.on,u=null==l.value[i]?o||(o=rn(e)):void 0;c===n&&s===u||(r=(n=c).copy()).on(a,s=u),l.on=r}}(this._id,t)):this.styleTween(t,function(t,e,n){var r,s,o=n+"";return function(){var i=rt(this,t);return i===o?null:i===r?s:s=e(r=i,n)}}(t,r,e),n).on("end.style."+t,null)},styleTween:function(t,e,n){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==e)return this.tween(r,null);if("function"!=typeof e)throw new Error;return this.tween(r,function(t,e,n){var r,s;function o(){var o=e.apply(this,arguments);return o!==s&&(r=(s=o)&&function(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}(t,o,n)),r}return o._value=e,o}(t,e,null==n?"":n))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var e=t(this);this.textContent=null==e?"":e}}(Le(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var e="text";if(arguments.length<1)return(e=this.tween(e))&&e._value;if(null==t)return this.tween(e,null);if("function"!=typeof t)throw new Error;return this.tween(e,function(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&function(t){return function(e){this.textContent=t.call(this,e)}}(r)),e}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var e=this.parentNode;for(var n in this.__transition)if(+n!==t)return;e&&e.removeChild(this)}}(this._id))},tween:function(t,e){var n=this._id;if(t+="",arguments.length<2){for(var r,s=Ae(this.node(),n).tween,o=0,i=s.length;o<i;++o)if((r=s[o]).name===t)return r.value;return null}return this.each((null==e?Pe:De)(n,t,e))},delay:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?Xe:Qe)(e,t)):Ae(this.node(),e).delay},duration:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?tn:en)(e,t)):Ae(this.node(),e).duration},ease:function(t){var e=this._id;return arguments.length?this.each(function(t,e){if("function"!=typeof e)throw new Error;return function(){Se(this,t).ease=e}}(e,t)):Ae(this.node(),e).ease},easeVarying:function(t){if("function"!=typeof t)throw new Error;return this.each(function(t,e){return function(){var n=e.apply(this,arguments);if("function"!=typeof n)throw new Error;Se(this,t).ease=n}}(this._id,t))},end:function(){var t,e,n=this,r=n._id,s=n.size();return new Promise((function(o,i){var a={value:i},l={value:function(){0==--s&&o()}};n.each((function(){var n=Se(this,r),s=n.on;s!==t&&((e=(t=s).copy())._.cancel.push(a),e._.interrupt.push(a),e._.end.push(l)),n.on=e})),0===s&&o()}))},[Symbol.iterator]:cn[Symbol.iterator]};var hn={time:null,delay:0,duration:250,ease:dn};function pn(t,e){for(var n;!(n=t.__transition)||!(n=n[e]);)if(!(t=t.parentNode))throw new Error(`transition ${e} not found`);return n}Dt.prototype.interrupt=function(t){return this.each((function(){Me(this,t)}))},Dt.prototype.transition=function(t){var e,n;t instanceof on?(e=t._id,t=t._name):(e=ln(),(n=hn).time=ie(),t=null==t?null:t+"");for(var r=this._groups,s=r.length,o=0;o<s;++o)for(var i,a=r[o],l=a.length,c=0;c<l;++c)(i=a[c])&&qe(i,t,e,c,a,n||pn(i,e));return new on(r,this._parents,t,e)};var mn=[null];function gn(t,e){var n,r,s=t.__transition;if(s)for(r in e=null==e?null:e+"",s)if((n=s[r]).state>be&&n.name===e)return new on([[t]],mn,e,+r);return null}const yn=t=>()=>t;function bn(t,{sourceEvent:e,target:n,selection:r,mode:s,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:s,enumerable:!0,configurable:!0},_:{value:o}})}function vn(t){t.preventDefault(),t.stopImmediatePropagation()}var wn={name:"drag"},_n={name:"space"},xn={name:"handle"},kn={name:"center"};const{abs:qn,max:Nn,min:Sn}=Math;function An(t){return[+t[0],+t[1]]}function Mn(t){return[An(t[0]),An(t[1])]}var Tn={name:"x",handles:["w","e"].map(Pn),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Cn={name:"y",handles:["n","s"].map(Pn),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},jn={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(Pn),input:function(t){return null==t?null:Mn(t)},output:function(t){return t}},En={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},On={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},In={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Rn={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},Fn={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function Pn(t){return{type:t}}function Dn(t){return!t.ctrlKey&&!t.button}function Ln(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function $n(){return navigator.maxTouchPoints||"ontouchstart"in this}function zn(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function Zn(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Un(){return Jn(Tn)}function Bn(){return Jn(Cn)}function Gn(){return Jn(jn)}function Jn(t){var e,n=Ln,r=Dn,s=$n,o=!0,i=N("start","brush","end"),a=6;function l(e){var n=e.property("__brush",m).selectAll(".overlay").data([Pn("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",En.overlay).merge(n).each((function(){var t=zn(this).extent;Lt(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),e.selectAll(".selection").data([Pn("selection")]).enter().append("rect").attr("class","selection").attr("cursor",En.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return En[t.type]})),e.each(c).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",d).filter(s).on("touchstart.brush",d).on("touchmove.brush",h).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function c(){var t=Lt(this),e=zn(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?e[1][0]-a/2:e[0][0]-a/2})).attr("y",(function(t){return"s"===t.type[0]?e[1][1]-a/2:e[0][1]-a/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?e[1][0]-e[0][0]+a:a})).attr("height",(function(t){return"e"===t.type||"w"===t.type?e[1][1]-e[0][1]+a:a}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function u(t,e,n){var r=t.__brush.emitter;return!r||n&&r.clean?new f(t,e,n):r}function f(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n}function d(n){if((!e||n.touches)&&r.apply(this,arguments)){var s,i,a,l,f,d,h,p,m,g,y,b=this,v=n.target.__data__.type,w="selection"===(o&&n.metaKey?v="overlay":v)?wn:o&&n.altKey?kn:xn,_=t===Cn?null:Rn[v],x=t===Tn?null:Fn[v],k=zn(b),q=k.extent,N=k.selection,S=q[0][0],A=q[0][1],M=q[1][0],T=q[1][1],C=0,j=0,E=_&&x&&o&&n.shiftKey,O=Array.from(n.touches||[n],(t=>{const e=t.identifier;return(t=Wt(t,b)).point0=t.slice(),t.identifier=e,t}));Me(b);var I=u(b,arguments,!0).beforestart();if("overlay"===v){N&&(m=!0);const e=[O[0],O[1]||O[0]];k.selection=N=[[s=t===Cn?S:Sn(e[0][0],e[1][0]),a=t===Tn?A:Sn(e[0][1],e[1][1])],[f=t===Cn?M:Nn(e[0][0],e[1][0]),h=t===Tn?T:Nn(e[0][1],e[1][1])]],O.length>1&&L(n)}else s=N[0][0],a=N[0][1],f=N[1][0],h=N[1][1];i=s,l=a,d=f,p=h;var R=Lt(b).attr("pointer-events","none"),F=R.selectAll(".overlay").attr("cursor",En[v]);if(n.touches)I.moved=D,I.ended=$;else{var P=Lt(n.view).on("mousemove.brush",D,!0).on("mouseup.brush",$,!0);o&&P.on("keydown.brush",(function(t){switch(t.keyCode){case 16:E=_&&x;break;case 18:w===xn&&(_&&(f=d-C*_,s=i+C*_),x&&(h=p-j*x,a=l+j*x),w=kn,L(t));break;case 32:w!==xn&&w!==kn||(_<0?f=d-C:_>0&&(s=i-C),x<0?h=p-j:x>0&&(a=l-j),w=_n,F.attr("cursor",En.selection),L(t));break;default:return}vn(t)}),!0).on("keyup.brush",(function(t){switch(t.keyCode){case 16:E&&(g=y=E=!1,L(t));break;case 18:w===kn&&(_<0?f=d:_>0&&(s=i),x<0?h=p:x>0&&(a=l),w=xn,L(t));break;case 32:w===_n&&(t.altKey?(_&&(f=d-C*_,s=i+C*_),x&&(h=p-j*x,a=l+j*x),w=kn):(_<0?f=d:_>0&&(s=i),x<0?h=p:x>0&&(a=l),w=xn),F.attr("cursor",En[v]),L(t));break;default:return}vn(t)}),!0),Bt(n.view)}c.call(b),I.start(n,w.name)}function D(t){for(const e of t.changedTouches||[t])for(const t of O)t.identifier===e.identifier&&(t.cur=Wt(e,b));if(E&&!g&&!y&&1===O.length){const t=O[0];qn(t.cur[0]-t[0])>qn(t.cur[1]-t[1])?y=!0:g=!0}for(const t of O)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);m=!0,vn(t),L(t)}function L(t){const e=O[0],n=e.point0;var r;switch(C=e[0]-n[0],j=e[1]-n[1],w){case _n:case wn:_&&(C=Nn(S-s,Sn(M-f,C)),i=s+C,d=f+C),x&&(j=Nn(A-a,Sn(T-h,j)),l=a+j,p=h+j);break;case xn:O[1]?(_&&(i=Nn(S,Sn(M,O[0][0])),d=Nn(S,Sn(M,O[1][0])),_=1),x&&(l=Nn(A,Sn(T,O[0][1])),p=Nn(A,Sn(T,O[1][1])),x=1)):(_<0?(C=Nn(S-s,Sn(M-s,C)),i=s+C,d=f):_>0&&(C=Nn(S-f,Sn(M-f,C)),i=s,d=f+C),x<0?(j=Nn(A-a,Sn(T-a,j)),l=a+j,p=h):x>0&&(j=Nn(A-h,Sn(T-h,j)),l=a,p=h+j));break;case kn:_&&(i=Nn(S,Sn(M,s-C*_)),d=Nn(S,Sn(M,f+C*_))),x&&(l=Nn(A,Sn(T,a-j*x)),p=Nn(A,Sn(T,h+j*x)))}d<i&&(_*=-1,r=s,s=f,f=r,r=i,i=d,d=r,v in On&&F.attr("cursor",En[v=On[v]])),p<l&&(x*=-1,r=a,a=h,h=r,r=l,l=p,p=r,v in In&&F.attr("cursor",En[v=In[v]])),k.selection&&(N=k.selection),g&&(i=N[0][0],d=N[1][0]),y&&(l=N[0][1],p=N[1][1]),N[0][0]===i&&N[0][1]===l&&N[1][0]===d&&N[1][1]===p||(k.selection=[[i,l],[d,p]],c.call(b),I.brush(t,w.name))}function $(t){if(function(t){t.stopImmediatePropagation()}(t),t.touches){if(t.touches.length)return;e&&clearTimeout(e),e=setTimeout((function(){e=null}),500)}else Gt(t.view,m),P.on("keydown.brush keyup.brush mousemove.brush mouseup.brush",null);R.attr("pointer-events","all"),F.attr("cursor",En.overlay),k.selection&&(N=k.selection),function(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}(N)&&(k.selection=null,c.call(b)),I.end(t,w.name)}}function h(t){u(this,arguments).moved(t)}function p(t){u(this,arguments).ended(t)}function m(){var e=this.__brush||{selection:null};return e.extent=Mn(n.apply(this,arguments)),e.dim=t,e}return l.move=function(e,n,r){e.tween?e.on("start.brush",(function(t){u(this,arguments).beforestart().start(t)})).on("interrupt.brush end.brush",(function(t){u(this,arguments).end(t)})).tween("brush",(function(){var e=this,r=e.__brush,s=u(e,arguments),o=r.selection,i=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),a=(0,Jt.Z)(o,i);function l(t){r.selection=1===t&&null===i?null:a(t),c.call(e),s.brush()}return null!==o&&null!==i?l:l(1)})):e.each((function(){var e=this,s=arguments,o=e.__brush,i=t.input("function"==typeof n?n.apply(e,s):n,o.extent),a=u(e,s).beforestart();Me(e),o.selection=null===i?null:i,c.call(e),a.start(r).brush(r).end(r)}))},l.clear=function(t,e){l.move(t,null,e)},f.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(t,e){return this.starting?(this.starting=!1,this.emit("start",t,e)):this.emit("brush",t),this},brush:function(t,e){return this.emit("brush",t,e),this},end:function(t,e){return 0==--this.active&&(delete this.state.emitter,this.emit("end",t,e)),this},emit:function(e,n,r){var s=Lt(this.that).datum();i.call(e,this.that,new bn(e,{sourceEvent:n,target:l,selection:t.output(this.state.selection),mode:r,dispatch:i}),s)}},l.extent=function(t){return arguments.length?(n="function"==typeof t?t:yn(Mn(t)),l):n},l.filter=function(t){return arguments.length?(r="function"==typeof t?t:yn(!!t),l):r},l.touchable=function(t){return arguments.length?(s="function"==typeof t?t:yn(!!t),l):s},l.handleSize=function(t){return arguments.length?(a=+t,l):a},l.keyModifiers=function(t){return arguments.length?(o=!!t,l):o},l.on=function(){var t=i.on.apply(i,arguments);return t===i?l:t},l}var Hn=Math.abs,Wn=Math.cos,Vn=Math.sin,Yn=Math.PI,Kn=Yn/2,Xn=2*Yn,Qn=Math.max,tr=1e-12;function er(t,e){return Array.from({length:e-t},((e,n)=>t+n))}function nr(){return or(!1,!1)}function rr(){return or(!1,!0)}function sr(){return or(!0,!1)}function or(t,e){var n=0,r=null,s=null,o=null;function i(i){var a,l=i.length,c=new Array(l),u=er(0,l),f=new Array(l*l),d=new Array(l),h=0;i=Float64Array.from({length:l*l},e?(t,e)=>i[e%l][e/l|0]:(t,e)=>i[e/l|0][e%l]);for(let e=0;e<l;++e){let n=0;for(let r=0;r<l;++r)n+=i[e*l+r]+t*i[r*l+e];h+=c[e]=n}a=(h=Qn(0,Xn-n*l)/h)?n:Xn/l;{let e=0;r&&u.sort(((t,e)=>r(c[t],c[e])));for(const n of u){const r=e;if(t){const t=er(1+~l,l).filter((t=>t<0?i[~t*l+n]:i[n*l+t]));s&&t.sort(((t,e)=>s(t<0?-i[~t*l+n]:i[n*l+t],e<0?-i[~e*l+n]:i[n*l+e])));for(const r of t)if(r<0){(f[~r*l+n]||(f[~r*l+n]={source:null,target:null})).target={index:n,startAngle:e,endAngle:e+=i[~r*l+n]*h,value:i[~r*l+n]}}else{(f[n*l+r]||(f[n*l+r]={source:null,target:null})).source={index:n,startAngle:e,endAngle:e+=i[n*l+r]*h,value:i[n*l+r]}}d[n]={index:n,startAngle:r,endAngle:e,value:c[n]}}else{const t=er(0,l).filter((t=>i[n*l+t]||i[t*l+n]));s&&t.sort(((t,e)=>s(i[n*l+t],i[n*l+e])));for(const r of t){let t;if(n<r?(t=f[n*l+r]||(f[n*l+r]={source:null,target:null}),t.source={index:n,startAngle:e,endAngle:e+=i[n*l+r]*h,value:i[n*l+r]}):(t=f[r*l+n]||(f[r*l+n]={source:null,target:null}),t.target={index:n,startAngle:e,endAngle:e+=i[n*l+r]*h,value:i[n*l+r]},n===r&&(t.source=t.target)),t.source&&t.target&&t.source.value<t.target.value){const e=t.source;t.source=t.target,t.target=e}}d[n]={index:n,startAngle:r,endAngle:e,value:c[n]}}e+=a}}return(f=Object.values(f)).groups=d,o?f.sort(o):f}return i.padAngle=function(t){return arguments.length?(n=Qn(0,t),i):n},i.sortGroups=function(t){return arguments.length?(r=t,i):r},i.sortSubgroups=function(t){return arguments.length?(s=t,i):s},i.sortChords=function(t){return arguments.length?(null==t?o=null:(e=t,o=function(t,n){return e(t.source.value+t.target.value,n.source.value+n.target.value)})._=t,i):o&&o._;var e},i}const ir=Math.PI,ar=2*ir,lr=1e-6,cr=ar-lr;function ur(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function fr(){return new ur}ur.prototype=fr.prototype={constructor:ur,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},quadraticCurveTo:function(t,e,n,r){this._+="Q"+ +t+","+ +e+","+(this._x1=+n)+","+(this._y1=+r)},bezierCurveTo:function(t,e,n,r,s,o){this._+="C"+ +t+","+ +e+","+ +n+","+ +r+","+(this._x1=+s)+","+(this._y1=+o)},arcTo:function(t,e,n,r,s){t=+t,e=+e,n=+n,r=+r,s=+s;var o=this._x1,i=this._y1,a=n-t,l=r-e,c=o-t,u=i-e,f=c*c+u*u;if(s<0)throw new Error("negative radius: "+s);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(f>lr)if(Math.abs(u*a-l*c)>lr&&s){var d=n-o,h=r-i,p=a*a+l*l,m=d*d+h*h,g=Math.sqrt(p),y=Math.sqrt(f),b=s*Math.tan((ir-Math.acos((p+f-m)/(2*g*y)))/2),v=b/y,w=b/g;Math.abs(v-1)>lr&&(this._+="L"+(t+v*c)+","+(e+v*u)),this._+="A"+s+","+s+",0,0,"+ +(u*d>c*h)+","+(this._x1=t+w*a)+","+(this._y1=e+w*l)}else this._+="L"+(this._x1=t)+","+(this._y1=e);else;},arc:function(t,e,n,r,s,o){t=+t,e=+e,o=!!o;var i=(n=+n)*Math.cos(r),a=n*Math.sin(r),l=t+i,c=e+a,u=1^o,f=o?r-s:s-r;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+l+","+c:(Math.abs(this._x1-l)>lr||Math.abs(this._y1-c)>lr)&&(this._+="L"+l+","+c),n&&(f<0&&(f=f%ar+ar),f>cr?this._+="A"+n+","+n+",0,1,"+u+","+(t-i)+","+(e-a)+"A"+n+","+n+",0,1,"+u+","+(this._x1=l)+","+(this._y1=c):f>lr&&(this._+="A"+n+","+n+",0,"+ +(f>=ir)+","+u+","+(this._x1=t+n*Math.cos(s))+","+(this._y1=e+n*Math.sin(s))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const dr=fr;var hr=Array.prototype.slice;function pr(t){return function(){return t}}function mr(t){return t.source}function gr(t){return t.target}function yr(t){return t.radius}function br(t){return t.startAngle}function vr(t){return t.endAngle}function wr(){return 0}function _r(){return 10}function xr(t){var e=mr,n=gr,r=yr,s=yr,o=br,i=vr,a=wr,l=null;function c(){var c,u=e.apply(this,arguments),f=n.apply(this,arguments),d=a.apply(this,arguments)/2,h=hr.call(arguments),p=+r.apply(this,(h[0]=u,h)),m=o.apply(this,h)-Kn,g=i.apply(this,h)-Kn,y=+s.apply(this,(h[0]=f,h)),b=o.apply(this,h)-Kn,v=i.apply(this,h)-Kn;if(l||(l=c=dr()),d>tr&&(Hn(g-m)>2*d+tr?g>m?(m+=d,g-=d):(m-=d,g+=d):m=g=(m+g)/2,Hn(v-b)>2*d+tr?v>b?(b+=d,v-=d):(b-=d,v+=d):b=v=(b+v)/2),l.moveTo(p*Wn(m),p*Vn(m)),l.arc(0,0,p,m,g),m!==b||g!==v)if(t){var w=y-+t.apply(this,arguments),_=(b+v)/2;l.quadraticCurveTo(0,0,w*Wn(b),w*Vn(b)),l.lineTo(y*Wn(_),y*Vn(_)),l.lineTo(w*Wn(v),w*Vn(v))}else l.quadraticCurveTo(0,0,y*Wn(b),y*Vn(b)),l.arc(0,0,y,b,v);if(l.quadraticCurveTo(0,0,p*Wn(m),p*Vn(m)),l.closePath(),c)return l=null,c+""||null}return t&&(c.headRadius=function(e){return arguments.length?(t="function"==typeof e?e:pr(+e),c):t}),c.radius=function(t){return arguments.length?(r=s="function"==typeof t?t:pr(+t),c):r},c.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:pr(+t),c):r},c.targetRadius=function(t){return arguments.length?(s="function"==typeof t?t:pr(+t),c):s},c.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:pr(+t),c):o},c.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:pr(+t),c):i},c.padAngle=function(t){return arguments.length?(a="function"==typeof t?t:pr(+t),c):a},c.source=function(t){return arguments.length?(e=t,c):e},c.target=function(t){return arguments.length?(n=t,c):n},c.context=function(t){return arguments.length?(l=null==t?null:t,c):l},c}function kr(){return xr()}function qr(){return xr(_r)}var Nr=n(3456);const Sr=Math.PI/180,Ar=180/Math.PI,Mr=.96422,Tr=1,Cr=.82521,jr=4/29,Er=6/29,Or=3*Er*Er,Ir=Er*Er*Er;function Rr(t){if(t instanceof Dr)return new Dr(t.l,t.a,t.b,t.opacity);if(t instanceof Jr)return Hr(t);t instanceof $e.Ss||(t=(0,$e.SU)(t));var e,n,r=Zr(t.r),s=Zr(t.g),o=Zr(t.b),i=Lr((.2225045*r+.7168786*s+.0606169*o)/Tr);return r===s&&s===o?e=n=i:(e=Lr((.4360747*r+.3850649*s+.1430804*o)/Mr),n=Lr((.0139322*r+.0971045*s+.7141733*o)/Cr)),new Dr(116*i-16,500*(e-i),200*(i-n),t.opacity)}function Fr(t,e){return new Dr(t,0,0,null==e?1:e)}function Pr(t,e,n,r){return 1===arguments.length?Rr(t):new Dr(t,e,n,null==r?1:r)}function Dr(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}function Lr(t){return t>Ir?Math.pow(t,1/3):t/Or+jr}function $r(t){return t>Er?t*t*t:Or*(t-jr)}function zr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Zr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ur(t){if(t instanceof Jr)return new Jr(t.h,t.c,t.l,t.opacity);if(t instanceof Dr||(t=Rr(t)),0===t.a&&0===t.b)return new Jr(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);var e=Math.atan2(t.b,t.a)*Ar;return new Jr(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function Br(t,e,n,r){return 1===arguments.length?Ur(t):new Jr(n,e,t,null==r?1:r)}function Gr(t,e,n,r){return 1===arguments.length?Ur(t):new Jr(t,e,n,null==r?1:r)}function Jr(t,e,n,r){this.h=+t,this.c=+e,this.l=+n,this.opacity=+r}function Hr(t){if(isNaN(t.h))return new Dr(t.l,0,0,t.opacity);var e=t.h*Sr;return new Dr(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}(0,Nr.Z)(Dr,Pr,(0,Nr.l)($e.Il,{brighter(t){return new Dr(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker(t){return new Dr(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,n=isNaN(this.b)?t:t-this.b/200;return e=Mr*$r(e),t=Tr*$r(t),n=Cr*$r(n),new $e.Ss(zr(3.1338561*e-1.6168667*t-.4906146*n),zr(-.9787684*e+1.9161415*t+.033454*n),zr(.0719453*e-.2289914*t+1.4052427*n),this.opacity)}})),(0,Nr.Z)(Jr,Gr,(0,Nr.l)($e.Il,{brighter(t){return new Jr(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker(t){return new Jr(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb(){return Hr(this).rgb()}}));var Wr=-.14861,Vr=1.78277,Yr=-.29227,Kr=-.90649,Xr=1.97294,Qr=Xr*Kr,ts=Xr*Vr,es=Vr*Yr-Kr*Wr;function ns(t,e,n,r){return 1===arguments.length?function(t){if(t instanceof rs)return new rs(t.h,t.s,t.l,t.opacity);t instanceof $e.Ss||(t=(0,$e.SU)(t));var e=t.r/255,n=t.g/255,r=t.b/255,s=(es*r+Qr*e-ts*n)/(es+Qr-ts),o=r-s,i=(Xr*(n-s)-Yr*o)/Kr,a=Math.sqrt(i*i+o*o)/(Xr*s*(1-s)),l=a?Math.atan2(i,o)*Ar-120:NaN;return new rs(l<0?l+360:l,a,s,t.opacity)}(t):new rs(t,e,n,null==r?1:r)}function rs(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}(0,Nr.Z)(rs,ns,(0,Nr.l)($e.Il,{brighter(t){return t=null==t?$e.J5:Math.pow($e.J5,t),new rs(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?$e.xV:Math.pow($e.xV,t),new rs(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=isNaN(this.h)?0:(this.h+120)*Sr,e=+this.l,n=isNaN(this.s)?0:this.s*e*(1-e),r=Math.cos(t),s=Math.sin(t);return new $e.Ss(255*(e+n*(Wr*r+Vr*s)),255*(e+n*(Yr*r+Kr*s)),255*(e+n*(Xr*r)),this.opacity)}}));var ss=n(2327),os=n(2038),is=n(6106),as=Array.prototype.slice;function ls(t,e){return t-e}const cs=t=>()=>t;function us(t,e){for(var n,r=-1,s=e.length;++r<s;)if(n=fs(t,e[r]))return n;return 0}function fs(t,e){for(var n=e[0],r=e[1],s=-1,o=0,i=t.length,a=i-1;o<i;a=o++){var l=t[o],c=l[0],u=l[1],f=t[a],d=f[0],h=f[1];if(ds(l,f,e))return 0;u>r!=h>r&&n<(d-c)*(r-u)/(h-u)+c&&(s=-s)}return s}function ds(t,e,n){var r;return function(t,e,n){return(e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&function(t,e,n){return t<=e&&e<=n||n<=e&&e<=t}(t[r=+(t[0]===e[0])],n[r],e[r])}function hs(){}var ps=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function ms(){var t=1,e=1,n=ss.Z,r=a;function s(t){var e=n(t);if(Array.isArray(e))e=e.slice().sort(ls);else{const n=(0,os.Z)(t),r=(0,is.ly)(n[0],n[1],e);e=(0,is.ZP)(Math.floor(n[0]/r)*r,Math.floor(n[1]/r-1)*r,e)}return e.map((e=>o(t,e)))}function o(n,s){var o=[],a=[];return function(n,r,s){var o,a,l,c,u,f,d=new Array,h=new Array;o=a=-1,c=n[0]>=r,ps[c<<1].forEach(p);for(;++o<t-1;)l=c,c=n[o+1]>=r,ps[l|c<<1].forEach(p);ps[c<<0].forEach(p);for(;++a<e-1;){for(o=-1,c=n[a*t+t]>=r,u=n[a*t]>=r,ps[c<<1|u<<2].forEach(p);++o<t-1;)l=c,c=n[a*t+t+o+1]>=r,f=u,u=n[a*t+o+1]>=r,ps[l|c<<1|u<<2|f<<3].forEach(p);ps[c|u<<3].forEach(p)}o=-1,u=n[a*t]>=r,ps[u<<2].forEach(p);for(;++o<t-1;)f=u,u=n[a*t+o+1]>=r,ps[u<<2|f<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+o,t[0][1]+a],l=[t[1][0]+o,t[1][1]+a],c=i(r),u=i(l);(e=h[c])?(n=d[u])?(delete h[e.end],delete d[n.start],e===n?(e.ring.push(l),s(e.ring)):d[e.start]=h[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[e.end],e.ring.push(l),h[e.end=u]=e):(e=d[u])?(n=h[c])?(delete d[e.start],delete h[n.end],e===n?(e.ring.push(l),s(e.ring)):d[n.start]=h[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[e.start],e.ring.unshift(r),d[e.start=c]=e):d[c]=h[u]={start:c,end:u,ring:[r,l]}}ps[u<<3].forEach(p)}(n,s,(function(t){r(t,n,s),function(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++e<n;)r+=t[e-1][1]*t[e][0]-t[e-1][0]*t[e][1];return r}(t)>0?o.push([t]):a.push(t)})),a.forEach((function(t){for(var e,n=0,r=o.length;n<r;++n)if(-1!==us((e=o[n])[0],t))return void e.push(t)})),{type:"MultiPolygon",value:s,coordinates:o}}function i(e){return 2*e[0]+e[1]*(t+1)*4}function a(n,r,s){n.forEach((function(n){var o,i=n[0],a=n[1],l=0|i,c=0|a,u=r[c*t+l];i>0&&i<t&&l===i&&(o=r[c*t+l-1],n[0]=i+(s-o)/(u-o)-.5),a>0&&a<e&&c===a&&(o=r[(c-1)*t+l],n[1]=a+(s-o)/(u-o)-.5)}))}return s.contour=o,s.size=function(n){if(!arguments.length)return[t,e];var r=Math.floor(n[0]),o=Math.floor(n[1]);if(!(r>=0&&o>=0))throw new Error("invalid size");return t=r,e=o,s},s.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?cs(as.call(t)):cs(t),s):n},s.smooth=function(t){return arguments.length?(r=t?a:hs,s):r===a},s}var gs=n(1045),ys=n(8319);function bs(t){return t[0]}function vs(t){return t[1]}function ws(){return 1}function _s(){var t=bs,e=vs,n=ws,r=960,s=500,o=20,i=2,a=3*o,l=r+2*a>>i,c=s+2*a>>i,u=cs(20);function f(r){var s=new Float32Array(l*c),u=Math.pow(2,-i),f=-1;for(const o of r){var d=(t(o,++f,r)+a)*u,h=(e(o,f,r)+a)*u,p=+n(o,f,r);if(d>=0&&d<l&&h>=0&&h<c){var m=Math.floor(d),g=Math.floor(h),y=d-m-.5,b=h-g-.5;s[m+g*l]+=(1-y)*(1-b)*p,s[m+1+g*l]+=y*(1-b)*p,s[m+1+(g+1)*l]+=y*b*p,s[m+(g+1)*l]+=(1-y)*b*p}}return(0,gs.u8)({data:s,width:l,height:c},o*u),s}function d(t){var e=f(t),n=u(e),r=Math.pow(2,2*i);return Array.isArray(n)||(n=(0,is.ZP)(Number.MIN_VALUE,(0,ys.Z)(e)/r,n)),ms().size([l,c]).thresholds(n.map((t=>t*r)))(e).map(((t,e)=>(t.value=+n[e],h(t))))}function h(t){return t.coordinates.forEach(p),t}function p(t){t.forEach(m)}function m(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,i)-a,t[1]=t[1]*Math.pow(2,i)-a}function y(){return l=r+2*(a=3*o)>>i,c=s+2*a>>i,d}return d.contours=function(t){var e=f(t),n=ms().size([l,c]),r=Math.pow(2,2*i),s=t=>{t=+t;var s=h(n.contour(e,t*r));return s.value=t,s};return Object.defineProperty(s,"max",{get:()=>(0,ys.Z)(e)/r}),s},d.x=function(e){return arguments.length?(t="function"==typeof e?e:cs(+e),d):t},d.y=function(t){return arguments.length?(e="function"==typeof t?t:cs(+t),d):e},d.weight=function(t){return arguments.length?(n="function"==typeof t?t:cs(+t),d):n},d.size=function(t){if(!arguments.length)return[r,s];var e=+t[0],n=+t[1];if(!(e>=0&&n>=0))throw new Error("invalid size");return r=e,s=n,y()},d.cellSize=function(t){if(!arguments.length)return 1<<i;if(!((t=+t)>=1))throw new Error("invalid cell size");return i=Math.floor(Math.log(t)/Math.LN2),y()},d.thresholds=function(t){return arguments.length?(u="function"==typeof t?t:Array.isArray(t)?cs(as.call(t)):cs(t),d):u},d.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=(Math.sqrt(4*t*t+1)-1)/2,y()},d}const xs=134217729,ks=33306690738754706e-32;function qs(t,e,n,r,s){let o,i,a,l,c=e[0],u=r[0],f=0,d=0;u>c==u>-c?(o=c,c=e[++f]):(o=u,u=r[++d]);let h=0;if(f<t&&d<n)for(u>c==u>-c?(i=c+o,a=o-(i-c),c=e[++f]):(i=u+o,a=o-(i-u),u=r[++d]),o=i,0!==a&&(s[h++]=a);f<t&&d<n;)u>c==u>-c?(i=o+c,l=i-o,a=o-(i-l)+(c-l),c=e[++f]):(i=o+u,l=i-o,a=o-(i-l)+(u-l),u=r[++d]),o=i,0!==a&&(s[h++]=a);for(;f<t;)i=o+c,l=i-o,a=o-(i-l)+(c-l),c=e[++f],o=i,0!==a&&(s[h++]=a);for(;d<n;)i=o+u,l=i-o,a=o-(i-l)+(u-l),u=r[++d],o=i,0!==a&&(s[h++]=a);return 0===o&&0!==h||(s[h++]=o),h}function Ns(t){return new Float64Array(t)}const Ss=22204460492503146e-32,As=11093356479670487e-47,Ms=Ns(4),Ts=Ns(8),Cs=Ns(12),js=Ns(16),Es=Ns(4);function Os(t,e,n,r,s,o){const i=(e-o)*(n-s),a=(t-s)*(r-o),l=i-a;if(0===i||0===a||i>0!=a>0)return l;const c=Math.abs(i+a);return Math.abs(l)>=33306690738754716e-32*c?l:-function(t,e,n,r,s,o,i){let a,l,c,u,f,d,h,p,m,g,y,b,v,w,_,x,k,q;const N=t-s,S=n-s,A=e-o,M=r-o;w=N*M,d=xs*N,h=d-(d-N),p=N-h,d=xs*M,m=d-(d-M),g=M-m,_=p*g-(w-h*m-p*m-h*g),x=A*S,d=xs*A,h=d-(d-A),p=A-h,d=xs*S,m=d-(d-S),g=S-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Ms[0]=_-(y+f)+(f-k),b=w+y,f=b-w,v=w-(b-f)+(y-f),y=v-x,f=v-y,Ms[1]=v-(y+f)+(f-x),q=b+y,f=q-b,Ms[2]=b-(q-f)+(y-f),Ms[3]=q;let T=function(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}(4,Ms),C=Ss*i;if(T>=C||-T>=C)return T;if(f=t-N,a=t-(N+f)+(f-s),f=n-S,c=n-(S+f)+(f-s),f=e-A,l=e-(A+f)+(f-o),f=r-M,u=r-(M+f)+(f-o),0===a&&0===l&&0===c&&0===u)return T;if(C=As*i+ks*Math.abs(T),T+=N*u+M*a-(A*c+S*l),T>=C||-T>=C)return T;w=a*M,d=xs*a,h=d-(d-a),p=a-h,d=xs*M,m=d-(d-M),g=M-m,_=p*g-(w-h*m-p*m-h*g),x=l*S,d=xs*l,h=d-(d-l),p=l-h,d=xs*S,m=d-(d-S),g=S-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Es[0]=_-(y+f)+(f-k),b=w+y,f=b-w,v=w-(b-f)+(y-f),y=v-x,f=v-y,Es[1]=v-(y+f)+(f-x),q=b+y,f=q-b,Es[2]=b-(q-f)+(y-f),Es[3]=q;const j=qs(4,Ms,4,Es,Ts);w=N*u,d=xs*N,h=d-(d-N),p=N-h,d=xs*u,m=d-(d-u),g=u-m,_=p*g-(w-h*m-p*m-h*g),x=A*c,d=xs*A,h=d-(d-A),p=A-h,d=xs*c,m=d-(d-c),g=c-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Es[0]=_-(y+f)+(f-k),b=w+y,f=b-w,v=w-(b-f)+(y-f),y=v-x,f=v-y,Es[1]=v-(y+f)+(f-x),q=b+y,f=q-b,Es[2]=b-(q-f)+(y-f),Es[3]=q;const E=qs(j,Ts,4,Es,Cs);w=a*u,d=xs*a,h=d-(d-a),p=a-h,d=xs*u,m=d-(d-u),g=u-m,_=p*g-(w-h*m-p*m-h*g),x=l*c,d=xs*l,h=d-(d-l),p=l-h,d=xs*c,m=d-(d-c),g=c-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Es[0]=_-(y+f)+(f-k),b=w+y,f=b-w,v=w-(b-f)+(y-f),y=v-x,f=v-y,Es[1]=v-(y+f)+(f-x),q=b+y,f=q-b,Es[2]=b-(q-f)+(y-f),Es[3]=q;const O=qs(E,Cs,4,Es,js);return js[O-1]}(t,e,n,r,s,o,c)}Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(8),Ns(8),Ns(8),Ns(4),Ns(8),Ns(8),Ns(8),Ns(12);Ns(192),Ns(192);Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(8),Ns(8),Ns(8),Ns(8),Ns(8),Ns(8),Ns(8),Ns(8),Ns(8),Ns(4),Ns(4),Ns(4),Ns(8),Ns(16),Ns(16),Ns(16),Ns(32),Ns(32),Ns(48),Ns(64);Ns(1152),Ns(1152);Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(4),Ns(24),Ns(24),Ns(24),Ns(24),Ns(24),Ns(24),Ns(24),Ns(24),Ns(24),Ns(24),Ns(1152),Ns(1152),Ns(1152),Ns(1152),Ns(1152),Ns(2304),Ns(2304),Ns(3456),Ns(5760),Ns(8),Ns(8),Ns(8),Ns(16),Ns(24),Ns(48),Ns(48),Ns(96),Ns(192),Ns(384),Ns(384),Ns(384),Ns(768);Ns(96),Ns(96),Ns(96),Ns(1152);const Is=Math.pow(2,-52),Rs=new Uint32Array(512);class Fs{static from(t,e=Zs,n=Us){const r=t.length,s=new Float64Array(2*r);for(let o=0;o<r;o++){const r=t[o];s[2*o]=e(r),s[2*o+1]=n(r)}return new Fs(s)}constructor(t){const e=t.length>>1;if(e>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const n=Math.max(2*e-5,0);this._triangles=new Uint32Array(3*n),this._halfedges=new Int32Array(3*n),this._hashSize=Math.ceil(Math.sqrt(e)),this._hullPrev=new Uint32Array(e),this._hullNext=new Uint32Array(e),this._hullTri=new Uint32Array(e),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(e),this._dists=new Float64Array(e),this.update()}update(){const{coords:t,_hullPrev:e,_hullNext:n,_hullTri:r,_hullHash:s}=this,o=t.length>>1;let i=1/0,a=1/0,l=-1/0,c=-1/0;for(let e=0;e<o;e++){const n=t[2*e],r=t[2*e+1];n<i&&(i=n),r<a&&(a=r),n>l&&(l=n),r>c&&(c=r),this._ids[e]=e}const u=(i+l)/2,f=(a+c)/2;let d,h,p,m=1/0;for(let e=0;e<o;e++){const n=Ps(u,f,t[2*e],t[2*e+1]);n<m&&(d=e,m=n)}const g=t[2*d],y=t[2*d+1];m=1/0;for(let e=0;e<o;e++){if(e===d)continue;const n=Ps(g,y,t[2*e],t[2*e+1]);n<m&&n>0&&(h=e,m=n)}let b=t[2*h],v=t[2*h+1],w=1/0;for(let e=0;e<o;e++){if(e===d||e===h)continue;const n=Ls(g,y,b,v,t[2*e],t[2*e+1]);n<w&&(p=e,w=n)}let _=t[2*p],x=t[2*p+1];if(w===1/0){for(let e=0;e<o;e++)this._dists[e]=t[2*e]-t[0]||t[2*e+1]-t[1];$s(this._ids,this._dists,0,o-1);const e=new Uint32Array(o);let n=0;for(let t=0,r=-1/0;t<o;t++){const s=this._ids[t];this._dists[s]>r&&(e[n++]=s,r=this._dists[s])}return this.hull=e.subarray(0,n),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Os(g,y,b,v,_,x)<0){const t=h,e=b,n=v;h=p,b=_,v=x,p=t,_=e,x=n}const k=function(t,e,n,r,s,o){const i=n-t,a=r-e,l=s-t,c=o-e,u=i*i+a*a,f=l*l+c*c,d=.5/(i*c-a*l),h=t+(c*u-a*f)*d,p=e+(i*f-l*u)*d;return{x:h,y:p}}(g,y,b,v,_,x);this._cx=k.x,this._cy=k.y;for(let e=0;e<o;e++)this._dists[e]=Ps(t[2*e],t[2*e+1],k.x,k.y);$s(this._ids,this._dists,0,o-1),this._hullStart=d;let q=3;n[d]=e[p]=h,n[h]=e[d]=p,n[p]=e[h]=d,r[d]=0,r[h]=1,r[p]=2,s.fill(-1),s[this._hashKey(g,y)]=d,s[this._hashKey(b,v)]=h,s[this._hashKey(_,x)]=p,this.trianglesLen=0,this._addTriangle(d,h,p,-1,-1,-1);for(let o,i,a=0;a<this._ids.length;a++){const l=this._ids[a],c=t[2*l],u=t[2*l+1];if(a>0&&Math.abs(c-o)<=Is&&Math.abs(u-i)<=Is)continue;if(o=c,i=u,l===d||l===h||l===p)continue;let f=0;for(let t=0,e=this._hashKey(c,u);t<this._hashSize&&(f=s[(e+t)%this._hashSize],-1===f||f===n[f]);t++);f=e[f];let m,g=f;for(;m=n[g],Os(c,u,t[2*g],t[2*g+1],t[2*m],t[2*m+1])>=0;)if(g=m,g===f){g=-1;break}if(-1===g)continue;let y=this._addTriangle(g,l,n[g],-1,-1,r[g]);r[l]=this._legalize(y+2),r[g]=y,q++;let b=n[g];for(;m=n[b],Os(c,u,t[2*b],t[2*b+1],t[2*m],t[2*m+1])<0;)y=this._addTriangle(b,l,m,r[l],-1,r[b]),r[l]=this._legalize(y+2),n[b]=b,q--,b=m;if(g===f)for(;m=e[g],Os(c,u,t[2*m],t[2*m+1],t[2*g],t[2*g+1])<0;)y=this._addTriangle(m,l,g,-1,r[g],r[m]),this._legalize(y+2),r[m]=y,n[g]=g,q--,g=m;this._hullStart=e[l]=g,n[g]=e[b]=l,n[l]=b,s[this._hashKey(c,u)]=l,s[this._hashKey(t[2*g],t[2*g+1])]=g}this.hull=new Uint32Array(q);for(let t=0,e=this._hullStart;t<q;t++)this.hull[t]=e,e=n[e];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(t,e){return Math.floor(function(t,e){const n=t/(Math.abs(t)+Math.abs(e));return(e>0?3-n:1+n)/4}(t-this._cx,e-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:e,_halfedges:n,coords:r}=this;let s=0,o=0;for(;;){const i=n[t],a=t-t%3;if(o=a+(t+2)%3,-1===i){if(0===s)break;t=Rs[--s];continue}const l=i-i%3,c=a+(t+1)%3,u=l+(i+2)%3,f=e[o],d=e[t],h=e[c],p=e[u];if(Ds(r[2*f],r[2*f+1],r[2*d],r[2*d+1],r[2*h],r[2*h+1],r[2*p],r[2*p+1])){e[t]=p,e[i]=f;const r=n[u];if(-1===r){let e=this._hullStart;do{if(this._hullTri[e]===u){this._hullTri[e]=t;break}e=this._hullPrev[e]}while(e!==this._hullStart)}this._link(t,r),this._link(i,n[o]),this._link(o,u);const a=l+(i+1)%3;s<Rs.length&&(Rs[s++]=a)}else{if(0===s)break;t=Rs[--s]}}return o}_link(t,e){this._halfedges[t]=e,-1!==e&&(this._halfedges[e]=t)}_addTriangle(t,e,n,r,s,o){const i=this.trianglesLen;return this._triangles[i]=t,this._triangles[i+1]=e,this._triangles[i+2]=n,this._link(i,r),this._link(i+1,s),this._link(i+2,o),this.trianglesLen+=3,i}}function Ps(t,e,n,r){const s=t-n,o=e-r;return s*s+o*o}function Ds(t,e,n,r,s,o,i,a){const l=t-i,c=e-a,u=n-i,f=r-a,d=s-i,h=o-a,p=u*u+f*f,m=d*d+h*h;return l*(f*m-p*h)-c*(u*m-p*d)+(l*l+c*c)*(u*h-f*d)<0}function Ls(t,e,n,r,s,o){const i=n-t,a=r-e,l=s-t,c=o-e,u=i*i+a*a,f=l*l+c*c,d=.5/(i*c-a*l),h=(c*u-a*f)*d,p=(i*f-l*u)*d;return h*h+p*p}function $s(t,e,n,r){if(r-n<=20)for(let s=n+1;s<=r;s++){const r=t[s],o=e[r];let i=s-1;for(;i>=n&&e[t[i]]>o;)t[i+1]=t[i--];t[i+1]=r}else{let s=n+1,o=r;zs(t,n+r>>1,s),e[t[n]]>e[t[r]]&&zs(t,n,r),e[t[s]]>e[t[r]]&&zs(t,s,r),e[t[n]]>e[t[s]]&&zs(t,n,s);const i=t[s],a=e[i];for(;;){do{s++}while(e[t[s]]<a);do{o--}while(e[t[o]]>a);if(o<s)break;zs(t,s,o)}t[n+1]=t[o],t[o]=i,r-s+1>=o-n?($s(t,e,s,r),$s(t,e,n,o-1)):($s(t,e,n,o-1),$s(t,e,s,r))}}function zs(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function Zs(t){return t[0]}function Us(t){return t[1]}const Bs=1e-6;class Gs{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,e){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,e){this._+=`L${this._x1=+t},${this._y1=+e}`}arc(t,e,n){const r=(t=+t)+(n=+n),s=e=+e;if(n<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${s}`:(Math.abs(this._x1-r)>Bs||Math.abs(this._y1-s)>Bs)&&(this._+="L"+r+","+s),n&&(this._+=`A${n},${n},0,1,1,${t-n},${e}A${n},${n},0,1,1,${this._x1=r},${this._y1=s}`)}rect(t,e,n,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${+n}v${+r}h${-n}Z`}value(){return this._||null}}class Js{constructor(){this._=[]}moveTo(t,e){this._.push([t,e])}closePath(){this._.push(this._[0].slice())}lineTo(t,e){this._.push([t,e])}value(){return this._.length?this._:null}}class Hs{constructor(t,[e,n,r,s]=[0,0,960,500]){if(!((r=+r)>=(e=+e)&&(s=+s)>=(n=+n)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=e,this.ymax=s,this.ymin=n,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:e,triangles:n},vectors:r}=this,s=this.circumcenters=this._circumcenters.subarray(0,n.length/3*2);for(let e,r,o=0,i=0,a=n.length;o<a;o+=3,i+=2){const a=2*n[o],l=2*n[o+1],c=2*n[o+2],u=t[a],f=t[a+1],d=t[l],h=t[l+1],p=t[c],m=t[c+1],g=d-u,y=h-f,b=p-u,v=m-f,w=2*(g*v-y*b);if(Math.abs(w)<1e-9){let s=1e9;const o=2*n[0];s*=Math.sign((t[o]-u)*v-(t[o+1]-f)*b),e=(u+p)/2-s*v,r=(f+m)/2+s*b}else{const t=1/w,n=g*g+y*y,s=b*b+v*v;e=u+(v*n-y*s)*t,r=f+(g*s-b*n)*t}s[i]=e,s[i+1]=r}let o,i,a,l=e[e.length-1],c=4*l,u=t[2*l],f=t[2*l+1];r.fill(0);for(let n=0;n<e.length;++n)l=e[n],o=c,i=u,a=f,c=4*l,u=t[2*l],f=t[2*l+1],r[o+2]=r[c]=a-f,r[o+3]=r[c+1]=u-i}render(t){const e=null==t?t=new Gs:void 0,{delaunay:{halfedges:n,inedges:r,hull:s},circumcenters:o,vectors:i}=this;if(s.length<=1)return null;for(let e=0,r=n.length;e<r;++e){const r=n[e];if(r<e)continue;const s=2*Math.floor(e/3),i=2*Math.floor(r/3),a=o[s],l=o[s+1],c=o[i],u=o[i+1];this._renderSegment(a,l,c,u,t)}let a,l=s[s.length-1];for(let e=0;e<s.length;++e){a=l,l=s[e];const n=2*Math.floor(r[l]/3),c=o[n],u=o[n+1],f=4*a,d=this._project(c,u,i[f+2],i[f+3]);d&&this._renderSegment(c,u,d[0],d[1],t)}return e&&e.value()}renderBounds(t){const e=null==t?t=new Gs:void 0;return t.rect(this.xmin,this.ymin,this.xmax-this.xmin,this.ymax-this.ymin),e&&e.value()}renderCell(t,e){const n=null==e?e=new Gs:void 0,r=this._clip(t);if(null===r||!r.length)return;e.moveTo(r[0],r[1]);let s=r.length;for(;r[0]===r[s-2]&&r[1]===r[s-1]&&s>1;)s-=2;for(let t=2;t<s;t+=2)r[t]===r[t-2]&&r[t+1]===r[t-1]||e.lineTo(r[t],r[t+1]);return e.closePath(),n&&n.value()}*cellPolygons(){const{delaunay:{points:t}}=this;for(let e=0,n=t.length/2;e<n;++e){const t=this.cellPolygon(e);t&&(t.index=e,yield t)}}cellPolygon(t){const e=new Js;return this.renderCell(t,e),e.value()}_renderSegment(t,e,n,r,s){let o;const i=this._regioncode(t,e),a=this._regioncode(n,r);0===i&&0===a?(s.moveTo(t,e),s.lineTo(n,r)):(o=this._clipSegment(t,e,n,r,i,a))&&(s.moveTo(o[0],o[1]),s.lineTo(o[2],o[3]))}contains(t,e,n){return(e=+e)==e&&(n=+n)==n&&this.delaunay._step(t,e,n)===t}*neighbors(t){const e=this._clip(t);if(e)for(const n of this.delaunay.neighbors(t)){const t=this._clip(n);if(t)t:for(let r=0,s=e.length;r<s;r+=2)for(let o=0,i=t.length;o<i;o+=2)if(e[r]==t[o]&&e[r+1]==t[o+1]&&e[(r+2)%s]==t[(o+i-2)%i]&&e[(r+3)%s]==t[(o+i-1)%i]){yield n;break t}}}_cell(t){const{circumcenters:e,delaunay:{inedges:n,halfedges:r,triangles:s}}=this,o=n[t];if(-1===o)return null;const i=[];let a=o;do{const n=Math.floor(a/3);if(i.push(e[2*n],e[2*n+1]),a=a%3==2?a-2:a+1,s[a]!==t)break;a=r[a]}while(a!==o&&-1!==a);return i}_clip(t){if(0===t&&1===this.delaunay.hull.length)return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];const e=this._cell(t);if(null===e)return null;const{vectors:n}=this,r=4*t;return n[r]||n[r+1]?this._clipInfinite(t,e,n[r],n[r+1],n[r+2],n[r+3]):this._clipFinite(t,e)}_clipFinite(t,e){const n=e.length;let r,s,o,i,a=null,l=e[n-2],c=e[n-1],u=this._regioncode(l,c),f=0;for(let d=0;d<n;d+=2)if(r=l,s=c,l=e[d],c=e[d+1],o=u,u=this._regioncode(l,c),0===o&&0===u)i=f,f=0,a?a.push(l,c):a=[l,c];else{let e,n,d,h,p;if(0===o){if(null===(e=this._clipSegment(r,s,l,c,o,u)))continue;[n,d,h,p]=e}else{if(null===(e=this._clipSegment(l,c,r,s,u,o)))continue;[h,p,n,d]=e,i=f,f=this._edgecode(n,d),i&&f&&this._edge(t,i,f,a,a.length),a?a.push(n,d):a=[n,d]}i=f,f=this._edgecode(h,p),i&&f&&this._edge(t,i,f,a,a.length),a?a.push(h,p):a=[h,p]}if(a)i=f,f=this._edgecode(a[0],a[1]),i&&f&&this._edge(t,i,f,a,a.length);else if(this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2))return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];return a}_clipSegment(t,e,n,r,s,o){for(;;){if(0===s&&0===o)return[t,e,n,r];if(s&o)return null;let i,a,l=s||o;8&l?(i=t+(n-t)*(this.ymax-e)/(r-e),a=this.ymax):4&l?(i=t+(n-t)*(this.ymin-e)/(r-e),a=this.ymin):2&l?(a=e+(r-e)*(this.xmax-t)/(n-t),i=this.xmax):(a=e+(r-e)*(this.xmin-t)/(n-t),i=this.xmin),s?(t=i,e=a,s=this._regioncode(t,e)):(n=i,r=a,o=this._regioncode(n,r))}}_clipInfinite(t,e,n,r,s,o){let i,a=Array.from(e);if((i=this._project(a[0],a[1],n,r))&&a.unshift(i[0],i[1]),(i=this._project(a[a.length-2],a[a.length-1],s,o))&&a.push(i[0],i[1]),a=this._clipFinite(t,a))for(let e,n=0,r=a.length,s=this._edgecode(a[r-2],a[r-1]);n<r;n+=2)e=s,s=this._edgecode(a[n],a[n+1]),e&&s&&(n=this._edge(t,e,s,a,n),r=a.length);else this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2)&&(a=[this.xmin,this.ymin,this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax]);return a}_edge(t,e,n,r,s){for(;e!==n;){let n,o;switch(e){case 5:e=4;continue;case 4:e=6,n=this.xmax,o=this.ymin;break;case 6:e=2;continue;case 2:e=10,n=this.xmax,o=this.ymax;break;case 10:e=8;continue;case 8:e=9,n=this.xmin,o=this.ymax;break;case 9:e=1;continue;case 1:e=5,n=this.xmin,o=this.ymin}r[s]===n&&r[s+1]===o||!this.contains(t,n,o)||(r.splice(s,0,n,o),s+=2)}if(r.length>4)for(let t=0;t<r.length;t+=2){const e=(t+2)%r.length,n=(t+4)%r.length;(r[t]===r[e]&&r[e]===r[n]||r[t+1]===r[e+1]&&r[e+1]===r[n+1])&&(r.splice(e,2),t-=2)}return s}_project(t,e,n,r){let s,o,i,a=1/0;if(r<0){if(e<=this.ymin)return null;(s=(this.ymin-e)/r)<a&&(i=this.ymin,o=t+(a=s)*n)}else if(r>0){if(e>=this.ymax)return null;(s=(this.ymax-e)/r)<a&&(i=this.ymax,o=t+(a=s)*n)}if(n>0){if(t>=this.xmax)return null;(s=(this.xmax-t)/n)<a&&(o=this.xmax,i=e+(a=s)*r)}else if(n<0){if(t<=this.xmin)return null;(s=(this.xmin-t)/n)<a&&(o=this.xmin,i=e+(a=s)*r)}return[o,i]}_edgecode(t,e){return(t===this.xmin?1:t===this.xmax?2:0)|(e===this.ymin?4:e===this.ymax?8:0)}_regioncode(t,e){return(t<this.xmin?1:t>this.xmax?2:0)|(e<this.ymin?4:e>this.ymax?8:0)}}const Ws=2*Math.PI,Vs=Math.pow;function Ys(t){return t[0]}function Ks(t){return t[1]}function Xs(t,e,n){return[t+Math.sin(t+e)*n,e+Math.cos(t-e)*n]}class Qs{static from(t,e=Ys,n=Ks,r){return new Qs("length"in t?function(t,e,n,r){const s=t.length,o=new Float64Array(2*s);for(let i=0;i<s;++i){const s=t[i];o[2*i]=e.call(r,s,i,t),o[2*i+1]=n.call(r,s,i,t)}return o}(t,e,n,r):Float64Array.from(function*(t,e,n,r){let s=0;for(const o of t)yield e.call(r,o,s,t),yield n.call(r,o,s,t),++s}(t,e,n,r)))}constructor(t){this._delaunator=new Fs(t),this.inedges=new Int32Array(t.length/2),this._hullIndex=new Int32Array(t.length/2),this.points=this._delaunator.coords,this._init()}update(){return this._delaunator.update(),this._init(),this}_init(){const t=this._delaunator,e=this.points;if(t.hull&&t.hull.length>2&&function(t){const{triangles:e,coords:n}=t;for(let t=0;t<e.length;t+=3){const r=2*e[t],s=2*e[t+1],o=2*e[t+2];if((n[o]-n[r])*(n[s+1]-n[r+1])-(n[s]-n[r])*(n[o+1]-n[r+1])>1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:e.length/2},((t,e)=>e)).sort(((t,n)=>e[2*t]-e[2*n]||e[2*t+1]-e[2*n+1]));const t=this.collinear[0],n=this.collinear[this.collinear.length-1],r=[e[2*t],e[2*t+1],e[2*n],e[2*n+1]],s=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,n=e.length/2;t<n;++t){const n=Xs(e[2*t],e[2*t+1],s);e[2*t]=n[0],e[2*t+1]=n[1]}this._delaunator=new Fs(e)}else delete this.collinear;const n=this.halfedges=this._delaunator.halfedges,r=this.hull=this._delaunator.hull,s=this.triangles=this._delaunator.triangles,o=this.inedges.fill(-1),i=this._hullIndex.fill(-1);for(let t=0,e=n.length;t<e;++t){const e=s[t%3==2?t-2:t+1];-1!==n[t]&&-1!==o[e]||(o[e]=t)}for(let t=0,e=r.length;t<e;++t)i[r[t]]=t;r.length<=2&&r.length>0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],o[r[0]]=1,2===r.length&&(o[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]))}voronoi(t){return new Hs(this,t)}*neighbors(t){const{inedges:e,hull:n,_hullIndex:r,halfedges:s,triangles:o,collinear:i}=this;if(i){const e=i.indexOf(t);return e>0&&(yield i[e-1]),void(e<i.length-1&&(yield i[e+1]))}const a=e[t];if(-1===a)return;let l=a,c=-1;do{if(yield c=o[l],l=l%3==2?l-2:l+1,o[l]!==t)return;if(l=s[l],-1===l){const e=n[(r[t]+1)%n.length];return void(e!==c&&(yield e))}}while(l!==a)}find(t,e,n=0){if((t=+t)!=t||(e=+e)!=e)return-1;const r=n;let s;for(;(s=this._step(n,t,e))>=0&&s!==n&&s!==r;)n=s;return s}_step(t,e,n){const{inedges:r,hull:s,_hullIndex:o,halfedges:i,triangles:a,points:l}=this;if(-1===r[t]||!l.length)return(t+1)%(l.length>>1);let c=t,u=Vs(e-l[2*t],2)+Vs(n-l[2*t+1],2);const f=r[t];let d=f;do{let r=a[d];const f=Vs(e-l[2*r],2)+Vs(n-l[2*r+1],2);if(f<u&&(u=f,c=r),d=d%3==2?d-2:d+1,a[d]!==t)break;if(d=i[d],-1===d){if(d=s[(o[t]+1)%s.length],d!==r&&Vs(e-l[2*d],2)+Vs(n-l[2*d+1],2)<u)return d;break}}while(d!==f);return c}render(t){const e=null==t?t=new Gs:void 0,{points:n,halfedges:r,triangles:s}=this;for(let e=0,o=r.length;e<o;++e){const o=r[e];if(o<e)continue;const i=2*s[e],a=2*s[o];t.moveTo(n[i],n[i+1]),t.lineTo(n[a],n[a+1])}return this.renderHull(t),e&&e.value()}renderPoints(t,e){void 0!==e||t&&"function"==typeof t.moveTo||(e=t,t=null),e=null==e?2:+e;const n=null==t?t=new Gs:void 0,{points:r}=this;for(let n=0,s=r.length;n<s;n+=2){const s=r[n],o=r[n+1];t.moveTo(s+e,o),t.arc(s,o,e,0,Ws)}return n&&n.value()}renderHull(t){const e=null==t?t=new Gs:void 0,{hull:n,points:r}=this,s=2*n[0],o=n.length;t.moveTo(r[s],r[s+1]);for(let e=1;e<o;++e){const s=2*n[e];t.lineTo(r[s],r[s+1])}return t.closePath(),e&&e.value()}hullPolygon(){const t=new Js;return this.renderHull(t),t.value()}renderTriangle(t,e){const n=null==e?e=new Gs:void 0,{points:r,triangles:s}=this,o=2*s[t*=3],i=2*s[t+1],a=2*s[t+2];return e.moveTo(r[o],r[o+1]),e.lineTo(r[i],r[i+1]),e.lineTo(r[a],r[a+1]),e.closePath(),n&&n.value()}*trianglePolygons(){const{triangles:t}=this;for(let e=0,n=t.length/3;e<n;++e)yield this.trianglePolygon(e)}trianglePolygon(t){const e=new Js;return this.renderTriangle(t,e),e.value()}}const to=t=>()=>t;function eo(t,{sourceEvent:e,subject:n,target:r,identifier:s,active:o,x:i,y:a,dx:l,dy:c,dispatch:u}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:u}})}function no(t){return!t.ctrlKey&&!t.button}function ro(){return this.parentNode}function so(t,e){return null==e?{x:t.x,y:t.y}:e}function oo(){return navigator.maxTouchPoints||"ontouchstart"in this}function io(){var t,e,n,r,s=no,o=ro,i=so,a=oo,l={},c=N("start","drag","end"),u=0,f=0;function d(t){t.on("mousedown.drag",h).filter(a).on("touchstart.drag",g).on("touchmove.drag",y,$t).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(i,a){if(!r&&s.call(this,i,a)){var l=v(this,o.call(this,i,a),i,a,"mouse");l&&(Lt(i.view).on("mousemove.drag",p,zt).on("mouseup.drag",m,zt),Bt(i.view),Zt(i),n=!1,t=i.clientX,e=i.clientY,l("start",i))}}function p(r){if(Ut(r),!n){var s=r.clientX-t,o=r.clientY-e;n=s*s+o*o>f}l.mouse("drag",r)}function m(t){Lt(t.view).on("mousemove.drag mouseup.drag",null),Gt(t.view,n),Ut(t),l.mouse("end",t)}function g(t,e){if(s.call(this,t,e)){var n,r,i=t.changedTouches,a=o.call(this,t,e),l=i.length;for(n=0;n<l;++n)(r=v(this,a,t,e,i[n].identifier,i[n]))&&(Zt(t),r("start",t,i[n]))}}function y(t){var e,n,r=t.changedTouches,s=r.length;for(e=0;e<s;++e)(n=l[r[e].identifier])&&(Ut(t),n("drag",t,r[e]))}function b(t){var e,n,s=t.changedTouches,o=s.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null}),500),e=0;e<o;++e)(n=l[s[e].identifier])&&(Zt(t),n("end",t,s[e]))}function v(t,e,n,r,s,o){var a,f,h,p=c.copy(),m=Wt(o||n,e);if(null!=(h=i.call(t,new eo("beforestart",{sourceEvent:n,target:d,identifier:s,active:u,x:m[0],y:m[1],dx:0,dy:0,dispatch:p}),r)))return a=h.x-m[0]||0,f=h.y-m[1]||0,function n(o,i,c){var g,y=m;switch(o){case"start":l[s]=n,g=u++;break;case"end":delete l[s],--u;case"drag":m=Wt(c||i,e),g=u}p.call(o,t,new eo(o,{sourceEvent:i,subject:h,target:d,identifier:s,active:g,x:m[0]+a,y:m[1]+f,dx:m[0]-y[0],dy:m[1]-y[1],dispatch:p}),r)}}return d.filter=function(t){return arguments.length?(s="function"==typeof t?t:to(!!t),d):s},d.container=function(t){return arguments.length?(o="function"==typeof t?t:to(t),d):o},d.subject=function(t){return arguments.length?(i="function"==typeof t?t:to(t),d):i},d.touchable=function(t){return arguments.length?(a="function"==typeof t?t:to(!!t),d):a},d.on=function(){var t=c.on.apply(c,arguments);return t===c?d:t},d.clickDistance=function(t){return arguments.length?(f=(t=+t)*t,d):Math.sqrt(f)},d}eo.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var ao=n(4476),lo=(0,ao.Z)(","),co=lo.parse,uo=lo.parseRows,fo=lo.format,ho=lo.formatBody,po=lo.formatRows,mo=lo.formatRow,go=lo.formatValue,yo=n(5026);function bo(t){for(var e in t){var n,r,s=t[e].trim();if(s)if("true"===s)s=!0;else if("false"===s)s=!1;else if("NaN"===s)s=NaN;else if(isNaN(n=+s)){if(!(r=s.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;vo&&r[4]&&!r[7]&&(s=s.replace(/-/g,"/").replace(/T/," ")),s=new Date(s)}else s=n;else s=null;t[e]=s}return t}const vo=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours(),wo=t=>+t;function _o(t){return t*t}function xo(t){return t*(2-t)}function ko(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}var qo=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),No=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),So=function t(e){function n(t){return((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3),Ao=Math.PI,Mo=Ao/2;function To(t){return 1==+t?1:1-Math.cos(t*Mo)}function Co(t){return Math.sin(t*Mo)}function jo(t){return(1-Math.cos(Ao*t))/2}function Eo(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}function Oo(t){return Eo(1-+t)}function Io(t){return 1-Eo(t)}function Ro(t){return((t*=2)<=1?Eo(1-t):2-Eo(t-1))/2}function Fo(t){return 1-Math.sqrt(1-t*t)}function Po(t){return Math.sqrt(1- --t*t)}function Do(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}var Lo=4/11,$o=6/11,zo=8/11,Zo=3/4,Uo=9/11,Bo=10/11,Go=15/16,Jo=21/22,Ho=63/64,Wo=1/Lo/Lo;function Vo(t){return 1-Yo(1-t)}function Yo(t){return(t=+t)<Lo?Wo*t*t:t<zo?Wo*(t-=$o)*t+Zo:t<Bo?Wo*(t-=Uo)*t+Go:Wo*(t-=Jo)*t+Ho}function Ko(t){return((t*=2)<=1?1-Yo(1-t):Yo(t-1)+1)/2}var Xo=1.70158,Qo=function t(e){function n(t){return(t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(Xo),ti=function t(e){function n(t){return--t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(Xo),ei=function t(e){function n(t){return((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(Xo),ni=2*Math.PI,ri=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ni);function s(t){return e*Eo(- --t)*Math.sin((r-t)/n)}return s.amplitude=function(e){return t(e,n*ni)},s.period=function(n){return t(e,n)},s}(1,.3),si=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ni);function s(t){return 1-e*Eo(t=+t)*Math.sin((t+r)/n)}return s.amplitude=function(e){return t(e,n*ni)},s.period=function(n){return t(e,n)},s}(1,.3),oi=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ni);function s(t){return((t=2*t-1)<0?e*Eo(-t)*Math.sin((r-t)/n):2-e*Eo(t)*Math.sin((r+t)/n))/2}return s.amplitude=function(e){return t(e,n*ni)},s.period=function(n){return t(e,n)},s}(1,.3);function ii(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function ai(t,e){return fetch(t,e).then(ii)}function li(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function ci(t,e){return fetch(t,e).then(li)}function ui(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function fi(t,e){return fetch(t,e).then(ui)}function di(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),fi(e,n).then((function(e){return t(e,r)}))}}function hi(t,e,n,r){3===arguments.length&&"function"==typeof n&&(r=n,n=void 0);var s=(0,ao.Z)(t);return fi(e,n).then((function(t){return s.parse(t,r)}))}var pi=di(co),mi=di(yo.tJ);function gi(t,e){return new Promise((function(n,r){var s=new Image;for(var o in e)s[o]=e[o];s.onerror=r,s.onload=function(){n(s)},s.src=t}))}function yi(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function bi(t,e){return fetch(t,e).then(yi)}function vi(t){return(e,n)=>fi(e,n).then((e=>(new DOMParser).parseFromString(e,t)))}const wi=vi("application/xml");var _i=vi("text/html"),xi=vi("image/svg+xml");function ki(t,e){var n,r=1;function s(){var s,o,i=n.length,a=0,l=0;for(s=0;s<i;++s)a+=(o=n[s]).x,l+=o.y;for(a=(a/i-t)*r,l=(l/i-e)*r,s=0;s<i;++s)(o=n[s]).x-=a,o.y-=l}return null==t&&(t=0),null==e&&(e=0),s.initialize=function(t){n=t},s.x=function(e){return arguments.length?(t=+e,s):t},s.y=function(t){return arguments.length?(e=+t,s):e},s.strength=function(t){return arguments.length?(r=+t,s):r},s}function qi(t,e,n,r){if(isNaN(e)||isNaN(n))return t;var s,o,i,a,l,c,u,f,d,h=t._root,p={data:r},m=t._x0,g=t._y0,y=t._x1,b=t._y1;if(!h)return t._root=p,t;for(;h.length;)if((c=e>=(o=(m+y)/2))?m=o:y=o,(u=n>=(i=(g+b)/2))?g=i:b=i,s=h,!(h=h[f=u<<1|c]))return s[f]=p,t;if(a=+t._x.call(null,h.data),l=+t._y.call(null,h.data),e===a&&n===l)return p.next=h,s?s[f]=p:t._root=p,t;do{s=s?s[f]=new Array(4):t._root=new Array(4),(c=e>=(o=(m+y)/2))?m=o:y=o,(u=n>=(i=(g+b)/2))?g=i:b=i}while((f=u<<1|c)==(d=(l>=i)<<1|a>=o));return s[d]=h,s[f]=p,t}function Ni(t,e,n,r,s){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=s}function Si(t){return t[0]}function Ai(t){return t[1]}function Mi(t,e,n){var r=new Ti(null==e?Si:e,null==n?Ai:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Ti(t,e,n,r,s,o){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=s,this._y1=o,this._root=void 0}function Ci(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var ji=Mi.prototype=Ti.prototype;function Ei(t){return function(){return t}}function Oi(t){return 1e-6*(t()-.5)}function Ii(t){return t.x+t.vx}function Ri(t){return t.y+t.vy}function Fi(t){var e,n,r,s=1,o=1;function i(){for(var t,i,l,c,u,f,d,h=e.length,p=0;p<o;++p)for(i=Mi(e,Ii,Ri).visitAfter(a),t=0;t<h;++t)l=e[t],f=n[l.index],d=f*f,c=l.x+l.vx,u=l.y+l.vy,i.visit(m);function m(t,e,n,o,i){var a=t.data,h=t.r,p=f+h;if(!a)return e>c+p||o<c-p||n>u+p||i<u-p;if(a.index>l.index){var m=c-a.x-a.vx,g=u-a.y-a.vy,y=m*m+g*g;y<p*p&&(0===m&&(y+=(m=Oi(r))*m),0===g&&(y+=(g=Oi(r))*g),y=(p-(y=Math.sqrt(y)))/y*s,l.vx+=(m*=y)*(p=(h*=h)/(d+h)),l.vy+=(g*=y)*p,a.vx-=m*(p=1-p),a.vy-=g*p)}}}function a(t){if(t.data)return t.r=n[t.data.index];for(var e=t.r=0;e<4;++e)t[e]&&t[e].r>t.r&&(t.r=t[e].r)}function l(){if(e){var r,s,o=e.length;for(n=new Array(o),r=0;r<o;++r)s=e[r],n[s.index]=+t(s,r,e)}}return"function"!=typeof t&&(t=Ei(null==t?1:+t)),i.initialize=function(t,n){e=t,r=n,l()},i.iterations=function(t){return arguments.length?(o=+t,i):o},i.strength=function(t){return arguments.length?(s=+t,i):s},i.radius=function(e){return arguments.length?(t="function"==typeof e?e:Ei(+e),l(),i):t},i}function Pi(t){return t.index}function Di(t,e){var n=t.get(e);if(!n)throw new Error("node not found: "+e);return n}function Li(t){var e,n,r,s,o,i,a=Pi,l=function(t){return 1/Math.min(s[t.source.index],s[t.target.index])},c=Ei(30),u=1;function f(r){for(var s=0,a=t.length;s<u;++s)for(var l,c,f,d,h,p,m,g=0;g<a;++g)c=(l=t[g]).source,d=(f=l.target).x+f.vx-c.x-c.vx||Oi(i),h=f.y+f.vy-c.y-c.vy||Oi(i),d*=p=((p=Math.sqrt(d*d+h*h))-n[g])/p*r*e[g],h*=p,f.vx-=d*(m=o[g]),f.vy-=h*m,c.vx+=d*(m=1-m),c.vy+=h*m}function d(){if(r){var i,l,c=r.length,u=t.length,f=new Map(r.map(((t,e)=>[a(t,e,r),t])));for(i=0,s=new Array(c);i<u;++i)(l=t[i]).index=i,"object"!=typeof l.source&&(l.source=Di(f,l.source)),"object"!=typeof l.target&&(l.target=Di(f,l.target)),s[l.source.index]=(s[l.source.index]||0)+1,s[l.target.index]=(s[l.target.index]||0)+1;for(i=0,o=new Array(u);i<u;++i)l=t[i],o[i]=s[l.source.index]/(s[l.source.index]+s[l.target.index]);e=new Array(u),h(),n=new Array(u),p()}}function h(){if(r)for(var n=0,s=t.length;n<s;++n)e[n]=+l(t[n],n,t)}function p(){if(r)for(var e=0,s=t.length;e<s;++e)n[e]=+c(t[e],e,t)}return null==t&&(t=[]),f.initialize=function(t,e){r=t,i=e,d()},f.links=function(e){return arguments.length?(t=e,d(),f):t},f.id=function(t){return arguments.length?(a=t,f):a},f.iterations=function(t){return arguments.length?(u=+t,f):u},f.strength=function(t){return arguments.length?(l="function"==typeof t?t:Ei(+t),h(),f):l},f.distance=function(t){return arguments.length?(c="function"==typeof t?t:Ei(+t),p(),f):c},f}ji.copy=function(){var t,e,n=new Ti(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=Ci(r),n;for(t=[{source:r,target:n._root=new Array(4)}];r=t.pop();)for(var s=0;s<4;++s)(e=r.source[s])&&(e.length?t.push({source:e,target:r.target[s]=new Array(4)}):r.target[s]=Ci(e));return n},ji.add=function(t){const e=+this._x.call(null,t),n=+this._y.call(null,t);return qi(this.cover(e,n),e,n,t)},ji.addAll=function(t){var e,n,r,s,o=t.length,i=new Array(o),a=new Array(o),l=1/0,c=1/0,u=-1/0,f=-1/0;for(n=0;n<o;++n)isNaN(r=+this._x.call(null,e=t[n]))||isNaN(s=+this._y.call(null,e))||(i[n]=r,a[n]=s,r<l&&(l=r),r>u&&(u=r),s<c&&(c=s),s>f&&(f=s));if(l>u||c>f)return this;for(this.cover(l,c).cover(u,f),n=0;n<o;++n)qi(this,i[n],a[n],t[n]);return this},ji.cover=function(t,e){if(isNaN(t=+t)||isNaN(e=+e))return this;var n=this._x0,r=this._y0,s=this._x1,o=this._y1;if(isNaN(n))s=(n=Math.floor(t))+1,o=(r=Math.floor(e))+1;else{for(var i,a,l=s-n||1,c=this._root;n>t||t>=s||r>e||e>=o;)switch(a=(e<r)<<1|t<n,(i=new Array(4))[a]=c,c=i,l*=2,a){case 0:s=n+l,o=r+l;break;case 1:n=s-l,o=r+l;break;case 2:s=n+l,r=o-l;break;case 3:n=s-l,r=o-l}this._root&&this._root.length&&(this._root=c)}return this._x0=n,this._y0=r,this._x1=s,this._y1=o,this},ji.data=function(){var t=[];return this.visit((function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)})),t},ji.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},ji.find=function(t,e,n){var r,s,o,i,a,l,c,u=this._x0,f=this._y0,d=this._x1,h=this._y1,p=[],m=this._root;for(m&&p.push(new Ni(m,u,f,d,h)),null==n?n=1/0:(u=t-n,f=e-n,d=t+n,h=e+n,n*=n);l=p.pop();)if(!(!(m=l.node)||(s=l.x0)>d||(o=l.y0)>h||(i=l.x1)<u||(a=l.y1)<f))if(m.length){var g=(s+i)/2,y=(o+a)/2;p.push(new Ni(m[3],g,y,i,a),new Ni(m[2],s,y,g,a),new Ni(m[1],g,o,i,y),new Ni(m[0],s,o,g,y)),(c=(e>=y)<<1|t>=g)&&(l=p[p.length-1],p[p.length-1]=p[p.length-1-c],p[p.length-1-c]=l)}else{var b=t-+this._x.call(null,m.data),v=e-+this._y.call(null,m.data),w=b*b+v*v;if(w<n){var _=Math.sqrt(n=w);u=t-_,f=e-_,d=t+_,h=e+_,r=m.data}}return r},ji.remove=function(t){if(isNaN(o=+this._x.call(null,t))||isNaN(i=+this._y.call(null,t)))return this;var e,n,r,s,o,i,a,l,c,u,f,d,h=this._root,p=this._x0,m=this._y0,g=this._x1,y=this._y1;if(!h)return this;if(h.length)for(;;){if((c=o>=(a=(p+g)/2))?p=a:g=a,(u=i>=(l=(m+y)/2))?m=l:y=l,e=h,!(h=h[f=u<<1|c]))return this;if(!h.length)break;(e[f+1&3]||e[f+2&3]||e[f+3&3])&&(n=e,d=f)}for(;h.data!==t;)if(r=h,!(h=h.next))return this;return(s=h.next)&&delete h.next,r?(s?r.next=s:delete r.next,this):e?(s?e[f]=s:delete e[f],(h=e[0]||e[1]||e[2]||e[3])&&h===(e[3]||e[2]||e[1]||e[0])&&!h.length&&(n?n[d]=h:this._root=h),this):(this._root=s,this)},ji.removeAll=function(t){for(var e=0,n=t.length;e<n;++e)this.remove(t[e]);return this},ji.root=function(){return this._root},ji.size=function(){var t=0;return this.visit((function(e){if(!e.length)do{++t}while(e=e.next)})),t},ji.visit=function(t){var e,n,r,s,o,i,a=[],l=this._root;for(l&&a.push(new Ni(l,this._x0,this._y0,this._x1,this._y1));e=a.pop();)if(!t(l=e.node,r=e.x0,s=e.y0,o=e.x1,i=e.y1)&&l.length){var c=(r+o)/2,u=(s+i)/2;(n=l[3])&&a.push(new Ni(n,c,u,o,i)),(n=l[2])&&a.push(new Ni(n,r,u,c,i)),(n=l[1])&&a.push(new Ni(n,c,s,o,u)),(n=l[0])&&a.push(new Ni(n,r,s,c,u))}return this},ji.visitAfter=function(t){var e,n=[],r=[];for(this._root&&n.push(new Ni(this._root,this._x0,this._y0,this._x1,this._y1));e=n.pop();){var s=e.node;if(s.length){var o,i=e.x0,a=e.y0,l=e.x1,c=e.y1,u=(i+l)/2,f=(a+c)/2;(o=s[0])&&n.push(new Ni(o,i,a,u,f)),(o=s[1])&&n.push(new Ni(o,u,a,l,f)),(o=s[2])&&n.push(new Ni(o,i,f,u,c)),(o=s[3])&&n.push(new Ni(o,u,f,l,c))}r.push(e)}for(;e=r.pop();)t(e.node,e.x0,e.y0,e.x1,e.y1);return this},ji.x=function(t){return arguments.length?(this._x=t,this):this._x},ji.y=function(t){return arguments.length?(this._y=t,this):this._y};const $i=1664525,zi=1013904223,Zi=4294967296;function Ui(t){return t.x}function Bi(t){return t.y}var Gi=10,Ji=Math.PI*(3-Math.sqrt(5));function Hi(t){var e,n=1,r=.001,s=1-Math.pow(r,1/300),o=0,i=.6,a=new Map,l=ce(f),c=N("tick","end"),u=function(){let t=1;return()=>(t=($i*t+zi)%Zi)/Zi}();function f(){d(),c.call("tick",e),n<r&&(l.stop(),c.call("end",e))}function d(r){var l,c,u=t.length;void 0===r&&(r=1);for(var f=0;f<r;++f)for(n+=(o-n)*s,a.forEach((function(t){t(n)})),l=0;l<u;++l)null==(c=t[l]).fx?c.x+=c.vx*=i:(c.x=c.fx,c.vx=0),null==c.fy?c.y+=c.vy*=i:(c.y=c.fy,c.vy=0);return e}function h(){for(var e,n=0,r=t.length;n<r;++n){if((e=t[n]).index=n,null!=e.fx&&(e.x=e.fx),null!=e.fy&&(e.y=e.fy),isNaN(e.x)||isNaN(e.y)){var s=Gi*Math.sqrt(.5+n),o=n*Ji;e.x=s*Math.cos(o),e.y=s*Math.sin(o)}(isNaN(e.vx)||isNaN(e.vy))&&(e.vx=e.vy=0)}}function p(e){return e.initialize&&e.initialize(t,u),e}return null==t&&(t=[]),h(),e={tick:d,restart:function(){return l.restart(f),e},stop:function(){return l.stop(),e},nodes:function(n){return arguments.length?(t=n,h(),a.forEach(p),e):t},alpha:function(t){return arguments.length?(n=+t,e):n},alphaMin:function(t){return arguments.length?(r=+t,e):r},alphaDecay:function(t){return arguments.length?(s=+t,e):+s},alphaTarget:function(t){return arguments.length?(o=+t,e):o},velocityDecay:function(t){return arguments.length?(i=1-t,e):1-i},randomSource:function(t){return arguments.length?(u=t,a.forEach(p),e):u},force:function(t,n){return arguments.length>1?(null==n?a.delete(t):a.set(t,p(n)),e):a.get(t)},find:function(e,n,r){var s,o,i,a,l,c=0,u=t.length;for(null==r?r=1/0:r*=r,c=0;c<u;++c)(i=(s=e-(a=t[c]).x)*s+(o=n-a.y)*o)<r&&(l=a,r=i);return l},on:function(t,n){return arguments.length>1?(c.on(t,n),e):c.on(t)}}}function Wi(){var t,e,n,r,s,o=Ei(-30),i=1,a=1/0,l=.81;function c(n){var s,o=t.length,i=Mi(t,Ui,Bi).visitAfter(f);for(r=n,s=0;s<o;++s)e=t[s],i.visit(d)}function u(){if(t){var e,n,r=t.length;for(s=new Array(r),e=0;e<r;++e)n=t[e],s[n.index]=+o(n,e,t)}}function f(t){var e,n,r,o,i,a=0,l=0;if(t.length){for(r=o=i=0;i<4;++i)(e=t[i])&&(n=Math.abs(e.value))&&(a+=e.value,l+=n,r+=n*e.x,o+=n*e.y);t.x=r/l,t.y=o/l}else{(e=t).x=e.data.x,e.y=e.data.y;do{a+=s[e.data.index]}while(e=e.next)}t.value=a}function d(t,o,c,u){if(!t.value)return!0;var f=t.x-e.x,d=t.y-e.y,h=u-o,p=f*f+d*d;if(h*h/l<p)return p<a&&(0===f&&(p+=(f=Oi(n))*f),0===d&&(p+=(d=Oi(n))*d),p<i&&(p=Math.sqrt(i*p)),e.vx+=f*t.value*r/p,e.vy+=d*t.value*r/p),!0;if(!(t.length||p>=a)){(t.data!==e||t.next)&&(0===f&&(p+=(f=Oi(n))*f),0===d&&(p+=(d=Oi(n))*d),p<i&&(p=Math.sqrt(i*p)));do{t.data!==e&&(h=s[t.data.index]*r/p,e.vx+=f*h,e.vy+=d*h)}while(t=t.next)}}return c.initialize=function(e,r){t=e,n=r,u()},c.strength=function(t){return arguments.length?(o="function"==typeof t?t:Ei(+t),u(),c):o},c.distanceMin=function(t){return arguments.length?(i=t*t,c):Math.sqrt(i)},c.distanceMax=function(t){return arguments.length?(a=t*t,c):Math.sqrt(a)},c.theta=function(t){return arguments.length?(l=t*t,c):Math.sqrt(l)},c}function Vi(t,e,n){var r,s,o,i=Ei(.1);function a(t){for(var i=0,a=r.length;i<a;++i){var l=r[i],c=l.x-e||1e-6,u=l.y-n||1e-6,f=Math.sqrt(c*c+u*u),d=(o[i]-f)*s[i]*t/f;l.vx+=c*d,l.vy+=u*d}}function l(){if(r){var e,n=r.length;for(s=new Array(n),o=new Array(n),e=0;e<n;++e)o[e]=+t(r[e],e,r),s[e]=isNaN(o[e])?0:+i(r[e],e,r)}}return"function"!=typeof t&&(t=Ei(+t)),null==e&&(e=0),null==n&&(n=0),a.initialize=function(t){r=t,l()},a.strength=function(t){return arguments.length?(i="function"==typeof t?t:Ei(+t),l(),a):i},a.radius=function(e){return arguments.length?(t="function"==typeof e?e:Ei(+e),l(),a):t},a.x=function(t){return arguments.length?(e=+t,a):e},a.y=function(t){return arguments.length?(n=+t,a):n},a}function Yi(t){var e,n,r,s=Ei(.1);function o(t){for(var s,o=0,i=e.length;o<i;++o)(s=e[o]).vx+=(r[o]-s.x)*n[o]*t}function i(){if(e){var o,i=e.length;for(n=new Array(i),r=new Array(i),o=0;o<i;++o)n[o]=isNaN(r[o]=+t(e[o],o,e))?0:+s(e[o],o,e)}}return"function"!=typeof t&&(t=Ei(null==t?0:+t)),o.initialize=function(t){e=t,i()},o.strength=function(t){return arguments.length?(s="function"==typeof t?t:Ei(+t),i(),o):s},o.x=function(e){return arguments.length?(t="function"==typeof e?e:Ei(+e),i(),o):t},o}function Ki(t){var e,n,r,s=Ei(.1);function o(t){for(var s,o=0,i=e.length;o<i;++o)(s=e[o]).vy+=(r[o]-s.y)*n[o]*t}function i(){if(e){var o,i=e.length;for(n=new Array(i),r=new Array(i),o=0;o<i;++o)n[o]=isNaN(r[o]=+t(e[o],o,e))?0:+s(e[o],o,e)}}return"function"!=typeof t&&(t=Ei(null==t?0:+t)),o.initialize=function(t){e=t,i()},o.strength=function(t){return arguments.length?(s="function"==typeof t?t:Ei(+t),i(),o):s},o.y=function(e){return arguments.length?(t="function"==typeof e?e:Ei(+e),i(),o):t},o}var Xi=n(2163),Qi=n(2107),ta=n(7259),ea=n(9680),na=n(3150),ra=n(3621),sa=n(9343),oa=1e-6,ia=1e-12,aa=Math.PI,la=aa/2,ca=aa/4,ua=2*aa,fa=180/aa,da=aa/180,ha=Math.abs,pa=Math.atan,ma=Math.atan2,ga=Math.cos,ya=Math.ceil,ba=Math.exp,va=(Math.floor,Math.hypot),wa=Math.log,_a=Math.pow,xa=Math.sin,ka=Math.sign||function(t){return t>0?1:t<0?-1:0},qa=Math.sqrt,Na=Math.tan;function Sa(t){return t>1?0:t<-1?aa:Math.acos(t)}function Aa(t){return t>1?la:t<-1?-la:Math.asin(t)}function Ma(t){return(t=xa(t/2))*t}function Ta(){}function Ca(t,e){t&&Ea.hasOwnProperty(t.type)&&Ea[t.type](t,e)}var ja={Feature:function(t,e){Ca(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,s=n.length;++r<s;)Ca(n[r].geometry,e)}},Ea={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,s=n.length;++r<s;)t=n[r],e.point(t[0],t[1],t[2])},LineString:function(t,e){Oa(t.coordinates,e,0)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,s=n.length;++r<s;)Oa(n[r],e,0)},Polygon:function(t,e){Ia(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,s=n.length;++r<s;)Ia(n[r],e)},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,s=n.length;++r<s;)Ca(n[r],e)}};function Oa(t,e,n){var r,s=-1,o=t.length-n;for(e.lineStart();++s<o;)r=t[s],e.point(r[0],r[1],r[2]);e.lineEnd()}function Ia(t,e){var n=-1,r=t.length;for(e.polygonStart();++n<r;)Oa(t[n],e,1);e.polygonEnd()}function Ra(t,e){t&&ja.hasOwnProperty(t.type)?ja[t.type](t,e):Ca(t,e)}var Fa,Pa,Da,La,$a,za,Za,Ua,Ba,Ga,Ja,Ha,Wa,Va,Ya,Ka,Xa=new sa.dU,Qa=new sa.dU,tl={point:Ta,lineStart:Ta,lineEnd:Ta,polygonStart:function(){Xa=new sa.dU,tl.lineStart=el,tl.lineEnd=nl},polygonEnd:function(){var t=+Xa;Qa.add(t<0?ua+t:t),this.lineStart=this.lineEnd=this.point=Ta},sphere:function(){Qa.add(ua)}};function el(){tl.point=rl}function nl(){sl(Fa,Pa)}function rl(t,e){tl.point=sl,Fa=t,Pa=e,Da=t*=da,La=ga(e=(e*=da)/2+ca),$a=xa(e)}function sl(t,e){var n=(t*=da)-Da,r=n>=0?1:-1,s=r*n,o=ga(e=(e*=da)/2+ca),i=xa(e),a=$a*i,l=La*o+a*ga(s),c=a*r*xa(s);Xa.add(ma(c,l)),Da=t,La=o,$a=i}function ol(t){return Qa=new sa.dU,Ra(t,tl),2*Qa}function il(t){return[ma(t[1],t[0]),Aa(t[2])]}function al(t){var e=t[0],n=t[1],r=ga(n);return[r*ga(e),r*xa(e),xa(n)]}function ll(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function cl(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function ul(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function fl(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function dl(t){var e=qa(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}var hl,pl,ml,gl,yl,bl,vl,wl,_l,xl,kl,ql,Nl,Sl,Al,Ml,Tl={point:Cl,lineStart:El,lineEnd:Ol,polygonStart:function(){Tl.point=Il,Tl.lineStart=Rl,Tl.lineEnd=Fl,Va=new sa.dU,tl.polygonStart()},polygonEnd:function(){tl.polygonEnd(),Tl.point=Cl,Tl.lineStart=El,Tl.lineEnd=Ol,Xa<0?(za=-(Ua=180),Za=-(Ba=90)):Va>oa?Ba=90:Va<-oa&&(Za=-90),Ka[0]=za,Ka[1]=Ua},sphere:function(){za=-(Ua=180),Za=-(Ba=90)}};function Cl(t,e){Ya.push(Ka=[za=t,Ua=t]),e<Za&&(Za=e),e>Ba&&(Ba=e)}function jl(t,e){var n=al([t*da,e*da]);if(Wa){var r=cl(Wa,n),s=cl([r[1],-r[0],0],r);dl(s),s=il(s);var o,i=t-Ga,a=i>0?1:-1,l=s[0]*fa*a,c=ha(i)>180;c^(a*Ga<l&&l<a*t)?(o=s[1]*fa)>Ba&&(Ba=o):c^(a*Ga<(l=(l+360)%360-180)&&l<a*t)?(o=-s[1]*fa)<Za&&(Za=o):(e<Za&&(Za=e),e>Ba&&(Ba=e)),c?t<Ga?Pl(za,t)>Pl(za,Ua)&&(Ua=t):Pl(t,Ua)>Pl(za,Ua)&&(za=t):Ua>=za?(t<za&&(za=t),t>Ua&&(Ua=t)):t>Ga?Pl(za,t)>Pl(za,Ua)&&(Ua=t):Pl(t,Ua)>Pl(za,Ua)&&(za=t)}else Ya.push(Ka=[za=t,Ua=t]);e<Za&&(Za=e),e>Ba&&(Ba=e),Wa=n,Ga=t}function El(){Tl.point=jl}function Ol(){Ka[0]=za,Ka[1]=Ua,Tl.point=Cl,Wa=null}function Il(t,e){if(Wa){var n=t-Ga;Va.add(ha(n)>180?n+(n>0?360:-360):n)}else Ja=t,Ha=e;tl.point(t,e),jl(t,e)}function Rl(){tl.lineStart()}function Fl(){Il(Ja,Ha),tl.lineEnd(),ha(Va)>oa&&(za=-(Ua=180)),Ka[0]=za,Ka[1]=Ua,Wa=null}function Pl(t,e){return(e-=t)<0?e+360:e}function Dl(t,e){return t[0]-e[0]}function Ll(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}function $l(t){var e,n,r,s,o,i,a;if(Ba=Ua=-(za=Za=1/0),Ya=[],Ra(t,Tl),n=Ya.length){for(Ya.sort(Dl),e=1,o=[r=Ya[0]];e<n;++e)Ll(r,(s=Ya[e])[0])||Ll(r,s[1])?(Pl(r[0],s[1])>Pl(r[0],r[1])&&(r[1]=s[1]),Pl(s[0],r[1])>Pl(r[0],r[1])&&(r[0]=s[0])):o.push(r=s);for(i=-1/0,e=0,r=o[n=o.length-1];e<=n;r=s,++e)s=o[e],(a=Pl(r[1],s[0]))>i&&(i=a,za=s[0],Ua=r[1])}return Ya=Ka=null,za===1/0||Za===1/0?[[NaN,NaN],[NaN,NaN]]:[[za,Za],[Ua,Ba]]}var zl={sphere:Ta,point:Zl,lineStart:Bl,lineEnd:Hl,polygonStart:function(){zl.lineStart=Wl,zl.lineEnd=Vl},polygonEnd:function(){zl.lineStart=Bl,zl.lineEnd=Hl}};function Zl(t,e){t*=da;var n=ga(e*=da);Ul(n*ga(t),n*xa(t),xa(e))}function Ul(t,e,n){++hl,ml+=(t-ml)/hl,gl+=(e-gl)/hl,yl+=(n-yl)/hl}function Bl(){zl.point=Gl}function Gl(t,e){t*=da;var n=ga(e*=da);Sl=n*ga(t),Al=n*xa(t),Ml=xa(e),zl.point=Jl,Ul(Sl,Al,Ml)}function Jl(t,e){t*=da;var n=ga(e*=da),r=n*ga(t),s=n*xa(t),o=xa(e),i=ma(qa((i=Al*o-Ml*s)*i+(i=Ml*r-Sl*o)*i+(i=Sl*s-Al*r)*i),Sl*r+Al*s+Ml*o);pl+=i,bl+=i*(Sl+(Sl=r)),vl+=i*(Al+(Al=s)),wl+=i*(Ml+(Ml=o)),Ul(Sl,Al,Ml)}function Hl(){zl.point=Zl}function Wl(){zl.point=Yl}function Vl(){Kl(ql,Nl),zl.point=Zl}function Yl(t,e){ql=t,Nl=e,t*=da,e*=da,zl.point=Kl;var n=ga(e);Sl=n*ga(t),Al=n*xa(t),Ml=xa(e),Ul(Sl,Al,Ml)}function Kl(t,e){t*=da;var n=ga(e*=da),r=n*ga(t),s=n*xa(t),o=xa(e),i=Al*o-Ml*s,a=Ml*r-Sl*o,l=Sl*s-Al*r,c=va(i,a,l),u=Aa(c),f=c&&-u/c;_l.add(f*i),xl.add(f*a),kl.add(f*l),pl+=u,bl+=u*(Sl+(Sl=r)),vl+=u*(Al+(Al=s)),wl+=u*(Ml+(Ml=o)),Ul(Sl,Al,Ml)}function Xl(t){hl=pl=ml=gl=yl=bl=vl=wl=0,_l=new sa.dU,xl=new sa.dU,kl=new sa.dU,Ra(t,zl);var e=+_l,n=+xl,r=+kl,s=va(e,n,r);return s<ia&&(e=bl,n=vl,r=wl,pl<oa&&(e=ml,n=gl,r=yl),(s=va(e,n,r))<ia)?[NaN,NaN]:[ma(n,e)*fa,Aa(r/s)*fa]}function Ql(t){return function(){return t}}function tc(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,r){return(n=e.invert(n,r))&&t.invert(n[0],n[1])}),n}function ec(t,e){return[ha(t)>aa?t+Math.round(-t/ua)*ua:t,e]}function nc(t,e,n){return(t%=ua)?e||n?tc(sc(t),oc(e,n)):sc(t):e||n?oc(e,n):ec}function rc(t){return function(e,n){return[(e+=t)>aa?e-ua:e<-aa?e+ua:e,n]}}function sc(t){var e=rc(t);return e.invert=rc(-t),e}function oc(t,e){var n=ga(t),r=xa(t),s=ga(e),o=xa(e);function i(t,e){var i=ga(e),a=ga(t)*i,l=xa(t)*i,c=xa(e),u=c*n+a*r;return[ma(l*s-u*o,a*n-c*r),Aa(u*s+l*o)]}return i.invert=function(t,e){var i=ga(e),a=ga(t)*i,l=xa(t)*i,c=xa(e),u=c*s-l*o;return[ma(l*s+c*o,a*n+u*r),Aa(u*n-a*r)]},i}function ic(t){function e(e){return(e=t(e[0]*da,e[1]*da))[0]*=fa,e[1]*=fa,e}return t=nc(t[0]*da,t[1]*da,t.length>2?t[2]*da:0),e.invert=function(e){return(e=t.invert(e[0]*da,e[1]*da))[0]*=fa,e[1]*=fa,e},e}function ac(t,e,n,r,s,o){if(n){var i=ga(e),a=xa(e),l=r*n;null==s?(s=e+r*ua,o=e-l/2):(s=lc(i,s),o=lc(i,o),(r>0?s<o:s>o)&&(s+=r*ua));for(var c,u=s;r>0?u>o:u<o;u-=l)c=il([i,-a*ga(u),-a*xa(u)]),t.point(c[0],c[1])}}function lc(t,e){(e=al(e))[0]-=t,dl(e);var n=Sa(-e[1]);return((-e[2]<0?-n:n)+ua-oa)%ua}function cc(){var t,e,n=Ql([0,0]),r=Ql(90),s=Ql(6),o={point:function(n,r){t.push(n=e(n,r)),n[0]*=fa,n[1]*=fa}};function i(){var i=n.apply(this,arguments),a=r.apply(this,arguments)*da,l=s.apply(this,arguments)*da;return t=[],e=nc(-i[0]*da,-i[1]*da,0).invert,ac(o,a,l,1),i={type:"Polygon",coordinates:[t]},t=e=null,i}return i.center=function(t){return arguments.length?(n="function"==typeof t?t:Ql([+t[0],+t[1]]),i):n},i.radius=function(t){return arguments.length?(r="function"==typeof t?t:Ql(+t),i):r},i.precision=function(t){return arguments.length?(s="function"==typeof t?t:Ql(+t),i):s},i}function uc(){var t,e=[];return{point:function(e,n,r){t.push([e,n,r])},lineStart:function(){e.push(t=[])},lineEnd:Ta,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function fc(t,e){return ha(t[0]-e[0])<oa&&ha(t[1]-e[1])<oa}function dc(t,e,n,r){this.x=t,this.z=e,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function hc(t,e,n,r,s){var o,i,a=[],l=[];if(t.forEach((function(t){if(!((e=t.length-1)<=0)){var e,n,r=t[0],i=t[e];if(fc(r,i)){if(!r[2]&&!i[2]){for(s.lineStart(),o=0;o<e;++o)s.point((r=t[o])[0],r[1]);return void s.lineEnd()}i[0]+=2*oa}a.push(n=new dc(r,t,null,!0)),l.push(n.o=new dc(r,null,n,!1)),a.push(n=new dc(i,t,null,!1)),l.push(n.o=new dc(i,null,n,!0))}})),a.length){for(l.sort(e),pc(a),pc(l),o=0,i=l.length;o<i;++o)l[o].e=n=!n;for(var c,u,f=a[0];;){for(var d=f,h=!0;d.v;)if((d=d.n)===f)return;c=d.z,s.lineStart();do{if(d.v=d.o.v=!0,d.e){if(h)for(o=0,i=c.length;o<i;++o)s.point((u=c[o])[0],u[1]);else r(d.x,d.n.x,1,s);d=d.n}else{if(h)for(c=d.p.z,o=c.length-1;o>=0;--o)s.point((u=c[o])[0],u[1]);else r(d.x,d.p.x,-1,s);d=d.p}c=(d=d.o).z,h=!h}while(!d.v);s.lineEnd()}}}function pc(t){if(e=t.length){for(var e,n,r=0,s=t[0];++r<e;)s.n=n=t[r],n.p=s,s=n;s.n=n=t[0],n.p=s}}function mc(t){return ha(t[0])<=aa?t[0]:ka(t[0])*((ha(t[0])+aa)%ua-aa)}function gc(t,e){var n=mc(e),r=e[1],s=xa(r),o=[xa(n),-ga(n),0],i=0,a=0,l=new sa.dU;1===s?r=la+oa:-1===s&&(r=-la-oa);for(var c=0,u=t.length;c<u;++c)if(d=(f=t[c]).length)for(var f,d,h=f[d-1],p=mc(h),m=h[1]/2+ca,g=xa(m),y=ga(m),b=0;b<d;++b,p=w,g=x,y=k,h=v){var v=f[b],w=mc(v),_=v[1]/2+ca,x=xa(_),k=ga(_),q=w-p,N=q>=0?1:-1,S=N*q,A=S>aa,M=g*x;if(l.add(ma(M*N*xa(S),y*k+M*ga(S))),i+=A?q+N*ua:q,A^p>=n^w>=n){var T=cl(al(h),al(v));dl(T);var C=cl(o,T);dl(C);var j=(A^q>=0?-1:1)*Aa(C[2]);(r>j||r===j&&(T[0]||T[1]))&&(a+=A^q>=0?1:-1)}}return(i<-oa||i<oa&&l<-ia)^1&a}ec.invert=ec;var yc=n(1740);function bc(t,e,n,r){return function(s){var o,i,a,l=e(s),c=uc(),u=e(c),f=!1,d={point:h,lineStart:m,lineEnd:g,polygonStart:function(){d.point=y,d.lineStart=b,d.lineEnd=v,i=[],o=[]},polygonEnd:function(){d.point=h,d.lineStart=m,d.lineEnd=g,i=(0,yc.Z)(i);var t=gc(o,r);i.length?(f||(s.polygonStart(),f=!0),hc(i,wc,t,n,s)):t&&(f||(s.polygonStart(),f=!0),s.lineStart(),n(null,null,1,s),s.lineEnd()),f&&(s.polygonEnd(),f=!1),i=o=null},sphere:function(){s.polygonStart(),s.lineStart(),n(null,null,1,s),s.lineEnd(),s.polygonEnd()}};function h(e,n){t(e,n)&&s.point(e,n)}function p(t,e){l.point(t,e)}function m(){d.point=p,l.lineStart()}function g(){d.point=h,l.lineEnd()}function y(t,e){a.push([t,e]),u.point(t,e)}function b(){u.lineStart(),a=[]}function v(){y(a[0][0],a[0][1]),u.lineEnd();var t,e,n,r,l=u.clean(),d=c.result(),h=d.length;if(a.pop(),o.push(a),a=null,h)if(1&l){if((e=(n=d[0]).length-1)>0){for(f||(s.polygonStart(),f=!0),s.lineStart(),t=0;t<e;++t)s.point((r=n[t])[0],r[1]);s.lineEnd()}}else h>1&&2&l&&d.push(d.pop().concat(d.shift())),i.push(d.filter(vc))}return d}}function vc(t){return t.length>1}function wc(t,e){return((t=t.x)[0]<0?t[1]-la-oa:la-t[1])-((e=e.x)[0]<0?e[1]-la-oa:la-e[1])}const _c=bc((function(){return!0}),(function(t){var e,n=NaN,r=NaN,s=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,i){var a=o>0?aa:-aa,l=ha(o-n);ha(l-aa)<oa?(t.point(n,r=(r+i)/2>0?la:-la),t.point(s,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):s!==a&&l>=aa&&(ha(n-s)<oa&&(n-=s*oa),ha(o-a)<oa&&(o-=a*oa),r=function(t,e,n,r){var s,o,i=xa(t-n);return ha(i)>oa?pa((xa(e)*(o=ga(r))*xa(n)-xa(r)*(s=ga(e))*xa(t))/(s*o*i)):(e+r)/2}(n,r,o,i),t.point(s,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=i),s=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var s;if(null==t)s=n*la,r.point(-aa,s),r.point(0,s),r.point(aa,s),r.point(aa,0),r.point(aa,-s),r.point(0,-s),r.point(-aa,-s),r.point(-aa,0),r.point(-aa,s);else if(ha(t[0]-e[0])>oa){var o=t[0]<e[0]?aa:-aa;s=n*o/2,r.point(-o,s),r.point(0,s),r.point(o,s)}else r.point(e[0],e[1])}),[-aa,-la]);function xc(t){var e=ga(t),n=6*da,r=e>0,s=ha(e)>oa;function o(t,n){return ga(t)*ga(n)>e}function i(t,n,r){var s=[1,0,0],o=cl(al(t),al(n)),i=ll(o,o),a=o[0],l=i-a*a;if(!l)return!r&&t;var c=e*i/l,u=-e*a/l,f=cl(s,o),d=fl(s,c);ul(d,fl(o,u));var h=f,p=ll(d,h),m=ll(h,h),g=p*p-m*(ll(d,d)-1);if(!(g<0)){var y=qa(g),b=fl(h,(-p-y)/m);if(ul(b,d),b=il(b),!r)return b;var v,w=t[0],_=n[0],x=t[1],k=n[1];_<w&&(v=w,w=_,_=v);var q=_-w,N=ha(q-aa)<oa;if(!N&&k<x&&(v=x,x=k,k=v),N||q<oa?N?x+k>0^b[1]<(ha(b[0]-w)<oa?x:k):x<=b[1]&&b[1]<=k:q>aa^(w<=b[0]&&b[0]<=_)){var S=fl(h,(-p+y)/m);return ul(S,d),[b,il(S)]}}}function a(e,n){var s=r?t:aa-t,o=0;return e<-s?o|=1:e>s&&(o|=2),n<-s?o|=4:n>s&&(o|=8),o}return bc(o,(function(t){var e,n,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(f,d){var h,p=[f,d],m=o(f,d),g=r?m?0:a(f,d):m?a(f+(f<0?aa:-aa),d):0;if(!e&&(c=l=m)&&t.lineStart(),m!==l&&(!(h=i(e,p))||fc(e,h)||fc(p,h))&&(p[2]=1),m!==l)u=0,m?(t.lineStart(),h=i(p,e),t.point(h[0],h[1])):(h=i(e,p),t.point(h[0],h[1],2),t.lineEnd()),e=h;else if(s&&e&&r^m){var y;g&n||!(y=i(p,e,!0))||(u=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!m||e&&fc(e,p)||t.point(p[0],p[1]),e=p,l=m,n=g},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return u|(c&&l)<<1}}}),(function(e,r,s,o){ac(o,t,n,s,e,r)}),r?[0,-t]:[-aa,t-aa])}var kc,qc,Nc,Sc,Ac=1e9,Mc=-Ac;function Tc(t,e,n,r){function s(s,o){return t<=s&&s<=n&&e<=o&&o<=r}function o(s,o,a,c){var u=0,f=0;if(null==s||(u=i(s,a))!==(f=i(o,a))||l(s,o)<0^a>0)do{c.point(0===u||3===u?t:n,u>1?r:e)}while((u=(u+a+4)%4)!==f);else c.point(o[0],o[1])}function i(r,s){return ha(r[0]-t)<oa?s>0?0:3:ha(r[0]-n)<oa?s>0?2:1:ha(r[1]-e)<oa?s>0?1:0:s>0?3:2}function a(t,e){return l(t.x,e.x)}function l(t,e){var n=i(t,1),r=i(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(i){var l,c,u,f,d,h,p,m,g,y,b,v=i,w=uc(),_={point:x,lineStart:function(){_.point=k,c&&c.push(u=[]);y=!0,g=!1,p=m=NaN},lineEnd:function(){l&&(k(f,d),h&&g&&w.rejoin(),l.push(w.result()));_.point=x,g&&v.lineEnd()},polygonStart:function(){v=w,l=[],c=[],b=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,s=c.length;n<s;++n)for(var o,i,a=c[n],l=1,u=a.length,f=a[0],d=f[0],h=f[1];l<u;++l)o=d,i=h,d=(f=a[l])[0],h=f[1],i<=r?h>r&&(d-o)*(r-i)>(h-i)*(t-o)&&++e:h<=r&&(d-o)*(r-i)<(h-i)*(t-o)&&--e;return e}(),n=b&&e,s=(l=(0,yc.Z)(l)).length;(n||s)&&(i.polygonStart(),n&&(i.lineStart(),o(null,null,1,i),i.lineEnd()),s&&hc(l,a,e,o,i),i.polygonEnd());v=i,l=c=u=null}};function x(t,e){s(t,e)&&v.point(t,e)}function k(o,i){var a=s(o,i);if(c&&u.push([o,i]),y)f=o,d=i,h=a,y=!1,a&&(v.lineStart(),v.point(o,i));else if(a&&g)v.point(o,i);else{var l=[p=Math.max(Mc,Math.min(Ac,p)),m=Math.max(Mc,Math.min(Ac,m))],w=[o=Math.max(Mc,Math.min(Ac,o)),i=Math.max(Mc,Math.min(Ac,i))];!function(t,e,n,r,s,o){var i,a=t[0],l=t[1],c=0,u=1,f=e[0]-a,d=e[1]-l;if(i=n-a,f||!(i>0)){if(i/=f,f<0){if(i<c)return;i<u&&(u=i)}else if(f>0){if(i>u)return;i>c&&(c=i)}if(i=s-a,f||!(i<0)){if(i/=f,f<0){if(i>u)return;i>c&&(c=i)}else if(f>0){if(i<c)return;i<u&&(u=i)}if(i=r-l,d||!(i>0)){if(i/=d,d<0){if(i<c)return;i<u&&(u=i)}else if(d>0){if(i>u)return;i>c&&(c=i)}if(i=o-l,d||!(i<0)){if(i/=d,d<0){if(i>u)return;i>c&&(c=i)}else if(d>0){if(i<c)return;i<u&&(u=i)}return c>0&&(t[0]=a+c*f,t[1]=l+c*d),u<1&&(e[0]=a+u*f,e[1]=l+u*d),!0}}}}}(l,w,t,e,n,r)?a&&(v.lineStart(),v.point(o,i),b=!1):(g||(v.lineStart(),v.point(l[0],l[1])),v.point(w[0],w[1]),a||v.lineEnd(),b=!1)}p=o,m=i,g=a}return _}}function Cc(){var t,e,n,r=0,s=0,o=960,i=500;return n={stream:function(n){return t&&e===n?t:t=Tc(r,s,o,i)(e=n)},extent:function(a){return arguments.length?(r=+a[0][0],s=+a[0][1],o=+a[1][0],i=+a[1][1],t=e=null,n):[[r,s],[o,i]]}}}var jc={sphere:Ta,point:Ta,lineStart:function(){jc.point=Oc,jc.lineEnd=Ec},lineEnd:Ta,polygonStart:Ta,polygonEnd:Ta};function Ec(){jc.point=jc.lineEnd=Ta}function Oc(t,e){qc=t*=da,Nc=xa(e*=da),Sc=ga(e),jc.point=Ic}function Ic(t,e){t*=da;var n=xa(e*=da),r=ga(e),s=ha(t-qc),o=ga(s),i=r*xa(s),a=Sc*n-Nc*r*o,l=Nc*n+Sc*r*o;kc.add(ma(qa(i*i+a*a),l)),qc=t,Nc=n,Sc=r}function Rc(t){return kc=new sa.dU,Ra(t,jc),+kc}var Fc=[null,null],Pc={type:"LineString",coordinates:Fc};function Dc(t,e){return Fc[0]=t,Fc[1]=e,Rc(Pc)}var Lc={Feature:function(t,e){return zc(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,s=n.length;++r<s;)if(zc(n[r].geometry,e))return!0;return!1}},$c={Sphere:function(){return!0},Point:function(t,e){return Zc(t.coordinates,e)},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,s=n.length;++r<s;)if(Zc(n[r],e))return!0;return!1},LineString:function(t,e){return Uc(t.coordinates,e)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,s=n.length;++r<s;)if(Uc(n[r],e))return!0;return!1},Polygon:function(t,e){return Bc(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,s=n.length;++r<s;)if(Bc(n[r],e))return!0;return!1},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,s=n.length;++r<s;)if(zc(n[r],e))return!0;return!1}};function zc(t,e){return!(!t||!$c.hasOwnProperty(t.type))&&$c[t.type](t,e)}function Zc(t,e){return 0===Dc(t,e)}function Uc(t,e){for(var n,r,s,o=0,i=t.length;o<i;o++){if(0===(r=Dc(t[o],e)))return!0;if(o>0&&(s=Dc(t[o],t[o-1]))>0&&n<=s&&r<=s&&(n+r-s)*(1-Math.pow((n-r)/s,2))<ia*s)return!0;n=r}return!1}function Bc(t,e){return!!gc(t.map(Gc),Jc(e))}function Gc(t){return(t=t.map(Jc)).pop(),t}function Jc(t){return[t[0]*da,t[1]*da]}function Hc(t,e){return(t&&Lc.hasOwnProperty(t.type)?Lc[t.type]:zc)(t,e)}var Wc=n(1265);function Vc(t,e,n){var r=(0,Wc.Z)(t,e-oa,n).concat(e);return function(t){return r.map((function(e){return[t,e]}))}}function Yc(t,e,n){var r=(0,Wc.Z)(t,e-oa,n).concat(e);return function(t){return r.map((function(e){return[e,t]}))}}function Kc(){var t,e,n,r,s,o,i,a,l,c,u,f,d=10,h=d,p=90,m=360,g=2.5;function y(){return{type:"MultiLineString",coordinates:b()}}function b(){return(0,Wc.Z)(ya(r/p)*p,n,p).map(u).concat((0,Wc.Z)(ya(a/m)*m,i,m).map(f)).concat((0,Wc.Z)(ya(e/d)*d,t,d).filter((function(t){return ha(t%p)>oa})).map(l)).concat((0,Wc.Z)(ya(o/h)*h,s,h).filter((function(t){return ha(t%m)>oa})).map(c))}return y.lines=function(){return b().map((function(t){return{type:"LineString",coordinates:t}}))},y.outline=function(){return{type:"Polygon",coordinates:[u(r).concat(f(i).slice(1),u(n).reverse().slice(1),f(a).reverse().slice(1))]}},y.extent=function(t){return arguments.length?y.extentMajor(t).extentMinor(t):y.extentMinor()},y.extentMajor=function(t){return arguments.length?(r=+t[0][0],n=+t[1][0],a=+t[0][1],i=+t[1][1],r>n&&(t=r,r=n,n=t),a>i&&(t=a,a=i,i=t),y.precision(g)):[[r,a],[n,i]]},y.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],o=+n[0][1],s=+n[1][1],e>t&&(n=e,e=t,t=n),o>s&&(n=o,o=s,s=n),y.precision(g)):[[e,o],[t,s]]},y.step=function(t){return arguments.length?y.stepMajor(t).stepMinor(t):y.stepMinor()},y.stepMajor=function(t){return arguments.length?(p=+t[0],m=+t[1],y):[p,m]},y.stepMinor=function(t){return arguments.length?(d=+t[0],h=+t[1],y):[d,h]},y.precision=function(d){return arguments.length?(g=+d,l=Vc(o,s,90),c=Yc(e,t,g),u=Vc(a,i,90),f=Yc(r,n,g),y):g},y.extentMajor([[-180,-90+oa],[180,90-oa]]).extentMinor([[-180,-80-oa],[180,80+oa]])}function Xc(){return Kc()()}function Qc(t,e){var n=t[0]*da,r=t[1]*da,s=e[0]*da,o=e[1]*da,i=ga(r),a=xa(r),l=ga(o),c=xa(o),u=i*ga(n),f=i*xa(n),d=l*ga(s),h=l*xa(s),p=2*Aa(qa(Ma(o-r)+i*l*Ma(s-n))),m=xa(p),g=p?function(t){var e=xa(t*=p)/m,n=xa(p-t)/m,r=n*u+e*d,s=n*f+e*h,o=n*a+e*c;return[ma(s,r)*fa,ma(o,qa(r*r+s*s))*fa]}:function(){return[n*fa,r*fa]};return g.distance=p,g}const tu=t=>t;var eu,nu,ru,su,ou=new sa.dU,iu=new sa.dU,au={point:Ta,lineStart:Ta,lineEnd:Ta,polygonStart:function(){au.lineStart=lu,au.lineEnd=fu},polygonEnd:function(){au.lineStart=au.lineEnd=au.point=Ta,ou.add(ha(iu)),iu=new sa.dU},result:function(){var t=ou/2;return ou=new sa.dU,t}};function lu(){au.point=cu}function cu(t,e){au.point=uu,eu=ru=t,nu=su=e}function uu(t,e){iu.add(su*t-ru*e),ru=t,su=e}function fu(){uu(eu,nu)}const du=au;var hu=1/0,pu=hu,mu=-hu,gu=mu,yu={point:function(t,e){t<hu&&(hu=t);t>mu&&(mu=t);e<pu&&(pu=e);e>gu&&(gu=e)},lineStart:Ta,lineEnd:Ta,polygonStart:Ta,polygonEnd:Ta,result:function(){var t=[[hu,pu],[mu,gu]];return mu=gu=-(pu=hu=1/0),t}};const bu=yu;var vu,wu,_u,xu,ku=0,qu=0,Nu=0,Su=0,Au=0,Mu=0,Tu=0,Cu=0,ju=0,Eu={point:Ou,lineStart:Iu,lineEnd:Pu,polygonStart:function(){Eu.lineStart=Du,Eu.lineEnd=Lu},polygonEnd:function(){Eu.point=Ou,Eu.lineStart=Iu,Eu.lineEnd=Pu},result:function(){var t=ju?[Tu/ju,Cu/ju]:Mu?[Su/Mu,Au/Mu]:Nu?[ku/Nu,qu/Nu]:[NaN,NaN];return ku=qu=Nu=Su=Au=Mu=Tu=Cu=ju=0,t}};function Ou(t,e){ku+=t,qu+=e,++Nu}function Iu(){Eu.point=Ru}function Ru(t,e){Eu.point=Fu,Ou(_u=t,xu=e)}function Fu(t,e){var n=t-_u,r=e-xu,s=qa(n*n+r*r);Su+=s*(_u+t)/2,Au+=s*(xu+e)/2,Mu+=s,Ou(_u=t,xu=e)}function Pu(){Eu.point=Ou}function Du(){Eu.point=$u}function Lu(){zu(vu,wu)}function $u(t,e){Eu.point=zu,Ou(vu=_u=t,wu=xu=e)}function zu(t,e){var n=t-_u,r=e-xu,s=qa(n*n+r*r);Su+=s*(_u+t)/2,Au+=s*(xu+e)/2,Mu+=s,Tu+=(s=xu*t-_u*e)*(_u+t),Cu+=s*(xu+e),ju+=3*s,Ou(_u=t,xu=e)}const Zu=Eu;function Uu(t){this._context=t}Uu.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,ua)}},result:Ta};var Bu,Gu,Ju,Hu,Wu,Vu=new sa.dU,Yu={point:Ta,lineStart:function(){Yu.point=Ku},lineEnd:function(){Bu&&Xu(Gu,Ju),Yu.point=Ta},polygonStart:function(){Bu=!0},polygonEnd:function(){Bu=null},result:function(){var t=+Vu;return Vu=new sa.dU,t}};function Ku(t,e){Yu.point=Xu,Gu=Hu=t,Ju=Wu=e}function Xu(t,e){Hu-=t,Wu-=e,Vu.add(qa(Hu*Hu+Wu*Wu)),Hu=t,Wu=e}const Qu=Yu;function tf(){this._string=[]}function ef(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function nf(t,e){var n,r,s=4.5;function o(t){return t&&("function"==typeof s&&r.pointRadius(+s.apply(this,arguments)),Ra(t,n(r))),r.result()}return o.area=function(t){return Ra(t,n(du)),du.result()},o.measure=function(t){return Ra(t,n(Qu)),Qu.result()},o.bounds=function(t){return Ra(t,n(bu)),bu.result()},o.centroid=function(t){return Ra(t,n(Zu)),Zu.result()},o.projection=function(e){return arguments.length?(n=null==e?(t=null,tu):(t=e).stream,o):t},o.context=function(t){return arguments.length?(r=null==t?(e=null,new tf):new Uu(e=t),"function"!=typeof s&&r.pointRadius(s),o):e},o.pointRadius=function(t){return arguments.length?(s="function"==typeof t?t:(r.pointRadius(+t),+t),o):s},o.projection(t).context(e)}function rf(t){return{stream:sf(t)}}function sf(t){return function(e){var n=new of;for(var r in t)n[r]=t[r];return n.stream=e,n}}function of(){}function af(t,e,n){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Ra(n,t.stream(bu)),e(bu.result()),null!=r&&t.clipExtent(r),t}function lf(t,e,n){return af(t,(function(n){var r=e[1][0]-e[0][0],s=e[1][1]-e[0][1],o=Math.min(r/(n[1][0]-n[0][0]),s/(n[1][1]-n[0][1])),i=+e[0][0]+(r-o*(n[1][0]+n[0][0]))/2,a=+e[0][1]+(s-o*(n[1][1]+n[0][1]))/2;t.scale(150*o).translate([i,a])}),n)}function cf(t,e,n){return lf(t,[[0,0],e],n)}function uf(t,e,n){return af(t,(function(n){var r=+e,s=r/(n[1][0]-n[0][0]),o=(r-s*(n[1][0]+n[0][0]))/2,i=-s*n[0][1];t.scale(150*s).translate([o,i])}),n)}function ff(t,e,n){return af(t,(function(n){var r=+e,s=r/(n[1][1]-n[0][1]),o=-s*n[0][0],i=(r-s*(n[1][1]+n[0][1]))/2;t.scale(150*s).translate([o,i])}),n)}tf.prototype={_radius:4.5,_circle:ef(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=ef(this._radius)),this._string.push("M",t,",",e,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},of.prototype={constructor:of,point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var df=16,hf=ga(30*da);function pf(t,e){return+e?function(t,e){function n(r,s,o,i,a,l,c,u,f,d,h,p,m,g){var y=c-r,b=u-s,v=y*y+b*b;if(v>4*e&&m--){var w=i+d,_=a+h,x=l+p,k=qa(w*w+_*_+x*x),q=Aa(x/=k),N=ha(ha(x)-1)<oa||ha(o-f)<oa?(o+f)/2:ma(_,w),S=t(N,q),A=S[0],M=S[1],T=A-r,C=M-s,j=b*T-y*C;(j*j/v>e||ha((y*T+b*C)/v-.5)>.3||i*d+a*h+l*p<hf)&&(n(r,s,o,i,a,l,A,M,N,w/=k,_/=k,x,m,g),g.point(A,M),n(A,M,N,w,_,x,c,u,f,d,h,p,m,g))}}return function(e){var r,s,o,i,a,l,c,u,f,d,h,p,m={point:g,lineStart:y,lineEnd:v,polygonStart:function(){e.polygonStart(),m.lineStart=w},polygonEnd:function(){e.polygonEnd(),m.lineStart=y}};function g(n,r){n=t(n,r),e.point(n[0],n[1])}function y(){u=NaN,m.point=b,e.lineStart()}function b(r,s){var o=al([r,s]),i=t(r,s);n(u,f,c,d,h,p,u=i[0],f=i[1],c=r,d=o[0],h=o[1],p=o[2],df,e),e.point(u,f)}function v(){m.point=g,e.lineEnd()}function w(){y(),m.point=_,m.lineEnd=x}function _(t,e){b(r=t,e),s=u,o=f,i=d,a=h,l=p,m.point=b}function x(){n(u,f,c,d,h,p,s,o,r,i,a,l,df,e),m.lineEnd=v,v()}return m}}(t,e):function(t){return sf({point:function(e,n){e=t(e,n),this.stream.point(e[0],e[1])}})}(t)}var mf=sf({point:function(t,e){this.stream.point(t*da,e*da)}});function gf(t,e,n,r,s,o){if(!o)return function(t,e,n,r,s){function o(o,i){return[e+t*(o*=r),n-t*(i*=s)]}return o.invert=function(o,i){return[(o-e)/t*r,(n-i)/t*s]},o}(t,e,n,r,s);var i=ga(o),a=xa(o),l=i*t,c=a*t,u=i/t,f=a/t,d=(a*n-i*e)/t,h=(a*e+i*n)/t;function p(t,o){return[l*(t*=r)-c*(o*=s)+e,n-c*t-l*o]}return p.invert=function(t,e){return[r*(u*t-f*e+d),s*(h-f*t-u*e)]},p}function yf(t){return bf((function(){return t}))()}function bf(t){var e,n,r,s,o,i,a,l,c,u,f=150,d=480,h=250,p=0,m=0,g=0,y=0,b=0,v=0,w=1,_=1,x=null,k=_c,q=null,N=tu,S=.5;function A(t){return l(t[0]*da,t[1]*da)}function M(t){return(t=l.invert(t[0],t[1]))&&[t[0]*fa,t[1]*fa]}function T(){var t=gf(f,0,0,w,_,v).apply(null,e(p,m)),r=gf(f,d-t[0],h-t[1],w,_,v);return n=nc(g,y,b),a=tc(e,r),l=tc(n,a),i=pf(a,S),C()}function C(){return c=u=null,A}return A.stream=function(t){return c&&u===t?c:c=mf(function(t){return sf({point:function(e,n){var r=t(e,n);return this.stream.point(r[0],r[1])}})}(n)(k(i(N(u=t)))))},A.preclip=function(t){return arguments.length?(k=t,x=void 0,C()):k},A.postclip=function(t){return arguments.length?(N=t,q=r=s=o=null,C()):N},A.clipAngle=function(t){return arguments.length?(k=+t?xc(x=t*da):(x=null,_c),C()):x*fa},A.clipExtent=function(t){return arguments.length?(N=null==t?(q=r=s=o=null,tu):Tc(q=+t[0][0],r=+t[0][1],s=+t[1][0],o=+t[1][1]),C()):null==q?null:[[q,r],[s,o]]},A.scale=function(t){return arguments.length?(f=+t,T()):f},A.translate=function(t){return arguments.length?(d=+t[0],h=+t[1],T()):[d,h]},A.center=function(t){return arguments.length?(p=t[0]%360*da,m=t[1]%360*da,T()):[p*fa,m*fa]},A.rotate=function(t){return arguments.length?(g=t[0]%360*da,y=t[1]%360*da,b=t.length>2?t[2]%360*da:0,T()):[g*fa,y*fa,b*fa]},A.angle=function(t){return arguments.length?(v=t%360*da,T()):v*fa},A.reflectX=function(t){return arguments.length?(w=t?-1:1,T()):w<0},A.reflectY=function(t){return arguments.length?(_=t?-1:1,T()):_<0},A.precision=function(t){return arguments.length?(i=pf(a,S=t*t),C()):qa(S)},A.fitExtent=function(t,e){return lf(A,t,e)},A.fitSize=function(t,e){return cf(A,t,e)},A.fitWidth=function(t,e){return uf(A,t,e)},A.fitHeight=function(t,e){return ff(A,t,e)},function(){return e=t.apply(this,arguments),A.invert=e.invert&&M,T()}}function vf(t){var e=0,n=aa/3,r=bf(t),s=r(e,n);return s.parallels=function(t){return arguments.length?r(e=t[0]*da,n=t[1]*da):[e*fa,n*fa]},s}function wf(t,e){var n=xa(t),r=(n+xa(e))/2;if(ha(r)<oa)return function(t){var e=ga(t);function n(t,n){return[t*e,xa(n)/e]}return n.invert=function(t,n){return[t/e,Aa(n*e)]},n}(t);var s=1+n*(2*r-n),o=qa(s)/r;function i(t,e){var n=qa(s-2*r*xa(e))/r;return[n*xa(t*=r),o-n*ga(t)]}return i.invert=function(t,e){var n=o-e,i=ma(t,ha(n))*ka(n);return n*r<0&&(i-=aa*ka(t)*ka(n)),[i/r,Aa((s-(t*t+n*n)*r*r)/(2*r))]},i}function _f(){return vf(wf).scale(155.424).center([0,33.6442])}function xf(){return _f().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function kf(){var t,e,n,r,s,o,i=xf(),a=_f().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=_f().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(t,e){o=[t,e]}};function u(t){var e=t[0],i=t[1];return o=null,n.point(e,i),o||(r.point(e,i),o)||(s.point(e,i),o)}function f(){return t=e=null,u}return u.invert=function(t){var e=i.scale(),n=i.translate(),r=(t[0]-n[0])/e,s=(t[1]-n[1])/e;return(s>=.12&&s<.234&&r>=-.425&&r<-.214?a:s>=.166&&s<.234&&r>=-.214&&r<-.115?l:i).invert(t)},u.stream=function(n){return t&&e===n?t:(r=[i.stream(e=n),a.stream(n),l.stream(n)],s=r.length,t={point:function(t,e){for(var n=-1;++n<s;)r[n].point(t,e)},sphere:function(){for(var t=-1;++t<s;)r[t].sphere()},lineStart:function(){for(var t=-1;++t<s;)r[t].lineStart()},lineEnd:function(){for(var t=-1;++t<s;)r[t].lineEnd()},polygonStart:function(){for(var t=-1;++t<s;)r[t].polygonStart()},polygonEnd:function(){for(var t=-1;++t<s;)r[t].polygonEnd()}});var r,s},u.precision=function(t){return arguments.length?(i.precision(t),a.precision(t),l.precision(t),f()):i.precision()},u.scale=function(t){return arguments.length?(i.scale(t),a.scale(.35*t),l.scale(t),u.translate(i.translate())):i.scale()},u.translate=function(t){if(!arguments.length)return i.translate();var e=i.scale(),o=+t[0],u=+t[1];return n=i.translate(t).clipExtent([[o-.455*e,u-.238*e],[o+.455*e,u+.238*e]]).stream(c),r=a.translate([o-.307*e,u+.201*e]).clipExtent([[o-.425*e+oa,u+.12*e+oa],[o-.214*e-oa,u+.234*e-oa]]).stream(c),s=l.translate([o-.205*e,u+.212*e]).clipExtent([[o-.214*e+oa,u+.166*e+oa],[o-.115*e-oa,u+.234*e-oa]]).stream(c),f()},u.fitExtent=function(t,e){return lf(u,t,e)},u.fitSize=function(t,e){return cf(u,t,e)},u.fitWidth=function(t,e){return uf(u,t,e)},u.fitHeight=function(t,e){return ff(u,t,e)},u.scale(1070)}function qf(t){return function(e,n){var r=ga(e),s=ga(n),o=t(r*s);return o===1/0?[2,0]:[o*s*xa(e),o*xa(n)]}}function Nf(t){return function(e,n){var r=qa(e*e+n*n),s=t(r),o=xa(s),i=ga(s);return[ma(e*o,r*i),Aa(r&&n*o/r)]}}var Sf=qf((function(t){return qa(2/(1+t))}));function Af(){return yf(Sf).scale(124.75).clipAngle(179.999)}Sf.invert=Nf((function(t){return 2*Aa(t/2)}));var Mf=qf((function(t){return(t=Sa(t))&&t/xa(t)}));function Tf(){return yf(Mf).scale(79.4188).clipAngle(179.999)}function Cf(t,e){return[t,wa(Na((la+e)/2))]}function jf(){return Ef(Cf).scale(961/ua)}function Ef(t){var e,n,r,s=yf(t),o=s.center,i=s.scale,a=s.translate,l=s.clipExtent,c=null;function u(){var o=aa*i(),a=s(ic(s.rotate()).invert([0,0]));return l(null==c?[[a[0]-o,a[1]-o],[a[0]+o,a[1]+o]]:t===Cf?[[Math.max(a[0]-o,c),e],[Math.min(a[0]+o,n),r]]:[[c,Math.max(a[1]-o,e)],[n,Math.min(a[1]+o,r)]])}return s.scale=function(t){return arguments.length?(i(t),u()):i()},s.translate=function(t){return arguments.length?(a(t),u()):a()},s.center=function(t){return arguments.length?(o(t),u()):o()},s.clipExtent=function(t){return arguments.length?(null==t?c=e=n=r=null:(c=+t[0][0],e=+t[0][1],n=+t[1][0],r=+t[1][1]),u()):null==c?null:[[c,e],[n,r]]},u()}function Of(t){return Na((la+t)/2)}function If(t,e){var n=ga(t),r=t===e?xa(t):wa(n/ga(e))/wa(Of(e)/Of(t)),s=n*_a(Of(t),r)/r;if(!r)return Cf;function o(t,e){s>0?e<-la+oa&&(e=-la+oa):e>la-oa&&(e=la-oa);var n=s/_a(Of(e),r);return[n*xa(r*t),s-n*ga(r*t)]}return o.invert=function(t,e){var n=s-e,o=ka(r)*qa(t*t+n*n),i=ma(t,ha(n))*ka(n);return n*r<0&&(i-=aa*ka(t)*ka(n)),[i/r,2*pa(_a(s/o,1/r))-la]},o}function Rf(){return vf(If).scale(109.5).parallels([30,30])}function Ff(t,e){return[t,e]}function Pf(){return yf(Ff).scale(152.63)}function Df(t,e){var n=ga(t),r=t===e?xa(t):(n-ga(e))/(e-t),s=n/r+t;if(ha(r)<oa)return Ff;function o(t,e){var n=s-e,o=r*t;return[n*xa(o),s-n*ga(o)]}return o.invert=function(t,e){var n=s-e,o=ma(t,ha(n))*ka(n);return n*r<0&&(o-=aa*ka(t)*ka(n)),[o/r,s-ka(r)*qa(t*t+n*n)]},o}function Lf(){return vf(Df).scale(131.154).center([0,13.9389])}Mf.invert=Nf((function(t){return t})),Cf.invert=function(t,e){return[t,2*pa(ba(e))-la]},Ff.invert=Ff;var $f=1.340264,zf=-.081106,Zf=893e-6,Uf=.003796,Bf=qa(3)/2;function Gf(t,e){var n=Aa(Bf*xa(e)),r=n*n,s=r*r*r;return[t*ga(n)/(Bf*($f+3*zf*r+s*(7*Zf+9*Uf*r))),n*($f+zf*r+s*(Zf+Uf*r))]}function Jf(){return yf(Gf).scale(177.158)}function Hf(t,e){var n=ga(e),r=ga(t)*n;return[n*xa(t)/r,xa(e)/r]}function Wf(){return yf(Hf).scale(144.049).clipAngle(60)}function Vf(){var t,e,n,r,s,o,i,a=1,l=0,c=0,u=1,f=1,d=0,h=null,p=1,m=1,g=sf({point:function(t,e){var n=v([t,e]);this.stream.point(n[0],n[1])}}),y=tu;function b(){return p=a*u,m=a*f,o=i=null,v}function v(n){var r=n[0]*p,s=n[1]*m;if(d){var o=s*t-r*e;r=r*t+s*e,s=o}return[r+l,s+c]}return v.invert=function(n){var r=n[0]-l,s=n[1]-c;if(d){var o=s*t+r*e;r=r*t-s*e,s=o}return[r/p,s/m]},v.stream=function(t){return o&&i===t?o:o=g(y(i=t))},v.postclip=function(t){return arguments.length?(y=t,h=n=r=s=null,b()):y},v.clipExtent=function(t){return arguments.length?(y=null==t?(h=n=r=s=null,tu):Tc(h=+t[0][0],n=+t[0][1],r=+t[1][0],s=+t[1][1]),b()):null==h?null:[[h,n],[r,s]]},v.scale=function(t){return arguments.length?(a=+t,b()):a},v.translate=function(t){return arguments.length?(l=+t[0],c=+t[1],b()):[l,c]},v.angle=function(n){return arguments.length?(e=xa(d=n%360*da),t=ga(d),b()):d*fa},v.reflectX=function(t){return arguments.length?(u=t?-1:1,b()):u<0},v.reflectY=function(t){return arguments.length?(f=t?-1:1,b()):f<0},v.fitExtent=function(t,e){return lf(v,t,e)},v.fitSize=function(t,e){return cf(v,t,e)},v.fitWidth=function(t,e){return uf(v,t,e)},v.fitHeight=function(t,e){return ff(v,t,e)},v}function Yf(t,e){var n=e*e,r=n*n;return[t*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),e*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}function Kf(){return yf(Yf).scale(175.295)}function Xf(t,e){return[ga(e)*xa(t),xa(e)]}function Qf(){return yf(Xf).scale(249.5).clipAngle(90+oa)}function td(t,e){var n=ga(e),r=1+ga(t)*n;return[n*xa(t)/r,xa(e)/r]}function ed(){return yf(td).scale(250).clipAngle(142)}function nd(t,e){return[wa(Na((la+e)/2)),-t]}function rd(){var t=Ef(nd),e=t.center,n=t.rotate;return t.center=function(t){return arguments.length?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return arguments.length?n([t[0],t[1],t.length>2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}function sd(t,e){return t.parent===e.parent?1:2}function od(t,e){return t+e.x}function id(t,e){return Math.max(t,e.y)}function ad(){var t=sd,e=1,n=1,r=!1;function s(s){var o,i=0;s.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(od,0)/t.length}(n),e.y=function(t){return 1+t.reduce(id,0)}(n)):(e.x=o?i+=t(e,o):0,e.y=0,o=e)}));var a=function(t){for(var e;e=t.children;)t=e[0];return t}(s),l=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(s),c=a.x-t(a,l)/2,u=l.x+t(l,a)/2;return s.eachAfter(r?function(t){t.x=(t.x-s.x)*e,t.y=(s.y-t.y)*n}:function(t){t.x=(t.x-c)/(u-c)*e,t.y=(1-(s.y?t.y/s.y:1))*n})}return s.separation=function(e){return arguments.length?(t=e,s):t},s.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],s):r?null:[e,n]},s.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],s):r?[e,n]:null},s}Gf.invert=function(t,e){for(var n,r=e,s=r*r,o=s*s*s,i=0;i<12&&(o=(s=(r-=n=(r*($f+zf*s+o*(Zf+Uf*s))-e)/($f+3*zf*s+o*(7*Zf+9*Uf*s)))*r)*s*s,!(ha(n)<ia));++i);return[Bf*t*($f+3*zf*s+o*(7*Zf+9*Uf*s))/ga(r),Aa(xa(r)/Bf)]},Hf.invert=Nf(pa),Yf.invert=function(t,e){var n,r=e,s=25;do{var o=r*r,i=o*o;r-=n=(r*(1.007226+o*(.015085+i*(.028874*o-.044475-.005916*i)))-e)/(1.007226+o*(.045255+i*(.259866*o-.311325-.005916*11*i)))}while(ha(n)>oa&&--s>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},Xf.invert=Nf(Aa),td.invert=Nf((function(t){return 2*pa(t)})),nd.invert=function(t,e){return[-e,2*pa(ba(t))-la]};var ld=n(5220),cd=n(9466);function ud(){return 0}function fd(t){return function(){return t}}const dd=1664525,hd=1013904223,pd=4294967296;function md(){let t=1;return()=>(t=(dd*t+hd)%pd)/pd}function gd(t){return yd(t,md())}function yd(t,e){for(var n,r,s=0,o=(t=function(t,e){let n,r,s=t.length;for(;s;)r=e()*s--|0,n=t[s],t[s]=t[r],t[r]=n;return t}(Array.from(t),e)).length,i=[];s<o;)n=t[s],r&&wd(r,n)?++s:(r=xd(i=bd(i,n)),s=0);return r}function bd(t,e){var n,r;if(_d(e,t))return[e];for(n=0;n<t.length;++n)if(vd(e,t[n])&&_d(kd(t[n],e),t))return[t[n],e];for(n=0;n<t.length-1;++n)for(r=n+1;r<t.length;++r)if(vd(kd(t[n],t[r]),e)&&vd(kd(t[n],e),t[r])&&vd(kd(t[r],e),t[n])&&_d(qd(t[n],t[r],e),t))return[t[n],t[r],e];throw new Error}function vd(t,e){var n=t.r-e.r,r=e.x-t.x,s=e.y-t.y;return n<0||n*n<r*r+s*s}function wd(t,e){var n=t.r-e.r+1e-9*Math.max(t.r,e.r,1),r=e.x-t.x,s=e.y-t.y;return n>0&&n*n>r*r+s*s}function _d(t,e){for(var n=0;n<e.length;++n)if(!wd(t,e[n]))return!1;return!0}function xd(t){switch(t.length){case 1:return function(t){return{x:t.x,y:t.y,r:t.r}}(t[0]);case 2:return kd(t[0],t[1]);case 3:return qd(t[0],t[1],t[2])}}function kd(t,e){var n=t.x,r=t.y,s=t.r,o=e.x,i=e.y,a=e.r,l=o-n,c=i-r,u=a-s,f=Math.sqrt(l*l+c*c);return{x:(n+o+l/f*u)/2,y:(r+i+c/f*u)/2,r:(f+s+a)/2}}function qd(t,e,n){var r=t.x,s=t.y,o=t.r,i=e.x,a=e.y,l=e.r,c=n.x,u=n.y,f=n.r,d=r-i,h=r-c,p=s-a,m=s-u,g=l-o,y=f-o,b=r*r+s*s-o*o,v=b-i*i-a*a+l*l,w=b-c*c-u*u+f*f,_=h*p-d*m,x=(p*w-m*v)/(2*_)-r,k=(m*g-p*y)/_,q=(h*v-d*w)/(2*_)-s,N=(d*y-h*g)/_,S=k*k+N*N-1,A=2*(o+x*k+q*N),M=x*x+q*q-o*o,T=-(Math.abs(S)>1e-6?(A+Math.sqrt(A*A-4*S*M))/(2*S):M/A);return{x:r+x+k*T,y:s+q+N*T,r:T}}function Nd(t,e,n){var r,s,o,i,a=t.x-e.x,l=t.y-e.y,c=a*a+l*l;c?(s=e.r+n.r,s*=s,i=t.r+n.r,s>(i*=i)?(r=(c+i-s)/(2*c),o=Math.sqrt(Math.max(0,i/c-r*r)),n.x=t.x-r*a-o*l,n.y=t.y-r*l+o*a):(r=(c+s-i)/(2*c),o=Math.sqrt(Math.max(0,s/c-r*r)),n.x=e.x+r*a-o*l,n.y=e.y+r*l+o*a)):(n.x=e.x+n.r,n.y=e.y)}function Sd(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,s=e.y-t.y;return n>0&&n*n>r*r+s*s}function Ad(t){var e=t._,n=t.next._,r=e.r+n.r,s=(e.x*n.r+n.x*e.r)/r,o=(e.y*n.r+n.y*e.r)/r;return s*s+o*o}function Md(t){this._=t,this.next=null,this.previous=null}function Td(t,e){if(!(o=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var n,r,s,o,i,a,l,c,u,f,d;if((n=t[0]).x=0,n.y=0,!(o>1))return n.r;if(r=t[1],n.x=-r.r,r.x=n.r,r.y=0,!(o>2))return n.r+r.r;Nd(r,n,s=t[2]),n=new Md(n),r=new Md(r),s=new Md(s),n.next=s.previous=r,r.next=n.previous=s,s.next=r.previous=n;t:for(l=3;l<o;++l){Nd(n._,r._,s=t[l]),s=new Md(s),c=r.next,u=n.previous,f=r._.r,d=n._.r;do{if(f<=d){if(Sd(c._,s._)){r=c,n.next=r,r.previous=n,--l;continue t}f+=c._.r,c=c.next}else{if(Sd(u._,s._)){(n=u).next=r,r.previous=n,--l;continue t}d+=u._.r,u=u.previous}}while(c!==u.next);for(s.previous=n,s.next=r,n.next=r.previous=r=s,i=Ad(n);(s=s.next)!==r;)(a=Ad(s))<i&&(n=s,i=a);r=n.next}for(n=[r._],s=r;(s=s.next)!==r;)n.push(s._);for(s=yd(n,e),l=0;l<o;++l)(n=t[l]).x-=s.x,n.y-=s.y;return s.r}function Cd(t){return Td(t,md()),t}function jd(t){return Math.sqrt(t.value)}function Ed(){var t=null,e=1,n=1,r=ud;function s(s){const o=md();return s.x=e/2,s.y=n/2,t?s.eachBefore(Od(t)).eachAfter(Id(r,.5,o)).eachBefore(Rd(1)):s.eachBefore(Od(jd)).eachAfter(Id(ud,1,o)).eachAfter(Id(r,s.r/Math.min(e,n),o)).eachBefore(Rd(Math.min(e,n)/(2*s.r))),s}return s.radius=function(e){return arguments.length?(t=(0,cd.j)(e),s):t},s.size=function(t){return arguments.length?(e=+t[0],n=+t[1],s):[e,n]},s.padding=function(t){return arguments.length?(r="function"==typeof t?t:fd(+t),s):r},s}function Od(t){return function(e){e.children||(e.r=Math.max(0,+t(e)||0))}}function Id(t,e,n){return function(r){if(s=r.children){var s,o,i,a=s.length,l=t(r)*e||0;if(l)for(o=0;o<a;++o)s[o].r+=l;if(i=Td(s,n),l)for(o=0;o<a;++o)s[o].r-=l;r.r=i+l}}}function Rd(t){return function(e){var n=e.parent;e.r*=t,n&&(e.x=n.x+t*e.x,e.y=n.y+t*e.y)}}function Fd(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function Pd(t,e,n,r,s){for(var o,i=t.children,a=-1,l=i.length,c=t.value&&(r-e)/t.value;++a<l;)(o=i[a]).y0=n,o.y1=s,o.x0=e,o.x1=e+=o.value*c}function Dd(){var t=1,e=1,n=0,r=!1;function s(s){var o=s.height+1;return s.x0=s.y0=n,s.x1=t,s.y1=e/o,s.eachBefore(function(t,e){return function(r){r.children&&Pd(r,r.x0,t*(r.depth+1)/e,r.x1,t*(r.depth+2)/e);var s=r.x0,o=r.y0,i=r.x1-n,a=r.y1-n;i<s&&(s=i=(s+i)/2),a<o&&(o=a=(o+a)/2),r.x0=s,r.y0=o,r.x1=i,r.y1=a}}(e,o)),r&&s.eachBefore(Fd),s}return s.round=function(t){return arguments.length?(r=!!t,s):r},s.size=function(n){return arguments.length?(t=+n[0],e=+n[1],s):[t,e]},s.padding=function(t){return arguments.length?(n=+t,s):n},s}var Ld=n(4766);function $d(t,e){return t.parent===e.parent?1:2}function zd(t){var e=t.children;return e?e[0]:t.t}function Zd(t){var e=t.children;return e?e[e.length-1]:t.t}function Ud(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n}function Bd(t,e,n){return t.a.parent===e.parent?t.a:n}function Gd(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e}function Jd(){var t=$d,e=1,n=1,r=null;function s(s){var l=function(t){for(var e,n,r,s,o,i=new Gd(t,0),a=[i];e=a.pop();)if(r=e._.children)for(e.children=new Array(o=r.length),s=o-1;s>=0;--s)a.push(n=e.children[s]=new Gd(r[s],s)),n.parent=e;return(i.parent=new Gd(null,0)).children=[i],i}(s);if(l.eachAfter(o),l.parent.m=-l.z,l.eachBefore(i),r)s.eachBefore(a);else{var c=s,u=s,f=s;s.eachBefore((function(t){t.x<c.x&&(c=t),t.x>u.x&&(u=t),t.depth>f.depth&&(f=t)}));var d=c===u?1:t(c,u)/2,h=d-c.x,p=e/(u.x+d+h),m=n/(f.depth||1);s.eachBefore((function(t){t.x=(t.x+h)*p,t.y=t.depth*m}))}return s}function o(e){var n=e.children,r=e.parent.children,s=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,s=t.children,o=s.length;--o>=0;)(e=s[o]).z+=n,e.m+=n,n+=e.s+(r+=e.c)}(e);var o=(n[0].z+n[n.length-1].z)/2;s?(e.z=s.z+t(e._,s._),e.m=e.z-o):e.z=o}else s&&(e.z=s.z+t(e._,s._));e.parent.A=function(e,n,r){if(n){for(var s,o=e,i=e,a=n,l=o.parent.children[0],c=o.m,u=i.m,f=a.m,d=l.m;a=Zd(a),o=zd(o),a&&o;)l=zd(l),(i=Zd(i)).a=e,(s=a.z+f-o.z-c+t(a._,o._))>0&&(Ud(Bd(a,e,r),e,s),c+=s,u+=s),f+=a.m,c+=o.m,d+=l.m,u+=i.m;a&&!Zd(i)&&(i.t=a,i.m+=f-u),o&&!zd(l)&&(l.t=o,l.m+=c-d,r=e)}return r}(e,s,e.parent.A||r[0])}function i(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function a(t){t.x*=e,t.y=t.depth*n}return s.separation=function(e){return arguments.length?(t=e,s):t},s.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],s):r?null:[e,n]},s.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],s):r?[e,n]:null},s}function Hd(t,e,n,r,s){for(var o,i=t.children,a=-1,l=i.length,c=t.value&&(s-n)/t.value;++a<l;)(o=i[a]).x0=e,o.x1=r,o.y0=n,o.y1=n+=o.value*c}Gd.prototype=Object.create(ld.NB.prototype);var Wd=(1+Math.sqrt(5))/2;function Vd(t,e,n,r,s,o){for(var i,a,l,c,u,f,d,h,p,m,g,y=[],b=e.children,v=0,w=0,_=b.length,x=e.value;v<_;){l=s-n,c=o-r;do{u=b[w++].value}while(!u&&w<_);for(f=d=u,g=u*u*(m=Math.max(c/l,l/c)/(x*t)),p=Math.max(d/g,g/f);w<_;++w){if(u+=a=b[w].value,a<f&&(f=a),a>d&&(d=a),g=u*u*m,(h=Math.max(d/g,g/f))>p){u-=a;break}p=h}y.push(i={value:u,dice:l<c,children:b.slice(v,w)}),i.dice?Pd(i,n,r,s,x?r+=c*u/x:o):Hd(i,n,r,x?n+=l*u/x:s,o),x-=u,v=w}return y}const Yd=function t(e){function n(t,n,r,s,o){Vd(e,t,n,r,s,o)}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(Wd);function Kd(){var t=Yd,e=!1,n=1,r=1,s=[0],o=ud,i=ud,a=ud,l=ud,c=ud;function u(t){return t.x0=t.y0=0,t.x1=n,t.y1=r,t.eachBefore(f),s=[0],e&&t.eachBefore(Fd),t}function f(e){var n=s[e.depth],r=e.x0+n,u=e.y0+n,f=e.x1-n,d=e.y1-n;f<r&&(r=f=(r+f)/2),d<u&&(u=d=(u+d)/2),e.x0=r,e.y0=u,e.x1=f,e.y1=d,e.children&&(n=s[e.depth+1]=o(e)/2,r+=c(e)-n,u+=i(e)-n,(f-=a(e)-n)<r&&(r=f=(r+f)/2),(d-=l(e)-n)<u&&(u=d=(u+d)/2),t(e,r,u,f,d))}return u.round=function(t){return arguments.length?(e=!!t,u):e},u.size=function(t){return arguments.length?(n=+t[0],r=+t[1],u):[n,r]},u.tile=function(e){return arguments.length?(t=(0,cd.C)(e),u):t},u.padding=function(t){return arguments.length?u.paddingInner(t).paddingOuter(t):u.paddingInner()},u.paddingInner=function(t){return arguments.length?(o="function"==typeof t?t:fd(+t),u):o},u.paddingOuter=function(t){return arguments.length?u.paddingTop(t).paddingRight(t).paddingBottom(t).paddingLeft(t):u.paddingTop()},u.paddingTop=function(t){return arguments.length?(i="function"==typeof t?t:fd(+t),u):i},u.paddingRight=function(t){return arguments.length?(a="function"==typeof t?t:fd(+t),u):a},u.paddingBottom=function(t){return arguments.length?(l="function"==typeof t?t:fd(+t),u):l},u.paddingLeft=function(t){return arguments.length?(c="function"==typeof t?t:fd(+t),u):c},u}function Xd(t,e,n,r,s){var o,i,a=t.children,l=a.length,c=new Array(l+1);for(c[0]=i=o=0;o<l;++o)c[o+1]=i+=a[o].value;!function t(e,n,r,s,o,i,l){if(e>=n-1){var u=a[e];return u.x0=s,u.y0=o,u.x1=i,void(u.y1=l)}var f=c[e],d=r/2+f,h=e+1,p=n-1;for(;h<p;){var m=h+p>>>1;c[m]<d?h=m+1:p=m}d-c[h-1]<c[h]-d&&e+1<h&&--h;var g=c[h]-f,y=r-g;if(i-s>l-o){var b=r?(s*y+i*g)/r:i;t(e,h,g,s,o,b,l),t(h,n,y,b,o,i,l)}else{var v=r?(o*y+l*g)/r:l;t(e,h,g,s,o,i,v),t(h,n,y,s,v,i,l)}}(0,l,t.value,e,n,r,s)}function Qd(t,e,n,r,s){(1&t.depth?Hd:Pd)(t,e,n,r,s)}const th=function t(e){function n(t,n,r,s,o){if((i=t._squarify)&&i.ratio===e)for(var i,a,l,c,u,f=-1,d=i.length,h=t.value;++f<d;){for(l=(a=i[f]).children,c=a.value=0,u=l.length;c<u;++c)a.value+=l[c].value;a.dice?Pd(a,n,r,s,h?r+=(o-r)*a.value/h:o):Hd(a,n,r,h?n+=(s-n)*a.value/h:s,o),h-=a.value}else t._squarify=i=Vd(e,t,n,r,s,o),i.ratio=e}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(Wd);var eh=n(4321),nh=n(5409),rh=n(7855),sh=n(6261);function oh(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}var ih=n(8190);function ah(t,e){var n=(0,ih.wx)(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}var lh=n(5003),ch=n(8765),uh=n(5250);function fh(t){return((t=Math.exp(t))+1/t)/2}const dh=function t(e,n,r){function s(t,s){var o,i,a=t[0],l=t[1],c=t[2],u=s[0],f=s[1],d=s[2],h=u-a,p=f-l,m=h*h+p*p;if(m<1e-12)i=Math.log(d/c)/e,o=function(t){return[a+t*h,l+t*p,c*Math.exp(e*t*i)]};else{var g=Math.sqrt(m),y=(d*d-c*c+r*m)/(2*c*n*g),b=(d*d-c*c-r*m)/(2*d*n*g),v=Math.log(Math.sqrt(y*y+1)-y),w=Math.log(Math.sqrt(b*b+1)-b);i=(w-v)/e,o=function(t){var r=t*i,s=fh(v),o=c/(n*g)*(s*function(t){return((t=Math.exp(2*t))-1)/(t+1)}(e*r+v)-function(t){return((t=Math.exp(t))-1/t)/2}(v));return[a+o*h,l+o*p,c*s/fh(e*r+v)]}}return o.duration=1e3*i*e/Math.SQRT2,o}return s.rho=function(e){var n=Math.max(.001,+e),r=n*n;return t(n,r,r*r)},s}(Math.SQRT2,2,4);function hh(t){return function(e,n){var r=t((e=(0,$e.Ym)(e)).h,(n=(0,$e.Ym)(n)).h),s=(0,ih.ZP)(e.s,n.s),o=(0,ih.ZP)(e.l,n.l),i=(0,ih.ZP)(e.opacity,n.opacity);return function(t){return e.h=r(t),e.s=s(t),e.l=o(t),e.opacity=i(t),e+""}}}const ph=hh(ih.wx);var mh=hh(ih.ZP);function gh(t,e){var n=(0,ih.ZP)((t=Pr(t)).l,(e=Pr(e)).l),r=(0,ih.ZP)(t.a,e.a),s=(0,ih.ZP)(t.b,e.b),o=(0,ih.ZP)(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=r(e),t.b=s(e),t.opacity=o(e),t+""}}function yh(t){return function(e,n){var r=t((e=Gr(e)).h,(n=Gr(n)).h),s=(0,ih.ZP)(e.c,n.c),o=(0,ih.ZP)(e.l,n.l),i=(0,ih.ZP)(e.opacity,n.opacity);return function(t){return e.h=r(t),e.c=s(t),e.l=o(t),e.opacity=i(t),e+""}}}const bh=yh(ih.wx);var vh=yh(ih.ZP);function wh(t){return function e(n){function r(e,r){var s=t((e=ns(e)).h,(r=ns(r)).h),o=(0,ih.ZP)(e.s,r.s),i=(0,ih.ZP)(e.l,r.l),a=(0,ih.ZP)(e.opacity,r.opacity);return function(t){return e.h=s(t),e.s=o(t),e.l=i(Math.pow(t,n)),e.opacity=a(t),e+""}}return n=+n,r.gamma=e,r}(1)}const _h=wh(ih.wx);var xh=wh(ih.ZP),kh=n(9444);function qh(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t(r/(e-1));return n}function Nh(t){for(var e,n=-1,r=t.length,s=t[r-1],o=0;++n<r;)e=s,s=t[n],o+=e[1]*s[0]-e[0]*s[1];return o/2}function Sh(t){for(var e,n,r=-1,s=t.length,o=0,i=0,a=t[s-1],l=0;++r<s;)e=a,a=t[r],l+=n=e[0]*a[1]-a[0]*e[1],o+=(e[0]+a[0])*n,i+=(e[1]+a[1])*n;return[o/(l*=3),i/l]}function Ah(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}function Mh(t,e){return t[0]-e[0]||t[1]-e[1]}function Th(t){const e=t.length,n=[0,1];let r,s=2;for(r=2;r<e;++r){for(;s>1&&Ah(t[n[s-2]],t[n[s-1]],t[r])<=0;)--s;n[s++]=r}return n.slice(0,s)}function Ch(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),s=new Array(n);for(e=0;e<n;++e)r[e]=[+t[e][0],+t[e][1],e];for(r.sort(Mh),e=0;e<n;++e)s[e]=[r[e][0],-r[e][1]];var o=Th(r),i=Th(s),a=i[0]===o[0],l=i[i.length-1]===o[o.length-1],c=[];for(e=o.length-1;e>=0;--e)c.push(t[r[o[e]][2]]);for(e=+a;e<i.length-l;++e)c.push(t[r[i[e]][2]]);return c}function jh(t,e){for(var n,r,s=t.length,o=t[s-1],i=e[0],a=e[1],l=o[0],c=o[1],u=!1,f=0;f<s;++f)n=(o=t[f])[0],(r=o[1])>a!=c>a&&i<(l-n)*(a-r)/(c-r)+n&&(u=!u),l=n,c=r;return u}function Eh(t){for(var e,n,r=-1,s=t.length,o=t[s-1],i=o[0],a=o[1],l=0;++r<s;)e=i,n=a,e-=i=(o=t[r])[0],n-=a=o[1],l+=Math.hypot(e,n);return l}const Oh=Math.random,Ih=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,1===arguments.length?(n=t,t=0):n-=t,function(){return e()*n+t}}return n.source=t,n}(Oh),Rh=function t(e){function n(t,n){return arguments.length<2&&(n=t,t=0),t=Math.floor(t),n=Math.floor(n)-t,function(){return Math.floor(e()*n+t)}}return n.source=t,n}(Oh),Fh=function t(e){function n(t,n){var r,s;return t=null==t?0:+t,n=null==n?1:+n,function(){var o;if(null!=r)o=r,r=null;else do{r=2*e()-1,o=2*e()-1,s=r*r+o*o}while(!s||s>1);return t+n*o*Math.sqrt(-2*Math.log(s)/s)}}return n.source=t,n}(Oh),Ph=function t(e){var n=Fh.source(e);function r(){var t=n.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Oh),Dh=function t(e){function n(t){return(t=+t)<=0?()=>0:function(){for(var n=0,r=t;r>1;--r)n+=e();return n+r*e()}}return n.source=t,n}(Oh),Lh=function t(e){var n=Dh.source(e);function r(t){if(0==(t=+t))return e;var r=n(t);return function(){return r()/t}}return r.source=t,r}(Oh),$h=function t(e){function n(t){return function(){return-Math.log1p(-e())/t}}return n.source=t,n}(Oh),zh=function t(e){function n(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-e(),t)}}return n.source=t,n}(Oh),Zh=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(e()+t)}}return n.source=t,n}(Oh),Uh=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-e())/t)})}return n.source=t,n}(Oh),Bh=function t(e){var n=Fh.source(e)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-e())*r;var s=(t<1?t+1:t)-1/3,o=1/(3*Math.sqrt(s)),i=t<1?()=>Math.pow(e(),1/t):()=>1;return function(){do{do{var t=n(),a=1+o*t}while(a<=0);a*=a*a;var l=1-e()}while(l>=1-.0331*t*t*t*t&&Math.log(l)>=.5*t*t+s*(1-a+Math.log(a)));return s*a*i()*r}}return r.source=t,r}(Oh),Gh=function t(e){var n=Bh.source(e);function r(t,e){var r=n(t),s=n(e);return function(){var t=r();return 0===t?0:t/(t+s())}}return r.source=t,r}(Oh),Jh=function t(e){var n=Uh.source(e),r=Gh.source(e);function s(t,e){return t=+t,(e=+e)>=1?()=>t:e<=0?()=>0:function(){for(var s=0,o=t,i=e;o*i>16&&o*(1-i)>16;){var a=Math.floor((o+1)*i),l=r(a,o-a+1)();l<=i?(s+=a,o-=a,i=(i-l)/(1-l)):(o=a-1,i/=l)}for(var c=i<.5,u=n(c?i:1-i),f=u(),d=0;f<=o;++d)f+=u();return s+(c?d:o-d)}}return s.source=t,s}(Oh),Hh=function t(e){function n(t,n,r){var s;return 0==(t=+t)?s=t=>-Math.log(t):(t=1/t,s=e=>Math.pow(e,t)),n=null==n?0:+n,r=null==r?1:+r,function(){return n+r*s(-Math.log1p(-e()))}}return n.source=t,n}(Oh),Wh=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){return t+n*Math.tan(Math.PI*e())}}return n.source=t,n}(Oh),Vh=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){var r=e();return t+n*Math.log(r/(1-r))}}return n.source=t,n}(Oh),Yh=function t(e){var n=Bh.source(e),r=Jh.source(e);function s(t){return function(){for(var s=0,o=t;o>16;){var i=Math.floor(.875*o),a=n(i)();if(a>o)return s+r(i-1,o/a)();s+=i,o-=a}for(var l=-Math.log1p(-e()),c=0;l<=o;++c)l-=Math.log1p(-e());return s+c}}return s.source=t,s}(Oh),Kh=1664525,Xh=1013904223,Qh=1/4294967296;function tp(t=Math.random()){let e=0|(0<=t&&t<1?t/Qh:Math.abs(t));return()=>(e=Kh*e+Xh|0,Qh*(e>>>0))}var ep=n(4635),np=n(7763),rp=n(4090);const sp=(0,rp.Z)("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),op=(0,rp.Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),ip=(0,rp.Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),ap=(0,rp.Z)("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),lp=(0,rp.Z)("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),cp=(0,rp.Z)("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),up=(0,rp.Z)("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),fp=(0,rp.Z)("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),dp=(0,rp.Z)("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),hp=t=>(0,ze.hD)(t[t.length-1]);var pp=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(rp.Z);const mp=hp(pp);var gp=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(rp.Z);const yp=hp(gp);var bp=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(rp.Z);const vp=hp(bp);var wp=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(rp.Z);const _p=hp(wp);var xp=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(rp.Z);const kp=hp(xp);var qp=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(rp.Z);const Np=hp(qp);var Sp=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(rp.Z);const Ap=hp(Sp);var Mp=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(rp.Z);const Tp=hp(Mp);var Cp=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(rp.Z);const jp=hp(Cp);var Ep=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(rp.Z);const Op=hp(Ep);var Ip=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(rp.Z);const Rp=hp(Ip);var Fp=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(rp.Z);const Pp=hp(Fp);var Dp=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(rp.Z);const Lp=hp(Dp);var $p=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(rp.Z);const zp=hp($p);var Zp=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(rp.Z);const Up=hp(Zp);var Bp=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(rp.Z);const Gp=hp(Bp);var Jp=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(rp.Z);const Hp=hp(Jp);var Wp=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(rp.Z);const Vp=hp(Wp);var Yp=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(rp.Z);const Kp=hp(Yp);var Xp=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(rp.Z);const Qp=hp(Xp);var tm=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(rp.Z);const em=hp(tm);var nm=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(rp.Z);const rm=hp(nm);var sm=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(rp.Z);const om=hp(sm);var im=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(rp.Z);const am=hp(im);var lm=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(rp.Z);const cm=hp(lm);var um=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(rp.Z);const fm=hp(um);var dm=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(rp.Z);const hm=hp(dm);function pm(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"}const mm=xh(ns(300,.5,0),ns(-240,.5,1));var gm=xh(ns(-100,.75,.35),ns(80,1.5,.8)),ym=xh(ns(260,.75,.35),ns(80,1.5,.8)),bm=ns();function vm(t){(t<0||t>1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return bm.h=360*t-100,bm.s=1.5-1.5*e,bm.l=.8-.9*e,bm+""}var wm=(0,$e.B8)(),_m=Math.PI/3,xm=2*Math.PI/3;function km(t){var e;return t=(.5-t)*Math.PI,wm.r=255*(e=Math.sin(t))*e,wm.g=255*(e=Math.sin(t+_m))*e,wm.b=255*(e=Math.sin(t+xm))*e,wm+""}function qm(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}function Nm(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const Sm=Nm((0,rp.Z)("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var Am=Nm((0,rp.Z)("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Mm=Nm((0,rp.Z)("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Tm=Nm((0,rp.Z)("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Cm(t){return Lt(Nt(t).call(document.documentElement))}var jm=0;function Em(){return new Om}function Om(){this._="@"+(++jm).toString(36)}function Im(t,e){return t.target&&(t=Ht(t),void 0===e&&(e=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>Wt(t,e)))}function Rm(t){return"string"==typeof t?new Ft([document.querySelectorAll(t)],[document.documentElement]):new Ft([M(t)],Rt)}function Fm(t){return function(){return t}}Om.prototype=Em.prototype={constructor:Om,get:function(t){for(var e=this._;!(e in t);)if(!(t=t.parentNode))return;return t[e]},set:function(t,e){return t[this._]=e},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}};const Pm=Math.abs,Dm=Math.atan2,Lm=Math.cos,$m=Math.max,zm=Math.min,Zm=Math.sin,Um=Math.sqrt,Bm=1e-12,Gm=Math.PI,Jm=Gm/2,Hm=2*Gm;function Wm(t){return t>=1?Jm:t<=-1?-Jm:Math.asin(t)}function Vm(t){return t.innerRadius}function Ym(t){return t.outerRadius}function Km(t){return t.startAngle}function Xm(t){return t.endAngle}function Qm(t){return t&&t.padAngle}function tg(t,e,n,r,s,o,i){var a=t-n,l=e-r,c=(i?o:-o)/Um(a*a+l*l),u=c*l,f=-c*a,d=t+u,h=e+f,p=n+u,m=r+f,g=(d+p)/2,y=(h+m)/2,b=p-d,v=m-h,w=b*b+v*v,_=s-o,x=d*m-p*h,k=(v<0?-1:1)*Um($m(0,_*_*w-x*x)),q=(x*v-b*k)/w,N=(-x*b-v*k)/w,S=(x*v+b*k)/w,A=(-x*b+v*k)/w,M=q-g,T=N-y,C=S-g,j=A-y;return M*M+T*T>C*C+j*j&&(q=S,N=A),{cx:q,cy:N,x01:-u,y01:-f,x11:q*(s/_-1),y11:N*(s/_-1)}}function eg(){var t=Vm,e=Ym,n=Fm(0),r=null,s=Km,o=Xm,i=Qm,a=null;function l(){var l,c,u=+t.apply(this,arguments),f=+e.apply(this,arguments),d=s.apply(this,arguments)-Jm,h=o.apply(this,arguments)-Jm,p=Pm(h-d),m=h>d;if(a||(a=l=dr()),f<u&&(c=f,f=u,u=c),f>Bm)if(p>Hm-Bm)a.moveTo(f*Lm(d),f*Zm(d)),a.arc(0,0,f,d,h,!m),u>Bm&&(a.moveTo(u*Lm(h),u*Zm(h)),a.arc(0,0,u,h,d,m));else{var g,y,b=d,v=h,w=d,_=h,x=p,k=p,q=i.apply(this,arguments)/2,N=q>Bm&&(r?+r.apply(this,arguments):Um(u*u+f*f)),S=zm(Pm(f-u)/2,+n.apply(this,arguments)),A=S,M=S;if(N>Bm){var T=Wm(N/u*Zm(q)),C=Wm(N/f*Zm(q));(x-=2*T)>Bm?(w+=T*=m?1:-1,_-=T):(x=0,w=_=(d+h)/2),(k-=2*C)>Bm?(b+=C*=m?1:-1,v-=C):(k=0,b=v=(d+h)/2)}var j=f*Lm(b),E=f*Zm(b),O=u*Lm(_),I=u*Zm(_);if(S>Bm){var R,F=f*Lm(v),P=f*Zm(v),D=u*Lm(w),L=u*Zm(w);if(p<Gm&&(R=function(t,e,n,r,s,o,i,a){var l=n-t,c=r-e,u=i-s,f=a-o,d=f*l-u*c;if(!(d*d<Bm))return[t+(d=(u*(e-o)-f*(t-s))/d)*l,e+d*c]}(j,E,D,L,F,P,O,I))){var $=j-R[0],z=E-R[1],Z=F-R[0],U=P-R[1],B=1/Zm(function(t){return t>1?0:t<-1?Gm:Math.acos(t)}(($*Z+z*U)/(Um($*$+z*z)*Um(Z*Z+U*U)))/2),G=Um(R[0]*R[0]+R[1]*R[1]);A=zm(S,(u-G)/(B-1)),M=zm(S,(f-G)/(B+1))}}k>Bm?M>Bm?(g=tg(D,L,j,E,f,M,m),y=tg(F,P,O,I,f,M,m),a.moveTo(g.cx+g.x01,g.cy+g.y01),M<S?a.arc(g.cx,g.cy,M,Dm(g.y01,g.x01),Dm(y.y01,y.x01),!m):(a.arc(g.cx,g.cy,M,Dm(g.y01,g.x01),Dm(g.y11,g.x11),!m),a.arc(0,0,f,Dm(g.cy+g.y11,g.cx+g.x11),Dm(y.cy+y.y11,y.cx+y.x11),!m),a.arc(y.cx,y.cy,M,Dm(y.y11,y.x11),Dm(y.y01,y.x01),!m))):(a.moveTo(j,E),a.arc(0,0,f,b,v,!m)):a.moveTo(j,E),u>Bm&&x>Bm?A>Bm?(g=tg(O,I,F,P,u,-A,m),y=tg(j,E,D,L,u,-A,m),a.lineTo(g.cx+g.x01,g.cy+g.y01),A<S?a.arc(g.cx,g.cy,A,Dm(g.y01,g.x01),Dm(y.y01,y.x01),!m):(a.arc(g.cx,g.cy,A,Dm(g.y01,g.x01),Dm(g.y11,g.x11),!m),a.arc(0,0,u,Dm(g.cy+g.y11,g.cx+g.x11),Dm(y.cy+y.y11,y.cx+y.x11),m),a.arc(y.cx,y.cy,A,Dm(y.y11,y.x11),Dm(y.y01,y.x01),!m))):a.arc(0,0,u,_,w,m):a.lineTo(O,I)}else a.moveTo(0,0);if(a.closePath(),l)return a=null,l+""||null}return l.centroid=function(){var n=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,r=(+s.apply(this,arguments)+ +o.apply(this,arguments))/2-Gm/2;return[Lm(r)*n,Zm(r)*n]},l.innerRadius=function(e){return arguments.length?(t="function"==typeof e?e:Fm(+e),l):t},l.outerRadius=function(t){return arguments.length?(e="function"==typeof t?t:Fm(+t),l):e},l.cornerRadius=function(t){return arguments.length?(n="function"==typeof t?t:Fm(+t),l):n},l.padRadius=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Fm(+t),l):r},l.startAngle=function(t){return arguments.length?(s="function"==typeof t?t:Fm(+t),l):s},l.endAngle=function(t){return arguments.length?(o="function"==typeof t?t:Fm(+t),l):o},l.padAngle=function(t){return arguments.length?(i="function"==typeof t?t:Fm(+t),l):i},l.context=function(t){return arguments.length?(a=null==t?null:t,l):a},l}var ng=Array.prototype.slice;function rg(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function sg(t){this._context=t}function og(t){return new sg(t)}function ig(t){return t[0]}function ag(t){return t[1]}function lg(t,e){var n=Fm(!0),r=null,s=og,o=null;function i(i){var a,l,c,u=(i=rg(i)).length,f=!1;for(null==r&&(o=s(c=dr())),a=0;a<=u;++a)!(a<u&&n(l=i[a],a,i))===f&&((f=!f)?o.lineStart():o.lineEnd()),f&&o.point(+t(l,a,i),+e(l,a,i));if(c)return o=null,c+""||null}return t="function"==typeof t?t:void 0===t?ig:Fm(t),e="function"==typeof e?e:void 0===e?ag:Fm(e),i.x=function(e){return arguments.length?(t="function"==typeof e?e:Fm(+e),i):t},i.y=function(t){return arguments.length?(e="function"==typeof t?t:Fm(+t),i):e},i.defined=function(t){return arguments.length?(n="function"==typeof t?t:Fm(!!t),i):n},i.curve=function(t){return arguments.length?(s=t,null!=r&&(o=s(r)),i):s},i.context=function(t){return arguments.length?(null==t?r=o=null:o=s(r=t),i):r},i}function cg(t,e,n){var r=null,s=Fm(!0),o=null,i=og,a=null;function l(l){var c,u,f,d,h,p=(l=rg(l)).length,m=!1,g=new Array(p),y=new Array(p);for(null==o&&(a=i(h=dr())),c=0;c<=p;++c){if(!(c<p&&s(d=l[c],c,l))===m)if(m=!m)u=c,a.areaStart(),a.lineStart();else{for(a.lineEnd(),a.lineStart(),f=c-1;f>=u;--f)a.point(g[f],y[f]);a.lineEnd(),a.areaEnd()}m&&(g[c]=+t(d,c,l),y[c]=+e(d,c,l),a.point(r?+r(d,c,l):g[c],n?+n(d,c,l):y[c]))}if(h)return a=null,h+""||null}function c(){return lg().defined(s).curve(i).context(o)}return t="function"==typeof t?t:void 0===t?ig:Fm(+t),e="function"==typeof e?e:Fm(void 0===e?0:+e),n="function"==typeof n?n:void 0===n?ag:Fm(+n),l.x=function(e){return arguments.length?(t="function"==typeof e?e:Fm(+e),r=null,l):t},l.x0=function(e){return arguments.length?(t="function"==typeof e?e:Fm(+e),l):t},l.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Fm(+t),l):r},l.y=function(t){return arguments.length?(e="function"==typeof t?t:Fm(+t),n=null,l):e},l.y0=function(t){return arguments.length?(e="function"==typeof t?t:Fm(+t),l):e},l.y1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:Fm(+t),l):n},l.lineX0=l.lineY0=function(){return c().x(t).y(e)},l.lineY1=function(){return c().x(t).y(n)},l.lineX1=function(){return c().x(r).y(e)},l.defined=function(t){return arguments.length?(s="function"==typeof t?t:Fm(!!t),l):s},l.curve=function(t){return arguments.length?(i=t,null!=o&&(a=i(o)),l):i},l.context=function(t){return arguments.length?(null==t?o=a=null:a=i(o=t),l):o},l}function ug(t,e){return e<t?-1:e>t?1:e>=t?0:NaN}function fg(t){return t}function dg(){var t=fg,e=ug,n=null,r=Fm(0),s=Fm(Hm),o=Fm(0);function i(i){var a,l,c,u,f,d=(i=rg(i)).length,h=0,p=new Array(d),m=new Array(d),g=+r.apply(this,arguments),y=Math.min(Hm,Math.max(-Hm,s.apply(this,arguments)-g)),b=Math.min(Math.abs(y)/d,o.apply(this,arguments)),v=b*(y<0?-1:1);for(a=0;a<d;++a)(f=m[p[a]=a]=+t(i[a],a,i))>0&&(h+=f);for(null!=e?p.sort((function(t,n){return e(m[t],m[n])})):null!=n&&p.sort((function(t,e){return n(i[t],i[e])})),a=0,c=h?(y-d*v)/h:0;a<d;++a,g=u)l=p[a],u=g+((f=m[l])>0?f*c:0)+v,m[l]={data:i[l],index:a,value:f,startAngle:g,endAngle:u,padAngle:b};return m}return i.value=function(e){return arguments.length?(t="function"==typeof e?e:Fm(+e),i):t},i.sortValues=function(t){return arguments.length?(e=t,n=null,i):e},i.sort=function(t){return arguments.length?(n=t,e=null,i):n},i.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:Fm(+t),i):r},i.endAngle=function(t){return arguments.length?(s="function"==typeof t?t:Fm(+t),i):s},i.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:Fm(+t),i):o},i}sg.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}};var hg=mg(og);function pg(t){this._curve=t}function mg(t){function e(e){return new pg(t(e))}return e._curve=t,e}function gg(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e(mg(t)):e()._curve},t}function yg(){return gg(lg().curve(hg))}function bg(){var t=cg().curve(hg),e=t.curve,n=t.lineX0,r=t.lineX1,s=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return gg(n())},delete t.lineX0,t.lineEndAngle=function(){return gg(r())},delete t.lineX1,t.lineInnerRadius=function(){return gg(s())},delete t.lineY0,t.lineOuterRadius=function(){return gg(o())},delete t.lineY1,t.curve=function(t){return arguments.length?e(mg(t)):e()._curve},t}function vg(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}pg.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}};class wg{constructor(t,e){this._context=t,this._x=e}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e)}this._x0=t,this._y0=e}}class _g{constructor(t){this._context=t}lineStart(){this._point=0}lineEnd(){}point(t,e){if(t=+t,e=+e,0==this._point++)this._x0=t,this._y0=e;else{const n=vg(this._x0,this._y0),r=vg(this._x0,this._y0=(this._y0+e)/2),s=vg(t,this._y0),o=vg(t,e);this._context.moveTo(...n),this._context.bezierCurveTo(...r,...s,...o)}}}function xg(t){return new wg(t,!0)}function kg(t){return new wg(t,!1)}function qg(t){return new _g(t)}function Ng(t){return t.source}function Sg(t){return t.target}function Ag(t){let e=Ng,n=Sg,r=ig,s=ag,o=null,i=null;function a(){let a;const l=ng.call(arguments),c=e.apply(this,l),u=n.apply(this,l);if(null==o&&(i=t(a=dr())),i.lineStart(),l[0]=c,i.point(+r.apply(this,l),+s.apply(this,l)),l[0]=u,i.point(+r.apply(this,l),+s.apply(this,l)),i.lineEnd(),a)return i=null,a+""||null}return a.source=function(t){return arguments.length?(e=t,a):e},a.target=function(t){return arguments.length?(n=t,a):n},a.x=function(t){return arguments.length?(r="function"==typeof t?t:Fm(+t),a):r},a.y=function(t){return arguments.length?(s="function"==typeof t?t:Fm(+t),a):s},a.context=function(e){return arguments.length?(null==e?o=i=null:i=t(o=e),a):o},a}function Mg(){return Ag(xg)}function Tg(){return Ag(kg)}function Cg(){const t=Ag(qg);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}const jg=Um(3),Eg={draw(t,e){const n=.59436*Um(e+zm(e/28,.75)),r=n/2,s=r*jg;t.moveTo(0,n),t.lineTo(0,-n),t.moveTo(-s,-r),t.lineTo(s,r),t.moveTo(-s,r),t.lineTo(s,-r)}},Og={draw(t,e){const n=Um(e/Gm);t.moveTo(n,0),t.arc(0,0,n,0,Hm)}},Ig={draw(t,e){const n=Um(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}},Rg=Um(1/3),Fg=2*Rg,Pg={draw(t,e){const n=Um(e/Fg),r=n*Rg;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},Dg={draw(t,e){const n=.62625*Um(e);t.moveTo(0,-n),t.lineTo(n,0),t.lineTo(0,n),t.lineTo(-n,0),t.closePath()}},Lg={draw(t,e){const n=.87559*Um(e-zm(e/7,2));t.moveTo(-n,0),t.lineTo(n,0),t.moveTo(0,n),t.lineTo(0,-n)}},$g={draw(t,e){const n=Um(e),r=-n/2;t.rect(r,r,n,n)}},zg={draw(t,e){const n=.4431*Um(e);t.moveTo(n,n),t.lineTo(n,-n),t.lineTo(-n,-n),t.lineTo(-n,n),t.closePath()}},Zg=Zm(Gm/10)/Zm(7*Gm/10),Ug=Zm(Hm/10)*Zg,Bg=-Lm(Hm/10)*Zg,Gg={draw(t,e){const n=Um(.8908130915292852*e),r=Ug*n,s=Bg*n;t.moveTo(0,-n),t.lineTo(r,s);for(let e=1;e<5;++e){const o=Hm*e/5,i=Lm(o),a=Zm(o);t.lineTo(a*n,-i*n),t.lineTo(i*r-a*s,a*r+i*s)}t.closePath()}},Jg=Um(3),Hg={draw(t,e){const n=-Um(e/(3*Jg));t.moveTo(0,2*n),t.lineTo(-Jg*n,-n),t.lineTo(Jg*n,-n),t.closePath()}},Wg=Um(3),Vg={draw(t,e){const n=.6824*Um(e),r=n/2,s=n*Wg/2;t.moveTo(0,-n),t.lineTo(s,r),t.lineTo(-s,r),t.closePath()}},Yg=-.5,Kg=Um(3)/2,Xg=1/Um(12),Qg=3*(Xg/2+1),ty={draw(t,e){const n=Um(e/Qg),r=n/2,s=n*Xg,o=r,i=n*Xg+n,a=-o,l=i;t.moveTo(r,s),t.lineTo(o,i),t.lineTo(a,l),t.lineTo(Yg*r-Kg*s,Kg*r+Yg*s),t.lineTo(Yg*o-Kg*i,Kg*o+Yg*i),t.lineTo(Yg*a-Kg*l,Kg*a+Yg*l),t.lineTo(Yg*r+Kg*s,Yg*s-Kg*r),t.lineTo(Yg*o+Kg*i,Yg*i-Kg*o),t.lineTo(Yg*a+Kg*l,Yg*l-Kg*a),t.closePath()}},ey={draw(t,e){const n=.6189*Um(e-zm(e/6,1.7));t.moveTo(-n,-n),t.lineTo(n,n),t.moveTo(-n,n),t.lineTo(n,-n)}},ny=[Og,Ig,Pg,$g,Gg,Hg,ty],ry=[Og,Lg,ey,Vg,Eg,zg,Dg];function sy(t,e){let n=null;function r(){let r;if(n||(n=r=dr()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),r)return n=null,r+""||null}return t="function"==typeof t?t:Fm(t||Og),e="function"==typeof e?e:Fm(void 0===e?64:+e),r.type=function(e){return arguments.length?(t="function"==typeof e?e:Fm(e),r):t},r.size=function(t){return arguments.length?(e="function"==typeof t?t:Fm(+t),r):e},r.context=function(t){return arguments.length?(n=null==t?null:t,r):n},r}function oy(){}function iy(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function ay(t){this._context=t}function ly(t){return new ay(t)}function cy(t){this._context=t}function uy(t){return new cy(t)}function fy(t){this._context=t}function dy(t){return new fy(t)}function hy(t,e){this._basis=new ay(t),this._beta=e}ay.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:iy(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:iy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},cy.prototype={areaStart:oy,areaEnd:oy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:iy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},fy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:iy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},hy.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,s=t[0],o=e[0],i=t[n]-s,a=e[n]-o,l=-1;++l<=n;)r=l/n,this._basis.point(this._beta*t[l]+(1-this._beta)*(s+r*i),this._beta*e[l]+(1-this._beta)*(o+r*a));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};const py=function t(e){function n(t){return 1===e?new ay(t):new hy(t,e)}return n.beta=function(e){return t(+e)},n}(.85);function my(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function gy(t,e){this._context=t,this._k=(1-e)/6}gy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:my(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const yy=function t(e){function n(t){return new gy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function by(t,e){this._context=t,this._k=(1-e)/6}by.prototype={areaStart:oy,areaEnd:oy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const vy=function t(e){function n(t){return new by(t,e)}return n.tension=function(e){return t(+e)},n}(0);function wy(t,e){this._context=t,this._k=(1-e)/6}wy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const _y=function t(e){function n(t){return new wy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function xy(t,e,n){var r=t._x1,s=t._y1,o=t._x2,i=t._y2;if(t._l01_a>Bm){var a=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,l=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*a-t._x0*t._l12_2a+t._x2*t._l01_2a)/l,s=(s*a-t._y0*t._l12_2a+t._y2*t._l01_2a)/l}if(t._l23_a>Bm){var c=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,u=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*c+t._x1*t._l23_2a-e*t._l12_2a)/u,i=(i*c+t._y1*t._l23_2a-n*t._l12_2a)/u}t._context.bezierCurveTo(r,s,o,i,t._x2,t._y2)}function ky(t,e){this._context=t,this._alpha=e}ky.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const qy=function t(e){function n(t){return e?new ky(t,e):new gy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ny(t,e){this._context=t,this._alpha=e}Ny.prototype={areaStart:oy,areaEnd:oy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const Sy=function t(e){function n(t){return e?new Ny(t,e):new by(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ay(t,e){this._context=t,this._alpha=e}Ay.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const My=function t(e){function n(t){return e?new Ay(t,e):new wy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ty(t){this._context=t}function Cy(t){return new Ty(t)}function jy(t){return t<0?-1:1}function Ey(t,e,n){var r=t._x1-t._x0,s=e-t._x1,o=(t._y1-t._y0)/(r||s<0&&-0),i=(n-t._y1)/(s||r<0&&-0),a=(o*s+i*r)/(r+s);return(jy(o)+jy(i))*Math.min(Math.abs(o),Math.abs(i),.5*Math.abs(a))||0}function Oy(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function Iy(t,e,n){var r=t._x0,s=t._y0,o=t._x1,i=t._y1,a=(o-r)/3;t._context.bezierCurveTo(r+a,s+a*e,o-a,i-a*n,o,i)}function Ry(t){this._context=t}function Fy(t){this._context=new Py(t)}function Py(t){this._context=t}function Dy(t){return new Ry(t)}function Ly(t){return new Fy(t)}function $y(t){this._context=t}function zy(t){var e,n,r=t.length-1,s=new Array(r),o=new Array(r),i=new Array(r);for(s[0]=0,o[0]=2,i[0]=t[0]+2*t[1],e=1;e<r-1;++e)s[e]=1,o[e]=4,i[e]=4*t[e]+2*t[e+1];for(s[r-1]=2,o[r-1]=7,i[r-1]=8*t[r-1]+t[r],e=1;e<r;++e)n=s[e]/o[e-1],o[e]-=n,i[e]-=n*i[e-1];for(s[r-1]=i[r-1]/o[r-1],e=r-2;e>=0;--e)s[e]=(i[e]-s[e+1])/o[e];for(o[r-1]=(t[r]+s[r-1])/2,e=0;e<r-1;++e)o[e]=2*t[e+1]-s[e+1];return[s,o]}function Zy(t){return new $y(t)}function Uy(t,e){this._context=t,this._t=e}function By(t){return new Uy(t,.5)}function Gy(t){return new Uy(t,0)}function Jy(t){return new Uy(t,1)}function Hy(t,e){if((s=t.length)>1)for(var n,r,s,o=1,i=t[e[0]],a=i.length;o<s;++o)for(r=i,i=t[e[o]],n=0;n<a;++n)i[n][1]+=i[n][0]=isNaN(r[n][1])?r[n][0]:r[n][1]}function Wy(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function Vy(t,e){return t[e]}function Yy(t){const e=[];return e.key=t,e}function Ky(){var t=Fm([]),e=Wy,n=Hy,r=Vy;function s(s){var o,i,a=Array.from(t.apply(this,arguments),Yy),l=a.length,c=-1;for(const t of s)for(o=0,++c;o<l;++o)(a[o][c]=[0,+r(t,a[o].key,c,s)]).data=t;for(o=0,i=rg(e(a));o<l;++o)a[i[o]].index=o;return n(a,i),a}return s.keys=function(e){return arguments.length?(t="function"==typeof e?e:Fm(Array.from(e)),s):t},s.value=function(t){return arguments.length?(r="function"==typeof t?t:Fm(+t),s):r},s.order=function(t){return arguments.length?(e=null==t?Wy:"function"==typeof t?t:Fm(Array.from(t)),s):e},s.offset=function(t){return arguments.length?(n=null==t?Hy:t,s):n},s}function Xy(t,e){if((r=t.length)>0){for(var n,r,s,o=0,i=t[0].length;o<i;++o){for(s=n=0;n<r;++n)s+=t[n][o][1]||0;if(s)for(n=0;n<r;++n)t[n][o][1]/=s}Hy(t,e)}}function Qy(t,e){if((a=t.length)>0)for(var n,r,s,o,i,a,l=0,c=t[e[0]].length;l<c;++l)for(o=i=0,n=0;n<a;++n)(s=(r=t[e[n]][l])[1]-r[0])>0?(r[0]=o,r[1]=o+=s):s<0?(r[1]=i,r[0]=i+=s):(r[0]=0,r[1]=s)}function tb(t,e){if((n=t.length)>0){for(var n,r=0,s=t[e[0]],o=s.length;r<o;++r){for(var i=0,a=0;i<n;++i)a+=t[i][r][1]||0;s[r][1]+=s[r][0]=-a/2}Hy(t,e)}}function eb(t,e){if((s=t.length)>0&&(r=(n=t[e[0]]).length)>0){for(var n,r,s,o=0,i=1;i<r;++i){for(var a=0,l=0,c=0;a<s;++a){for(var u=t[e[a]],f=u[i][1]||0,d=(f-(u[i-1][1]||0))/2,h=0;h<a;++h){var p=t[e[h]];d+=(p[i][1]||0)-(p[i-1][1]||0)}l+=f,c+=d*f}n[i-1][1]+=n[i-1][0]=o,l&&(o-=c/l)}n[i-1][1]+=n[i-1][0]=o,Hy(t,e)}}function nb(t){var e=t.map(rb);return Wy(t).sort((function(t,n){return e[t]-e[n]}))}function rb(t){for(var e,n=-1,r=0,s=t.length,o=-1/0;++n<s;)(e=+t[n][1])>o&&(o=e,r=n);return r}function sb(t){var e=t.map(ob);return Wy(t).sort((function(t,n){return e[t]-e[n]}))}function ob(t){for(var e,n=0,r=-1,s=t.length;++r<s;)(e=+t[r][1])&&(n+=e);return n}function ib(t){return sb(t).reverse()}function ab(t){var e,n,r=t.length,s=t.map(ob),o=nb(t),i=0,a=0,l=[],c=[];for(e=0;e<r;++e)n=o[e],i<a?(i+=s[n],l.push(n)):(a+=s[n],c.push(n));return c.reverse().concat(l)}function lb(t){return Wy(t).reverse()}Ty.prototype={areaStart:oy,areaEnd:oy,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}},Ry.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Iy(this,this._t0,Oy(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,Iy(this,Oy(this,n=Ey(this,t,e)),n);break;default:Iy(this,this._t0,n=Ey(this,t,e))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}},(Fy.prototype=Object.create(Ry.prototype)).point=function(t,e){Ry.prototype.point.call(this,e,t)},Py.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,s,o){this._context.bezierCurveTo(e,t,r,n,o,s)}},$y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===n)this._context.lineTo(t[1],e[1]);else for(var r=zy(t),s=zy(e),o=0,i=1;i<n;++o,++i)this._context.bezierCurveTo(r[0][o],s[0][o],r[1][o],s[1][o],t[i],e[i]);(this._line||0!==this._line&&1===n)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,e){this._x.push(+t),this._y.push(+e)}},Uy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&2===this._point&&this._context.lineTo(this._x,this._y),(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}};var cb=n(3606),ub=n(8383),fb=n(1343),db=n(2991),hb=n(6596),pb=n(8467),mb=n(6018),gb=n(7905),yb=n(2311),bb=n(8593),vb=n(8927),wb=n(7445),_b=n(1887),xb=n(7351),kb=n(4552),qb=n(7150),Nb=n(1852),Sb=n(3015),Ab="%Y-%m-%dT%H:%M:%S.%LZ";var Mb=Date.prototype.toISOString?function(t){return t.toISOString()}:(0,Nb.g0)(Ab);const Tb=Mb;var Cb=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:(0,Nb.wp)(Ab);const jb=Cb;function Eb(t,e,n){var r=new le,s=e;return null==e?(r.restart(t,e,n),r):(r._restart=r.restart,r.restart=function(t,e,n){e=+e,n=null==n?ie():+n,r._restart((function o(i){i+=s,r._restart(o,s+=e,n),t(i)}),e,n)},r.restart(t,e,n),r)}const Ob=t=>()=>t;function Ib(t,{sourceEvent:e,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function Rb(t,e,n){this.k=t,this.x=e,this.y=n}Rb.prototype={constructor:Rb,scale:function(t){return 1===t?this:new Rb(this.k*t,this.x,this.y)},translate:function(t,e){return 0===t&0===e?this:new Rb(this.k,this.x+this.k*t,this.y+this.k*e)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Fb=new Rb(1,0,0);function Pb(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Fb;return t.__zoom}function Db(t){t.stopImmediatePropagation()}function Lb(t){t.preventDefault(),t.stopImmediatePropagation()}function $b(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function zb(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function Zb(){return this.__zoom||Fb}function Ub(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function Bb(){return navigator.maxTouchPoints||"ontouchstart"in this}function Gb(t,e,n){var r=t.invertX(e[0][0])-n[0][0],s=t.invertX(e[1][0])-n[1][0],o=t.invertY(e[0][1])-n[0][1],i=t.invertY(e[1][1])-n[1][1];return t.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>o?(o+i)/2:Math.min(0,o)||Math.max(0,i))}function Jb(){var t,e,n,r=$b,s=zb,o=Gb,i=Ub,a=Bb,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],u=250,f=dh,d=N("start","zoom","end"),h=500,p=150,m=0,g=10;function y(t){t.property("__zoom",Zb).on("wheel.zoom",q,{passive:!1}).on("mousedown.zoom",S).on("dblclick.zoom",A).filter(a).on("touchstart.zoom",M).on("touchmove.zoom",T).on("touchend.zoom touchcancel.zoom",C).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function b(t,e){return(e=Math.max(l[0],Math.min(l[1],e)))===t.k?t:new Rb(e,t.x,t.y)}function v(t,e,n){var r=e[0]-n[0]*t.k,s=e[1]-n[1]*t.k;return r===t.x&&s===t.y?t:new Rb(t.k,r,s)}function w(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function _(t,e,n,r){t.on("start.zoom",(function(){x(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){x(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,o=arguments,i=x(t,o).event(r),a=s.apply(t,o),l=null==n?w(a):"function"==typeof n?n.apply(t,o):n,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),u=t.__zoom,d="function"==typeof e?e.apply(t,o):e,h=f(u.invert(l).concat(c/u.k),d.invert(l).concat(c/d.k));return function(t){if(1===t)t=d;else{var e=h(t),n=c/e[2];t=new Rb(n,l[0]-e[0]*n,l[1]-e[1]*n)}i.zoom(null,t)}}))}function x(t,e,n){return!n&&t.__zooming||new k(t,e)}function k(t,e){this.that=t,this.args=e,this.active=0,this.sourceEvent=null,this.extent=s.apply(t,e),this.taps=0}function q(t,...e){if(r.apply(this,arguments)){var n=x(this,e).event(t),s=this.__zoom,a=Math.max(l[0],Math.min(l[1],s.k*Math.pow(2,i.apply(this,arguments)))),u=Wt(t);if(n.wheel)n.mouse[0][0]===u[0]&&n.mouse[0][1]===u[1]||(n.mouse[1]=s.invert(n.mouse[0]=u)),clearTimeout(n.wheel);else{if(s.k===a)return;n.mouse=[u,s.invert(u)],Me(this),n.start()}Lb(t),n.wheel=setTimeout((function(){n.wheel=null,n.end()}),p),n.zoom("mouse",o(v(b(s,a),n.mouse[0],n.mouse[1]),n.extent,c))}}function S(t,...e){if(!n&&r.apply(this,arguments)){var s=t.currentTarget,i=x(this,e,!0).event(t),a=Lt(t.view).on("mousemove.zoom",(function(t){if(Lb(t),!i.moved){var e=t.clientX-u,n=t.clientY-f;i.moved=e*e+n*n>m}i.event(t).zoom("mouse",o(v(i.that.__zoom,i.mouse[0]=Wt(t,s),i.mouse[1]),i.extent,c))}),!0).on("mouseup.zoom",(function(t){a.on("mousemove.zoom mouseup.zoom",null),Gt(t.view,i.moved),Lb(t),i.event(t).end()}),!0),l=Wt(t,s),u=t.clientX,f=t.clientY;Bt(t.view),Db(t),i.mouse=[l,this.__zoom.invert(l)],Me(this),i.start()}}function A(t,...e){if(r.apply(this,arguments)){var n=this.__zoom,i=Wt(t.changedTouches?t.changedTouches[0]:t,this),a=n.invert(i),l=n.k*(t.shiftKey?.5:2),f=o(v(b(n,l),i,a),s.apply(this,e),c);Lb(t),u>0?Lt(this).transition().duration(u).call(_,f,i,t):Lt(this).call(y.transform,f,i,t)}}function M(n,...s){if(r.apply(this,arguments)){var o,i,a,l,c=n.touches,u=c.length,f=x(this,s,n.changedTouches.length===u).event(n);for(Db(n),i=0;i<u;++i)l=[l=Wt(a=c[i],this),this.__zoom.invert(l),a.identifier],f.touch0?f.touch1||f.touch0[2]===l[2]||(f.touch1=l,f.taps=0):(f.touch0=l,o=!0,f.taps=1+!!t);t&&(t=clearTimeout(t)),o&&(f.taps<2&&(e=l[0],t=setTimeout((function(){t=null}),h)),Me(this),f.start())}}function T(t,...e){if(this.__zooming){var n,r,s,i,a=x(this,e).event(t),l=t.changedTouches,u=l.length;for(Lb(t),n=0;n<u;++n)s=Wt(r=l[n],this),a.touch0&&a.touch0[2]===r.identifier?a.touch0[0]=s:a.touch1&&a.touch1[2]===r.identifier&&(a.touch1[0]=s);if(r=a.that.__zoom,a.touch1){var f=a.touch0[0],d=a.touch0[1],h=a.touch1[0],p=a.touch1[1],m=(m=h[0]-f[0])*m+(m=h[1]-f[1])*m,g=(g=p[0]-d[0])*g+(g=p[1]-d[1])*g;r=b(r,Math.sqrt(m/g)),s=[(f[0]+h[0])/2,(f[1]+h[1])/2],i=[(d[0]+p[0])/2,(d[1]+p[1])/2]}else{if(!a.touch0)return;s=a.touch0[0],i=a.touch0[1]}a.zoom("touch",o(v(r,s,i),a.extent,c))}}function C(t,...r){if(this.__zooming){var s,o,i=x(this,r).event(t),a=t.changedTouches,l=a.length;for(Db(t),n&&clearTimeout(n),n=setTimeout((function(){n=null}),h),s=0;s<l;++s)o=a[s],i.touch0&&i.touch0[2]===o.identifier?delete i.touch0:i.touch1&&i.touch1[2]===o.identifier&&delete i.touch1;if(i.touch1&&!i.touch0&&(i.touch0=i.touch1,delete i.touch1),i.touch0)i.touch0[1]=this.__zoom.invert(i.touch0[0]);else if(i.end(),2===i.taps&&(o=Wt(o,this),Math.hypot(e[0]-o[0],e[1]-o[1])<g)){var c=Lt(this).on("dblclick.zoom");c&&c.apply(this,arguments)}}}return y.transform=function(t,e,n,r){var s=t.selection?t.selection():t;s.property("__zoom",Zb),t!==s?_(t,e,n,r):s.interrupt().each((function(){x(this,arguments).event(r).start().zoom(null,"function"==typeof e?e.apply(this,arguments):e).end()}))},y.scaleBy=function(t,e,n,r){y.scaleTo(t,(function(){return this.__zoom.k*("function"==typeof e?e.apply(this,arguments):e)}),n,r)},y.scaleTo=function(t,e,n,r){y.transform(t,(function(){var t=s.apply(this,arguments),r=this.__zoom,i=null==n?w(t):"function"==typeof n?n.apply(this,arguments):n,a=r.invert(i),l="function"==typeof e?e.apply(this,arguments):e;return o(v(b(r,l),i,a),t,c)}),n,r)},y.translateBy=function(t,e,n,r){y.transform(t,(function(){return o(this.__zoom.translate("function"==typeof e?e.apply(this,arguments):e,"function"==typeof n?n.apply(this,arguments):n),s.apply(this,arguments),c)}),null,r)},y.translateTo=function(t,e,n,r,i){y.transform(t,(function(){var t=s.apply(this,arguments),i=this.__zoom,a=null==r?w(t):"function"==typeof r?r.apply(this,arguments):r;return o(Fb.translate(a[0],a[1]).scale(i.k).translate("function"==typeof e?-e.apply(this,arguments):-e,"function"==typeof n?-n.apply(this,arguments):-n),t,c)}),r,i)},k.prototype={event:function(t){return t&&(this.sourceEvent=t),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(t,e){return this.mouse&&"mouse"!==t&&(this.mouse[1]=e.invert(this.mouse[0])),this.touch0&&"touch"!==t&&(this.touch0[1]=e.invert(this.touch0[0])),this.touch1&&"touch"!==t&&(this.touch1[1]=e.invert(this.touch1[0])),this.that.__zoom=e,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(t){var e=Lt(this.that).datum();d.call(t,this.that,new Ib(t,{sourceEvent:this.sourceEvent,target:y,type:t,transform:this.that.__zoom,dispatch:d}),e)}},y.wheelDelta=function(t){return arguments.length?(i="function"==typeof t?t:Ob(+t),y):i},y.filter=function(t){return arguments.length?(r="function"==typeof t?t:Ob(!!t),y):r},y.touchable=function(t){return arguments.length?(a="function"==typeof t?t:Ob(!!t),y):a},y.extent=function(t){return arguments.length?(s="function"==typeof t?t:Ob([[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]]),y):s},y.scaleExtent=function(t){return arguments.length?(l[0]=+t[0],l[1]=+t[1],y):[l[0],l[1]]},y.translateExtent=function(t){return arguments.length?(c[0][0]=+t[0][0],c[1][0]=+t[1][0],c[0][1]=+t[0][1],c[1][1]=+t[1][1],y):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},y.constrain=function(t){return arguments.length?(o=t,y):o},y.duration=function(t){return arguments.length?(u=+t,y):u},y.interpolate=function(t){return arguments.length?(f=t,y):f},y.on=function(){var t=d.on.apply(d,arguments);return t===d?y:t},y.clickDistance=function(t){return arguments.length?(m=(t=+t)*t,y):Math.sqrt(m)},y.tapDistance=function(t){return arguments.length?(g=+t,y):g},y}Pb.prototype=Rb.prototype},8828:(t,e,n)=>{"use strict";n.d(e,{H:()=>s,L:()=>r});class r extends Map{constructor(t,e=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const[e,n]of t)this.set(e,n)}get(t){return super.get(o(this,t))}has(t){return super.has(o(this,t))}set(t,e){return super.set(i(this,t),e)}delete(t){return super.delete(a(this,t))}}class s extends Set{constructor(t,e=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const e of t)this.add(e)}has(t){return super.has(o(this,t))}add(t){return super.add(i(this,t))}delete(t){return super.delete(a(this,t))}}function o({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function i({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function a({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function l(t){return null!==t&&"object"==typeof t?t.valueOf():t}}},e={};function n(r){var s=e[r];if(void 0!==s)return s.exports;var o=e[r]={exports:{}};return t[r](o,o.exports,n),o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{"use strict";var t=n(334),e=n.n(t),r=n(3065),s=n(7147),o=n.n(s),i=n(1017),a=n.n(i);{const t=o().readdirSync(a().join(e().binpath,"/routes")).filter((t=>t.endsWith(".ts"))).map((t=>{const e=n(126)(`./${t}`);return e.file=t,e}));!function(t,e,n={}){const r=Object.assign({basepath:""},n);for(const n of e){const e=n.api;for(const n in e.methods){const s=e.methods[n];t[n](`${r.basepath}/${e.endpoint}`,s.init(r))}}!function(t,e){if(e.apiJson){const n=JSON.stringify(t.map((t=>t.api))),r=i.dirname(e.apiJson);s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(e.apiJson,n)}if(e.types){const n=function(t,e){const n={};for(const{file:e,route:r}of t){const t=r.api;for(const r in t.methods){const s=t.methods[r];s.alternativeFor||(n[e]||(n[e]=new Set),s.request.typeId&&n[e].add(s.request.typeId),s.response.typeId&&n[e].add(s.response.typeId))}}const r=["import { createValidate } from 'typia'"],s=[];for(const t in n){const o=Array.from(n[t]);r.push(`import { ${o.join(", ")} } from '${e}/${t}'`);for(const t of o)s.push(`export const valid${t} = createValidate<${t}>()`)}return r.join("\n")+"\n\n"+s.join("\n")}(t.map((t=>({file:t.file,route:t}))),e.types.importDir),r=i.dirname(e.types.outputFile);s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(e.types.outputFile,n)}}(e,r)}(r.l2,t,{app:r.l2,genomes:r.g_,basepath:r.LJ,apiJson:a().join(__dirname,"../../public/docs/server-api.json"),types:{importDir:"../types/routes",outputFile:a().join(__dirname,"./shared/checkers-raw/index.ts")}})}(0,r.lE)(e()).then((async()=>{if(console.log(`\n${new Date} ${e().commitHash||""}`),console.log("\nValidation succeeded.\n"),"validate"!=process.argv[2])if("phewas-precompute"!=process.argv[2])await(0,r.OG)();else{const t=process.argv[3],e=process.argv[4],n=r.g_[t];if(!n)throw"invalid genome name: "+t;const s=n.datasets[e];if(!s)throw"invalid dataset: "+e;r.U_.do_precompute(s)}else console.log("You may now run the server.")})).catch((t=>{let n=1;if(!o().existsSync(e().tpmasterdir)){const t=e().maintenance||{};if("start"in t&&"stop"in t&&"tpErrorCode"in t){const e=+new Date(t.start),r=+new Date(t.stop),s=+new Date;e<=s&&s<=r&&(n=t.tpErrorCode)}}t.stack&&console.log(t.stack),n?console.error("\n!!!\n"+t+"\n\n"):console.log("\n!!!\n"+t+"\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 u=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({},f,e.query);await(0,l.Sf)(n,JSON.stringify(r));const{fit:i,surv:c,sample:u}=t.cohort.cumburden.files;if(!i||!c||!u)throw"missing one or more of ds.cohort.burden.files.{fit, surv, sample}";const d=[n,`${a().tpmasterdir}/${i}`,`${a().tpmasterdir}/${c}`,`${a().tpmasterdir}/${u}`],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}}(u);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 f=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:()=>u,maxTotalSizeCompressed:()=>f});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",f=n.n(a)().features.gdcMafMaxFileSize||4e8,u={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 "+u.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:f}}(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:()=>u});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),f=n(2538);const u={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),u=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>=f.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(`${u.length} out of ${e.fileIdLst.length} input MAF files accepted by size limit`,Date.now()-s);const d={fileIdLst:u,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=f.query,r=f.getVariables(e));const u=await o().post(i.graphql,{headers:l,body:JSON.stringify({query:n,variables:r})}),d=JSON.parse(u.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}},f={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:f,request:{typeId:"HicdataRequest"},response:{typeId:"HicdataResponse"}},post:{alternativeFor:"get",init:f}}};function f(){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 f=["log(oe)"==e.matrixType?"oe":e.matrixType?e.matrixType:"observed",e.nmeth||"NONE",a,e.pos1,e.pos2,e.isfrag?"FRAG":"BP",e.resolution],u=(0,r.spawn)(l().hicstraw,f),d=i().createInterface({input:u.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])})),u.stderr.on("data",(e=>m.push(e))),u.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:()=>f});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 f={endpoint:"hicstat",methods:{get:{init:u,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:u}}};function u(){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 f=Number(j());let u=[];const d=1e5;if(8==l||7==l){let t=await q(e,f,d);const n=t.getInt32(0,!0);n>0&&(t=await q(e,f+n+4,d),u=await x(t,f+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);u=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=u,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 u("string");r.push(e),8==l||7==l?(e=await u("string"),c(4),c(8*await u("int32")),c(12*await u("int32"))):9==l&&(i+=4,e=await u("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&&f(),i+=e}async function f(){t=await q(e,n+i,d),n+=i,i=0}async function u(e){let n;if("string"==e){let e,s="";for(;i<t.byteLength&&0!=(e=t.getUint8(i++));)i>d&&await f(),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 f(),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 f=c.buffer;return f.buffer.slice(f.byteOffset,f.byteOffset+f.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},f=await(0,r.Yu)(c,o,i);if(f.error)throw f.error;const u=[];if("geneVariant"==e.type){const t=f.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)u.push({dt:e,classes:t})}else{const t=new Map;for(const n in f.samples){const s=f.samples[n][e.tid];s&&("key"in s&&t.set(s.key,1+(t.get(s.key)||0)))}for(const[n,s]of t)u.push({samplecount:s,key:n,label:f.refs?.byTermId?.[e.tid]?.events?.find((e=>e.event===n)).label||l?.values?.[n]?.label||n})}const d=(0,s.Tt)(l,f.refs?.byTermId?.[e.tid]?.bins||[],f.refs?.byTermId?.[e.tid]?.events,e.term1_q);d.length&&u.sort(((e,t)=>d.indexOf(e.label)-d.indexOf(t.label)));t.send({lst:u,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),f=n.n(c),u=n(1169),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(),u=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(f().cachedir,Math.random().toString()+".json");await l.Sf(o,JSON.stringify(s));const c=JSON.parse(await(0,a.default)(r().join(f().binpath,"utils/hclust.R"),[],[o]));await i().promises.unlink(o);const u=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 u){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);f().debugmode&&console.log("clustering done:",Date.now()-c,"ms");return{clustering:u,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(f().tpmasterdir)||(e.file=r().join(f().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,u.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:()=>u,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),f=n(1169);const u={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,f.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:()=>u,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),f=n(1169);const u={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),r.sameLegend=n.queries.singleCell.samples.sameLegend}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,f.z7)(e,t);else{if("native"!=n.samples.src)throw"unknown singleCell.samples.src";!function(e,t){const n=[],s=t.cohort.termdb.q.getAllValues4term(e.isSampleTerm);for(const e of s.keys())n.push({sample:t.cohort.termdb.q.id2sampleName(e)});if(0==n.length)throw"no sample with sc data";e.get=()=>({samples:n,fields:["sample"],columnNames:["Sample"]})}(n.samples,e)}if("gdcapi"==n.data.src)(0,f.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 f=(await(0,a.b5)(l)).trim().split("\n"),u=[];for(let t=1;t<f.length;t++){const r=f[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";u.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:u,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(1169),r=n(1017),o=n.n(r),i=n(1271),a=n(6452),l=n.n(a),c=n(334),f=n.n(c),u=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);f().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(f().features.gdcGenes)return console.log("!!GDC!! using serverconfig.features.gdcGenes[]"),f().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),u=o().join(a.geneExp,"/gene_expression/gene_selection");try{const e=await l().post(u,{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,u.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),f=n(3345),u=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,u.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,f]of Object.entries(t.samples)){const e=f[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(!f[s?.id])continue;if(s.term?.values?.[f[s.id]?.key]?.uncomputable){const e=s.term.values[f[s.id]?.value]?.label;l[e]=(l[e]||0)+1}o.has(f[s.id]?.key)||o.set(f[s.id]?.key,[]),o.get(f[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,f.Sf)(o,JSON.stringify(r));const l=await(0,a.default)(c().join(i().binpath,"utils/wilcoxon.R"),[],[o]);(0,s.unlink)(o,(()=>{}));const u=JSON.parse(l);for(const e of u)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,f=c*Math.PI;let u=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,f):s.arc(e.radius,+o(t),c,0,f),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=u}(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 f=a.position1;if(!f)return void c.push([e,"missing position1",i]);let u=Number.parseInt(f);if(Number.isNaN(u)||u<=0)c.push([e,"invalid value for position1",i]);else if(a.position1=u,f=a.position2,f){if(u=Number.parseInt(f),Number.isNaN(u)||u<=0)c.push([e,"invalid value for position2",i]);else if(a.position2=u,!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 f;try{f=JSON.parse(l.jsontext)}catch(t){return void c.push([e,"invalid JSON text",i])}if(Array.isArray(f))for(const e of f){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(f);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(f);const r=e.b.name.toUpperCase();n.data[r]||(n.data[r]=[]),n.data[r].push(t)}}else{switch(f.dt=f.typecode,delete f.typecode,f.dt){case s.dtitd:f.class=s.mclassitd,f.mname="ITD";break;case s.dtnloss:f.class=s.mclassnloss,f.mname="N-loss";break;case s.dtcloss:f.class=s.mclasscloss,f.mname="C-loss";break;case s.dtdel:f.class=s.mclassdel,f.mname="Del";break;case s.dtsv:f.class=s.mclasssv,f.mname="SV";break;default:return void c.push([e,"unknown datatype",i])}if(!f.gene)return void c.push([e,"json.gene missing",i]);n.good++;for(const e in l)"jsontext"!=e&&(f[e]=l[e]);const t=(n.geneToUpper,f.gene.toUpperCase());n.data[t]||(n.data[t]=[]),n.data[t].push(f)}}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:()=>f,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:()=>z,dt2label:()=>k,dtcloss:()=>v,dtcnv:()=>m,dtdel:()=>y,dtfusionrna:()=>d,dtgeneexpression:()=>p,dtitd:()=>g,dtloh:()=>w,dtnloss:()=>b,dtsnvindel:()=>u,dtsv:()=>h,exoncolor:()=>l,fasta2gmframecheck:()=>fe,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:()=>ue,validtkt:()=>Q,vcfcopymclass:()=>ye,vepinfo:()=>U});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,f=!1,u=1,d=2,p=3,m=4,h=5,g=6,y=7,b=8,v=9,w=10,_="#ce768e",k={[u]:"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:u,desc:"A substitution variant in the coding region resulting in altered protein coding.",key:"M"},E:{label:"EXON",color:"#bcbd22",dt:u,desc:"A variant in the exon of a non-coding RNA.",key:"E"},F:{label:"FRAMESHIFT",color:"#db3d3d",dt:u,desc:"An insertion or deletion variant that alters the protein coding frame.",key:"F"},N:{label:"NONSENSE",color:"#ff7f0e",dt:u,desc:"A variant altering protein coding to produce a premature stopgain or stoploss.",key:"N"},S:{label:"SILENT",color:"#2ca02c",dt:u,desc:"A substitution variant in the coding region that does not alter protein coding.",key:"S"},D:{label:"PROTEINDEL",color:"#7f7f7f",dt:u,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:u,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:u,desc:"A variant in an intron within 10 nt of an exon boundary.",key:"P"},L:{label:"SPLICE",color:"#6633FF",dt:u,desc:"A variant near an exon edge that may affect splicing functionality.",key:"L"},Intron:{label:"INTRON",color:"#656565",dt:u,desc:"An intronic variant.",key:"Intron"},Blank:{label:"Not tested",color:"#fff",dt:u,desc:"This gene is not tested.",key:"Blank"},WT:{label:"Wildtype",color:"#D3D3D3",dt:u,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:u,desc:"A variant in the 3' untranslated region.",key:C};const j="Utr5";q[j]={label:"UTR_5",color:"#819981",dt:u,desc:"A variant in the 5' untranslated region.",key:j};const T="X";q[T]={label:"NONSTANDARD",color:"black",dt:u,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:u,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%\">&#9680;</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%\">&#9681;</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:u,desc:"Single nucleotide variation",key:D};const L="mnv";q[L]={label:"MNV",color:"#92a2d4",dt:u,desc:"Multiple nucleotide variation",key:L};const P="insertion";q[P]={label:"Sequence insertion",color:"#bd8e91",dt:u,desc:"Sequence insertion",key:P};const G="deletion";q[G]={label:"Sequence deletion",color:"#b5a174",dt:u,desc:"Sequence deletion",key:G};const z={[u]: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 U=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")?[u,"L",n]:(n++,-1!=t.indexOf("splice_donor_variant")?[u,"L",n]:(n++,-1!=t.indexOf("stop_gained")?[u,"N",n]:(n++,-1!=t.indexOf("frameshift_variant")?[u,"F",n]:(n++,-1!=t.indexOf("stop_lost")?[u,"N",n]:(n++,-1!=t.indexOf("start_lost")?[u,"N",n]:(n++,-1!=t.indexOf("transcript_amplification")?[u,T,n]:(n++,-1!=t.indexOf("inframe_insertion")||-1!=t.indexOf("conservative_inframe_insertion")||-1!=t.indexOf("disruptive_inframe_insertion")?[u,"I",n]:(n++,-1!=t.indexOf("inframe_deletion")||-1!=t.indexOf("conservative_inframe_deletion")||-1!=t.indexOf("disruptive_inframe_deletion")?[u,"D",n]:(n++,-1!=t.indexOf("missense_variant")?[u,"M",n]:(n++,-1!=t.indexOf("protein_altering_variant")?[u,"N",n]:(n++,-1!=t.indexOf("splice_region_variant")?[u,"P",n]:(n++,-1!=t.indexOf("incomplete_terminal_codon_variant")?[u,"N",n]:(n++,-1!=t.indexOf("stop_retained_variant")?[u,"S",n]:(n++,-1!=t.indexOf("synonymous_variant")?[u,"S",n]:(n++,-1!=t.indexOf("coding_sequence_variant")?[u,T,n]:(n++,-1!=t.indexOf("mature_mirna_variant")?[u,"E",n]:(n++,-1!=t.indexOf("5_prime_utr_variant")?[u,j,n]:(n++,-1!=t.indexOf("3_prime_utr_variant")?[u,C,n]:(n++,-1!=t.indexOf("non_coding_transcript_exon_variant")?[u,"E",n]:(n++,-1!=t.indexOf("intron_variant")?[u,"Intron",n]:(n++,-1!=t.indexOf("nmd_transcript_variant")?[u,"S",n]:(n++,-1!=t.indexOf("non_coding_transcript_variant")?[u,"E",n]:(n++,-1!=t.indexOf("upstream_gene_variant")?[u,M,n]:(n++,-1!=t.indexOf("downstream_gene_variant")?[u,M,n]:(n++,-1!=t.indexOf("tfbs_ablation")?[u,M,n]:(n++,-1!=t.indexOf("tfbs_amplification")?[u,M,n]:(n++,-1!=t.indexOf("tf_binding_site_variant")?[u,M,n]:(n++,-1!=t.indexOf("regulatory_region_ablation")?[u,M,n]:(n++,-1!=t.indexOf("regulatory_region_amplification")?[u,M,n]:(n++,-1!=t.indexOf("feature_elongation")?[u,M,n]:(n++,-1!=t.indexOf("regulatory_region_variant")?[u,M,n]:(n++,-1!=t.indexOf("feature_truncation")?[u,M,n]:(n++,-1!=t.indexOf("intergenic_variant")?[u,M,n]:(n++,[u,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 fe(e,t){const n=t.split("\n");n.shift(),e.genomicseq=n.join("").toUpperCase();const s=re(e);let r=f;return s.indexOf(se)==s.length-1&&(r=c),r}function ue(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=u,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),f=(0,s.Z)(t,75),u=f-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(f,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(u,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 f=Math.floor(100*a.min)/100,u=Math.ceil(100*a.max)/100,d=s.first_bin.startunbounded?f:s.first_bin.start_percentile?a["p"+s.first_bin.start_percentile]:s.first_bin.start;let p,m,h=u;if(s.last_bin)h=s.last_bin.stopunbounded?u: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:u,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:u,h=m}else p=u,m=u;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:()=>u});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(/<(.+)>/),f={};for(const e in s.mclass)f[s.mclass[e].label.toUpperCase()]=e;function u(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],f={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]},u=[];for(const e of n[4].split(",")){const t={ref:f.ref,allele:e,allele_original:e,sampledata:[],_m:f,info:{}};if(f.alleles.push(t),"<"==e[0]){const n=e.match(c);if(!n){u.push(e);continue}t.type=n[1],t.allele=n[1],t.issymbolicallele=!0}else{const[e,n,s]=p(f.pos,f.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,f,t),f.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,f="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]):f?Number.parseFloat(e[n]):e[n]);continue}if("1"==l){t.info[r]=c?Number.parseInt(i):f?Number.parseFloat(i):i;continue}if(!i.split)continue;const u=i.split(",");t.info[r]=c?u.map(Number.parseInt):f?u.map(Number.parseFloat):u}return s}(d,f,t):f.info=d;const h=[];for(const e of f.alleles){const t={};for(const e in f)"alleles"!=e&&(t[e]=f[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,u.length>0?u: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,f]=s.Wem(t.values),u=Math.abs(l-a)/r;if(c==f)return{bins:[{x0:c,x1:f,density:1}],densityMax:f};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,f,u):i(e,t.values,r,f);return n&&0==d.densityMax&&(console.log("using histogram as max density with KDE is 0"),d=i(e,t.values,r,f)),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 f=require("http");var u=n.n(f);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),z=n(5558),B=n(3602),U=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 f(){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=f())!==V;){for(var u=[];s!==W&&s!==V;)u.push(s),s=f();t&&null==(u=t(u,a++))||r.push(u)}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 fe={depth:-1},ue={},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,f,u,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!=(f=p(o,i,s))&&(f+="")&&(u=c.id=f,h.set(u,h.has(u)?ue:c)),null!=(f=m(o,i,s))&&(f+="")&&(c.parent=f);for(i=0;i<r;++i)if(f=(c=d[i]).parent){if(!(l=h.get(f)))throw new Error("missing: "+f);if(l===ue)throw new Error("ambiguous: "+f);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=fe,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"),f=Number.parseInt(i[1]);if(Number.isNaN(f))return;const u=Number.parseInt(i[2]);if(Number.isNaN(u))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(f,t.start)-t.start)*c,h=n+(Math.min(u,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,f=(0,S.createCanvas)(e.width*r,c*r),u=f.getContext("2d");r>1&&u.scale(r,r),u.strokeStyle="black";for(const e of n)u.beginPath(),u.moveTo(a.get(e),0),u.lineTo(i.get(e),s),u.closePath(),u.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));u.fillStyle="rgb(255,"+l+","+l+")",u.beginPath(),u.moveTo(r,a-o/2),u.lineTo(r-o/2,a),u.lineTo(r,a+o/2),u.lineTo(r+o/2,a),u.lineTo(r,a-o/2),u.closePath(),u.fill()}return{height:c,src:f.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),f=c.getContext("2d"),u=(n?a.chr.replace("chr",""):a.chr)+":"+a.start+"-"+a.stop;await F.UE({args:[e.file,u],dir:t,callback:t=>{const[n,s,l,c]=t.split("\t"),u=Math.max(Number.parseInt(s),a.start),d=Math.min(Number.parseInt(l),a.stop),p=(a.reverse?a.stop-d:u-a.start)*a.width/(a.stop-a.start),m=(a.reverse?a.stop-u:d-a.start)*a.width/(a.stop-a.start);for(const t of c.split(",")){const n=Number(t);f.fillStyle=n>0?e.pcolor:e.ncolor;const s=i(n),a=Math.max(1,m-p);f.fillRect(p,s.y,a,2),n>o?(f.fillStyle=req.query.pcolor2,f.fillRect(p,0,a,2)):n<r&&(f.fillStyle=req.query.ncolor2,f.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 ze={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"]},Ue=[{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 Ue)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,ze,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,ze,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",ft="#ffdbdd",ut=(0,Pe.ZP)(ft,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,zt=7,Bt=40,Ut=.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)),f=t.canvasheight/c.length;let u=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,u*f,o,f-d*f),t+=1;u+=1}return{height:t.canvasheight,width:i,src:a.toDataURL(),read_height:f}}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"]),f=[],u=[];je.Readable.from(e).pipe(c.stdin),c.stdout.on("data",(e=>f.push(e))),c.stderr.on("data",(e=>u.push(e))),c.on("error",(e=>{console.log("stderr (clustalo):",u),l(e)})),c.on("close",(e=>{let t=0;const c=[],u={final_read_align:[],qual_r:[],qual_g:[],qual_b:[]};let d=0;for(const e of f.toString().split("\n"))if(e.includes("seq ")){let n=0,l="",f=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[f]&&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[f]&&a){const e=ut(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),f<r&&(d+=1))):(l+=" ",0==t&&c.push(s)),m+="255,",h+="255,",g+="255,";f+=1}t+=1,u.gaps_before_variant=d,u.read_count=a?t-1:t,u.qual_r.push(m),u.qual_g.push(h),u.qual_b.push(g),u.final_read_align.push(l),0!=o&&0!=i&&(u.partstack_start=o,u.partstack_stop=i)}else(e.includes("FATAL:")||e.includes("ERROR:"))&&(console.log(e),l(e));n(u)}))}))}(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 fn(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 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=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 f=c[0],u=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:f,segstart:v,segstart_original:v,segstop:v,boxes:[],forward:!(16&u),ridx:o,seq:y,qual:b,cigarstr:p,tlen:g,flag:u,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&u)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+Ut<o.width&&o.x<=a?e.fillRect(a,n,o.ntwidth+Ut,s.stackheight):a<o.width&&a+o.ntwidth+Ut>=o.width&&o.x<=a?e.fillRect(a,n,o.width-a,s.stackheight):a<=o.x&&a+o.ntwidth+Ut>o.x&&e.fillRect(o.x,n,o.ntwidth+Ut+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+Ut<o.width&&i<o.width&&o.x<i+Ut?e.fillRect(i,n,r.len*o.ntwidth+Ut,s.stackheight):i+r.len*o.ntwidth+Ut<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+Ut+i-o.x,s.stackheight):i+r.len*o.ntwidth+Ut>=o.width&&o.x<i?e.fillRect(i,n,o.width-i,s.stackheight):i+r.len*o.ntwidth+Ut>=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):ut(a),t+o.ntwidth+Ut<o.x+o.width&&o.x<=t?e.fillRect(t,n,o.ntwidth+Ut,s.stackheight):t<o.x+o.width&&t+o.ntwidth+Ut>=o.x+o.width&&o.x<=t?e.fillRect(t,n,o.width+o.x-t,s.stackheight):t<=o.x&&t+o.ntwidth+Ut>o.x&&e.fillRect(o.x,n,o.ntwidth+Ut+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+Ut<o.width&&o.x<i?e.fillRect(i,n,r.len*o.ntwidth+Ut,s.stackheight):i+r.len*o.ntwidth+Ut<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+Ut+i-o.x,s.stackheight):i+r.len*o.ntwidth+Ut<=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+Ut,s.stackheight),a+=o.ntwidth}))}else t.discord_unmapped2&&(e.fillStyle=ht),e.fillRect(i,n,r.len*o.ntwidth+Ut,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(zt,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+Ut<o.width&&o.x<i?e.fillRect(i,n,r.len*o.ntwidth+Ut,s.stackheight):i+r.len*o.ntwidth+Ut<o.width&&o.x>=i?e.fillRect(o.x,n,r.len*o.ntwidth+Ut+i-o.x,s.stackheight):i+r.len*o.ntwidth+Ut<=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+Ut);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:ut)+'">'+e.seq[t.cidx+n]+"</td>"):c.push('<td style="background:'+(r.toUpperCase()==o.toUpperCase()?rt:ut)(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 f=0,u=0,d=[],p=[],m=0;for(const t of e.boxes)f=u,u+=t.len,"S"==t.opr&&(m=1,d.push(f),p.push(u));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 f=c.mtimeMs;f<e?(await h().promises.unlink(t),a++,o+=c.size):(n.push({path:t,time:f,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),f=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(f,{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(1169);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,f,u]=n[0].split(/[:,]/);if(i!=e.chr)return;const d=Number.parseInt(a),p=Number.parseInt(f);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 zn=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=[],f=[],u=[],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?u.push([w,s]):u.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?f.push([i,a]):f.unshift([i,a]),k+=a-i),o?l.push([a,r]):c.unshift([a,r])):i<r&&(o?f.push([i,r]):f.unshift([i,r]),k+=r-i)):s<a?r<=a?s<r&&(o?f.push([s,r]):f.unshift([s,r]),k+=r-s):(s<a&&(o?f.push([s,a]):f.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)),u.length>0&&(q.intron=u),i==a||(q.cdslen=k,q.codingstart=i,q.codingstop=a,q.coding=f,c.length&&(q.utr5=c),l.length&&(q.utr3=l));const x=p.split(",");return x.pop(),x.length<1||x.some((e=>!zn.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 Un=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 f="+"==t;let u=Math.ceil(n+(r-a*c-l*(c-1))/2);for(let t=0;t<c;t++)e.beginPath(),f?(e.moveTo(u,s),e.lineTo(u+a,s+o/2),e.moveTo(u+a,s+o/2+1),e.lineTo(u,s+o)):(e.moveTo(u+a,s),e.lineTo(u,s+o/2),e.moveTo(u,s+o/2+1),e.lineTo(u+a,s+o)),e.stroke(),u+=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,f=0,u=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",f++):"long"==e.type?(l.type="integer",u++):"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(fs[t.id]){t.bins=fs[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:f}=await(0,F.fk)(l.graphql,{method:"POST",body:{query:r,variables:o}});if("object"!=typeof f.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 f.data.viewer.explore.cases.aggregations)){console.log("GDC: no stats object returned for numeric term",n),s.bins=cs,a++;continue}const r=f.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="+f,"integer="+u,"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=null,r,o=null,i=null)=>{(e=e.toLowerCase()).includes(" ")&&(e=e.replace(/\s/g,"_"));const a=[];for(const n of t.values())i&&!(0,os.CG)(n,i)||n.id.includes(e)&&a.push(JSON.parse(JSON.stringify(n)));return await s(a,o),a},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=[],f&&e.cohort.termdb.termtypeByCohort.push({cohort:"",type:"categorical"}),u&&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}}},fs={"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 ds(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 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,f,u,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,f=l.geneA||l.chrA,u=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,f=l.geneB||l.chrB,u=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,u,c,encodeURIComponent(f)].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:u,pairlstIdx:c,mname:f,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 f={case:s.map((e=>e)).join(","),control:i.map((e=>e)).join(","),input_file:n.file,output_path:y().join(r().binpath,"utils")},u=8;let d;if(s.length<=u&&i.length<=u||"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(f)),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(f)),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(f)),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 zs(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 Us(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 Us(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],f=Number(o[2]),u=o[3],d=o[4].split(","),p=o[5],m={pos:f-1};(0,gs.H)(n._tk,u,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 zs(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 f=[];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,f.push({chr:e,chrLen:n,xStart:a*(c-n),xStop:a*c})}const u=(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+u(i);p.fillRect(70+a,c,1,1)})),m.on("close",(()=>{!function(){p.strokeStyle="black",p.beginPath();{const e=220-u(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:f})}))}));function g(e){p.fillStyle="black",p.font="12px Arial",p.textAlign="right";const t=o+u(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 Us(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 Us(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(",")],f=[];for(const e of l){const n=ir(r,e,c,t);if(or(n)){if(f.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 f}(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"),fr="#aaa",ur="%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),f=c.getContext("2d");f.strokeStyle="black";for(const e of n)f.beginPath(),f.moveTo(i.get(e),0),f.lineTo(o.get(e),s),f.closePath(),f.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));f.fillStyle="rgb(255,"+l+","+l+")",f.beginPath(),f.moveTo(i,a-r/2),f.lineTo(i-r/2,a),f.lineTo(i,a+r/2),f.lineTo(i+r/2,a),f.lineTo(i,a-r/2),f.closePath(),f.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]),f={start:o,stop:a,strand:s[5],name:r,pvalue:c,score:Number.parseFloat(s[6]),logpvalue:-Math.log10(c)};t.fimo_motif.tf2attr&&(f.attr=t.fimo_motif.tf2attr[f.name]),i.push(f)}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]),f=JSON.parse(n[3]);if(t.has(f.sample)){if(f.dt==$.dtcnv){if(!o.cnv)return;if(o.cnv.focalsizelimit&&i-r>=o.cnv.focalsizelimit)return;if(o.cnv.valuecutoff&&Math.abs(f.value)<o.cnv.valuecutoff)return;return s?f.value>0?a.add(f.sample):l.add(f.sample):c.add(f.sample),void o.samples_cnv.add(f.sample)}if(f.dt==$.dtloh){if(!o.loh)return;if(o.loh.focalsizelimit&&i-r>=o.loh.focalsizelimit)return;if(o.loh.valuecutoff&&f.segmean<o.loh.valuecutoff)return;return c.add(f.sample),void o.samples_loh.add(f.sample)}if(f.dt==$.dtsv){if(!o.sv)return;return c.add(f.sample),void o.samples_sv.add(f.sample)}if(f.dt==$.dtfusionrna){if(!o.fusion)return;return c.add(f.sample),void o.samples_fusion.add(f.sample)}if(f.dt==$.dtitd){if(!o.itd)return;return c.add(f.sample),void o.samples_itd.add(f.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,zr=r().samtools,Br=r().bcftools,Ur=(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 u().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)(zr,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 f=[],u=[];c.stdout.on("data",(e=>f.push(e))),c.stderr.on("data",(e=>u.push(e))),c.on("close",(()=>{s(Number.parseInt(f.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)fo(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)fo(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 fo(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 f=!0;for(const s of n.get(c).samples)if(s.samplename==e){for(const e of t)s.items.push(e);f=!1;break}f&&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 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 f=[];c.stderr.on("data",(e=>f.push(e))),c.on("close",(t=>{const n=f.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 f=[];c.stderr.on("data",(e=>f.push(e))),c.on("close",(e=>{const t=f.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 f=e.query.color||"#3D7A4B",u=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,u,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||f;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],f=[];n.utr5&&f.push(...n.utr5),n.utr3&&f.push(...n.utr3),!n.exon||n.coding&&0!=n.coding.length||f.push(...n.exon);for(const e of f){const t=Math.max(c.start,e[0]),i=Math.min(c.stop,e[1]),a=l+c.scale(c.reverse?i:t),f=l+c.scale(c.reverse?t:i);s.fillRect(a,w,Math.max(1,f-a),o-2*w),es(r,a,f,1,n)}const u=[];n.exon?n.coding&&n.coding.length>0&&u.push(...n.coding):u.push([n.start,n.stop]);for(const e of u){const i=Math.max(c.start,e[0]),a=Math.min(c.stop,e[1]),f=l+c.scale(c.reverse?a:i),u=l+c.scale(c.reverse?i:a);s.fillRect(f,0,Math.max(1,u-f),o),es(r,f,u,1,n),n.strand&&t&&(s.strokeStyle="white",ts(s,n.strand,f,w,u-f,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;u&&(M=u.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+Un?(t.canvas.namestart=t.canvas.start-Un,r=t.canvas.namestart-n,t.canvas.textalign="right"):t.canvas.stop+n+Un<=l?(t.canvas.namestart=t.canvas.stop+Un,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-Un,r=t.canvas.namestart-n,t.canvas.textalign="right"):(t.canvas.namestart=t.canvas.stop+Un,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+Un?(t.canvas.namestart=t.canvas.start-Un,r=t.canvas.namestart-n,t.canvas.textalign="right"):t.canvas.stop+n+Un<=l?(t.canvas.namestart=t.canvas.stop+Un,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||f,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],f=[];t.utr3&&f.push(...t.utr3),t.utr5&&f.push(...t.utr5),!t.exon||t.coding&&0!=t.coding.length||f.push(...t.exon);for(const e of f){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 u=[];t.exon?t.coding&&t.coding.length>0&&u.push(...t.coding):u.push([t.start,t.stop]);let d=t.strand;n.stranded&&c.reverse&&(d="+"==t.strand?"-":"+");for(const e of u){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),f=l+c.scale(c.reverse?i:a);if(C.fillRect(e,r,Math.max(1,f-e),o),t.exon2color&&(C.fillStyle=s),n.stranded&&!t.willtranslate)if(C.strokeStyle="white",n.namein){const t=(f-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,f-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),f=l+c.scale(c.reverse?o:i);if(f<0)continue;R.push({chr:t.chr,start:s,stop:r,x1:a,x2:f,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||f,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 f=i.width/(i.stop-i.start),u=Math.min(o,3*f),d=u<8?null:u;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 u=Math.max(i.start,s),h=Math.min(i.stop,a);m+=p?a-h:u-s;let g=0;for(let e=0;e<h-u;e++){let t;if(m++,g++,m%3==0)t=m/3-1;else{if(e<h-u-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=f*g;if(p){const t=h-1-e;y=c+i.scale(t)}else{const t=u+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=[],f=[],u=[];if(e.alleleAlreadyUpdated)o=e.leftflankseqs,i=e.rightflankseqs,f=e.refseqs,u=e.altseqs,a=e.refalleles,l=e.altalleles,c=e.ref_positions,0!=f[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="",f="";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(),f=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,f=t,o.pos-=1}else f=o.alt,i=o.ref;const u=o.pos,d=i.toUpperCase(),p=f.toUpperCase();0==r?(t=u-s,n=u+i.length+1+s):(u-s<t&&(t=u-s),u+i.length+1+s>n&&(n=u+i.length+1+s)),a.push(d),l.push(p),c.push(u),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),f.push(m),u.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:f[e],altseq:u[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:f,altseqs:u,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 f=[];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,f.push(t))}return{groups:f}}(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=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=un(e,s);r=mn(s,e,r),await pn(s,e,r),await fn(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),f=(0,S.createCanvas)(e.devicePixelRatio*l,e.devicePixelRatio*c),u=f.getContext("2d");e.devicePixelRatio>1&&u.scale(e.devicePixelRatio,e.devicePixelRatio);u.fillStyle="black",u.font=r+"pt Arial",u.textAlign="center",u.fillText("Base quality",i+t/2,r);let d=2*r+o;function p(e,s,r){const o=i,a=u.createLinearGradient(o,r,o+t,r);a.addColorStop(0,s),a.addColorStop(1,e),u.fillStyle=a,u.fillRect(o,r,t,n)}return u.strokeStyle="black",u.beginPath(),u.moveTo(i,d),u.lineTo(i,d+a),u.moveTo(i+t/4,d),u.lineTo(i+t/4,d+a),u.moveTo(i+t/2,d),u.lineTo(i+t/2,d+a),u.moveTo(i+3*t/4,d),u.lineTo(i+3*t/4,d+a),u.moveTo(i+t,d),u.lineTo(i+t,d+a),u.closePath(),u.stroke(),u.fillText(40,i,d),u.fillText(30,i+t/4,d),u.fillText(20,i+t/2,d),u.fillText(10,i+3*t/4,d),u.fillText(0,i+t,d),u.textAlign="left",u.textBaseline="middle",d+=a,u.fillText("Match",0,d+n/2),p(st,nt,d),d+=n+s,u.fillStyle="black",u.fillText("Mismatch",0,d+n/2),p(ft,ct,d),d+=n+s,u.fillStyle="black",u.fillText("Softclip",0,d+n/2),p(pt,dt,d),d+=n+s,u.fillStyle="black",u.fillText("Insertion",0,d+n/2),p(wt,vt,d),{width:l,height:c,src:f.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(",")},f=await v()(l,{method:"POST",headers:a,body:JSON.stringify(c)});let u;try{u=JSON.parse(f.body)}catch(e){throw"invalid JSON from "+n.end_point}if(!Array.isArray(u.data?.hits))throw"data structure not re.data.hits[]";return u}}(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,f=e.query.gmafrestrict,u=(0,S.createCanvas)(e.query.width*e.query.devicePixelRatio,(3*o+4*a+2*i)*e.query.devicePixelRatio),d=u.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"),u=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-u:u-t.start)-l/2);d.fillStyle=h;const k=p/m;d.fillRect(_,o*(1-k),l,2);const q=v/w;if(f&&(q<f||q>1-f))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:u.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){if(e.atgenomic){if(!t.queries.snvindel.byrange)throw".atgenomic but missing byrange query method";return await t.queries.snvindel.byrange.get(e)}if(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),f=Number(e.query.regionspace),u=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(f))throw"regionspace is not integer";if(!Number.isFinite(u))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)(u,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",u/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 f=[];for(const e in s)f.push({nt:e,v:s[e]}),a+=s[e];y.fillStyle=w;const u=k*(v-a);if(y.fillRect(_+r,u,t,k*a),f.length>1){f.sort(((e,t)=>t.v-e.v));for(let e=1;e<f.length;e++){let n=0;for(let t=0;t<e;t++)n+=f[t].v;y.fillStyle=$.basecolor[f[e].nt],y.fillRect(_+r,u+k*n,t,k*f[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)),f.length>1)for(let e=1;e<f.length;e++){let n=0;for(let t=0;t<e;t++)n+=f[t].v;y.fillStyle=$.basecolor[f[e].nt],y.fillRect(_+r,d+q*(l-Math.min(l,a-n)),t,q*Math.min(l,f[e].v))}}_+=e.width+f}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,f,u]=F.ZX(e);if(c)throw c;if(f.endsWith(".gz")&&(l=!0,u&&(i=await F.d1(f,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,f,i);for(const t of e.query.rglst){let n;if(r().features.bigwig_rust){const s=f+","+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,f);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,f=(i?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;await F.UE({args:[s,f],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=U.parseheader(n[0],t,!0);if(s)throw"sv header line error: "+s;for(let e=1;e<n.length;e++)U.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=U.parseheader(n[0],t,!1);if(s)throw"fusion header line error: "+s;for(let e=1;e<n.length;e++)U.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=z.parseheader(n[0],t);if(s)throw"deletion header line error: "+s;for(let e=1;e<n.length;e++)z.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 f=c.split("\t"),u=Number.parseInt(f[1]),d=Number.parseInt(f[2]);if(n.file2){f[3];const t=f[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:u,stop:d,info:{type:{lst:[{attrValue:n}]}}},l=[];for(let e=5;e<f.length;e++){const t=f[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{f[3],f[4];if(!(u>=s.start&&u<=s.stop||d>=s.start&&d<=s.stop))return;o++;const c={chr:s.chr,start:u,stop:d,info:{type:{lst:[]}}},p=JSON.parse(f[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}),f=I().createInterface({input:a.stdout}),u=(t.stop-t.start)/t.width,d=[];for(let e=0;e<t.width;e++)d.push({positive:0,negative:0});f.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][Ur]){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 f=Math.max(t.start,r),p=Math.min(t.stop,i);let m,h;t.reverse?(m=Math.floor((t.stop-p)/u),h=Math.floor((t.stop-f)/u)):(m=Math.floor((f-t.start)/u),h=Math.floor((p-t.start)/u));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"),f={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),f.src=r.toDataURL(),void t.send(f);for(const e of n)for(const t of e)f.maxvalue=Math.max(f.maxvalue,t.positive,t.negative);const u=e.query.maxvalue||f.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(u,n.positive)/u),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(u,n.negative)/u),s=e.query.gain.barheight;a.fillRect(d,s,1,t)}d++}d+=e.query.regionspace}if(f.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([Ur,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}f.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++}f.hierarchySummary=n}}t.send(f)})).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,f,u;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=uo(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&&(f={set:t,sample2group:n})}if(e.query.hiddensampleattr){u={};for(const t in e.query.hiddensampleattr)u[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 f=new Promise(((l,f)=>{const u=[],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 f;try{f=JSON.parse(r[3])}catch(e){return}if(!(null==f.dt||s&&s.has(f.dt))){if(f.dt==$.dtloh){if(f.segmean&&n.query.segmeanValueCutoff&&f.segmean<n.query.segmeanValueCutoff)return;if(n.query.lohLengthUpperLimit&&c-l>n.query.lohLengthUpperLimit)return;f.chr=r[0],f.start=l,f.stop=c}else if(f.dt==$.dtfusionrna||f.dt==$.dtsv)f._chr=r[0],f._pos=l,f.chrA?(f.chrB=r[0],f.posB=l):(f.chrA=r[0],f.posA=l);else if(f.dt==$.dtcnv){if(n.query.hide_cnvloss&&f.value<0)return;if(n.query.hide_cnvgain&&f.value>0)return;if(n.query.valueCutoff&&Math.abs(f.value)<n.query.valueCutoff)return;if(n.query.bplengthUpperLimit&&c-l>n.query.bplengthUpperLimit)return;f.chr=r[0],f.start=l,f.stop=c}else{if(f.dt!=$.dtitd)return void console.error("unknown dt from svcnv file: "+f.dt);f.chr=r[0],f.start=l,f.stop=c}if(n.query.singlesample){if(f.sample!=n.query.singlesample)return}else if(a){if(!a.set.has(f.sample))return}else if(f.sample&&e.cohort&&e.cohort.annotation){const t=e.cohort.annotation[f.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=f.mattr?f.mattr[e]:void 0;if(null==t&&(t=$.not_annotated),i[e].has(t))return}u.push(f)}}));const p=[];d.stderr.on("data",(e=>p.push(e))),d.on("close",(e=>{const t=p.join("");!t||Dr(t)?l(u):f(t)}))}));l.push(f)}return Promise.all(l)}(s,o,e,i,u,a,f),[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,f){let u;n.iscustom?u=n.checkvcf:n.vcf_querykey&&t.queries[n.vcf_querykey]&&(u=t.queries[n.vcf_querykey]);if(!u)return[null,null];if(s.query.singlesample&&u.singlesamples){const n=u.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),[f,u,d,p]=D.e(a);if(p)throw p;return i.info=f,i.format=u,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 f=(0,x.spawn)(Gr,[n.file,(n.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop]);I().createInterface({input:f.stdout}).on("line",(r=>{const[l,c,f]=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 u=[];f.stderr.on("data",(e=>u.push(e))),f.on("close",(e=>{const t=u.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=u.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 u.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:u.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(f){const t=e.sampledata.filter((e=>f.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,u,f),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,f),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",ur,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=fr}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:fr,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=[],f=[];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&&f.push(t.sampleobj.name)}const u=Math.random().toString();s.ssid=u,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(f.length){const e="Homozygous alternative";s.groups[e]={size:f.length},d.push(e+"\t"+f.join(","))}await F.Sf(y().join(tr.cachedir_ssid,u),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}),f=I().createInterface({input:c.stdout}),u=new Map;f.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 u.has(r.gene)||u.set(r.gene,{chr:o,start:a,stop:l,allvalues:[]}),u.get(r.gene).thisvalue=r.value,void(r.ase&&(u.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),u.has(r.gene)||u.set(r.gene,{chr:o,start:a,stop:l,allvalues:[]}),u.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(u)}))})));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 f=c.join(", ");if(!a.has(f)){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(f,t)}a.get(f).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 f=[];for(const[e,t]of a)f.push({name:e,values:t.samples,attributes:t.attributes});l.length&&f.push({name:"Unannotated",values:l});c.length&&f.push({values:c});if(o.query.getalllst)return{lst:f[0].values};if(o.query.iscustom&&!i||1==f.length){if(f[0]){const e=f[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 u=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(f[0]){const e=f[0].values;if(e.sort(((e,t)=>t.value-e.value)),u)for(const t of e){const e=u.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 f){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(u){if(o.query.svcnv.usegain){const t=e.values.filter((e=>u.has(e.sample)&&u.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=>u.has(e.sample)&&u.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=>u.has(e.sample)&&u.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),f=i[a-1].genevalue,u=i[l-1].genevalue,d=i[c-1].genevalue;return[{name:r.gene+" "+o.datatype+" from 1st quartile (n="+a+", value<"+f+")",lst:i.slice(0,a),isfirstquartile:!0},{name:r.gene+" "+o.datatype+" from 2nd quartile (n="+(l-a)+", "+f+"<=value<"+u+")",lst:i.slice(a,l)},{name:r.gene+" "+o.datatype+" from 3rd quartile (n="+(c-l)+", "+u+"<=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 f;c.length>1&&(f=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 u={samplesets:c,pvalue:f};s.samplerule.set&&s.samplerule.set.mutation&&(u.count_snvindel=s.samplerule.set.samples_snvindel.size,u.count_cnv=s.samplerule.set.samples_cnv.size,u.count_loh=s.samplerule.set.samples_loh.size,u.count_sv=s.samplerule.set.samples_sv.size,u.count_fusion=s.samplerule.set.samples_fusion.size,u.count_itd=s.samplerule.set.samples_itd.size),n.send(u)}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,f=0;const u=[];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):f=Math.min(f,n.logpvaluediff),u.push(n));return{items:u,valuemin:f,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 f=!0,u=0,d=0;c.on("line",(i=>{if(f)return void(f=!1);const a=i.split(e.delimiter),c=[];for(const t of e.getpcd.coord)c.push(a[t]),u=Math.max(u,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(u),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 f=[],u=(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=u(t),f.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(f.filter((e=>e.category==t.value))[0])}for(const t of e.getgeneboxplot.cat_values)t.order||p.push(f.filter((e=>e.category==t.value))[0]);for(const t of f){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=f;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("")}(),f=JSON.stringify(e.body),u=s?hr(n,l):r().cachedir_massSession;await h().promises.access(u).then((()=>!0)).catch((()=>!1))||h().mkdirSync(u,{recursive:!0}),await F.Sf(y().join(u,c),f),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 f;try{f=(await h().promises.stat(c)).birthtime}catch(e){throw"invalid session"}const u=await F.b5(c),d=JSON.parse(u);if(e.query.route)return void t.send({state:d});const p=new Date,m=new Date(f),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=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=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[f,u,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 f={info:i,format:a,samples:l},u=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 u||[]){const[n,s,r]=D.S(t,f);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,f,u);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,f=!1;n-t<=e.width?(f=!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 u=Number.parseInt(s[2]);if(!Number.isInteger(u))return;const d=e.rnabarheight*Math.min(u,r)/r,p=f?(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(),u>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:f,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 f=0;for(const n of t)n.dnacount&&(n.pos<r||n.pos>o||(n.__x=e.width*(n.pos-r)/(o-r),f=Math.max(f,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)/f;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=zo(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 Uo(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)fo(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 zo(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 Uo(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 f={termdb:["matrix"],samples:["singleSampleData","getAllSamples","scatter","convertSampleId","getAllSamplesByName"]};function u(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(),f=Math.floor(c/1e3),u={dslabel:t.dslabel,id:n,iat:f,time:c,ip:e.ip,embedder:t.embedder,route:r.route,exp:f+Math.floor(o/1e3),email:l};r.dsnames&&(u.datasets=r.dsnames.map((e=>e.id)));const d=a().sign(u,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),f=i.ip;return n[e.dslabel]||(n[e.dslabel]={}),n[e.dslabel][c]={id:c,time:l,email:o,ip:f},await s.promises.appendFile(r,`${e.dslabel}\t${c}\t${l}\t${o}\t${f}\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):{},f=c.handleToken?.(l)||l,u=a().verify(f,o);if(r)return{iat:u.iat,email:u.email,ip:u.ip};if(c.handlePayload)try{c.handlePayload(n,u,i)}catch(e){if("bad decrypt"==e.reason)throw`Please login again to access this feature. (${e.reason})`;throw e}if(i>u.exp)throw"Please login again to access this feature. (expired token)";const d=(n.dsnames||[e.dslabel]).filter((e=>!u.datasets?.includes(e.id))).map((e=>e.id));if(d.length)throw{error:"Missing access",linkKey:d.join(",")};return{iat:u.iat,email:u.email,ip:u.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||f.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=u(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=u(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=u(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=u({query:Object.assign({},e.query,{dslabel:s}),headers:e.headers,cookies:e.cookies},a),f=q[s]?.[c],d=f?.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,f.samples);if(!n)return!0;if("basic"==n.type&&e.path.startsWith("/genomes"))return!1;const s=u(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),f=n(8064),u=n(5494),d=n(6733),p=n(5558),m=n(3602),h=n(6279);const g={snvindel:u,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=f.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.42.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 f=c.replace("server","client");if(i().existsSync(f)){const e=JSON.parse(i().readFileSync(f,{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 f=(0,a.spawn)(i().Rscript,[e,...n]);if(t&&t.length>0)try{const e=t.join("\n")+"\n";l.Readable.from(e).pipe(f.stdin)}catch(e){f.kill();let t=e;o.length>0&&(t+=`\nR stderr: ${o.join("").trim()}`),c(t)}f.stdout.on("data",(e=>s.push(e))),f.stderr.on("data",(e=>o.push(e))),f.on("error",(e=>c(e))),f.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}},1169:(e,t,n)=>{"use strict";n.d(t,{Ak:()=>h,Z5:()=>v,sV:()=>R,eG:()=>b,r8:()=>D,z7:()=>$,ws:()=>I,nD:()=>T,wm:()=>E,IK:()=>x,CN:()=>w,xq:()=>y,vK:()=>g});var s=n(2273),r=n(4048),o=n(6452),i=n.n(o),a=n(1017),l=n.n(a),c=n(4973);function f(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:u(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:u(n.tvs.term.id),value:e.stop}}):e.stopunbounded?t.content.push({op:e.startinclusive?n.tvs.isnot?"<":">=":n.tvs.isnot?"<=":">",content:{field:u(n.tvs.term.id),value:e.start}}):n.tvs.isnot?t.content.push({op:"or",content:[{op:"and",content:[{op:e.startinclusive?"<":"<=",content:{field:u(n.tvs.term.id),value:e.start}}]},{op:"and",content:[{op:e.stopinclusive?">":">=",content:{field:u(n.tvs.term.id),value:e.stop}}]}]}):t.content.push({op:"and",content:[{op:e.startinclusive?">=":">",content:{field:u(n.tvs.term.id),value:e.start}},{op:e.stopinclusive?"<=":"<",content:{field:u(n.tvs.term.id),value:e.stop}}]})}}return t}function u(e){const t=e.split(".");return"case"==t[0]&&(t[0]="cases"),t.join(".")}n(3345);var d=n(334),p=n.n(d);function m(...e){p().debugmode&&console.log(e.join(" "))}function h(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 g(e,t){const n=["consequence.transcript.is_canonical","consequence.transcript.transcript_id"];e.get=async e=>{if(!e.ssm_id)throw".ssm_id missing";const{host:s,headers:r}=t(e),o=await i()(s.rest+"/ssms/"+e.ssm_id+"?fields="+n.join(","),{method:"GET",headers:r});let a;try{a=JSON.parse(o.body)}catch(e){throw"invalid json in response"}if(!a.data||!a.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(a.data.consequence))throw".data.consequence not array";const l=a.data.consequence.find((e=>e.transcript.is_canonical));return l?l.transcript.transcript_id:a.data.consequence[0].transcript.transcript_id}}function y(e){e.queries.snvindel.byrange.get=async t=>await e.queries.snvindel.byisoform.get(t)}function b(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 v(n,e);if(0==o.length)return{gene2sample2value:s,byTermId:{}};const a=new Date;m(o.length,"cases with exp data:",a-r,"ms");const[l,c]=await async function(e,t,n,s,r){const o=[],a=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),a.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),a.set(t.alias,e);break}if(o.length>100)break}try{const{host:e,headers:t}=s.getHostHeaders(r),l=await i().post(`${e.geneExp}/gene_expression/gene_selection`,{headers:t,body:JSON.stringify({case_ids:n,gene_ids:o,selection_size:o.length})}),c=JSON.parse(l.body);if(!Array.isArray(c.gene_selection))throw"re.gene_selection[] not array";const f=[];for(const e of c.gene_selection){if("string"!=typeof e.gene_id)throw".gene_id missing from one of re.gene_selection[]";f.push(e.gene_id)}return[f,a]}catch(e){throw e}}(n.genes,t,o,e,n);if(0==l.length)return{gene2sample2value:s,byTermId:{}};const f=new Date;m(l.length,"out of",n.genes.length,"genes selected for exp:",f-a,"ms");const u={};for(const e of l){const t=c.get(e);u[t]={gencodeId:e},s.set(t,new Map)}const d=await async function(e,t,n,s,r,o){const{host:a,headers:l}=o.getHostHeaders(e),c=await i().post(`${a.geneExp}/gene_expression/values`,{headers:l,body:JSON.stringify({case_ids:n,gene_ids:t,format:"tsv",tsv_units:"uqfpkm"})});if("string"!=typeof c.body)throw"response.body is not tsv text";const f=c.body.trim().split("\n");if(f.length<=1)throw"less than 1 line from tsv response.body";const u=f[0].split("\t").slice(1);if(u.length!=n.length)throw"sample column length != case_ids.length";const d={};for(const e of u){const t=o.__gdc.caseid2submitter.get(e);if(!t)throw"case submitter id unknown for a uuid";d[e]={label:t}}for(let e=1;e<f.length;e++){const t=f[e].split("\t");if(t.length!=u.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 u.entries()){const s=Number(t[e+1]);if(!Number.isFinite(s))throw"non-numeric exp value from gdc";r.get(o)[n]=s}}return d}(n,l,o,c,s,e);return m("gene-case matrix built:",new Date-f,"ms"),{gene2sample2value:s,byTermId:u,bySampleId:d}}}async function v(e,t){const n={op:"and",content:[]};e.filter0&&n.content.push(e.filter0),e.filterObj&&n.content.push(f(e.filterObj)),e.filter&&n.content.push(f(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 i().post(l().join(n.rest,"cases"),{headers:r,body:JSON.stringify(s)}),a=JSON.parse(o.body);if(!Array.isArray(a.data.hits))throw"re.data.hits[] not array";const c=[];for(const e of a.data.hits)if(e.id&&t.__gdc.casesWithExpData.has(e.id)&&(c.push(e.id),1e3==c.length))break;return c}catch(e){throw e.stack&&console.log(e.stack),e}}function w(e){e.queries.snvindel.byisoform.get=async t=>{const n=_(t,e),r=await async function(e,t){const n=L,s=G,{host:r,headers:o}=t.getHostHeaders(e),a=i().post(l().join(r.rest,n.endpoint),{headers:o,body:JSON.stringify(Object.assign({size:n.size,fields:n.fields.join(",")},n.filters(e)))}),c=i().post(l().join(r.rest,s.endpoint),{headers:o,body:JSON.stringify(Object.assign({size:s.size,fields:s.fields.join(",")},s.filters(e,t)))}),[f,u]=await Promise.all([a,c]);let d,p;try{d=JSON.parse(f.body),p=JSON.parse(u.body)}catch(e){throw"invalid JSON returned by GDC"}if(!d.data||!d.data.hits)throw"query1 did not return .data.hits";if(!p.data||!p.data.hits)throw"query2 did not return .data.hits[]";if(!Array.isArray(d.data.hits)||!Array.isArray(p.data.hits))throw"re.data.hits[] is not array";const m=new Map;for(const t of d.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=[],m.set(t.ssm_id,t)}for(const e of p.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=m.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[...m.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(k(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 _(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 k(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 x(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(f("string"==typeof e.filterObj?JSON.parse(e.filterObj):e.filterObj)),t}e.queries.geneCnv.bygene.get=async t=>{const{host:o,headers:a}=e.getHostHeaders(t),c=await i().post(l().join(o.rest,"cnv_occurrences"),{headers:a,body:JSON.stringify(Object.assign({size:1e5,fields:n(t)},r(t)))}),f=JSON.parse(c.body);if(!Array.isArray(f?.data?.hits))throw"geneCnv response body is not {data:hits[]}";const u={ssm_id:"geneCnvGain",dt:s.dtcnv,class:s.mclasscnvgain,samples:[]},d={ssm_id:"geneCnvLoss",dt:s.dtcnv,class:s.mclasscnvloss,samples:[]};for(const e of f.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=u;else{if("Loss"!=e.cnv.cnv_change)throw"hit.cnv.cnv_change is not Gain/Loss";n=d}const s={sample_id:e.case.case_id};if(t.twLst)for(const n of t.twLst)S(s,e.case,n);n.samples.push(s)}const p=[];return u.samples.length&&p.push(u),d.samples.length&&p.push(d),p}}function N(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 S(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 A(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]=C(o,e))}}else if("continuous"!=s.q.mode)throw"mayApplyBinning: unknown numeric q.mode";return n}function C(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 j(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 T(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(f(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"],a=new Map;for(const e of r){const t=e.term.id.replace(/^case\./,"");o.push(t),a.set(t,e.term.id)}const{host:c,headers:u}=n.getHostHeaders(e),d=await i().post(l().join(c.rest,"cases"),{headers:u,body:JSON.stringify({size:n.__gdc.casesWithExpData.size,fields:o.join(","),case_filters:s.content.length?s:void 0})}),p=JSON.parse(d.body);if(!Array.isArray(p?.data?.hits))throw"re.data.hits[] not array";const m=[];for(const e of p.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)S(t,e,n);m.push(t)}const h=A(m,r);return{byTermId:h,samples:m}}(e,t,n);if(j(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 a={size:1e4,fields:o.join(",")};_(e,n),Object.assign(a,G.filters(e,n));const{host:u,headers:d}=n.getHostHeaders(e),p=await i().post(l().join(u.rest,G.endpoint),{headers:d,body:JSON.stringify(a)});let m;delete e.isoforms;try{m=JSON.parse(p.body)}catch(e){throw"invalid JSON from GDC for variant2samples query"}if(!m.data||!m.data.hits)throw"variant2samples data structure not data.hits[]";if(!Array.isArray(m.data.hits))throw"variant2samples re.data.hits is not array for query";const h=[];for(const t of m.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(k(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)S(s,t.case,e);M(t.case,s),O(s,n),h.push(s)}const g=A(h,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)h.push(t)}const y=new Map;for(const e of h)(0,c.z9)([e],y,e.ssm_id);return{byTermId:g,samples:[...y.values()]}}function M(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 O(e,t){const n=e["case.project.project_id"];n&&(e.caseIsOpenAccess=t.__gdc.gdcOpenProjects?.has(n))}async function I(e,t,n,s){j(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),a=function(e,t){const n={filters:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}}]}};z(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(f(e.filterObj));return n}(t,s),{host:l,headers:c}=s.getHostHeaders(t),u=await i().post(l.graphql,{headers:c,body:JSON.stringify({query:o,variables:a})});let d;try{d=JSON.parse(u.body)}catch(e){throw"invalid JSON from GDC for cohortTotal for query :"+o+" and filter: "+filter}const p=["data","explore","cases","aggregations"];let m=d[p[0]];for(let e=1;e<p.length;e++)if(m=m[p[e]],!m)throw`.${p[e]} missing from data structure of termid2totalsize2 for query :${o} and filter: ${filter}`;for(const e of r){if("categorical"==e.type&&!Array.isArray(m[e.path].buckets))throw p.join(".")+" not array for query :"+o+" and filter: "+filter;if(("integer"==e.type||"float"==e.type)&&"object"!=typeof m[e.path].stats)throw p.join(".")+" not object for query :"+o+" and filter: "+filter}const h=new Map;for(const e of r)if("categorical"==e.type){const t=m[e.path].buckets,n=[];for(const e of t)n.push([e.key.replace(".","__"),e.doc_count]);h.set(e.id,n)}else if("integer"==e.type||"float"==e.type){const t=m[e.path].stats.count;h.set(e.id,{total:t})}return n?[h,n]:h}function E(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 i()(s.rest+"/ssms/"+n.ssm_id+"?fields="+t.join(","),{method:"GET",headers:r});let a;try{a=JSON.parse(o.body)}catch(e){throw"invalid json in response"}if(!a.data||!a.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(a.data.consequence))throw".data.consequence not array";return a.data.consequence.map((e=>e.transcript))}}function R(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 F(t.sample,e)));return await async function(e,t,n){const r={mlst:[],dt2total:[]};{const{host:n,headers:o}=t.getHostHeaders(e),a=await i().post(l().join(n.rest,L.endpoint),{headers:o,body:JSON.stringify({size:1e4,fields:L.fields.join(","),filters:L.filters(e).filters})}),c=JSON.parse(a.body);if(!Number.isInteger(c.data?.pagination?.total))throw"re.data.pagination.total not integer";if(!Array.isArray(c.data?.hits))throw"re.data.hits[] not array";c.data.hits.length<c.data.pagination.total&&r.dt2total.push({dt:1,total:c.data.pagination.total});for(const e of c.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 i().post(l().join(n.rest,"files"),{headers:r,body:JSON.stringify({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)})}),a=JSON.parse(o.body);if(!Array.isArray(a.data.hits))throw"re.data.hits[] not array";let c,f,u;for(const e of a.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;c=e.file_id;continue}if("WGS"==e.experimental_strategy){if(!e.file_id)continue;if("Copy Number Segment"!=e.data_type)continue;f=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;u=e.file_id}const d=[];if(f){const e=(await i()(l().join(n.rest,"data")+"/"+f,{method:"GET",headers:r})).body.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)||(d.push(a),r>0&&0==i&&o>0&&d.push({dt:s.dtloh,chr:a.chr,start:a.start,stop:a.stop,segmean:.5}))}}else if(c){const e=(await i()(l().join(n.rest,"data")+"/"+c,{method:"GET",headers:r})).body.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)||d.push(r)}}if(u)try{const e=(await i()(l().join(n.rest,"data")+"/"+u,{method:"GET",headers:r})).body.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)&&(N(r,n[6]),d.push(r))}}catch(e){}return d}(e,t);r.mlst.push(...n)}return r}(t,e)}}async function F(e,t){const{host:n,headers:s}=t.getHostHeaders(q),r=await i().post(`${n.rest}/cases`,{headers:s,body:JSON.stringify({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]}}]}})}),o=JSON.parse(r.body);for(const e of o.data.hits)if(e.case_id)return e.case_id;throw"cannot convert to case_id (uuid)"}function $(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:["id","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),a=await i().post(l().join(r.rest,"files"),{headers:o,body:JSON.stringify(s)});let c;try{c=JSON.parse(a.body)}catch(e){throw"invalid JSON from "+api.endpoint}if(!Number.isInteger(c.data?.pagination?.total))throw"re.data.pagination.total is not int";if(!Array.isArray(c.data?.hits))throw"re.data.hits[] not array";const f=new Map;for(const e of c.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(f.has(s)||f.set(s,{sample:s,primarySite:n.primary_site,diseaseType:n.disease_type,projectId:n.project?.project_id,files:[]}),!n.samples?.[0])throw"h.cases[0].samples[0] missing";f.get(s).files.push({fileId:t,sampleName:n.samples[0].submitter_id,sampleType:n.samples[0].sample_type})}return{samples:[...f.values()],fields:e.queries.singleCell.samples.fields,columnNames:e.queries.singleCell.samples.columnNames}}}function D(e,t){e.queries.singleCell.data.get=async t=>{const{host:n,headers:s}=e.getHostHeaders(t),r=(await i()(l().join(n.rest,"data",t.sample),{method:"GET",headers:s})).body.trim().split("\n"),o={name:"UMAP",cells:[],colorBy:"Cluster"},a={name:"TSNE",cells:[],colorBy:"Cluster"},c={name:"PCA",cells:[],colorBy:"Cluster"},f={id:"cluster",name:"Seurat cluster",type:"categorical",values:{}},u={[f.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 i=n[3];if(!i)throw"seuratCluster missing from a line";f.values[i]={label:"Cluster "+i},u[f.id][s]=`Cluster ${i}`;const l=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(l))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 ${i}`;o.cells.push({cellId:s,x:l,y:d,category:y}),a.cells.push({cellId:s,x:p,y:m,category:y}),c.cells.push({cellId:s,x:h,y:g,category:y})}return{plots:[a,o,c],terms:[f],tid2cellvalue:u}}}const L={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],P(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(f(e.filterObj)),t}};function P(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 G={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],P(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(f(e.filterObj)),z(e.tid2value,n.case_filters.content,t),n}};function z(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:()=>u,uK:()=>d});var s=n(1881),r=n(1169),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),f=n(2974);const u=".";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(u);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,f]=r,u=decodeURIComponent(f),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==u&&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}]}),f=await n.queries.snvindel.byrange.get(c);for(const e of f)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,f.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 f=await Promise.all(s);for(const[e,n]of f)for(const[e,s]of v2counts.get(c)){const f=t.cohort.termdb.useLower?e.toLowerCase():e;i?(o.get(c).add(f),r.push({count:s,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:f})):o.get(c).has(f)&&r.push({count:s,id0:a,v0:n.v0,id1:l,v1:n.v1,id2:c,v2:f})}}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:()=>u,Tt:()=>m,TO:()=>f});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 f(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 u(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,f=n.total-s[t.dataId]-(e.total-t.total),u=e.seriesId,d=t.dataId;r.push({index:o,n1:a,n2:l,n3:c,n4:f}),i.set(o,{seriesId:u,dataId:d}),o++}const l={input:r},c=t.cohort.termdb.multipleTestingCorrection;c&&(l.mtc=c.method,c.skipLowSampleSize&&(l.skipLowSampleSize=c.skipLowSampleSize));const f=await(0,a.run_rust)("fisher",JSON.stringify(l)),u=[];for(const e of JSON.parse(f)){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,f=null===l,d=e.adjusted_p_value,p=u.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:f}):u.push({term1comparison:t,term2tests:[{term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:s,R2C1:r,R1C2:o,R2C2:a},isChi:c,skipped:f}]})}e.tests[n.chartId]=u}}(i.data,r,s.hiddenValues),n.send(i)}catch(e){n.send({error:e.message||e}),e.stack&&console.log(e.stack)}}}async function u(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()],f=await(0,l.Yu)({filter:e.filter,terms:a},e.ds,e.genome),u=new Map,d=[];if(f.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,f=l?.id?l.id:l?.name;f&&n.refs.byTermId[f]?.bins?t.push(n.refs.byTermId[f]?.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[f]?i[f].key:"",t.val2=i[f]?i[f].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[f],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,f,u,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&&f.refs.byTermId[s]?.bins?d.push(f.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(f.samples)){let r;if(u.get(t))r=u.get(t);else if(!u.has(t)){r={sample:parseInt(t)},u.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])):u.set(t,null)}else r[`key${e}`]="",r[`val${e}`]=""}}e.results.lst=[...u.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 f=0,u=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?(u+=2,l.has(s)?f+=2:c.has(s)&&f++):(u++,a.has(s)||f++)}return 0==u||0==f?0:(f/u).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),f=n(334),u=n.n(f);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 f=await p(c);return Object.assign(r.data,f),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(u().cachedir,Math.random().toString()+".json");await(0,i.Sf)(t,JSON.stringify(e));const n=await(0,c.default)(r().join(u().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 f=[],u=[],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)}}f.push(h.CTEname),u.push(...h.CTEs),d.push(...h.values)}const p="and"==e.join?"INTERSECT":"UNION",m=f.map((e=>"SELECT * FROM "+e)).join("\n"+p+"\n");return e.in?u.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\t${m}\n\t\t\t\t)\n\t\t\t`):u.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:u.join(",\n"),CTEs:u,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:()=>z,pq:()=>G,TO:()=>P});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)}(a,n,s),function(e,t){if(!t.queries?.singleCell?.data)return;e.singleCell=t.queries.singleCell.data}(a,n),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),f=n(5708),u=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={},f={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="*";f.series.add(a);const l=e.term0&&t[e.term0.id||e.term0.name]||{key:""};l.key in c||(c[l.key]=[],f.chart.add(l.key)),c[l.key].push({time:s,status:r,series:a})}const u=e.term2_id&&a.refs[e.term2.id]?.bins||[],d={keys:["chartId","seriesId","time","survival","lower","upper","nevent","ncensor","nrisk"],case:[],refs:{bins:u}};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,u?u.map((e=>e.name?e.name:e.label)):[]);return d.refs.orderedKeys={chart:[...f.chart].sort(),series:[...f.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);const L=10;function P(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]=G(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,L,e.cohortStr,e.treeFilter,e.usecase,o);a.push(...l.map(z));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 f.update_image(s,n):s.getgroup?await f.getgroup(s,n):await f.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,u.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 G(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 z(e){return JSON.parse(JSON.stringify(e))}},2974:(e,t,n)=>{"use strict";n.d(t,{Yu:()=>u,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),f=n(8599);async function u(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,f._)(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 f=`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")}`,u=e.ds.cohort.db.connection.prepare(f).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 u){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),f=n(2826),u=n(4521),d=n.n(u),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 u=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=f.iK(t.cohort.termdb.q.termjsonByOneid(e.term_id));for(const t of e.categories){const[a,c,f]=x(n,t.group1lst);let u,d,p;t.group2lst?[u,d,p]=x(n,t.group2lst):(u=s-a,d=o-c,p=r-f),a+u+c+d+f+p!=0&&i.push({term:l,group_name:e.group_name,parent_name:e.parent_name,group1label:t.group1label,group2label:t.group2label,table:[f,p,a,u,c,d]})}}return i}(e.filter,n,o,u,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),f=Number(n.rightpad),u=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+f;h.width=b*p;const v=u+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,u,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:u+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,u+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=u,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),f=n(7219),u=n.n(f),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),f=[],u=e.ds.cohort.termdb.ageEndOffset;if(!u)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+u:r};f.push({sample:t.sample,key:n,value:o,term_id:t.term_id})}else f.push(t);for(const{sample:e,term_id:s,key:r,value:o}of f){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:u()(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=[],f=[];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[u,d]=i.split("/");u==r.effAle||d==r.effAle?c.push(t):f.push(t)}o.push({group1_id:s+"_hasEffAllele",group1_values:c,group2_id:s+"_noEffAllele",group2_values:f}),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 f=await(0,a.default)(r().join(p().binpath,"utils/wilcoxon.R"),[],[l]);c().unlink(l,(()=>{}));const u=JSON.parse(f);for(const t of u){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),f=m.JC(r.sort(((e,t)=>e-t)).map((e=>({value:e}))));f.label=`Carry ${0==e.q.alleleType?"minor":"alternative"} allele, n=${r.length}`;const u=m.JC(o.sort(((e,t)=>e-t)).map((e=>({value:e}))));u.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:f,noEff:u}}}};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,f=0,u=0;for(const{sample:s,noOutcome:r}of t){if(r)continue;const t=n.data[u++],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?f++:c++}i.set(o,s);const d={index:o,n1:f,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,f]=l.split("/");o.series=i.effAle==c||i.effAle==f?"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),f=n(8907),u=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]),f=Number(i[2]);if(Number.isNaN(l)||Number.isNaN(f)){a++;continue}const u={sample:i[0],x:l,y:f},d=e.cohort.termdb.q.sampleName2id(i[0]);if(null==d){if(s[3]){u.info={};for(let e=3;e<s.length;e++)u.info[s[e]]=i[e]}r.push(u)}else c++,u.sampleId=d,t.filterableSamples.push(u)}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,u.w)(t.filter,t.ds);let o="";r&&(o+=(0,f.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:()=>f});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 u=e.cohort.termdb.q;if(s.has("buildDate")&&(u.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;u.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(u.id2sampleName=e=>t.get(e),u.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;u.getcohortsamplecount=e=>e?t[e]||0:o}else u.getcohortsamplecount=()=>o}if(s.has("category2vcfsample")){const e=n.prepare("SELECT * FROM category2vcfsample");let t;u.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;u.getAlltermsbyorder=()=>{if(t)return t;const n=e.all();t=[];for(const e of n){const n=u.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;u.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;u.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;u.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;u.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;u.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;u.getTermParent=t=>{if(e.has(t))return e.get(t);const n=u.getTermParentId(t);let s;return n&&(s=u.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;u.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 ?");u.findTermByName=(t,n=10,s="",r=null,o=null,a=null)=>{const l=e.all([s,"%"+t+"%"]);if(l){const e=a||{equals:[],startsWith:[],startsWord:[],includes:[]};for(const n of l){if(!n.jsondata)continue;const s=n.name.toLowerCase(),r=JSON.parse(n.jsondata);r.id=n.id,r.name=n.name||r.name,r.included_types=n.included_types?n.included_types.split(","):[],o&&!(0,i.CG)(r,o).has("plot")||(s===t?e.equals.push(r):s.startsWith(t)?e.startsWith.push(r):s.includes(" "+t)?e.startsWord.push(r):e.includes.push(r))}return[...e.equals,...e.startsWith,...e.startsWord,...e.includes].slice(0,n)}}}{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;u.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=?")};u.getAllValues4term=t=>{const n=u.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;u.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;u.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=?")};u.getSample2value=(n,r=null)=>{const o=u.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;u.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}}}u.getSupportedChartTypes=t=>{f(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")}return n},u.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])},u.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 f(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)),f=n.n(c),u=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(f().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(f().cache_snpgt.dir,e.cacheid))).split("\n"),u=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=f().cache_snpgt.sampleColumn;e<t.length;e++){const n=t[e];if(!n)continue;if(!o[e-f().cache_snpgt.sampleColumn])continue;u.add(r.samples[e-f().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:u.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(f().cachedir,await a.tG(l.join("\n"))),u=i().join(f().cachedir,await a.tG([...o].join("\n")));await a.UE({isbcf:!0,args:["query","-R",c,"-f",d,"-v",u],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(u,(()=>{}));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(f().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(","),f={snpid:c,chr:e.chr,pos:r};(0,u.H)(o,a,l,f,s[4],s[1]);for(const e of f.mlst)e.vcf_id&&(e.mname=e.vcf_id);g.snps.push(f);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(f().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:()=>u,continuous:()=>l,cubicSpline:()=>c,discrete:()=>f});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,f={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 f=[];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;f.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 u="bin_defs_"+o,d=C(t,s,"a");r.push(...d.values);return{sql:`${u} 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 ${u} 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${f.length?"value NOT IN ("+f.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}}},u=f,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"),f=`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(f).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=[],u=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(!u.has(e[n.groupby])){const t=Object.assign({samplecount:0},e);c.push(t),u.set(e[n.groupby],t)}u.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(f,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 f=l&&l.type?l:e.ds.cohort.termdb.q.termjsonByOneid(c);if(!f)throw`no term found by id='${c}'`;let u=a&&a.q||e["term"+n+"_q"]||{};"string"==typeof u&&(u=JSON.parse(decodeURIComponent(u)));const d="samplekey_"+n;let p;if("categorical"==f.type){const n=j(f,u);p=await r[n?"groupset":"values"].getCTE(d,f,e.ds,u,t,n)}else if("integer"==f.type||"float"==f.type){const r="spline"==u.mode?"cubicSpline":u.mode||"discrete";p=await s[r].getCTE(d,f,e.ds,u,t,n,i)}else if("condition"==f.type){const n=u.mode||"discrete";p=await o[n].getCTE(d,f,e.ds,u,t)}else if("survival"==f.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,f,0,t,i);else{if("samplelst"!=f.type)throw"unknown term type";p=await _.getCTE(d,a||{term:f,q:u},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 f=`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(","):""}`,u=e.cohort.db.connection.prepare(f).all(r),d=u.length?u[0]:{};return d.max=u[0].vmax,d.min=u[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:()=>z,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:()=>U,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),f=n(2273),u=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(f=s,d=e.dir,new Promise(((e,t)=>{const n=(0,a.spawn)(A,["view","-h",f],{cwd:d}),s=[];n.stdout.on("data",(e=>s.push(e))),n.on("close",(()=>{e(u.e(s.join("").trim().split("\n")))}))}))):await async function(e,t){return u.e(await z(e,t))}(s,e.dir);var f,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)}}),f.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 z(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}),f=c().createInterface({input:l.stdout}),u=[];f.on("line",(e=>n(e,l))),l.stderr.on("data",(e=>u.push(e))),l.on("close",(()=>{const e=u.join("").trim();e&&!ne(e)&&i(e),o()}))}))}function U(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 U(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 f.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 f=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:f}}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,f){const u=(0,s.w)(l);for(const t in e.info){if("A"==e.info[t].Number&&t in u&&(u[t]=u[t].split(",")),e.info[t].separator&&t in u){const n=u[t].split(e.info[t].separator);n.length>1&&(u[t]=n)}if("Float"==e.info[t].Type||"Integer"==e.info[t].Type)if(Array.isArray(u[t])){const e=u[t].map(Number);u[t]=e}else u[t]=Number(u[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&&u.CSQ&&(0,r.A)(u.CSQ,e.info.CSQ.csqheader,a);const d={};f&&(d.usegm={isoform:f});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 u)"A"==e.info?.[t]?.Number?s.info[t]=u[t][n]:s.info[t]=u[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:()=>f,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,f=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:()=>fe,median:()=>ue,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:()=>ze,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?(f(a,c,r,o,i),f(a,r,c,o,i),f(a,c,r,o,i),u(l,r,c,o,i),u(l,c,r,o,i),u(l,r,c,o,i)):a?(f(a,r,c,o,i),f(a,c,r,o,i),f(a,r,c,o,i)):l&&(u(l,r,c,o,i),u(l,c,r,o,i),u(l,r,c,o,i)),t}}function f(e,t,n,s,r){for(let o=0,i=s*r;o<i;)e(t,n,o,o+=s,1)}function u(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,f=c+a;for(let e=o,t=o+c;e<t;e+=a)l+=r[Math.min(i,e)];for(let t=o,u=i;t<=u;t+=a)l+=r[Math.min(i,t+c)],e[t]=(l+n*(r[Math.max(o,t-f)]+r[Math.min(i,t+f)]))/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=z(s[e],s[n]);if(t)return t}}))):(n=e.map(n),s.sort(((e,t)=>z(n[e],n[t])))),L(e,s)}return e.sort(G(n))}function G(e=r.Z){if(e===r.Z)return z;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 z(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 U=Array.prototype,J=U.slice;U.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 f=t(c),u=f[0],d=f[1],p=n(c,u,d);if(!Array.isArray(p)){const e=d,n=+p;if(t===k&&([u,d]=V(u,d,n)),(p=(0,W.ZP)(u,d,n))[0]<=u&&(a=(0,W.G9)(u,d,n)),p[p.length-1]>=d)if(e>=d&&t===k){const e=(0,W.G9)(u,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]<=u;)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]:u,h.x1=o<m?p[o]:d;if(isFinite(a)){if(a>0)for(o=0;o<l;++o)null!=(i=c[o])&&u<=i&&i<=d&&g[Math.min(m,Math.floor((i-u)/a))].push(r[o]);else if(a<0)for(o=0;o<l;++o)if(null!=(i=c[o])&&u<=i&&i<=d){const e=Math.floor((u-i)*a);g[Math.min(m,e+(p[e]<=i))].push(r[o])}}else for(o=0;o<l;++o)null!=(i=c[o])&&u<=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?z: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)=>z(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 fe(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 ue(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)=>z(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 ze(...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*",f="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",u=/^#([0-9a-f]{3,8})$/,d=new RegExp(`^rgb\\(${l},${l},${l}\\)$`),p=new RegExp(`^rgb\\(${f},${f},${f}\\)$`),m=new RegExp(`^rgba\\(${l},${l},${l},${c}\\)$`),h=new RegExp(`^rgba\\(${f},${f},${f},${c}\\)$`),g=new RegExp(`^hsl\\(${c},${f},${f}\\)$`),y=new RegExp(`^hsla\\(${c},${f},${f},${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=u.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:()=>u,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 f,u,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]+"",f=void 0===e.currency?"":e.currency[1]+"",u=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?f:/[%p]/.test(k)?h:"",N=l[k],S=/[defgprs%]/.test(k);function A(e){var r,a,l,c=q,f=x;if("c"===k)f=N(e)+f,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,f=("s"===k?m[8+o/3]:"")+f+(h&&"("===s?")":""),S)for(r=-1,a=e.length;++r<a;)if(48>(l=e.charCodeAt(r))||l>57){f=(46===l?u+e.slice(r+1):e.slice(r))+f,e=e.slice(0,r);break}}v&&!p&&(e=i(e,1/0));var A=c.length+e.length+f.length,C=A<b?new Array(b-A+1).join(t):"";switch(v&&p&&(e=i(C+e,C.length?b-f.length:1/0),C=""),n){case"<":e=c+e+f+C;break;case"=":e=c+C+e+f;break;case"^":e=C.slice(0,A=C.length>>1)+c+e+f+C.slice(A);break;default:e=C+c+e+f}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}}}}f=h({thousands:",",grouping:[3],currency:["$",""]}),u=f.format,d=f.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 f(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+""}}}f((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)}})),f((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,f=[],u=[];for(e+="",t+="";(n=r.exec(e))&&(i=o.exec(t));)(a=i.index)>l&&(a=t.slice(l,a),f[c]?f[c]+=a:f[++c]=a),(n=n[0])===(i=i[0])?f[c]?f[c]+=i:f[++c]=i:(f[++c]=null,u.push({i:c,x:(0,s.Z)(n,i)})),l=o.lastIndex;return l<t.length&&(a=t.slice(l),f[c]?f[c]+=a:f[++c]=a),f.length<2?u[0]?function(e){return function(t){return e(t)+""}}(u[0].x):function(e){return function(){return e}}(t):(t=u.length,function(e){for(var n,s=0;s<t;++s)f[(n=u[s]).i]=n.x(e);return f.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 f=n(9009),u=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,u.Z)(t):("number"===p?l.Z:"string"===p?(n=(0,r.ZP)(t))?(t=n,o.ZP):f.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,f=y;function u(){var e,t,n,l=Math.min(i.length,a.length);return f!==y&&(e=i[0],t=i[l-1],e>t&&(n=e,e=t,t=n),f=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(f(t)))}return d.invert=function(n){return f(t((o||(o=s(a,i.map(e),l.Z)))(n)))},d.domain=function(e){return arguments.length?(i=Array.from(e,h),u()):i.slice()},d.range=function(e){return arguments.length?(a=Array.from(e),u()):a.slice()},d.rangeRound=function(e){return a=Array.from(e),c=m,u()},d.clamp=function(e){return arguments.length?(f=!!e||y,u()):f!==y},d.interpolate=function(e){return arguments.length?(c=e,u()):c},d.unknown=function(e){return arguments.length?(n=e,d):n},function(n,s){return e=n,t=s,u()}}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:()=>f});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 f=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,f))||(r.precision=o),(0,l.jH)(r,f);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 f(){var e=(0,r.ZP)();return e.copy=function(){return(0,r.JG)(e,f())},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],f=i[l],u=10;for(f<c&&(o=c,c=f,f=o,o=a,a=l,l=o);u-- >0;){if((o=(0,s.G9)(c,f,n))===r)return i[a]=c,i[l]=f,t(i);if(o>0)c=Math.floor(c/o)*o,f=Math.ceil(f/o)*o;else{if(!(o<0))break;c=Math.ceil(c*o)/o,f=Math.floor(f*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:()=>zt.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 f(e){return function(t){return t.matches(e)}}var u=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,f=new Map,u=t.length,d=o.length,p=new Array(u);for(a=0;a<u;++a)(l=t[a])&&(p[a]=c=i.call(l,l.__data__,a,t)+"",f.has(c)?r[a]=l:f.set(c,l));for(a=0;a<d;++a)c=i.call(e,o[a],a,o)+"",(l=f.get(c))?(s[a]=l,l.__data__=o[a],f.delete(c)):n[a]=new g(e,o[a]);for(a=0;a<u;++a)(l=t[a])&&f.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 z(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 U(e){return function(){z(this,e)}}function J(e){return function(){B(this,e)}}function H(e,t){return function(){(t.apply(this,arguments)?z: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 fe(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 ue(e,t){return function(){return fe(this,e,t)}}function de(e,t){return function(){return fe(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,f=s[r]=new Array(c),u=0;u<c;++u)(i=l[u])&&(a=e.call(i,i.__data__,u,l))&&("__data__"in i&&(a.__data__=i.__data__),f[u]=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],f=c.length,u=0;u<f;++u)(i=c[u])&&(s.push(e.call(i,i.__data__,u,c)),r.push(i));return new me(s,r)},selectChild:function(e){return this.select(null==e?d:function(e){return function(){return u.call(this.children,e)}}("function"==typeof e?e:f(e)))},selectChildren:function(e){return this.selectAll(null==e?m:function(e){return function(){return p.call(this.children,e)}}("function"==typeof e?e:f(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]=[],f=0;f<a;++f)(o=i[f])&&e.call(o,o.__data__,f,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),f=0;f<i;++f){var u=r[f],d=o[f],p=d.length,m=w(e.call(u,u&&u.__data__,f,r)),h=m.length,g=l[f]=new Array(h),_=a[f]=new Array(h);s(u,d,g,_,c[f]=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,f=n[l],u=s[l],d=f.length,p=a[l]=new Array(d),m=0;m<d;++m)(c=f[m]||u[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),f=0;f<l;++f)(i=a[f])&&(c[f]=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?U: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,f=a.length;c<f;++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:ue)(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 ze=ke("start","end","cancel","interrupt"),Be=[],Ue=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,f,u,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(u=n.tween.length),c=0,f=-1;c<u;++c)(d=n.tween[c].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=d);s.length=f+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:ze,tween:Be,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:Ue})}function Ye(e,t){var n=et(e,t);if(n.state>Ue)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 ft(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 ut(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,f=s[a],u=f.length,d=i[a]=new Array(u),p=0;p<u;++p)(l=f[p])&&(c=e.call(l,l.__data__,p,f))&&("__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,f=s[l],u=f.length,d=0;d<u;++d)if(c=f[d]){for(var p,m=e.call(c,c.__data__,d,f),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]=[],f=0;f<a;++f)(o=i[f])&&e.call(o,o.__data__,f,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],f=n[a],u=c.length,d=i[a]=new Array(u),p=0;p<u;++p)(l=c[p]||f[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 f=et(i,t);Xe(i,e,n,c,a,{time:f.time+f.delay+f.duration,delay:0,duration:f.duration,ease:f.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,ut(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,ut(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,f=null==l.value[i]?o||(o=jt(t)):void 0;c===n&&r===f||(s=(n=c).copy()).on(a,r=f),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}}(ut(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:ft)(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 zt=n(8877),Bt=n(6106),Ut=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,f,u=s(i),d=s(a);const p=null==e?10:+e;let m=[];if(!(o%1)&&d-u<p){if(u=Math.floor(u),d=Math.ceil(d),i>0){for(;u<=d;++u)for(c=1;c<o;++c)if(f=u<0?c/r(-u):c*r(u),!(f<i)){if(f>a)break;m.push(f)}}else for(;u<=d;++u)for(c=o-1;c>=1;--c)if(f=u>0?c/r(-u):c*r(u),!(f<i)){if(f>a)break;m.push(f)}2*m.length<p&&(m=(0,Bt.ZP)(i,a,p))}else m=(0,Bt.ZP)(u,d,Math.min(d-u,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,Ut.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)}))})()})();
2
2
  //# sourceMappingURL=server.js.map