@idetik/core 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4119,7 +4119,7 @@ return ret;
4119
4119
  `,JC=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",LC],{type:"text/javascript;charset=utf-8"});function eo(g){let A;try{if(A=JC&&(self.URL||self.webkitURL).createObjectURL(JC),!A)throw"";const I=new Worker(A,{type:"module",name:g?.name});return I.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(A)}),I}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(LC),{type:"module",name:g?.name})}}const Ho=Math.max(1,navigator.hardwareConcurrency-2);let AI=[],qo=0,rC=0;const YI=new Map,iB=new Set;function nC(g){const A=AI.find(I=>I.worker===g);return A||V.error("ZarrWorker","Worker not found in pool - this should not happen"),A}function fo(g,A){const{id:I,success:B}=g.data,Q=YI.get(I);if(!Q){iB.has(I)?iB.delete(I):V.warn("ZarrWorker",`Received response for unknown message ID ${I}:`,g.data);return}YI.delete(I),Q.abortListener&&Q.abortSignal&&Q.abortSignal.removeEventListener("abort",Q.abortListener);const C=nC(A);C&&C.pendingCount>0?C.pendingCount--:C&&V.error("ZarrWorker","Received message but no pending tasks - this should not happen"),B&&g.data.type==="getChunk"?Q.resolve(g.data.data):B||Q.reject(new Error(g.data.error||"Unknown worker error"))}function YC(g,A){if(g instanceof MessageEvent){V.error("ZarrWorker","Message serialization error occurred - worker remains active");return}V.error("ZarrWorker","Worker failed - replacing worker and canceling its in-flight messages",g.message);const I=nC(A);if(I){const Q=AI.indexOf(I);AI.splice(Q,1)}const B=I?.workerId;if(B!==void 0)for(const[Q,C]of YI.entries())C.workerId===B&&(C.reject(new Error(`Worker error: ${g.message}`)),YI.delete(Q));try{const Q=KC();AI.push({worker:Q,pendingCount:0,workerId:rC++}),V.debug("ZarrWorker","Replacement worker created successfully")}catch(Q){V.error("ZarrWorker","Failed to create replacement worker",Q)}}function KC(){const g=new eo;return g.addEventListener("message",A=>fo(A,g)),g.addEventListener("error",A=>YC(A,g)),g.addEventListener("messageerror",A=>YC(A,g)),g}function lo(){if(AI.length===0)throw new Error("Worker pool is not initialized");return AI.sort((g,A)=>g.pendingCount-A.pendingCount)[0]}async function po(g,A,I,B){return new Promise((Q,C)=>{const E=lo(),i=qo++,D={resolve:Q,reject:C,workerId:E.workerId};if(YI.set(i,D),B?.signal){const a=()=>{E.worker.postMessage({id:i,type:"cancel"}),YI.delete(i),iB.add(i),E.pendingCount--,C(new DOMException("Operation was aborted","AbortError"))};if(B.signal.aborted){a(),iB.delete(i);return}B.signal.addEventListener("abort",a,{once:!0}),D.abortListener=a,D.abortSignal=B.signal}E.pendingCount++,E.worker.postMessage({id:i,type:"getChunk",arrayParams:g,index:A,sliceSpec:I})})}function Wo(){if(!(AI.length>0))try{for(let g=0;g<Ho;g++){const A=KC();AI.push({worker:A,pendingCount:0,workerId:rC++})}V.debug("ZarrWorker",`Initialized worker pool with ${AI.length} workers`)}catch{V.warn("ZarrWorker","Failed to create workers - clearing pool"),To();return}}async function mo(g,A,I,B,Q){Wo();try{return await po(A,I,B,Q)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;V.warn("ZarrWorker","Falling back to main thread",C);const E=await g.getChunk(I,Q);if(!Li(E.data))throw new Error(`Unsupported chunk data type: ${E.data.constructor.name}`);return Ko(E.data,E.shape,E.stride,B)}}function To(){for(const g of AI)g.worker.terminate();AI=[],YI.clear()}class xo{metadata_;arrays_;arrayParams_;dimensions_;bytesPerElement_;constructor(A){this.metadata_=A.metadata,this.arrays_=A.arrays,this.arrayParams_=A.arrayParams,this.dimensions_=uo(this.metadata_,this.arrays_),this.bytesPerElement_=Zo(this.arrays_[0].dtype)}getSourceDimensionMap(){return this.dimensions_}getBytesPerElement(){return this.bytesPerElement_}async loadChunkData(A,I){const B=[];if(B[this.dimensions_.x.index]=A.chunkIndex.x,B[this.dimensions_.y.index]=A.chunkIndex.y,this.dimensions_.z&&(B[this.dimensions_.z.index]=A.chunkIndex.z),this.dimensions_.c){const R=this.dimensions_.c.lods[A.lod];B[this.dimensions_.c.index]=Math.floor(A.chunkIndex.c/R.chunkSize)}if(this.dimensions_.t){const R=this.dimensions_.t.lods[A.lod];B[this.dimensions_.t.index]=Math.floor(A.chunkIndex.t/R.chunkSize)}const Q=this.arrays_[A.lod],C=this.arrayParams_[A.lod],E=this.dimensions_.c?.lods[A.lod],i=this.dimensions_.t?.lods[A.lod],D={targetShape:A.shape,chunkIndex:{c:A.chunkIndex.c,t:A.chunkIndex.t},dimIndices:{x:this.dimensions_.x.index,y:this.dimensions_.y.index,z:this.dimensions_.z?.index,c:this.dimensions_.c?.index,t:this.dimensions_.t?.index},cChunkSize:E?.chunkSize,tChunkSize:i?.chunkSize},a=await mo(Q,C,B,D,{signal:I}),G=a.BYTES_PER_ELEMENT;if(!yi(G))throw new Error("Invalid row alignment value. Possible values are 1, 2, 4, or 8");A.rowAlignmentBytes=G,ki(A,a)}}const MC={int8:1,uint8:1,int16:2,uint16:2,int32:4,uint32:4,float32:4};function Zo(g){const A=MC[g];if(A===void 0)throw new Error(`Unsupported zarr dtype "${g}". Supported dtypes: ${Object.keys(MC).join(", ")}`);return A}function uo(g,A){const I=g.axes.map(R=>R.name),B=g.axes.length,Q=eC(I,"x"),C=eC(I,"y"),E=(R,U)=>{const J=[];for(let r=0;r<g.datasets.length;r++){const H=g.datasets[r],K=A[r],l=H.coordinateTransformations[0].scale,O=H.coordinateTransformations.length===2?H.coordinateTransformations[1].translation:new Array(B).fill(0);J.push({size:K.shape[U],chunkSize:K.chunks[U],scale:l[U],translation:O[U]})}if(g.axes[U].type==="space"&&Po(J))for(const r of J)r.translation-=.5*r.scale;return{name:R,index:U,unit:g.axes[U].unit,lods:J}},i={x:E(I[Q],Q),y:E(I[C],C),numLods:A.length},D=oB(I,"z");D!==-1&&(i.z=E(I[D],D));const a=oB(I,"c");a!==-1&&(i.c=E(I[a],a));const G=oB(I,"t");return G!==-1&&(i.t=E(I[G],G)),i}function bo(g,A){return g.toLowerCase()===A.toLowerCase()}function eC(g,A){const I=oB(g,A);if(I===-1)throw new Error(`Could not find "${A}" dimension in [${g.join(", ")}]`);return I}function oB(g,A){return g.findIndex(I=>bo(I,A))}function Po(g){if(g.length<=1)return!1;for(let A=1;A<g.length;A++){const I=.5*(g[A].scale-g[A-1].scale),B=g[A].translation-g[A-1].translation;if(Math.abs(B-I)>1e-6)return!1}return!0}var DA;(function(g){g.assertEqual=Q=>{};function A(Q){}g.assertIs=A;function I(Q){throw new Error}g.assertNever=I,g.arrayToEnum=Q=>{const C={};for(const E of Q)C[E]=E;return C},g.getValidEnumValues=Q=>{const C=g.objectKeys(Q).filter(i=>typeof Q[Q[i]]!="number"),E={};for(const i of C)E[i]=Q[i];return g.objectValues(E)},g.objectValues=Q=>g.objectKeys(Q).map(function(C){return Q[C]}),g.objectKeys=typeof Object.keys=="function"?Q=>Object.keys(Q):Q=>{const C=[];for(const E in Q)Object.prototype.hasOwnProperty.call(Q,E)&&C.push(E);return C},g.find=(Q,C)=>{for(const E of Q)if(C(E))return E},g.isInteger=typeof Number.isInteger=="function"?Q=>Number.isInteger(Q):Q=>typeof Q=="number"&&Number.isFinite(Q)&&Math.floor(Q)===Q;function B(Q,C=" | "){return Q.map(E=>typeof E=="string"?`'${E}'`:E).join(C)}g.joinValues=B,g.jsonStringifyReplacer=(Q,C)=>typeof C=="bigint"?C.toString():C})(DA||(DA={}));var HC;(function(g){g.mergeShapes=(A,I)=>({...A,...I})})(HC||(HC={}));const u=DA.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yI=g=>{switch(typeof g){case"undefined":return u.undefined;case"string":return u.string;case"number":return Number.isNaN(g)?u.nan:u.number;case"boolean":return u.boolean;case"function":return u.function;case"bigint":return u.bigint;case"symbol":return u.symbol;case"object":return Array.isArray(g)?u.array:g===null?u.null:g.then&&typeof g.then=="function"&&g.catch&&typeof g.catch=="function"?u.promise:typeof Map<"u"&&g instanceof Map?u.map:typeof Set<"u"&&g instanceof Set?u.set:typeof Date<"u"&&g instanceof Date?u.date:u.object;default:return u.unknown}},q=DA.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class iI extends Error{get errors(){return this.issues}constructor(A){super(),this.issues=[],this.addIssue=B=>{this.issues=[...this.issues,B]},this.addIssues=(B=[])=>{this.issues=[...this.issues,...B]};const I=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,I):this.__proto__=I,this.name="ZodError",this.issues=A}format(A){const I=A||function(C){return C.message},B={_errors:[]},Q=C=>{for(const E of C.issues)if(E.code==="invalid_union")E.unionErrors.map(Q);else if(E.code==="invalid_return_type")Q(E.returnTypeError);else if(E.code==="invalid_arguments")Q(E.argumentsError);else if(E.path.length===0)B._errors.push(I(E));else{let i=B,D=0;for(;D<E.path.length;){const a=E.path[D];D===E.path.length-1?(i[a]=i[a]||{_errors:[]},i[a]._errors.push(I(E))):i[a]=i[a]||{_errors:[]},i=i[a],D++}}};return Q(this),B}static assert(A){if(!(A instanceof iI))throw new Error(`Not a ZodError: ${A}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,DA.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(A=I=>I.message){const I={},B=[];for(const Q of this.issues)if(Q.path.length>0){const C=Q.path[0];I[C]=I[C]||[],I[C].push(A(Q))}else B.push(A(Q));return{formErrors:B,fieldErrors:I}}get formErrors(){return this.flatten()}}iI.create=g=>new iI(g);const CQ=(g,A)=>{let I;switch(g.code){case q.invalid_type:g.received===u.undefined?I="Required":I=`Expected ${g.expected}, received ${g.received}`;break;case q.invalid_literal:I=`Invalid literal value, expected ${JSON.stringify(g.expected,DA.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:I=`Unrecognized key(s) in object: ${DA.joinValues(g.keys,", ")}`;break;case q.invalid_union:I="Invalid input";break;case q.invalid_union_discriminator:I=`Invalid discriminator value. Expected ${DA.joinValues(g.options)}`;break;case q.invalid_enum_value:I=`Invalid enum value. Expected ${DA.joinValues(g.options)}, received '${g.received}'`;break;case q.invalid_arguments:I="Invalid function arguments";break;case q.invalid_return_type:I="Invalid function return type";break;case q.invalid_date:I="Invalid date";break;case q.invalid_string:typeof g.validation=="object"?"includes"in g.validation?(I=`Invalid input: must include "${g.validation.includes}"`,typeof g.validation.position=="number"&&(I=`${I} at one or more positions greater than or equal to ${g.validation.position}`)):"startsWith"in g.validation?I=`Invalid input: must start with "${g.validation.startsWith}"`:"endsWith"in g.validation?I=`Invalid input: must end with "${g.validation.endsWith}"`:DA.assertNever(g.validation):g.validation!=="regex"?I=`Invalid ${g.validation}`:I="Invalid";break;case q.too_small:g.type==="array"?I=`Array must contain ${g.exact?"exactly":g.inclusive?"at least":"more than"} ${g.minimum} element(s)`:g.type==="string"?I=`String must contain ${g.exact?"exactly":g.inclusive?"at least":"over"} ${g.minimum} character(s)`:g.type==="number"?I=`Number must be ${g.exact?"exactly equal to ":g.inclusive?"greater than or equal to ":"greater than "}${g.minimum}`:g.type==="bigint"?I=`Number must be ${g.exact?"exactly equal to ":g.inclusive?"greater than or equal to ":"greater than "}${g.minimum}`:g.type==="date"?I=`Date must be ${g.exact?"exactly equal to ":g.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(g.minimum))}`:I="Invalid input";break;case q.too_big:g.type==="array"?I=`Array must contain ${g.exact?"exactly":g.inclusive?"at most":"less than"} ${g.maximum} element(s)`:g.type==="string"?I=`String must contain ${g.exact?"exactly":g.inclusive?"at most":"under"} ${g.maximum} character(s)`:g.type==="number"?I=`Number must be ${g.exact?"exactly":g.inclusive?"less than or equal to":"less than"} ${g.maximum}`:g.type==="bigint"?I=`BigInt must be ${g.exact?"exactly":g.inclusive?"less than or equal to":"less than"} ${g.maximum}`:g.type==="date"?I=`Date must be ${g.exact?"exactly":g.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(g.maximum))}`:I="Invalid input";break;case q.custom:I="Invalid input";break;case q.invalid_intersection_types:I="Intersection results could not be merged";break;case q.not_multiple_of:I=`Number must be a multiple of ${g.multipleOf}`;break;case q.not_finite:I="Number must be finite";break;default:I=A.defaultError,DA.assertNever(g)}return{message:I}};let Oo=CQ;function Vo(){return Oo}const Xo=g=>{const{data:A,path:I,errorMaps:B,issueData:Q}=g,C=[...I,...Q.path||[]],E={...Q,path:C};if(Q.message!==void 0)return{...Q,path:C,message:Q.message};let i="";const D=B.filter(a=>!!a).slice().reverse();for(const a of D)i=a(E,{data:A,defaultError:i}).message;return{...Q,path:C,message:i}};function m(g,A){const I=Vo(),B=Xo({issueData:A,data:g.data,path:g.path,errorMaps:[g.common.contextualErrorMap,g.schemaErrorMap,I,I===CQ?void 0:CQ].filter(Q=>!!Q)});g.common.issues.push(B)}class VA{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(A,I){const B=[];for(const Q of I){if(Q.status==="aborted")return z;Q.status==="dirty"&&A.dirty(),B.push(Q.value)}return{status:A.value,value:B}}static async mergeObjectAsync(A,I){const B=[];for(const Q of I){const C=await Q.key,E=await Q.value;B.push({key:C,value:E})}return VA.mergeObjectSync(A,B)}static mergeObjectSync(A,I){const B={};for(const Q of I){const{key:C,value:E}=Q;if(C.status==="aborted"||E.status==="aborted")return z;C.status==="dirty"&&A.dirty(),E.status==="dirty"&&A.dirty(),C.value!=="__proto__"&&(typeof E.value<"u"||Q.alwaysSet)&&(B[C.value]=E.value)}return{status:A.value,value:B}}}const z=Object.freeze({status:"aborted"}),ng=g=>({status:"dirty",value:g}),zA=g=>({status:"valid",value:g}),qC=g=>g.status==="aborted",dC=g=>g.status==="dirty",XI=g=>g.status==="valid",DB=g=>typeof Promise<"u"&&g instanceof Promise;var b;(function(g){g.errToObj=A=>typeof A=="string"?{message:A}:A||{},g.toString=A=>typeof A=="string"?A:A?.message})(b||(b={}));class hI{constructor(A,I,B,Q){this._cachedPath=[],this.parent=A,this.data=I,this._path=B,this._key=Q}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const fC=(g,A)=>{if(XI(A))return{success:!0,data:A.value};if(!g.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const I=new iI(g.common.issues);return this._error=I,this._error}}};function gA(g){if(!g)return{};const{errorMap:A,invalid_type_error:I,required_error:B,description:Q}=g;if(A&&(I||B))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return A?{errorMap:A,description:Q}:{errorMap:(E,i)=>{const{message:D}=g;return E.code==="invalid_enum_value"?{message:D??i.defaultError}:typeof i.data>"u"?{message:D??B??i.defaultError}:E.code!=="invalid_type"?{message:i.defaultError}:{message:D??I??i.defaultError}},description:Q}}class oA{get description(){return this._def.description}_getType(A){return yI(A.data)}_getOrReturnCtx(A,I){return I||{common:A.parent.common,data:A.data,parsedType:yI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}_processInputParams(A){return{status:new VA,ctx:{common:A.parent.common,data:A.data,parsedType:yI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}}_parseSync(A){const I=this._parse(A);if(DB(I))throw new Error("Synchronous parse encountered promise.");return I}_parseAsync(A){const I=this._parse(A);return Promise.resolve(I)}parse(A,I){const B=this.safeParse(A,I);if(B.success)return B.data;throw B.error}safeParse(A,I){const B={common:{issues:[],async:I?.async??!1,contextualErrorMap:I?.errorMap},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:yI(A)},Q=this._parseSync({data:A,path:B.path,parent:B});return fC(B,Q)}"~validate"(A){const I={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:yI(A)};if(!this["~standard"].async)try{const B=this._parseSync({data:A,path:[],parent:I});return XI(B)?{value:B.value}:{issues:I.common.issues}}catch(B){B?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),I.common={issues:[],async:!0}}return this._parseAsync({data:A,path:[],parent:I}).then(B=>XI(B)?{value:B.value}:{issues:I.common.issues})}async parseAsync(A,I){const B=await this.safeParseAsync(A,I);if(B.success)return B.data;throw B.error}async safeParseAsync(A,I){const B={common:{issues:[],contextualErrorMap:I?.errorMap,async:!0},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:yI(A)},Q=this._parse({data:A,path:B.path,parent:B}),C=await(DB(Q)?Q:Promise.resolve(Q));return fC(B,C)}refine(A,I){const B=Q=>typeof I=="string"||typeof I>"u"?{message:I}:typeof I=="function"?I(Q):I;return this._refinement((Q,C)=>{const E=A(Q),i=()=>C.addIssue({code:q.custom,...B(Q)});return typeof Promise<"u"&&E instanceof Promise?E.then(D=>D?!0:(i(),!1)):E?!0:(i(),!1)})}refinement(A,I){return this._refinement((B,Q)=>A(B)?!0:(Q.addIssue(typeof I=="function"?I(B,Q):I),!1))}_refinement(A){return new _I({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:A}})}superRefine(A){return this._refinement(A)}constructor(A){this.spa=this.safeParseAsync,this._def=A,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:I=>this["~validate"](I)}}optional(){return wI.create(this,this._def)}nullable(){return $I.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return QI.create(this)}promise(){return hB.create(this,this._def)}or(A){return sB.create([this,A],this._def)}and(A){return yB.create(this,A,this._def)}transform(A){return new _I({...gA(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:A}})}default(A){const I=typeof A=="function"?A:()=>A;return new sQ({...gA(this._def),innerType:this,defaultValue:I,typeName:_.ZodDefault})}brand(){return new SD({typeName:_.ZodBranded,type:this,...gA(this._def)})}catch(A){const I=typeof A=="function"?A:()=>A;return new yQ({...gA(this._def),innerType:this,catchValue:I,typeName:_.ZodCatch})}describe(A){const I=this.constructor;return new I({...this._def,description:A})}pipe(A){return hQ.create(this,A)}readonly(){return GQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const vo=/^c[^\s-]{8,}$/i,jo=/^[0-9a-z]+$/,zo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_o=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,$o=/^[a-z0-9_-]{21}$/i,AD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ID=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,gD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,BD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let EQ;const QD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,CD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ED=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iD=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,oD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,DD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lC="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aD=new RegExp(`^${lC}$`);function pC(g){let A="[0-5]\\d";g.precision?A=`${A}\\.\\d{${g.precision}}`:g.precision==null&&(A=`${A}(\\.\\d+)?`);const I=g.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${A})${I}`}function sD(g){return new RegExp(`^${pC(g)}$`)}function yD(g){let A=`${lC}T${pC(g)}`;const I=[];return I.push(g.local?"Z?":"Z"),g.offset&&I.push("([+-]\\d{2}:?\\d{2})"),A=`${A}(${I.join("|")})`,new RegExp(`^${A}$`)}function hD(g,A){return!!((A==="v4"||!A)&&QD.test(g)||(A==="v6"||!A)&&ED.test(g))}function GD(g,A){if(!AD.test(g))return!1;try{const[I]=g.split(".");if(!I)return!1;const B=I.replace(/-/g,"+").replace(/_/g,"/").padEnd(I.length+(4-I.length%4)%4,"="),Q=JSON.parse(atob(B));return!(typeof Q!="object"||Q===null||"typ"in Q&&Q?.typ!=="JWT"||!Q.alg||A&&Q.alg!==A)}catch{return!1}}function FD(g,A){return!!((A==="v4"||!A)&&CD.test(g)||(A==="v6"||!A)&&iD.test(g))}class GI extends oA{_parse(A){if(this._def.coerce&&(A.data=String(A.data)),this._getType(A)!==u.string){const C=this._getOrReturnCtx(A);return m(C,{code:q.invalid_type,expected:u.string,received:C.parsedType}),z}const B=new VA;let Q;for(const C of this._def.checks)if(C.kind==="min")A.data.length<C.value&&(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),B.dirty());else if(C.kind==="max")A.data.length>C.value&&(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),B.dirty());else if(C.kind==="length"){const E=A.data.length>C.value,i=A.data.length<C.value;(E||i)&&(Q=this._getOrReturnCtx(A,Q),E?m(Q,{code:q.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}):i&&m(Q,{code:q.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}),B.dirty())}else if(C.kind==="email")gD.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"email",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="emoji")EQ||(EQ=new RegExp(BD,"u")),EQ.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"emoji",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="uuid")_o.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"uuid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="nanoid")$o.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"nanoid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="cuid")vo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"cuid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="cuid2")jo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"cuid2",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="ulid")zo.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"ulid",code:q.invalid_string,message:C.message}),B.dirty());else if(C.kind==="url")try{new URL(A.data)}catch{Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"url",code:q.invalid_string,message:C.message}),B.dirty()}else C.kind==="regex"?(C.regex.lastIndex=0,C.regex.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"regex",code:q.invalid_string,message:C.message}),B.dirty())):C.kind==="trim"?A.data=A.data.trim():C.kind==="includes"?A.data.includes(C.value,C.position)||(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.invalid_string,validation:{includes:C.value,position:C.position},message:C.message}),B.dirty()):C.kind==="toLowerCase"?A.data=A.data.toLowerCase():C.kind==="toUpperCase"?A.data=A.data.toUpperCase():C.kind==="startsWith"?A.data.startsWith(C.value)||(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.invalid_string,validation:{startsWith:C.value},message:C.message}),B.dirty()):C.kind==="endsWith"?A.data.endsWith(C.value)||(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.invalid_string,validation:{endsWith:C.value},message:C.message}),B.dirty()):C.kind==="datetime"?yD(C).test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.invalid_string,validation:"datetime",message:C.message}),B.dirty()):C.kind==="date"?aD.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.invalid_string,validation:"date",message:C.message}),B.dirty()):C.kind==="time"?sD(C).test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.invalid_string,validation:"time",message:C.message}),B.dirty()):C.kind==="duration"?ID.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"duration",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="ip"?hD(A.data,C.version)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"ip",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="jwt"?GD(A.data,C.alg)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"jwt",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="cidr"?FD(A.data,C.version)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"cidr",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="base64"?oD.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"base64",code:q.invalid_string,message:C.message}),B.dirty()):C.kind==="base64url"?DD.test(A.data)||(Q=this._getOrReturnCtx(A,Q),m(Q,{validation:"base64url",code:q.invalid_string,message:C.message}),B.dirty()):DA.assertNever(C);return{status:B.value,value:A.data}}_regex(A,I,B){return this.refinement(Q=>A.test(Q),{validation:I,code:q.invalid_string,...b.errToObj(B)})}_addCheck(A){return new GI({...this._def,checks:[...this._def.checks,A]})}email(A){return this._addCheck({kind:"email",...b.errToObj(A)})}url(A){return this._addCheck({kind:"url",...b.errToObj(A)})}emoji(A){return this._addCheck({kind:"emoji",...b.errToObj(A)})}uuid(A){return this._addCheck({kind:"uuid",...b.errToObj(A)})}nanoid(A){return this._addCheck({kind:"nanoid",...b.errToObj(A)})}cuid(A){return this._addCheck({kind:"cuid",...b.errToObj(A)})}cuid2(A){return this._addCheck({kind:"cuid2",...b.errToObj(A)})}ulid(A){return this._addCheck({kind:"ulid",...b.errToObj(A)})}base64(A){return this._addCheck({kind:"base64",...b.errToObj(A)})}base64url(A){return this._addCheck({kind:"base64url",...b.errToObj(A)})}jwt(A){return this._addCheck({kind:"jwt",...b.errToObj(A)})}ip(A){return this._addCheck({kind:"ip",...b.errToObj(A)})}cidr(A){return this._addCheck({kind:"cidr",...b.errToObj(A)})}datetime(A){return typeof A=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:A}):this._addCheck({kind:"datetime",precision:typeof A?.precision>"u"?null:A?.precision,offset:A?.offset??!1,local:A?.local??!1,...b.errToObj(A?.message)})}date(A){return this._addCheck({kind:"date",message:A})}time(A){return typeof A=="string"?this._addCheck({kind:"time",precision:null,message:A}):this._addCheck({kind:"time",precision:typeof A?.precision>"u"?null:A?.precision,...b.errToObj(A?.message)})}duration(A){return this._addCheck({kind:"duration",...b.errToObj(A)})}regex(A,I){return this._addCheck({kind:"regex",regex:A,...b.errToObj(I)})}includes(A,I){return this._addCheck({kind:"includes",value:A,position:I?.position,...b.errToObj(I?.message)})}startsWith(A,I){return this._addCheck({kind:"startsWith",value:A,...b.errToObj(I)})}endsWith(A,I){return this._addCheck({kind:"endsWith",value:A,...b.errToObj(I)})}min(A,I){return this._addCheck({kind:"min",value:A,...b.errToObj(I)})}max(A,I){return this._addCheck({kind:"max",value:A,...b.errToObj(I)})}length(A,I){return this._addCheck({kind:"length",value:A,...b.errToObj(I)})}nonempty(A){return this.min(1,b.errToObj(A))}trim(){return new GI({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new GI({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new GI({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(A=>A.kind==="datetime")}get isDate(){return!!this._def.checks.find(A=>A.kind==="date")}get isTime(){return!!this._def.checks.find(A=>A.kind==="time")}get isDuration(){return!!this._def.checks.find(A=>A.kind==="duration")}get isEmail(){return!!this._def.checks.find(A=>A.kind==="email")}get isURL(){return!!this._def.checks.find(A=>A.kind==="url")}get isEmoji(){return!!this._def.checks.find(A=>A.kind==="emoji")}get isUUID(){return!!this._def.checks.find(A=>A.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(A=>A.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(A=>A.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(A=>A.kind==="cuid2")}get isULID(){return!!this._def.checks.find(A=>A.kind==="ulid")}get isIP(){return!!this._def.checks.find(A=>A.kind==="ip")}get isCIDR(){return!!this._def.checks.find(A=>A.kind==="cidr")}get isBase64(){return!!this._def.checks.find(A=>A.kind==="base64")}get isBase64url(){return!!this._def.checks.find(A=>A.kind==="base64url")}get minLength(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxLength(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}}GI.create=g=>new GI({checks:[],typeName:_.ZodString,coerce:g?.coerce??!1,...gA(g)});function wD(g,A){const I=(g.toString().split(".")[1]||"").length,B=(A.toString().split(".")[1]||"").length,Q=I>B?I:B,C=Number.parseInt(g.toFixed(Q).replace(".","")),E=Number.parseInt(A.toFixed(Q).replace(".",""));return C%E/10**Q}class vI extends oA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(A){if(this._def.coerce&&(A.data=Number(A.data)),this._getType(A)!==u.number){const C=this._getOrReturnCtx(A);return m(C,{code:q.invalid_type,expected:u.number,received:C.parsedType}),z}let B;const Q=new VA;for(const C of this._def.checks)C.kind==="int"?DA.isInteger(A.data)||(B=this._getOrReturnCtx(A,B),m(B,{code:q.invalid_type,expected:"integer",received:"float",message:C.message}),Q.dirty()):C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(B=this._getOrReturnCtx(A,B),m(B,{code:q.too_small,minimum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),Q.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(B=this._getOrReturnCtx(A,B),m(B,{code:q.too_big,maximum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),Q.dirty()):C.kind==="multipleOf"?wD(A.data,C.value)!==0&&(B=this._getOrReturnCtx(A,B),m(B,{code:q.not_multiple_of,multipleOf:C.value,message:C.message}),Q.dirty()):C.kind==="finite"?Number.isFinite(A.data)||(B=this._getOrReturnCtx(A,B),m(B,{code:q.not_finite,message:C.message}),Q.dirty()):DA.assertNever(C);return{status:Q.value,value:A.data}}gte(A,I){return this.setLimit("min",A,!0,b.toString(I))}gt(A,I){return this.setLimit("min",A,!1,b.toString(I))}lte(A,I){return this.setLimit("max",A,!0,b.toString(I))}lt(A,I){return this.setLimit("max",A,!1,b.toString(I))}setLimit(A,I,B,Q){return new vI({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:B,message:b.toString(Q)}]})}_addCheck(A){return new vI({...this._def,checks:[...this._def.checks,A]})}int(A){return this._addCheck({kind:"int",message:b.toString(A)})}positive(A){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(A)})}negative(A){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:b.toString(I)})}finite(A){return this._addCheck({kind:"finite",message:b.toString(A)})}safe(A){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(A)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(A)})}get minValue(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxValue(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}get isInt(){return!!this._def.checks.find(A=>A.kind==="int"||A.kind==="multipleOf"&&DA.isInteger(A.value))}get isFinite(){let A=null,I=null;for(const B of this._def.checks){if(B.kind==="finite"||B.kind==="int"||B.kind==="multipleOf")return!0;B.kind==="min"?(I===null||B.value>I)&&(I=B.value):B.kind==="max"&&(A===null||B.value<A)&&(A=B.value)}return Number.isFinite(I)&&Number.isFinite(A)}}vI.create=g=>new vI({checks:[],typeName:_.ZodNumber,coerce:g?.coerce||!1,...gA(g)});class Yg extends oA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(A){if(this._def.coerce)try{A.data=BigInt(A.data)}catch{return this._getInvalidInput(A)}if(this._getType(A)!==u.bigint)return this._getInvalidInput(A);let B;const Q=new VA;for(const C of this._def.checks)C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(B=this._getOrReturnCtx(A,B),m(B,{code:q.too_small,type:"bigint",minimum:C.value,inclusive:C.inclusive,message:C.message}),Q.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(B=this._getOrReturnCtx(A,B),m(B,{code:q.too_big,type:"bigint",maximum:C.value,inclusive:C.inclusive,message:C.message}),Q.dirty()):C.kind==="multipleOf"?A.data%C.value!==BigInt(0)&&(B=this._getOrReturnCtx(A,B),m(B,{code:q.not_multiple_of,multipleOf:C.value,message:C.message}),Q.dirty()):DA.assertNever(C);return{status:Q.value,value:A.data}}_getInvalidInput(A){const I=this._getOrReturnCtx(A);return m(I,{code:q.invalid_type,expected:u.bigint,received:I.parsedType}),z}gte(A,I){return this.setLimit("min",A,!0,b.toString(I))}gt(A,I){return this.setLimit("min",A,!1,b.toString(I))}lte(A,I){return this.setLimit("max",A,!0,b.toString(I))}lt(A,I){return this.setLimit("max",A,!1,b.toString(I))}setLimit(A,I,B,Q){return new Yg({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:B,message:b.toString(Q)}]})}_addCheck(A){return new Yg({...this._def,checks:[...this._def.checks,A]})}positive(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(A)})}negative(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:b.toString(I)})}get minValue(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxValue(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}}Yg.create=g=>new Yg({checks:[],typeName:_.ZodBigInt,coerce:g?.coerce??!1,...gA(g)});class iQ extends oA{_parse(A){if(this._def.coerce&&(A.data=!!A.data),this._getType(A)!==u.boolean){const B=this._getOrReturnCtx(A);return m(B,{code:q.invalid_type,expected:u.boolean,received:B.parsedType}),z}return zA(A.data)}}iQ.create=g=>new iQ({typeName:_.ZodBoolean,coerce:g?.coerce||!1,...gA(g)});class aB extends oA{_parse(A){if(this._def.coerce&&(A.data=new Date(A.data)),this._getType(A)!==u.date){const C=this._getOrReturnCtx(A);return m(C,{code:q.invalid_type,expected:u.date,received:C.parsedType}),z}if(Number.isNaN(A.data.getTime())){const C=this._getOrReturnCtx(A);return m(C,{code:q.invalid_date}),z}const B=new VA;let Q;for(const C of this._def.checks)C.kind==="min"?A.data.getTime()<C.value&&(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.too_small,message:C.message,inclusive:!0,exact:!1,minimum:C.value,type:"date"}),B.dirty()):C.kind==="max"?A.data.getTime()>C.value&&(Q=this._getOrReturnCtx(A,Q),m(Q,{code:q.too_big,message:C.message,inclusive:!0,exact:!1,maximum:C.value,type:"date"}),B.dirty()):DA.assertNever(C);return{status:B.value,value:new Date(A.data.getTime())}}_addCheck(A){return new aB({...this._def,checks:[...this._def.checks,A]})}min(A,I){return this._addCheck({kind:"min",value:A.getTime(),message:b.toString(I)})}max(A,I){return this._addCheck({kind:"max",value:A.getTime(),message:b.toString(I)})}get minDate(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A!=null?new Date(A):null}get maxDate(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A!=null?new Date(A):null}}aB.create=g=>new aB({checks:[],coerce:g?.coerce||!1,typeName:_.ZodDate,...gA(g)});class WC extends oA{_parse(A){if(this._getType(A)!==u.symbol){const B=this._getOrReturnCtx(A);return m(B,{code:q.invalid_type,expected:u.symbol,received:B.parsedType}),z}return zA(A.data)}}WC.create=g=>new WC({typeName:_.ZodSymbol,...gA(g)});class mC extends oA{_parse(A){if(this._getType(A)!==u.undefined){const B=this._getOrReturnCtx(A);return m(B,{code:q.invalid_type,expected:u.undefined,received:B.parsedType}),z}return zA(A.data)}}mC.create=g=>new mC({typeName:_.ZodUndefined,...gA(g)});class TC extends oA{_parse(A){if(this._getType(A)!==u.null){const B=this._getOrReturnCtx(A);return m(B,{code:q.invalid_type,expected:u.null,received:B.parsedType}),z}return zA(A.data)}}TC.create=g=>new TC({typeName:_.ZodNull,...gA(g)});class oQ extends oA{constructor(){super(...arguments),this._any=!0}_parse(A){return zA(A.data)}}oQ.create=g=>new oQ({typeName:_.ZodAny,...gA(g)});class xC extends oA{constructor(){super(...arguments),this._unknown=!0}_parse(A){return zA(A.data)}}xC.create=g=>new xC({typeName:_.ZodUnknown,...gA(g)});class FI extends oA{_parse(A){const I=this._getOrReturnCtx(A);return m(I,{code:q.invalid_type,expected:u.never,received:I.parsedType}),z}}FI.create=g=>new FI({typeName:_.ZodNever,...gA(g)});class ZC extends oA{_parse(A){if(this._getType(A)!==u.undefined){const B=this._getOrReturnCtx(A);return m(B,{code:q.invalid_type,expected:u.void,received:B.parsedType}),z}return zA(A.data)}}ZC.create=g=>new ZC({typeName:_.ZodVoid,...gA(g)});class QI extends oA{_parse(A){const{ctx:I,status:B}=this._processInputParams(A),Q=this._def;if(I.parsedType!==u.array)return m(I,{code:q.invalid_type,expected:u.array,received:I.parsedType}),z;if(Q.exactLength!==null){const E=I.data.length>Q.exactLength.value,i=I.data.length<Q.exactLength.value;(E||i)&&(m(I,{code:E?q.too_big:q.too_small,minimum:i?Q.exactLength.value:void 0,maximum:E?Q.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Q.exactLength.message}),B.dirty())}if(Q.minLength!==null&&I.data.length<Q.minLength.value&&(m(I,{code:q.too_small,minimum:Q.minLength.value,type:"array",inclusive:!0,exact:!1,message:Q.minLength.message}),B.dirty()),Q.maxLength!==null&&I.data.length>Q.maxLength.value&&(m(I,{code:q.too_big,maximum:Q.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Q.maxLength.message}),B.dirty()),I.common.async)return Promise.all([...I.data].map((E,i)=>Q.type._parseAsync(new hI(I,E,I.path,i)))).then(E=>VA.mergeArray(B,E));const C=[...I.data].map((E,i)=>Q.type._parseSync(new hI(I,E,I.path,i)));return VA.mergeArray(B,C)}get element(){return this._def.type}min(A,I){return new QI({...this._def,minLength:{value:A,message:b.toString(I)}})}max(A,I){return new QI({...this._def,maxLength:{value:A,message:b.toString(I)}})}length(A,I){return new QI({...this._def,exactLength:{value:A,message:b.toString(I)}})}nonempty(A){return this.min(1,A)}}QI.create=(g,A)=>new QI({type:g,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...gA(A)});function jI(g){if(g instanceof rA){const A={};for(const I in g.shape){const B=g.shape[I];A[I]=wI.create(jI(B))}return new rA({...g._def,shape:()=>A})}else return g instanceof QI?new QI({...g._def,type:jI(g.element)}):g instanceof wI?wI.create(jI(g.unwrap())):g instanceof $I?$I.create(jI(g.unwrap())):g instanceof KI?KI.create(g.items.map(A=>jI(A))):g}class rA extends oA{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const A=this._def.shape(),I=DA.objectKeys(A);return this._cached={shape:A,keys:I},this._cached}_parse(A){if(this._getType(A)!==u.object){const a=this._getOrReturnCtx(A);return m(a,{code:q.invalid_type,expected:u.object,received:a.parsedType}),z}const{status:B,ctx:Q}=this._processInputParams(A),{shape:C,keys:E}=this._getCached(),i=[];if(!(this._def.catchall instanceof FI&&this._def.unknownKeys==="strip"))for(const a in Q.data)E.includes(a)||i.push(a);const D=[];for(const a of E){const G=C[a],R=Q.data[a];D.push({key:{status:"valid",value:a},value:G._parse(new hI(Q,R,Q.path,a)),alwaysSet:a in Q.data})}if(this._def.catchall instanceof FI){const a=this._def.unknownKeys;if(a==="passthrough")for(const G of i)D.push({key:{status:"valid",value:G},value:{status:"valid",value:Q.data[G]}});else if(a==="strict")i.length>0&&(m(Q,{code:q.unrecognized_keys,keys:i}),B.dirty());else if(a!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const a=this._def.catchall;for(const G of i){const R=Q.data[G];D.push({key:{status:"valid",value:G},value:a._parse(new hI(Q,R,Q.path,G)),alwaysSet:G in Q.data})}}return Q.common.async?Promise.resolve().then(async()=>{const a=[];for(const G of D){const R=await G.key,U=await G.value;a.push({key:R,value:U,alwaysSet:G.alwaysSet})}return a}).then(a=>VA.mergeObjectSync(B,a)):VA.mergeObjectSync(B,D)}get shape(){return this._def.shape()}strict(A){return b.errToObj,new rA({...this._def,unknownKeys:"strict",...A!==void 0?{errorMap:(I,B)=>{const Q=this._def.errorMap?.(I,B).message??B.defaultError;return I.code==="unrecognized_keys"?{message:b.errToObj(A).message??Q}:{message:Q}}}:{}})}strip(){return new rA({...this._def,unknownKeys:"strip"})}passthrough(){return new rA({...this._def,unknownKeys:"passthrough"})}extend(A){return new rA({...this._def,shape:()=>({...this._def.shape(),...A})})}merge(A){return new rA({unknownKeys:A._def.unknownKeys,catchall:A._def.catchall,shape:()=>({...this._def.shape(),...A._def.shape()}),typeName:_.ZodObject})}setKey(A,I){return this.augment({[A]:I})}catchall(A){return new rA({...this._def,catchall:A})}pick(A){const I={};for(const B of DA.objectKeys(A))A[B]&&this.shape[B]&&(I[B]=this.shape[B]);return new rA({...this._def,shape:()=>I})}omit(A){const I={};for(const B of DA.objectKeys(this.shape))A[B]||(I[B]=this.shape[B]);return new rA({...this._def,shape:()=>I})}deepPartial(){return jI(this)}partial(A){const I={};for(const B of DA.objectKeys(this.shape)){const Q=this.shape[B];A&&!A[B]?I[B]=Q:I[B]=Q.optional()}return new rA({...this._def,shape:()=>I})}required(A){const I={};for(const B of DA.objectKeys(this.shape))if(A&&!A[B])I[B]=this.shape[B];else{let C=this.shape[B];for(;C instanceof wI;)C=C._def.innerType;I[B]=C}return new rA({...this._def,shape:()=>I})}keyof(){return PC(DA.objectKeys(this.shape))}}rA.create=(g,A)=>new rA({shape:()=>g,unknownKeys:"strip",catchall:FI.create(),typeName:_.ZodObject,...gA(A)}),rA.strictCreate=(g,A)=>new rA({shape:()=>g,unknownKeys:"strict",catchall:FI.create(),typeName:_.ZodObject,...gA(A)}),rA.lazycreate=(g,A)=>new rA({shape:g,unknownKeys:"strip",catchall:FI.create(),typeName:_.ZodObject,...gA(A)});class sB extends oA{_parse(A){const{ctx:I}=this._processInputParams(A),B=this._def.options;function Q(C){for(const i of C)if(i.result.status==="valid")return i.result;for(const i of C)if(i.result.status==="dirty")return I.common.issues.push(...i.ctx.common.issues),i.result;const E=C.map(i=>new iI(i.ctx.common.issues));return m(I,{code:q.invalid_union,unionErrors:E}),z}if(I.common.async)return Promise.all(B.map(async C=>{const E={...I,common:{...I.common,issues:[]},parent:null};return{result:await C._parseAsync({data:I.data,path:I.path,parent:E}),ctx:E}})).then(Q);{let C;const E=[];for(const D of B){const a={...I,common:{...I.common,issues:[]},parent:null},G=D._parseSync({data:I.data,path:I.path,parent:a});if(G.status==="valid")return G;G.status==="dirty"&&!C&&(C={result:G,ctx:a}),a.common.issues.length&&E.push(a.common.issues)}if(C)return I.common.issues.push(...C.ctx.common.issues),C.result;const i=E.map(D=>new iI(D));return m(I,{code:q.invalid_union,unionErrors:i}),z}}get options(){return this._def.options}}sB.create=(g,A)=>new sB({options:g,typeName:_.ZodUnion,...gA(A)});function DQ(g,A){const I=yI(g),B=yI(A);if(g===A)return{valid:!0,data:g};if(I===u.object&&B===u.object){const Q=DA.objectKeys(A),C=DA.objectKeys(g).filter(i=>Q.indexOf(i)!==-1),E={...g,...A};for(const i of C){const D=DQ(g[i],A[i]);if(!D.valid)return{valid:!1};E[i]=D.data}return{valid:!0,data:E}}else if(I===u.array&&B===u.array){if(g.length!==A.length)return{valid:!1};const Q=[];for(let C=0;C<g.length;C++){const E=g[C],i=A[C],D=DQ(E,i);if(!D.valid)return{valid:!1};Q.push(D.data)}return{valid:!0,data:Q}}else return I===u.date&&B===u.date&&+g==+A?{valid:!0,data:g}:{valid:!1}}class yB extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A),Q=(C,E)=>{if(qC(C)||qC(E))return z;const i=DQ(C.value,E.value);return i.valid?((dC(C)||dC(E))&&I.dirty(),{status:I.value,value:i.data}):(m(B,{code:q.invalid_intersection_types}),z)};return B.common.async?Promise.all([this._def.left._parseAsync({data:B.data,path:B.path,parent:B}),this._def.right._parseAsync({data:B.data,path:B.path,parent:B})]).then(([C,E])=>Q(C,E)):Q(this._def.left._parseSync({data:B.data,path:B.path,parent:B}),this._def.right._parseSync({data:B.data,path:B.path,parent:B}))}}yB.create=(g,A,I)=>new yB({left:g,right:A,typeName:_.ZodIntersection,...gA(I)});class KI extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==u.array)return m(B,{code:q.invalid_type,expected:u.array,received:B.parsedType}),z;if(B.data.length<this._def.items.length)return m(B,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),z;!this._def.rest&&B.data.length>this._def.items.length&&(m(B,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I.dirty());const C=[...B.data].map((E,i)=>{const D=this._def.items[i]||this._def.rest;return D?D._parse(new hI(B,E,B.path,i)):null}).filter(E=>!!E);return B.common.async?Promise.all(C).then(E=>VA.mergeArray(I,E)):VA.mergeArray(I,C)}get items(){return this._def.items}rest(A){return new KI({...this._def,rest:A})}}KI.create=(g,A)=>{if(!Array.isArray(g))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new KI({items:g,typeName:_.ZodTuple,rest:null,...gA(A)})};class uC extends oA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==u.map)return m(B,{code:q.invalid_type,expected:u.map,received:B.parsedType}),z;const Q=this._def.keyType,C=this._def.valueType,E=[...B.data.entries()].map(([i,D],a)=>({key:Q._parse(new hI(B,i,B.path,[a,"key"])),value:C._parse(new hI(B,D,B.path,[a,"value"]))}));if(B.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const D of E){const a=await D.key,G=await D.value;if(a.status==="aborted"||G.status==="aborted")return z;(a.status==="dirty"||G.status==="dirty")&&I.dirty(),i.set(a.value,G.value)}return{status:I.value,value:i}})}else{const i=new Map;for(const D of E){const a=D.key,G=D.value;if(a.status==="aborted"||G.status==="aborted")return z;(a.status==="dirty"||G.status==="dirty")&&I.dirty(),i.set(a.value,G.value)}return{status:I.value,value:i}}}}uC.create=(g,A,I)=>new uC({valueType:A,keyType:g,typeName:_.ZodMap,...gA(I)});class Kg extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.parsedType!==u.set)return m(B,{code:q.invalid_type,expected:u.set,received:B.parsedType}),z;const Q=this._def;Q.minSize!==null&&B.data.size<Q.minSize.value&&(m(B,{code:q.too_small,minimum:Q.minSize.value,type:"set",inclusive:!0,exact:!1,message:Q.minSize.message}),I.dirty()),Q.maxSize!==null&&B.data.size>Q.maxSize.value&&(m(B,{code:q.too_big,maximum:Q.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Q.maxSize.message}),I.dirty());const C=this._def.valueType;function E(D){const a=new Set;for(const G of D){if(G.status==="aborted")return z;G.status==="dirty"&&I.dirty(),a.add(G.value)}return{status:I.value,value:a}}const i=[...B.data.values()].map((D,a)=>C._parse(new hI(B,D,B.path,a)));return B.common.async?Promise.all(i).then(D=>E(D)):E(i)}min(A,I){return new Kg({...this._def,minSize:{value:A,message:b.toString(I)}})}max(A,I){return new Kg({...this._def,maxSize:{value:A,message:b.toString(I)}})}size(A,I){return this.min(A,I).max(A,I)}nonempty(A){return this.min(1,A)}}Kg.create=(g,A)=>new Kg({valueType:g,minSize:null,maxSize:null,typeName:_.ZodSet,...gA(A)});class bC extends oA{get schema(){return this._def.getter()}_parse(A){const{ctx:I}=this._processInputParams(A);return this._def.getter()._parse({data:I.data,path:I.path,parent:I})}}bC.create=(g,A)=>new bC({getter:g,typeName:_.ZodLazy,...gA(A)});class aQ extends oA{_parse(A){if(A.data!==this._def.value){const I=this._getOrReturnCtx(A);return m(I,{received:I.data,code:q.invalid_literal,expected:this._def.value}),z}return{status:"valid",value:A.data}}get value(){return this._def.value}}aQ.create=(g,A)=>new aQ({value:g,typeName:_.ZodLiteral,...gA(A)});function PC(g,A){return new zI({values:g,typeName:_.ZodEnum,...gA(A)})}class zI extends oA{_parse(A){if(typeof A.data!="string"){const I=this._getOrReturnCtx(A),B=this._def.values;return m(I,{expected:DA.joinValues(B),received:I.parsedType,code:q.invalid_type}),z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(A.data)){const I=this._getOrReturnCtx(A),B=this._def.values;return m(I,{received:I.data,code:q.invalid_enum_value,options:B}),z}return zA(A.data)}get options(){return this._def.values}get enum(){const A={};for(const I of this._def.values)A[I]=I;return A}get Values(){const A={};for(const I of this._def.values)A[I]=I;return A}get Enum(){const A={};for(const I of this._def.values)A[I]=I;return A}extract(A,I=this._def){return zI.create(A,{...this._def,...I})}exclude(A,I=this._def){return zI.create(this.options.filter(B=>!A.includes(B)),{...this._def,...I})}}zI.create=PC;class OC extends oA{_parse(A){const I=DA.getValidEnumValues(this._def.values),B=this._getOrReturnCtx(A);if(B.parsedType!==u.string&&B.parsedType!==u.number){const Q=DA.objectValues(I);return m(B,{expected:DA.joinValues(Q),received:B.parsedType,code:q.invalid_type}),z}if(this._cache||(this._cache=new Set(DA.getValidEnumValues(this._def.values))),!this._cache.has(A.data)){const Q=DA.objectValues(I);return m(B,{received:B.data,code:q.invalid_enum_value,options:Q}),z}return zA(A.data)}get enum(){return this._def.values}}OC.create=(g,A)=>new OC({values:g,typeName:_.ZodNativeEnum,...gA(A)});class hB extends oA{unwrap(){return this._def.type}_parse(A){const{ctx:I}=this._processInputParams(A);if(I.parsedType!==u.promise&&I.common.async===!1)return m(I,{code:q.invalid_type,expected:u.promise,received:I.parsedType}),z;const B=I.parsedType===u.promise?I.data:Promise.resolve(I.data);return zA(B.then(Q=>this._def.type.parseAsync(Q,{path:I.path,errorMap:I.common.contextualErrorMap})))}}hB.create=(g,A)=>new hB({type:g,typeName:_.ZodPromise,...gA(A)});class _I extends oA{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(A){const{status:I,ctx:B}=this._processInputParams(A),Q=this._def.effect||null,C={addIssue:E=>{m(B,E),E.fatal?I.abort():I.dirty()},get path(){return B.path}};if(C.addIssue=C.addIssue.bind(C),Q.type==="preprocess"){const E=Q.transform(B.data,C);if(B.common.async)return Promise.resolve(E).then(async i=>{if(I.value==="aborted")return z;const D=await this._def.schema._parseAsync({data:i,path:B.path,parent:B});return D.status==="aborted"?z:D.status==="dirty"||I.value==="dirty"?ng(D.value):D});{if(I.value==="aborted")return z;const i=this._def.schema._parseSync({data:E,path:B.path,parent:B});return i.status==="aborted"?z:i.status==="dirty"||I.value==="dirty"?ng(i.value):i}}if(Q.type==="refinement"){const E=i=>{const D=Q.refinement(i,C);if(B.common.async)return Promise.resolve(D);if(D instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(B.common.async===!1){const i=this._def.schema._parseSync({data:B.data,path:B.path,parent:B});return i.status==="aborted"?z:(i.status==="dirty"&&I.dirty(),E(i.value),{status:I.value,value:i.value})}else return this._def.schema._parseAsync({data:B.data,path:B.path,parent:B}).then(i=>i.status==="aborted"?z:(i.status==="dirty"&&I.dirty(),E(i.value).then(()=>({status:I.value,value:i.value}))))}if(Q.type==="transform")if(B.common.async===!1){const E=this._def.schema._parseSync({data:B.data,path:B.path,parent:B});if(!XI(E))return z;const i=Q.transform(E.value,C);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:I.value,value:i}}else return this._def.schema._parseAsync({data:B.data,path:B.path,parent:B}).then(E=>XI(E)?Promise.resolve(Q.transform(E.value,C)).then(i=>({status:I.value,value:i})):z);DA.assertNever(Q)}}_I.create=(g,A,I)=>new _I({schema:g,typeName:_.ZodEffects,effect:A,...gA(I)}),_I.createWithPreprocess=(g,A,I)=>new _I({schema:A,effect:{type:"preprocess",transform:g},typeName:_.ZodEffects,...gA(I)});class wI extends oA{_parse(A){return this._getType(A)===u.undefined?zA(void 0):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}wI.create=(g,A)=>new wI({innerType:g,typeName:_.ZodOptional,...gA(A)});class $I extends oA{_parse(A){return this._getType(A)===u.null?zA(null):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}$I.create=(g,A)=>new $I({innerType:g,typeName:_.ZodNullable,...gA(A)});class sQ extends oA{_parse(A){const{ctx:I}=this._processInputParams(A);let B=I.data;return I.parsedType===u.undefined&&(B=this._def.defaultValue()),this._def.innerType._parse({data:B,path:I.path,parent:I})}removeDefault(){return this._def.innerType}}sQ.create=(g,A)=>new sQ({innerType:g,typeName:_.ZodDefault,defaultValue:typeof A.default=="function"?A.default:()=>A.default,...gA(A)});class yQ extends oA{_parse(A){const{ctx:I}=this._processInputParams(A),B={...I,common:{...I.common,issues:[]}},Q=this._def.innerType._parse({data:B.data,path:B.path,parent:{...B}});return DB(Q)?Q.then(C=>({status:"valid",value:C.status==="valid"?C.value:this._def.catchValue({get error(){return new iI(B.common.issues)},input:B.data})})):{status:"valid",value:Q.status==="valid"?Q.value:this._def.catchValue({get error(){return new iI(B.common.issues)},input:B.data})}}removeCatch(){return this._def.innerType}}yQ.create=(g,A)=>new yQ({innerType:g,typeName:_.ZodCatch,catchValue:typeof A.catch=="function"?A.catch:()=>A.catch,...gA(A)});class VC extends oA{_parse(A){if(this._getType(A)!==u.nan){const B=this._getOrReturnCtx(A);return m(B,{code:q.invalid_type,expected:u.nan,received:B.parsedType}),z}return{status:"valid",value:A.data}}}VC.create=g=>new VC({typeName:_.ZodNaN,...gA(g)});class SD extends oA{_parse(A){const{ctx:I}=this._processInputParams(A),B=I.data;return this._def.type._parse({data:B,path:I.path,parent:I})}unwrap(){return this._def.type}}class hQ extends oA{_parse(A){const{status:I,ctx:B}=this._processInputParams(A);if(B.common.async)return(async()=>{const C=await this._def.in._parseAsync({data:B.data,path:B.path,parent:B});return C.status==="aborted"?z:C.status==="dirty"?(I.dirty(),ng(C.value)):this._def.out._parseAsync({data:C.value,path:B.path,parent:B})})();{const Q=this._def.in._parseSync({data:B.data,path:B.path,parent:B});return Q.status==="aborted"?z:Q.status==="dirty"?(I.dirty(),{status:"dirty",value:Q.value}):this._def.out._parseSync({data:Q.value,path:B.path,parent:B})}}static create(A,I){return new hQ({in:A,out:I,typeName:_.ZodPipeline})}}class GQ extends oA{_parse(A){const I=this._def.innerType._parse(A),B=Q=>(XI(Q)&&(Q.value=Object.freeze(Q.value)),Q);return DB(I)?I.then(Q=>B(Q)):B(I)}unwrap(){return this._def.innerType}}GQ.create=(g,A)=>new GQ({innerType:g,typeName:_.ZodReadonly,...gA(A)});var _;(function(g){g.ZodString="ZodString",g.ZodNumber="ZodNumber",g.ZodNaN="ZodNaN",g.ZodBigInt="ZodBigInt",g.ZodBoolean="ZodBoolean",g.ZodDate="ZodDate",g.ZodSymbol="ZodSymbol",g.ZodUndefined="ZodUndefined",g.ZodNull="ZodNull",g.ZodAny="ZodAny",g.ZodUnknown="ZodUnknown",g.ZodNever="ZodNever",g.ZodVoid="ZodVoid",g.ZodArray="ZodArray",g.ZodObject="ZodObject",g.ZodUnion="ZodUnion",g.ZodDiscriminatedUnion="ZodDiscriminatedUnion",g.ZodIntersection="ZodIntersection",g.ZodTuple="ZodTuple",g.ZodRecord="ZodRecord",g.ZodMap="ZodMap",g.ZodSet="ZodSet",g.ZodFunction="ZodFunction",g.ZodLazy="ZodLazy",g.ZodLiteral="ZodLiteral",g.ZodEnum="ZodEnum",g.ZodEffects="ZodEffects",g.ZodNativeEnum="ZodNativeEnum",g.ZodOptional="ZodOptional",g.ZodNullable="ZodNullable",g.ZodDefault="ZodDefault",g.ZodCatch="ZodCatch",g.ZodPromise="ZodPromise",g.ZodBranded="ZodBranded",g.ZodPipeline="ZodPipeline",g.ZodReadonly="ZodReadonly"})(_||(_={}));const hA=GI.create,CA=vI.create,XC=iQ.create,SI=oQ.create;FI.create;const GA=QI.create,v=rA.create;sB.create,yB.create,KI.create;const mA=aQ.create,Ag=zI.create;hB.create,wI.create,$I.create;const RD=v({multiscales:GA(v({name:hA().optional(),datasets:GA(v({path:hA(),coordinateTransformations:GA(SI().superRefine((g,A)=>{const I=[v({type:mA("scale"),scale:GA(CA()).min(2)}),v({type:mA("translation"),translation:GA(CA()).min(2)})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),version:mA("0.4").optional(),axes:GA(SI().superRefine((g,A)=>{const I=[v({name:hA(),type:Ag(["channel","time","space"])}),v({name:hA(),type:SI().refine(Q=>!Ag(["space","time","channel"]).safeParse(Q).success,"Invalid input: Should NOT be valid against schema").optional()})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:GA(SI().superRefine((g,A)=>{const I=[v({type:mA("scale"),scale:GA(CA()).min(2)}),v({type:mA("translation"),translation:GA(CA()).min(2)}),v({type:mA("identity")})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:v({channels:GA(v({window:v({end:CA(),max:CA(),min:CA(),start:CA()}),label:hA().optional(),family:hA().optional(),color:hA(),active:XC().optional()})),rdefs:v({defaultT:CA().optional(),defaultZ:CA().optional(),color:Ag(["color","greyscale"]).optional(),projection:hA().optional()}).optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),ND=v({plate:v({acquisitions:GA(v({id:CA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:CA().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:hA().describe("The name of the acquisition").optional(),description:hA().describe("The description of the acquisition").optional(),starttime:CA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:CA().int().gte(0).describe("The end timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional()})).describe("The acquisitions for this plate").optional(),version:mA("0.4").describe("The version of the specification").optional(),field_count:CA().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:hA().describe("The name of the plate").optional(),columns:GA(v({name:hA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:GA(v({name:hA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:GA(v({path:hA().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:CA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:CA().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}).optional()}).describe("JSON from OME-NGFF .zattrs"),tD=v({well:v({images:GA(v({acquisition:CA().int().describe("A unique identifier within the context of the plate").optional(),path:hA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The path for this field of view subgroup")})).min(1).describe("The fields of view for this well"),version:mA("0.4").describe("The version of the specification").optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),UD=v({ome:v({multiscales:GA(v({name:hA().optional(),datasets:GA(v({path:hA(),coordinateTransformations:GA(SI().superRefine((g,A)=>{const I=[v({type:mA("scale"),scale:GA(CA()).min(2)}),v({type:mA("translation"),translation:GA(CA()).min(2)})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),axes:GA(SI().superRefine((g,A)=>{const I=[v({name:hA(),type:Ag(["channel","time","space"])}),v({name:hA(),type:SI().refine(Q=>!Ag(["space","time","channel"]).safeParse(Q).success,"Invalid input: Should NOT be valid against schema").optional()})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:GA(SI().superRefine((g,A)=>{const I=[v({type:mA("scale"),scale:GA(CA()).min(2)}),v({type:mA("translation"),translation:GA(CA()).min(2)}),v({type:mA("identity")})],B=I.reduce((Q,C)=>(E=>E.error?[...Q,E.error]:Q)(C.safeParse(g)),[]);I.length-B.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:B,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:v({channels:GA(v({window:v({end:CA(),max:CA(),min:CA(),start:CA()}).optional(),label:hA().optional(),family:hA().optional(),color:hA().optional(),active:XC().optional()})),rdefs:v({defaultT:CA().optional(),defaultZ:CA().optional(),color:Ag(["color","greyscale"]).optional(),projection:hA().optional()}).optional()}).optional(),version:mA("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),kD=v({ome:v({plate:v({acquisitions:GA(v({id:CA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:CA().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:hA().describe("The name of the acquisition").optional(),description:hA().describe("The description of the acquisition").optional(),starttime:CA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:CA().int().gte(0).describe("The end timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional()})).describe("The acquisitions for this plate").optional(),field_count:CA().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:hA().describe("The name of the plate").optional(),columns:GA(v({name:hA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:GA(v({name:hA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:GA(v({path:hA().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:CA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:CA().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}),version:mA("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),cD=v({ome:v({well:v({images:GA(v({acquisition:CA().int().describe("A unique identifier within the context of the plate").optional(),path:hA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The path for this field of view subgroup")})).min(1).describe("The fields of view for this well")}),version:mA("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("JSON from OME-Zarr zarr.json"),LD=["0.4","0.5"],JD=new Set(LD);function rD(g){if(!("ome"in g)||!(g.ome instanceof Object))return;const A=g.ome;if("version"in A&&typeof A.version=="string"&&JD.has(A.version))return A.version}function FQ(g){const A=rD(g);return A===void 0?"0.4":A}function Ig(g){if(g!==void 0)switch(g){case"0.4":return"v2";case"0.5":return"v3"}}function vC(g,A){const I={...g};return delete I[A],I}async function nD(g,A){const I=new kg(g),B=new vA(I),Q=Ig(A),C=await rg(B,Q);try{return YD(C.attrs)}catch{throw Error(`Failed to parse OME-Zarr plate:
4120
4120
  ${JSON.stringify(C.attrs)}`)}}function YD(g){switch(FQ(g)){case"0.5":return{...kD.parse(g).ome,originalVersion:"0.5"};case"0.4":return{...KD(ND.parse(g)).ome,originalVersion:"0.4"}}}function KD(g){if(g.plate===void 0)throw new Error("Plate metadata is missing in OME-Zarr v0.4 plate");return{ome:{plate:vC(g.plate,"version"),version:"0.5"}}}function MD(g){if(g.well===void 0)throw new Error("Well metadata is missing in OME-Zarr v0.4 well");return{ome:{well:vC(g.well,"version"),version:"0.5"}}}function eD(g){switch(FQ(g)){case"0.5":return{...cD.parse(g).ome,originalVersion:"0.5"};case"0.4":return{...MD(tD.parse(g)).ome,originalVersion:"0.4"}}}async function HD(g,A,I){const B=g+"/"+A,Q=new kg(B),C=new vA(Q),E=Ig(I),i=await rg(C,E);try{return eD(i.attrs)}catch{throw Error(`Failed to parse OME-Zarr well:
4121
4121
  ${JSON.stringify(i.attrs)}`)}}async function qD(g){const A=Ig(g.version),I=await rg(g.location,A);return wQ(I.attrs).omero?.channels??[]}async function dD(g){const A=Ig(g.version),I=await rg(g.location,A);return wQ(I.attrs).omero?.rdefs}function fD(g){return{ome:{multiscales:g.multiscales,omero:g.omero,version:"0.5"}}}function lD(g){switch(FQ(g)){case"0.5":return{...UD.parse(g).ome,originalVersion:"0.5"};case"0.4":return{...fD(RD.parse(g)).ome,originalVersion:"0.4"}}}function wQ(g){try{return lD(g)}catch{throw Error(`Failed to parse OME-Zarr image:
4122
- ${JSON.stringify(g)}`)}}class gg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let B=Ig(I);const Q=await rg(A,B),C=wQ(Q.attrs),E=C.multiscales;if(E.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${E.length} images.`);const i=E[0];if(i.datasets.length===0)throw new Error("No datasets found in the multiscale image.");B||(B=Ig(C.originalVersion));const D=i.datasets.map(U=>Yo(A,U.path,B)),a=await Promise.all(D.map(U=>no(U))),G=a[0].shape,R=i.axes;if(R.length!==G.length)throw new Error(`Mismatch between number of axes (${R.length}) and array shape (${G.length})`);return new xo({metadata:i,arrays:a,arrayParams:D})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}get loader(){return this.loader_}static async fromHttp(A){const I=new vA(new kg(A.url)),B=await gg.openLoader(I,A.version);return new gg({location:I,version:A.version,loader:B})}static async fromFileSystem(A){const I=new vA(new QQ(A.directory),A.path),B=await gg.openLoader(I,A.version);return new gg({location:I,version:A.version,loader:B})}}class Mg{blendMode;occludes;requiresSceneDepth_=!1;coverageGroups_=new Map;state_="initialized";attached_=!1;callbacks_=[];opacity_;constructor({opacity:A=1,blendMode:I="none",occludes:B}={}){this.opacity_=EI(A,0,1),this.blendMode=I,this.occludes=B??I==="none"}get requiresSceneDepth(){return this.requiresSceneDepth_}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&V.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=EI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);if(this.occludes&&this.requiresSceneDepth_)throw new Error(`${this.type} cannot both occlude and read scene depth.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}get coverageGroups(){return this.coverageGroups_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(B=>B(A,I))}addObject(A,I=null){const B=this.coverageGroups_.get(I);B?B.push(A):this.coverageGroups_.set(I,[A])}clearObjects(){this.coverageGroups_.clear()}getUniforms(){return{}}}class pD extends uI{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*10),B=A.length>=3&&KB(A[0],A[A.length-1]);let Q=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[Q++]=i[0],I[Q++]=i[1],I[Q++]=i[2];const D=C===0?B?A[A.length-2]:A[C]:A[C-1];I[Q++]=D[0],I[Q++]=D[1],I[Q++]=D[2];const a=C===A.length-1?B?A[1]:A[C]:A[C+1];I[Q++]=a[0],I[Q++]=a[1],I[Q++]=a[2],I[Q++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class WD extends uI{constructor(A){if(super(),A.primitive!="triangles"){V.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){V.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const D=Math.min(E,i),a=Math.max(E,i);I.has({i0:D,i1:a})||(I.add({i0:D,i1:a}),B.push(D,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],D=C[E+1],a=C[E+2];Q(i,D),Q(D,a),Q(a,i)}this.indexData_=new Uint32Array(B)}}const mD=yA(0,1,0);class SQ{dirty_=!0;matrix_=WA();rotation_=Vg();translation_=AA();scale_=yA(1,1,1);addRotation(A){Qi(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){Ei(this.rotation_,A),this.dirty_=!0}get rotation(){return Ci(this.rotation_)}addTranslation(A){ug(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){LB(this.translation_,A),this.dirty_=!0}get translation(){return $A(this.translation_)}addScale(A){vE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){LB(this.scale_,A),this.dirty_=!0}targetTo(A){KB(this.translation_,A)&&(A=$A(A),A[2]+=wA);const I=VE(WA(),this.translation_,A,mD),B=mE(TQ(),I);HB(this.rotation_,B),Xg(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return $A(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return Sg(WA(),this.matrix)}computeMatrix(){ZE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class FA{static RED=new FA(1,0,0);static GREEN=new FA(0,1,0);static BLUE=new FA(0,0,1);static YELLOW=new FA(1,1,0);static MAGENTA=new FA(1,0,1);static CYAN=new FA(0,1,1);static BLACK=new FA(0,0,0);static WHITE=new FA(1,1,1);static TRANSPARENT=new FA(0,0,0,0);rgba_;constructor(A,I,B,Q){if(A<0||A>1||I<0||I>1||B<0||B>1)throw new Error("RGB values must be in the range [0, 1]");if(Q!==void 0&&(Q<0||Q>1))throw new Error("Alpha value must be in the range [0, 1]");this.rgba_=[A,I,B,Q??1]}get rgb(){return[this.rgba_[0],this.rgba_[1],this.rgba_[2]]}get rgba(){return this.rgba_}get r(){return this.rgba_[0]}get g(){return this.rgba_[1]}get b(){return this.rgba_[2]}get a(){return this.rgba_[3]}get rgbHex(){return`#${this.toHexComponent(this.r)}${this.toHexComponent(this.g)}${this.toHexComponent(this.b)}`}get packed(){return Math.round(this.r*255)<<24|Math.round(this.g*255)<<16|Math.round(this.b*255)<<8|Math.round(this.a*255)}static from(A){if(A instanceof FA)return A;if(Array.isArray(A))return new FA(A[0],A[1],A[2],A[3]);if(typeof A=="string")return FA.fromRgbHex(A);throw new Error("Unsupported color format")}static fromRgbHex(A){const I=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(A);if(!I)throw new Error("Invalid RGB hex, use form '#RRGGBB'");return new FA(parseInt(I[1],16)/255,parseInt(I[2],16)/255,parseInt(I[3],16)/255,1)}toHexComponent(A){const I=Math.round(A*255).toString(16).padStart(2,"0");return I.length===1?"0"+I:I}}class Bg extends xg{wireframeEnabled=!1;wireframeColor=FA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new SQ;geometry_=new uI;wireframeGeometry_=null;programName_=null;depthProgramName_=null;cullFaceMode_="none";setTexture(A,I){this.textures_[A]=I}clearTextures(){this.textures_.length=0}markStaleTexture(A){A!==void 0&&this.staleTextures_.push(A)}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new WD(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get depthProgramName(){return this.depthProgramName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}set depthProgramName(A){this.depthProgramName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class jC extends Bg{color_;width_;constructor({geometry:A,color:I,width:B}){super(),this.geometry=A,this.color_=FA.from(I),this.width_=B,this.programName="projectedLine",this.depthProgramName="projectedLineDepth"}get type(){return"ProjectedLineRenderable"}get color(){return this.color_}set color(A){this.color_=FA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{u_lineColor:this.color.rgb,u_lineWidth:this.width}}}class TD extends Mg{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(RQ({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(RQ({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(RQ({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function RQ(g){const{end:A,width:I,color:B}=g,Q=new pD([[0,0,0],A]);return new jC({geometry:Q,color:B,width:I})}const zC=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function GB(g={}){return FB(NQ({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},g))}function xD(g={}){return FB(NQ({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","visibleCurrent","prefetchTime","fallbackBackground","prefetchSpace"]},g))}function ZD(g={}){return FB(NQ({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},g))}function FB(g){uD(g);const A={x:g.prefetch.x,y:g.prefetch.y,z:g.prefetch.z??0,t:g.prefetch.t??0},I=Object.freeze(zC.reduce((C,E)=>{const i=g.priorityOrder.indexOf(E);return C[E]=i,C},{})),B={min:g.lod?.min??0,max:g.lod?.max??Number.MAX_SAFE_INTEGER,bias:g.lod?.bias??.5},Q={profile:g.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...g.priorityOrder]),priorityMap:I,lod:B};return Object.freeze(Q)}function uD(g){for(const[B,Q]of Object.entries(g.prefetch))if(Q!==void 0&&Q<0)throw new Error(`prefetch.${B} must be a non-negative number`);const A=g.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=g.priorityOrder;if(I.length!==zC.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function NQ(g,A={}){return{profile:A.profile??g.profile,prefetch:{...g.prefetch,...A.prefetch??{}},lod:{...g.lod,...A.lod??{}},priorityOrder:A.priorityOrder??g.priorityOrder}}const _C=32;function eg(g,{visible:A,color:I,contrastLimits:B,opacity:Q}){return A??=!0,I=I===void 0?FA.WHITE:FA.from(I),Q=Q===void 0?1:EI(Q,0,1),g!==null?B=bD(B,g):B===void 0&&(V.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B,opacity:Q}}function tQ(g,A){if(A.length>_C)throw new Error(`Maximum number of channels is ${_C}`);return A.map(I=>eg(g,I))}function $C(g,A){if(g&&g.length!==A)throw new Error(`channelProps length (${g.length}) must match source channel count (${A}).`)}function bD(g,A){if(g===void 0)return Fi(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AE extends uI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,D=Q,a=i+1,G=D+1,R=A/i,U=I/D;for(let J=0;J<G;++J){const r=J*U;for(let H=0;H<a;++H){const K=H*R,l=H/i,O=J/D,Z=[K,r,0],W=[0,0,1],p=[l,O];C.push(...Z,...W,...p)}}for(let J=0;J<D;++J)for(let r=0;r<i;++r){const H=r+a*J,K=r+a*(J+1),l=r+1+a*(J+1),O=r+1+a*J;E.push(H,K,O),E.push(K,l,O)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class IE extends Bg{worldToTexCoord=WA();channels_;constructor({width:A,height:I,texture:B,channelProps:Q=[]}){super(),this.geometry=new AE(A,I,1,1),this.setTexture(0,B),this.channels_=tQ(B,Q),this.programName=PD(B),this.depthProgramName="meshDepth"}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=tQ(this.textures[0],A)}setChannelProperty(A,I,B){const Q=eg(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:B,opacity:Q}=this.channels_[0]??eg(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-B[0],u_valueScale:1/(B[1]-B[0]),Opacity:Q,u_worldToTexCoord:this.worldToTexCoord}}}function PD(g){switch(g.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}class CI{normal;signedDistance;constructor(A=yA(0,1,0),I=0){this.normal=$A(A),this.signedDistance=I}static fromPointAndNormal(A,I){return new CI(I,-bg(I,A))}set(A,I){this.normal=$A(A),this.signedDistance=I}signedDistanceToPoint(A){return bg(this.normal,A)+this.signedDistance}normalize(){const A=cB(this.normal);if(A>0){const I=1/A;rB(this.normal,this.normal,I),this.signedDistance*=I}}}function gE(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return LA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=LA(C.clientX,C.clientY);if(ii(A,E)<Q){if(!B)return null;const D=g.worldRay;return D&&I(D).then(a=>{a!==null&&B(a)}).catch(a=>{V.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class UQ{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&V.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),V.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class kQ extends Mg{type="ImageLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;visibleChunks_=new Map;orderedChunks_=[];pool_=new UQ;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;context_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new FA(.6,.3,.3),new FA(.3,.6,.4),new FA(.4,.4,.7),new FA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,orientation:Q,channelProps:C,onPickValue:E,...i}){super({blendMode:"additive",occludes:!0,...i}),this.setState("initialized"),this.source_=A,this.policy_=B??GB(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.channelProps_=C,this.initialChannelProps_=C,this.onPickValue_=E}attach(A){this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),$C(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,B=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:B,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),B=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!B.has(C));this.releaseAndRemoveChunks(Q);for(const C of I)this.visibleChunks_.set(C,this.getImageForChunk(C,C.texture));this.orderedChunks_=I,this.rebuildRenderGroups()}rebuildRenderGroups(){this.clearObjects();for(const A of this.orderedChunks_){const I=this.visibleChunks_.get(A),B=A.chunkIndex.c;I===void 0||this.channelProps_?.[B]?.visible===!1||this.addObject(I,B)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>kQ.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=gE(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const B=I.value.transform,Q=uQ(AA(),yA(0,0,1),B.rotation),C=CI.fromPointAndNormal(B.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}getImageForChunk(A,I){const B=this.visibleChunks_.get(A);if(B)return B;const Q=this.pool_.acquire(wB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(Q,A),Q):this.createImage(A,I)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A,I){const B=new IE({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],texture:I,channelProps:this.getChannelPropsForChunk(A)});return this.updateImageChunk(B,A),B}updateSlicePosition(A,I){const{u:B,v:Q,w:C}=this.axes_,E=AA();E[RA[B]]=I.offset[B],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,B=this.sliceCoords_[I];if(B===void 0)return 0;const Q=(B-A.offset[I])/A.scale[I];return EI(Math.round(Q),0,A.shape[I]-1)}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1;const{u:B,v:Q}=this.axes_;A.transform.setScale([I.scale[B],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=jQ(I,this.axes_)}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const B of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==B)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,B){const Q=YB(AA(),B,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,B)=>{I.setChannelProps(this.getChannelPropsForChunk(B))}),this.rebuildRenderGroups(),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(wB(I,this.axes_),B),this.visibleChunks_.delete(I))}}}function wB(g,A){return[`plane${A.u}${A.v}`,`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class OD extends uI{constructor(A,I,B,Q,C,E){super();const i=[],D=[],a=Math.floor(Q),G=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,G,1,i,D),this.buildFace("z","y","x",1,-1,B,I,A,R,G,-1,i,D),this.buildFace("x","z","y",1,1,A,B,I,a,R,1,i,D),this.buildFace("x","z","y",1,-1,A,B,I,a,R,-1,i,D),this.buildFace("x","y","z",1,-1,A,I,B,a,G,1,i,D),this.buildFace("x","y","z",-1,-1,A,I,B,a,G,-1,i,D),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(D),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,D,a,G,R,U,J){const r=E/a,H=i/G,K=E/2,l=i/2,O=D/2*R,Z=a+1,W=G+1,p=U.length/8;for(let T=0;T<W;T++){const $=-l+T*H;for(let QA=0;QA<Z;QA++){const iA=-K+QA*r,EA={x:0,y:0,z:0};EA[A]=iA*Q,EA[I]=$*C,EA[B]=O;const sA={x:0,y:0,z:0};sA[B]=R;const qA=QA/a,kA=1-T/G;U.push(EA.x,EA.y,EA.z,sA.x,sA.y,sA.z,qA,kA)}}for(let T=0;T<G;T++)for(let $=0;$<a;$++){const QA=p+$+Z*T,iA=p+$+Z*(T+1),EA=p+($+1)+Z*(T+1),sA=p+($+1)+Z*T;J.push(QA,iA,sA,iA,EA,sA)}}}class BE extends Bg{voxelScale=yA(1,1,1);channels_;loadedChannels_=new Set;channelToTextureIndex_=new Map;constructor({channelProps:A=[]}={}){super(),this.geometry=new OD(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[],this.setChannelProps(A)}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){if(!A.texture)return;const I=A.chunkIndex.c,B=this.channelToTextureIndex_.get(I);B!==void 0?this.updateChannelTexture(B,A.texture):this.addChannelTexture(I,A.texture),this.loadedChannels_.add(I)}addChannelTexture(A,I){const B=this.textures.length;this.setTexture(B,I),this.channelToTextureIndex_.set(A,B);const Q=VD(I.dataType);if(this.programName&&this.programName!==Q)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${I.dataType} and program: ${Q}`);this.programName=Q}updateChannelTexture(A,I){this.setTexture(A,I)}clearLoadedChannels(){this.loadedChannels_=new Set}reset(){this.clearTextures(),this.channelToTextureIndex_.clear(),this.clearLoadedChannels()}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],B=[0,0,0,0],Q=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let D=0;D<i&&E.length<4;D++){const a=this.channelToTextureIndex_.get(D);if(a===void 0||!this.loadedChannels_.has(D))continue;const G=this.textures[a],R=eg(G,this.channels_[D]||{});if(!R.visible)continue;const U=E.length;I[U*3]=R.color.rgb[0],I[U*3+1]=R.color.rgb[1],I[U*3+2]=R.color.rgb[2],E.push(a),B[U]=-R.contrastLimits[0],Q[U]=1/(R.contrastLimits[1]-R.contrastLimits[0]),A[U]=1,C[U]=R.opacity}return E.reduce((D,a,G)=>(D[`u_channel${G}Sampler`]=a,D),{u_visible:A,"u_color[0]":I,u_valueOffset:B,u_valueScale:Q,u_channelOpacity:C,u_voxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const B=this.channelToTextureIndex_.get(A);if(B!==void 0)return this.textures[B]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=tQ(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,B){const Q=eg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:B});this.channels_[A]=Q}}function VD(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}const XD=2;class vD extends Mg{type="VolumeLayer";debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;requiresSceneDepth_=!0;source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new UQ;initialChannelProps_;channelChangeCallbacks_=[];policy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:B,channelProps:Q}){super({blendMode:"premultipliedOver"}),this.source_=A,this.sliceCoords_=I,this.policy_=B??GB(),this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const B=this.currentVolumes_.get(A);if(B){for(const E of I)B.updateVolumeWithChunk(E);return B}const Q=_D(I[0]),C=this.pool_.acquire(Q)??new BE;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),$C(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.currentVolumes_.clear(),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,B=zD(A);if(this.lastLoadedTime_!==I||B.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)B.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));for(const[C,E]of B){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length}}updateVolumeTransform(A,I){const B={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([B.x,B.y,B.z]),JI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+Q.x,I.offset.y+Q.y,I.offset.z+Q.z])}releaseAndRemoveVolume(A){A.reset(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?XD:1,this.updateChunks(),this.rebuildObjects(A.camera)}rebuildObjects(A){const I=Array.from(this.currentVolumes_.values());$D(I,A),this.clearObjects();for(const B of I)this.addObject(B)}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function jD(g){const{x:A,y:I,z:B,t:Q}=g.chunkIndex;return`${A}:${I}:${B}:${Q}`}function zD(g){const A=new Map;for(const I of g){const B=jD(I);let Q=A.get(B);Q||(Q=[],A.set(B,Q)),Q.push(I)}return A}function _D(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}function $D(g,A){const I=A.position,B=new Map;for(const Q of g){const C=Q.transform.translation;B.set(Q,jE(I,C))}g.sort((Q,C)=>B.get(C)-B.get(Q))}class QE extends lB{width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=dB(A),this.data_=A,this.width_=I,this.height_=B}get type(){return"Texture2D"}get width(){return this.width_}get height(){return this.height_}}const Aa=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Ia(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,FA.from(I)]))}function ga(g){return g=g??Aa,g.map(FA.from)}function SB(g={}){return{lookupTable:Ia(g.lookupTable),cycle:ga(g.cycle)}}const CE=new Set(["byte","short","int"]),Ba=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function Qa(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!CE.has(g.dataType)&&!Ba.has(g.dataType))throw new Error(`Image data type must be an integer, instead found: ${g.dataType}`);return g}function Ca(g){return CE.has(g.dataType)?"intLabelImage":"labelImage"}class EE extends Bg{worldToTexCoord=WA();outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new AE(A.width,A.height,1,1),this.setTexture(0,Qa(A.imageData));const I=SB(A.colorMap);this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable)),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName=Ca(A.imageData),this.depthProgramName="meshDepth"}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_worldToTexCoord:this.worldToTexCoord}}setColorMap(A){const I=SB(A);this.markStaleTexture(this.textures[1]),this.markStaleTexture(this.textures[2]),this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new QE(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,FA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,FA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new QE(C,Q,2)}}class cQ extends Mg{type="LabelLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new UQ;colorMap_;selectedValue_=null;policy_;chunkStoreView_;context_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:B,orientation:Q,colorMap:C={},onPickValue:E,outlineSelected:i=!1,...D}){super(D),this.setState("initialized"),this.source_=A,this.policy_=B??GB(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.colorMap_=SB(C),this.onPickValue_=E,this.outlineSelected_=i}attach(A){if(this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,B=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:B,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),B=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!B.has(C));this.releaseAndRemoveChunks(Q),this.clearObjects();for(const C of I){const E=this.getLabelForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E,0)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>cQ.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=gE(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const B=I.value.transform,Q=uQ(AA(),yA(0,0,1),B.rotation),C=CI.fromPointAndNormal(B.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=SB(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const B of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==B)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,B){const Q=YB(AA(),B,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}getLabelForChunk(A,I){const B=this.visibleChunks_.get(A);if(B)return B;const Q=this.pool_.acquire(wB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setColorMap(this.colorMap_),Q.setSelectedValue(this.selectedValue_),this.updateLabelChunk(Q,A),Q):this.createLabel(A,I)}createLabel(A,I){const B=new EE({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],imageData:I,colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(B,A),B}updateSlicePosition(A,I){const{u:B,v:Q,w:C}=this.axes_,E=AA();E[RA[B]]=I.offset[B],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,B=this.sliceCoords_[I];if(B===void 0)return 0;const Q=(B-A.offset[I])/A.scale[I];return EI(Math.round(Q),0,A.shape[I]-1)}updateLabelChunk(A,I){const{u:B,v:Q}=this.axes_;A.transform.setScale([I.scale[B],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=jQ(I,this.axes_)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(wB(I,this.axes_),B),this.visibleChunks_.delete(I))}}}class Ea extends lB{width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=dB(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}}const iE={circle:0,square:1,triangle:2};class ia extends Bg{constructor(A){super(),this.programName="points",this.depthProgramName="pointsDepth";const I=A.flatMap(Q=>{const C=FA.from(Q.color);return[Q.position[0],Q.position[1],Q.position[2],C.r,C.g,C.b,C.a,Q.size,iE[Q.marker]]}),B=new uI(I,[],"points");B.addAttribute({type:"position",itemSize:3,offset:0}),B.addAttribute({type:"color",itemSize:4,offset:B.strideBytes}),B.addAttribute({type:"size",itemSize:1,offset:B.strideBytes}),B.addAttribute({type:"marker",itemSize:1,offset:B.strideBytes}),this.geometry=B,this.setTexture(0,oa())}get type(){return"PointsRenderable"}}let LQ;function oa(){return LQ||(LQ=Da()),LQ}function Da(){const g=a=>{const G=new Float32Array(a*a);return G.fill(1),G},A=a=>{const G=new Float32Array(a*a);for(let R=0;R<a;R++)for(let U=0;U<a;U++)(R-a/2)**2+(U-a/2)**2<(a/2)**2&&(G[R*a+U]=1);return G},I=a=>{const G=new Float32Array(a*a);for(let R=0;R<a;R++)for(let U=0;U<a;U++)U>=(a-R)/2&&U<=(a+R)/2&&(G[R*a+U]=1);return G},C={circle:A(256),square:g(256),triangle:I(256)},E=Object.keys(C).length,i=new Float32Array(E*65536);for(const[a,G]of Object.entries(C))i.set(G,iE[a]*65536);const D=new Ea(i,256,256);return D.wrapR="clamp_to_edge",D.wrapS="clamp_to_edge",D.wrapT="clamp_to_edge",D}class oE{planes_;constructor(A){this.planes_=[new CI(AA(),0),new CI(AA(),0),new CI(AA(),0),new CI(AA(),0),new CI(AA(),0),new CI(AA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=AA();this.planes_[0].set(JI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(JI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(JI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(JI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(JI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(JI(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=AA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class JQ extends xg{transform_=new SQ;projectionMatrix_=WA();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get transform(){return this.transform_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return yA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return yA(A[4],A[5],A[6])}getViewProjection(){return Zg(WA(),this.projectionMatrix,this.viewMatrix)}get frustum(){return new oE(this.getViewProjection())}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=Og(A[0],A[1],A[2],1),B=Sg(WA(),this.projectionMatrix_),Q=Rg(ZI(),I,B);Ii(Q,Q,1/Q[3]);const C=Rg(ZI(),Q,this.transform.matrix);return yA(C[0],C[1],C[2])}}class DE{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return yA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const rQ=-1,aE=0,aa=1,sE=.009,sa=.001,ya=9e-4,ha=.5,Ga=60;class Fa{camera_;orbitVelocity_=new DE(0,0,0);panVelocity_=AA();currPos_;currCenter_=AA();dampingFactor_;currMouseButton_=rQ;constructor(A,I){this.camera_=A,this.currPos_=new DE(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&LB(this.currCenter_,I.target),this.dampingFactor_=EI(I?.dampingFactor??ha,0,1),this.updateCamera()}get radius(){return this.currPos_.radius}get yaw(){return this.currPos_.phi}get pitch(){return this.currPos_.theta}get target(){return $A(this.currCenter_)}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&KB(this.panVelocity_,yA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,ug(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-wA;this.currPos_.theta=EI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const B=Math.pow(1-this.dampingFactor_,A*Ga);this.orbitVelocity_.phi*=B,this.orbitVelocity_.theta*=B,this.orbitVelocity_.radius*=B,rB(this.panVelocity_,this.panVelocity_,B),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==rQ)return;const I=A.event,B=I.movementX??0,Q=I.movementY??0,C=this.currMouseButton_===aE&&!I.shiftKey,E=this.currMouseButton_===aE&&I.shiftKey||this.currMouseButton_===aa;C&&this.orbit(B,Q),E&&this.pan(B,Q)}onWheel(A){const I=A.event;I.preventDefault();const B=I.deltaY??0;this.zoom(B)}onPointerEnd(A){this.currMouseButton_=rQ;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*sE,this.orbitVelocity_.theta+=I*sE}pan(A,I){const B=this.currPos_.radius*sa,Q=AA();nB(Q,Q,this.camera_.right,A),nB(Q,Q,this.camera_.up,I),rB(Q,Q,B),MB(this.panVelocity_,this.panVelocity_,Q)}zoom(A){this.orbitVelocity_.radius+=A*ya}updateCamera(){const A=ug(AA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<wA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<wA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<wA&&(this.orbitVelocity_.radius=0),cB(this.panVelocity_)<wA&&zE(this.panVelocity_)}}const yE=1.77,hE=128,GE=128/yE,wa=-1e6,Sa=1e6;class Ra extends JQ{width_=hE;height_=GE;viewportAspectRatio_=yE;viewportSize_=[hE,GE];axes_;rotation_;orientation_;constructor(A){super(),this.near_=A.near??wa,this.far_=A.far??Sa,this.orientation_=A.orientation??"XY",this.axes_=bI(this.orientation_),this.rotation_=PI(this.axes_),this.setFrame(A),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame({left:A,right:I,top:B,bottom:Q}){this.width_=Math.abs(I-A),this.height_=Math.abs(B-Q),this.updateProjectionMatrix();const C=AA();C[RA[this.axes_.u]]=.5*(A+I),C[RA[this.axes_.v]]=.5*(Q+B),this.transform.setTranslation(C),this.transform.setScale([1,1,1]),this.transform.setRotation(this.rotation_)}get type(){return"OrthographicCamera"}get orientation(){return this.orientation_}setOrientation(A){if(A===this.orientation_)return;const I=this.transform.translation[RA[this.axes_.u]],B=this.transform.translation[RA[this.axes_.v]];this.orientation_=A,this.axes_=bI(A),this.rotation_=PI(this.axes_);const Q=AA();Q[RA[this.axes_.u]]=I,Q[RA[this.axes_.v]]=B,this.transform.setTranslation(Q),this.transform.setRotation(this.rotation_)}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=Og(-1,-1,0,1),I=Og(1,1,0,1);const B=Sg(WA(),this.getViewProjection());A=Rg(ZI(),A,B),I=Rg(ZI(),I,B);const Q=RA[this.axes_.u],C=RA[this.axes_.v];return new ZA(LA(A[Q],A[C]),LA(I[Q],I[C]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],OE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const FE=0;class Na{camera_;dragActive_=!1;dragStart_=AA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=$A(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=MB(AA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==FE||(this.dragStart_=$A(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=MB(AA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==FE||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}const ta=60,Ua=1.77,RB=.1,nQ=180-RB;class ka extends JQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=ta,aspectRatio:B=Ua,near:Q=.1,far:C=1e4,position:E=yA(0,0,0)}=A;if(I<RB||I>nQ)throw new Error(`Invalid field of view: ${I}, must be in [${RB}, ${nQ}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(RB,Math.min(nQ,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){bE(this.projectionMatrix_,WE(this.fov),this.aspectRatio_,this.near_,this.far_)}}var YQ=(()=>{for(var g=new Uint8Array(128),A=0;A<64;A++)g[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var B=I.length,Q=new Uint8Array((B-(I[B-1]=="=")-(I[B-2]=="="))*3/4|0),C=0,E=0;C<B;){var i=g[I.charCodeAt(C++)],D=g[I.charCodeAt(C++)],a=g[I.charCodeAt(C++)],G=g[I.charCodeAt(C++)];Q[E++]=i<<2|D>>4,Q[E++]=D<<4|a>>2,Q[E++]=a<<6|G}return Q}})(),ca=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(g={}){var A=g,I,B;A.ready=new Promise((s,h)=>{I=s,B=h});var Q=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,Q),Q=null,A.thisProgram&&(C=A.thisProgram);var D;A.wasmBinary&&(D=A.wasmBinary),typeof WebAssembly!="object"&&EA("no native wasm support detected");var a,G=!1,R,U,J,r,H,K,l,O;function Z(){var s=a.buffer;A.HEAP8=R=new Int8Array(s),A.HEAP16=J=new Int16Array(s),A.HEAPU8=U=new Uint8Array(s),A.HEAPU16=r=new Uint16Array(s),A.HEAP32=H=new Int32Array(s),A.HEAPU32=K=new Uint32Array(s),A.HEAPF32=l=new Float32Array(s),A.HEAPF64=O=new Float64Array(s)}var W=[],p=[],T=[];function $(){var s=A.preRun.shift();W.unshift(s)}var QA=0,iA=null;function EA(s){throw A.onAbort?.(s),s="Aborted("+s+")",i(s),G=!0,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),B(s),s}var sA=s=>s.startsWith("data:application/octet-stream;base64,"),qA=s=>s.startsWith("file://"),kA;if(kA="blosc_codec.wasm",!sA(kA)){var aA=kA;kA=A.locateFile?A.locateFile(aA,""):""+aA}function oI(s){return Promise.resolve().then(()=>{if(s==kA&&D)var h=new Uint8Array(D);else throw"both async and sync fetching of the wasm failed";return h})}function II(s,h,S){return oI(s).then(c=>WebAssembly.instantiate(c,h)).then(c=>c).then(S,c=>{i(`failed to asynchronously prepare wasm: ${c}`),EA(c)})}function DI(s,h){var S=kA;return D||typeof WebAssembly.instantiateStreaming!="function"||sA(S)||qA(S)||typeof fetch!="function"?II(S,s,h):fetch(S,{credentials:"same-origin"}).then(c=>WebAssembly.instantiateStreaming(c,s).then(h,function(o){return i(`wasm streaming compile failed: ${o}`),i("falling back to ArrayBuffer instantiation"),II(S,s,h)}))}var RI=s=>{for(;0<s.length;)s.shift()(A)};function NI(s){this.H=s-24,this.N=function(h){K[this.H+4>>2]=h},this.M=function(h){K[this.H+8>>2]=h},this.I=function(h,S){this.J(),this.N(h),this.M(S)},this.J=function(){K[this.H+16>>2]=0}}var fA=0,nA,NA=s=>{for(var h="";U[s];)h+=nA[U[s++]];return h},eA={},SA={},cA={},YA,MI=s=>{throw new YA(s)},eI,XA=(s,h)=>{function S(t){if(t=h(t),t.length!==c.length)throw new eI("Mismatched type converter count");for(var N=0;N<c.length;++N)tA(c[N],t[N])}var c=[];c.forEach(function(t){cA[t]=s});var o=Array(s.length),y=[],w=0;s.forEach((t,N)=>{SA.hasOwnProperty(t)?o[N]=SA[t]:(y.push(t),eA.hasOwnProperty(t)||(eA[t]=[]),eA[t].push(()=>{o[N]=SA[t],++w,w===y.length&&S(o)}))}),y.length===0&&S(o)};function uA(s,h,S={}){var c=h.name;if(!s)throw new YA(`type "${c}" must have a positive integer typeid pointer`);if(SA.hasOwnProperty(s)){if(S.P)return;throw new YA(`Cannot register type '${c}' twice`)}SA[s]=h,delete cA[s],eA.hasOwnProperty(s)&&(h=eA[s],delete eA[s],h.forEach(o=>o()))}function tA(s,h,S={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");uA(s,h,S)}function bA(){this.F=[void 0],this.K=[]}var dA=new bA,aI=s=>{s>=dA.H&&--dA.get(s).L===0&&dA.J(s)},og=s=>{switch(s){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return dA.I({L:1,value:s})}};function tI(s){return this.fromWireType(H[s>>2])}var HI=(s,h)=>{switch(h){case 4:return function(S){return this.fromWireType(l[S>>2])};case 8:return function(S){return this.fromWireType(O[S>>3])};default:throw new TypeError(`invalid float width (${h}): ${s}`)}},UI=(s,h)=>Object.defineProperty(h,"name",{value:s}),Dg=s=>{for(;s.length;){var h=s.pop();s.pop()(h)}};function ag(s){for(var h=1;h<s.length;++h)if(s[h]!==null&&s[h].G===void 0)return!0;return!1}function Hg(s){var h=Function;if(!(h instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof h} which is not a function`);var S=UI(h.name||"unknownFunctionName",function(){});return S.prototype=h.prototype,S=new S,s=h.apply(S,s),s instanceof Object?s:S}var qg=(s,h)=>{if(A[s].C===void 0){var S=A[s];A[s]=function(){if(!A[s].C.hasOwnProperty(arguments.length))throw new YA(`Function '${h}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[s].C})!`);return A[s].C[arguments.length].apply(this,arguments)},A[s].C=[],A[s].C[S.O]=S}},qI=(s,h,S)=>{if(A.hasOwnProperty(s)){if(S===void 0||A[s].C!==void 0&&A[s].C[S]!==void 0)throw new YA(`Cannot register public name '${s}' twice`);if(qg(s,s),A.hasOwnProperty(S))throw new YA(`Cannot register multiple overloads of a function with the same number of arguments (${S})!`);A[s].C[S]=h}else A[s]=h,S!==void 0&&(A[s].S=S)},dI=(s,h)=>{for(var S=[],c=0;c<s;c++)S.push(K[h+4*c>>2]);return S},fI,sg=(s,h)=>{var S=[];return function(){if(S.length=0,Object.assign(S,arguments),s.includes("j")){var c=A["dynCall_"+s];c=S&&S.length?c.apply(null,[h].concat(S)):c.call(null,h)}else c=fI.get(h).apply(null,S);return c}},yg=(s,h)=>{s=NA(s);var S=s.includes("j")?sg(s,h):fI.get(h);if(typeof S!="function")throw new YA(`unknown function pointer with signature ${s}: ${h}`);return S},lI,pI=s=>{s=f(s);var h=NA(s);return n(s),h},dg=(s,h)=>{function S(y){o[y]||SA[y]||(cA[y]?cA[y].forEach(S):(c.push(y),o[y]=!0))}var c=[],o={};throw h.forEach(S),new lI(`${s}: `+c.map(pI).join([", "]))},fg=s=>{s=s.trim();const h=s.indexOf("(");return h!==-1?s.substr(0,h):s},hg=(s,h,S)=>{switch(h){case 1:return S?c=>R[c>>0]:c=>U[c>>0];case 2:return S?c=>J[c>>1]:c=>r[c>>1];case 4:return S?c=>H[c>>2]:c=>K[c>>2];default:throw new TypeError(`invalid integer width (${h}): ${s}`)}};function WI(s){return this.fromWireType(K[s>>2])}for(var kI=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,mI=(s,h,S)=>{var c=h+S;for(S=h;s[S]&&!(S>=c);)++S;if(16<S-h&&s.buffer&&kI)return kI.decode(s.subarray(h,S));for(c="";h<S;){var o=s[h++];if(o&128){var y=s[h++]&63;if((o&224)==192)c+=String.fromCharCode((o&31)<<6|y);else{var w=s[h++]&63;o=(o&240)==224?(o&15)<<12|y<<6|w:(o&7)<<18|y<<12|w<<6|s[h++]&63,65536>o?c+=String.fromCharCode(o):(o-=65536,c+=String.fromCharCode(55296|o>>10,56320|o&1023))}}else c+=String.fromCharCode(o)}return c},Gg=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,lg=(s,h)=>{for(var S=s>>1,c=S+h/2;!(S>=c)&&r[S];)++S;if(S<<=1,32<S-s&&Gg)return Gg.decode(U.subarray(s,S));for(S="",c=0;!(c>=h/2);++c){var o=J[s+2*c>>1];if(o==0)break;S+=String.fromCharCode(o)}return S},pg=(s,h,S)=>{if(S??=2147483647,2>S)return 0;S-=2;var c=h;S=S<2*s.length?S/2:s.length;for(var o=0;o<S;++o)J[h>>1]=s.charCodeAt(o),h+=2;return J[h>>1]=0,h-c},Wg=s=>2*s.length,Fg=(s,h)=>{for(var S=0,c="";!(S>=h/4);){var o=H[s+4*S>>2];if(o==0)break;++S,65536<=o?(o-=65536,c+=String.fromCharCode(55296|o>>10,56320|o&1023)):c+=String.fromCharCode(o)}return c},cI=(s,h,S)=>{if(S??=2147483647,4>S)return 0;var c=h;S=c+S-4;for(var o=0;o<s.length;++o){var y=s.charCodeAt(o);if(55296<=y&&57343>=y){var w=s.charCodeAt(++o);y=65536+((y&1023)<<10)|w&1023}if(H[h>>2]=y,h+=4,h+4>S)break}return H[h>>2]=0,h-c},TI=s=>{for(var h=0,S=0;S<s.length;++S){var c=s.charCodeAt(S);55296<=c&&57343>=c&&++S,h+=4}return h},TA={},gI=()=>{if(!xA){var s={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"},h;for(h in TA)TA[h]===void 0?delete s[h]:s[h]=TA[h];var S=[];for(h in s)S.push(`${h}=${s[h]}`);xA=S}return xA},xA,UA=[null,[],[]],BI=Array(256),HA=0;256>HA;++HA)BI[HA]=String.fromCharCode(HA);nA=BI,YA=A.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},eI=A.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Object.assign(bA.prototype,{get(s){return this.F[s]},has(s){return this.F[s]!==void 0},I(s){var h=this.K.pop()||this.F.length;return this.F[h]=s,h},J(s){this.F[s]=void 0,this.K.push(s)}}),dA.F.push({value:void 0},{value:null},{value:!0},{value:!1}),dA.H=dA.F.length,A.count_emval_handles=()=>{for(var s=0,h=dA.H;h<dA.F.length;++h)dA.F[h]!==void 0&&++s;return s},lI=A.UnboundTypeError=((s,h)=>{var S=UI(h,function(c){this.name=h,this.message=c,c=Error(c).stack,c!==void 0&&(this.stack=this.toString()+`
4122
+ ${JSON.stringify(g)}`)}}class gg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let B=Ig(I);const Q=await rg(A,B),C=wQ(Q.attrs),E=C.multiscales;if(E.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${E.length} images.`);const i=E[0];if(i.datasets.length===0)throw new Error("No datasets found in the multiscale image.");B||(B=Ig(C.originalVersion));const D=i.datasets.map(U=>Yo(A,U.path,B)),a=await Promise.all(D.map(U=>no(U))),G=a[0].shape,R=i.axes;if(R.length!==G.length)throw new Error(`Mismatch between number of axes (${R.length}) and array shape (${G.length})`);return new xo({metadata:i,arrays:a,arrayParams:D})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}get loader(){return this.loader_}static async fromHttp(A){const I=new vA(new kg(A.url)),B=await gg.openLoader(I,A.version);return new gg({location:I,version:A.version,loader:B})}static async fromFileSystem(A){const I=new vA(new QQ(A.directory),A.path),B=await gg.openLoader(I,A.version);return new gg({location:I,version:A.version,loader:B})}}class Mg{blendMode;occludes;requiresSceneDepth_=!1;coverageGroups_=new Map;state_="initialized";attached_=!1;callbacks_=[];opacity_;constructor({opacity:A=1,blendMode:I="none",occludes:B}={}){this.opacity_=EI(A,0,1),this.blendMode=I,this.occludes=B??I==="none"}get requiresSceneDepth(){return this.requiresSceneDepth_}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&V.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=EI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);if(this.occludes&&this.requiresSceneDepth_)throw new Error(`${this.type} cannot both occlude and read scene depth.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}get coverageGroups(){return this.coverageGroups_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(B=>B(A,I))}addObject(A,I=null){const B=this.coverageGroups_.get(I);B?B.push(A):this.coverageGroups_.set(I,[A])}clearObjects(){this.coverageGroups_.clear()}getUniforms(){return{}}}class pD extends uI{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*10),B=A.length>=3&&KB(A[0],A[A.length-1]);let Q=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[Q++]=i[0],I[Q++]=i[1],I[Q++]=i[2];const D=C===0?B?A[A.length-2]:A[C]:A[C-1];I[Q++]=D[0],I[Q++]=D[1],I[Q++]=D[2];const a=C===A.length-1?B?A[1]:A[C]:A[C+1];I[Q++]=a[0],I[Q++]=a[1],I[Q++]=a[2],I[Q++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class WD extends uI{constructor(A){if(super(),A.primitive!="triangles"){V.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){V.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const D=Math.min(E,i),a=Math.max(E,i);I.has({i0:D,i1:a})||(I.add({i0:D,i1:a}),B.push(D,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],D=C[E+1],a=C[E+2];Q(i,D),Q(D,a),Q(a,i)}this.indexData_=new Uint32Array(B)}}const mD=yA(0,1,0);class SQ{dirty_=!0;matrix_=WA();rotation_=Vg();translation_=AA();scale_=yA(1,1,1);addRotation(A){Qi(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){Ei(this.rotation_,A),this.dirty_=!0}get rotation(){return Ci(this.rotation_)}addTranslation(A){ug(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){LB(this.translation_,A),this.dirty_=!0}get translation(){return $A(this.translation_)}addScale(A){vE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){LB(this.scale_,A),this.dirty_=!0}targetTo(A){KB(this.translation_,A)&&(A=$A(A),A[2]+=wA);const I=VE(WA(),this.translation_,A,mD),B=mE(TQ(),I);HB(this.rotation_,B),Xg(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return $A(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return Sg(WA(),this.matrix)}computeMatrix(){ZE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class FA{static RED=new FA(1,0,0);static GREEN=new FA(0,1,0);static BLUE=new FA(0,0,1);static YELLOW=new FA(1,1,0);static MAGENTA=new FA(1,0,1);static CYAN=new FA(0,1,1);static BLACK=new FA(0,0,0);static WHITE=new FA(1,1,1);static TRANSPARENT=new FA(0,0,0,0);rgba_;constructor(A,I,B,Q){if(A<0||A>1||I<0||I>1||B<0||B>1)throw new Error("RGB values must be in the range [0, 1]");if(Q!==void 0&&(Q<0||Q>1))throw new Error("Alpha value must be in the range [0, 1]");this.rgba_=[A,I,B,Q??1]}get rgb(){return[this.rgba_[0],this.rgba_[1],this.rgba_[2]]}get rgba(){return this.rgba_}get r(){return this.rgba_[0]}get g(){return this.rgba_[1]}get b(){return this.rgba_[2]}get a(){return this.rgba_[3]}get rgbHex(){return`#${this.toHexComponent(this.r)}${this.toHexComponent(this.g)}${this.toHexComponent(this.b)}`}get packed(){return Math.round(this.r*255)<<24|Math.round(this.g*255)<<16|Math.round(this.b*255)<<8|Math.round(this.a*255)}static from(A){if(A instanceof FA)return A;if(Array.isArray(A))return new FA(A[0],A[1],A[2],A[3]);if(typeof A=="string")return FA.fromRgbHex(A);throw new Error("Unsupported color format")}static fromRgbHex(A){const I=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(A);if(!I)throw new Error("Invalid RGB hex, use form '#RRGGBB'");return new FA(parseInt(I[1],16)/255,parseInt(I[2],16)/255,parseInt(I[3],16)/255,1)}toHexComponent(A){const I=Math.round(A*255).toString(16).padStart(2,"0");return I.length===1?"0"+I:I}}class Bg extends xg{wireframeEnabled=!1;wireframeColor=FA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new SQ;geometry_=new uI;wireframeGeometry_=null;programName_=null;depthProgramName_=null;cullFaceMode_="none";setTexture(A,I){this.textures_[A]=I}clearTextures(){this.textures_.length=0}markStaleTexture(A){A!==void 0&&this.staleTextures_.push(A)}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new WD(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get depthProgramName(){return this.depthProgramName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}set depthProgramName(A){this.depthProgramName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class jC extends Bg{color_;width_;constructor({geometry:A,color:I,width:B}){super(),this.geometry=A,this.color_=FA.from(I),this.width_=B,this.programName="projectedLine",this.depthProgramName="projectedLineDepth"}get type(){return"ProjectedLineRenderable"}get color(){return this.color_}set color(A){this.color_=FA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{u_lineColor:this.color.rgb,u_lineWidth:this.width}}}class TD extends Mg{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(RQ({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(RQ({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(RQ({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function RQ(g){const{end:A,width:I,color:B}=g,Q=new pD([[0,0,0],A]);return new jC({geometry:Q,color:B,width:I})}const zC=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function GB(g={}){return FB(NQ({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},g))}function xD(g={}){return FB(NQ({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","visibleCurrent","prefetchTime","fallbackBackground","prefetchSpace"]},g))}function ZD(g={}){return FB(NQ({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},g))}function FB(g){uD(g);const A={x:g.prefetch.x,y:g.prefetch.y,z:g.prefetch.z??0,t:g.prefetch.t??0},I=Object.freeze(zC.reduce((C,E)=>{const i=g.priorityOrder.indexOf(E);return C[E]=i,C},{})),B={min:g.lod?.min??0,max:g.lod?.max??Number.MAX_SAFE_INTEGER,bias:g.lod?.bias??.5},Q={profile:g.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...g.priorityOrder]),priorityMap:I,lod:B};return Object.freeze(Q)}function uD(g){for(const[B,Q]of Object.entries(g.prefetch))if(Q!==void 0&&Q<0)throw new Error(`prefetch.${B} must be a non-negative number`);const A=g.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=g.priorityOrder;if(I.length!==zC.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function NQ(g,A={}){return{profile:A.profile??g.profile,prefetch:{...g.prefetch,...A.prefetch??{}},lod:{...g.lod,...A.lod??{}},priorityOrder:A.priorityOrder??g.priorityOrder}}const _C=32;function eg(g,{visible:A,color:I,contrastLimits:B,opacity:Q}){return A??=!0,I=I===void 0?FA.WHITE:FA.from(I),Q=Q===void 0?1:EI(Q,0,1),g!==null?B=bD(B,g):B===void 0&&(V.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B,opacity:Q}}function tQ(g,A){if(A.length>_C)throw new Error(`Maximum number of channels is ${_C}`);return A.map(I=>eg(g,I))}function $C(g,A){if(g&&g.length!==A)throw new Error(`channelProps length (${g.length}) must match source channel count (${A}).`)}function bD(g,A){if(g===void 0)return Fi(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AE extends uI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,D=Q,a=i+1,G=D+1,R=A/i,U=I/D;for(let J=0;J<G;++J){const r=J*U;for(let H=0;H<a;++H){const K=H*R,l=H/i,O=J/D,Z=[K,r,0],W=[0,0,1],p=[l,O];C.push(...Z,...W,...p)}}for(let J=0;J<D;++J)for(let r=0;r<i;++r){const H=r+a*J,K=r+a*(J+1),l=r+1+a*(J+1),O=r+1+a*J;E.push(H,K,O),E.push(K,l,O)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class IE extends Bg{worldToTexCoord=WA();channels_;constructor({width:A,height:I,texture:B,channelProps:Q=[]}){super(),this.geometry=new AE(A,I,1,1),this.setTexture(0,B),this.channels_=tQ(B,Q),this.programName=PD(B),this.depthProgramName="meshDepth"}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=tQ(this.textures[0],A)}setChannelProperty(A,I,B){const Q=eg(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:B,opacity:Q}=this.channels_[0]??eg(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-B[0],u_valueScale:1/(B[1]-B[0]),Opacity:Q,u_worldToTexCoord:this.worldToTexCoord}}}function PD(g){switch(g.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}class CI{normal;signedDistance;constructor(A=yA(0,1,0),I=0){this.normal=$A(A),this.signedDistance=I}static fromPointAndNormal(A,I){return new CI(I,-bg(I,A))}set(A,I){this.normal=$A(A),this.signedDistance=I}signedDistanceToPoint(A){return bg(this.normal,A)+this.signedDistance}normalize(){const A=cB(this.normal);if(A>0){const I=1/A;rB(this.normal,this.normal,I),this.signedDistance*=I}}}function gE(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return LA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=LA(C.clientX,C.clientY);if(ii(A,E)<Q){if(!B)return null;const D=g.worldRay;return D&&I(D).then(a=>{a!==null&&B(a)}).catch(a=>{V.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class UQ{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&V.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),V.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class kQ extends Mg{type="ImageLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;visibleChunks_=new Map;orderedChunks_=[];pool_=new UQ;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;context_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new FA(.6,.3,.3),new FA(.3,.6,.4),new FA(.4,.4,.7),new FA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,orientation:Q,channelProps:C,onPickValue:E,...i}){super({blendMode:"additive",occludes:!0,...i}),this.setState("initialized"),this.source_=A,this.policy_=B??GB(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.channelProps_=C,this.initialChannelProps_=C,this.onPickValue_=E}attach(A){this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),$C(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,B=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:B,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.orderedChunks_=[],this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),B=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!B.has(C));this.releaseAndRemoveChunks(Q);for(const C of I)this.visibleChunks_.set(C,this.getImageForChunk(C,C.texture));this.orderedChunks_=I,this.rebuildRenderGroups()}rebuildRenderGroups(){this.clearObjects();for(const A of this.orderedChunks_){const I=this.visibleChunks_.get(A),B=A.chunkIndex.c;I===void 0||this.channelProps_?.[B]?.visible===!1||this.addObject(I,B)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>kQ.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=gE(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const B=I.value.transform,Q=uQ(AA(),yA(0,0,1),B.rotation),C=CI.fromPointAndNormal(B.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}getImageForChunk(A,I){const B=this.visibleChunks_.get(A);if(B)return B;const Q=this.pool_.acquire(wB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(Q,A),Q):this.createImage(A,I)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A,I){const B=new IE({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],texture:I,channelProps:this.getChannelPropsForChunk(A)});return this.updateImageChunk(B,A),B}updateSlicePosition(A,I){const{u:B,v:Q,w:C}=this.axes_,E=AA();E[RA[B]]=I.offset[B],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,B=this.sliceCoords_[I];if(B===void 0)return 0;const Q=(B-A.offset[I])/A.scale[I];return EI(Math.round(Q),0,A.shape[I]-1)}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1;const{u:B,v:Q}=this.axes_;A.transform.setScale([I.scale[B],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=jQ(I,this.axes_)}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const B of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==B)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,B){const Q=YB(AA(),B,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,B)=>{I.setChannelProps(this.getChannelPropsForChunk(B))}),this.rebuildRenderGroups(),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(wB(I,this.axes_),B),this.visibleChunks_.delete(I))}}}function wB(g,A){return[`plane${A.u}${A.v}`,`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class OD extends uI{constructor(A,I,B,Q,C,E){super();const i=[],D=[],a=Math.floor(Q),G=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,G,1,i,D),this.buildFace("z","y","x",1,-1,B,I,A,R,G,-1,i,D),this.buildFace("x","z","y",1,1,A,B,I,a,R,1,i,D),this.buildFace("x","z","y",1,-1,A,B,I,a,R,-1,i,D),this.buildFace("x","y","z",1,-1,A,I,B,a,G,1,i,D),this.buildFace("x","y","z",-1,-1,A,I,B,a,G,-1,i,D),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(D),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,D,a,G,R,U,J){const r=E/a,H=i/G,K=E/2,l=i/2,O=D/2*R,Z=a+1,W=G+1,p=U.length/8;for(let T=0;T<W;T++){const $=-l+T*H;for(let QA=0;QA<Z;QA++){const iA=-K+QA*r,EA={x:0,y:0,z:0};EA[A]=iA*Q,EA[I]=$*C,EA[B]=O;const sA={x:0,y:0,z:0};sA[B]=R;const qA=QA/a,kA=1-T/G;U.push(EA.x,EA.y,EA.z,sA.x,sA.y,sA.z,qA,kA)}}for(let T=0;T<G;T++)for(let $=0;$<a;$++){const QA=p+$+Z*T,iA=p+$+Z*(T+1),EA=p+($+1)+Z*(T+1),sA=p+($+1)+Z*T;J.push(QA,iA,sA,iA,EA,sA)}}}class BE extends Bg{voxelScale=yA(1,1,1);channels_;loadedChannels_=new Set;channelToTextureIndex_=new Map;constructor({channelProps:A=[]}={}){super(),this.geometry=new OD(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[],this.setChannelProps(A)}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){if(!A.texture)return;const I=A.chunkIndex.c,B=this.channelToTextureIndex_.get(I);B!==void 0?this.updateChannelTexture(B,A.texture):this.addChannelTexture(I,A.texture),this.loadedChannels_.add(I)}addChannelTexture(A,I){const B=this.textures.length;this.setTexture(B,I),this.channelToTextureIndex_.set(A,B);const Q=VD(I.dataType);if(this.programName&&this.programName!==Q)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${I.dataType} and program: ${Q}`);this.programName=Q}updateChannelTexture(A,I){this.setTexture(A,I)}clearLoadedChannels(){this.loadedChannels_=new Set}reset(){this.clearTextures(),this.channelToTextureIndex_.clear(),this.clearLoadedChannels()}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],B=[0,0,0,0],Q=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let D=0;D<i&&E.length<4;D++){const a=this.channelToTextureIndex_.get(D);if(a===void 0||!this.loadedChannels_.has(D))continue;const G=this.textures[a],R=eg(G,this.channels_[D]||{});if(!R.visible)continue;const U=E.length;I[U*3]=R.color.rgb[0],I[U*3+1]=R.color.rgb[1],I[U*3+2]=R.color.rgb[2],E.push(a),B[U]=-R.contrastLimits[0],Q[U]=1/(R.contrastLimits[1]-R.contrastLimits[0]),A[U]=1,C[U]=R.opacity}return E.reduce((D,a,G)=>(D[`u_channel${G}Sampler`]=a,D),{u_visible:A,"u_color[0]":I,u_valueOffset:B,u_valueScale:Q,u_channelOpacity:C,u_voxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const B=this.channelToTextureIndex_.get(A);if(B!==void 0)return this.textures[B]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=tQ(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,B){const Q=eg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:B});this.channels_[A]=Q}}function VD(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}const XD=2;class vD extends Mg{type="VolumeLayer";debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;requiresSceneDepth_=!0;source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new UQ;initialChannelProps_;channelChangeCallbacks_=[];policy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:B,channelProps:Q}){super({blendMode:"premultipliedOver"}),this.source_=A,this.sliceCoords_=I,this.policy_=B??GB(),this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const B=this.currentVolumes_.get(A);if(B){for(const E of I)B.updateVolumeWithChunk(E);return B}const Q=_D(I[0]),C=this.pool_.acquire(Q)??new BE;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),$C(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.currentVolumes_.clear(),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,B=zD(A);if(this.lastLoadedTime_!==I||B.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)B.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));for(const[C,E]of B){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length}}updateVolumeTransform(A,I){const B={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([B.x,B.y,B.z]),JI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+Q.x,I.offset.y+Q.y,I.offset.z+Q.z])}releaseAndRemoveVolume(A){A.reset(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?XD:1,this.updateChunks(),this.rebuildObjects(A.camera)}rebuildObjects(A){const I=Array.from(this.currentVolumes_.values());$D(I,A),this.clearObjects();for(const B of I)this.addObject(B)}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function jD(g){const{x:A,y:I,z:B,t:Q}=g.chunkIndex;return`${A}:${I}:${B}:${Q}`}function zD(g){const A=new Map;for(const I of g){const B=jD(I);let Q=A.get(B);Q||(Q=[],A.set(B,Q)),Q.push(I)}return A}function _D(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}function $D(g,A){const I=A.position,B=new Map;for(const Q of g){const C=Q.transform.translation;B.set(Q,jE(I,C))}g.sort((Q,C)=>B.get(C)-B.get(Q))}class QE extends lB{width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=dB(A),this.data_=A,this.width_=I,this.height_=B}get type(){return"Texture2D"}get width(){return this.width_}get height(){return this.height_}}const Aa=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Ia(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,FA.from(I)]))}function ga(g){return g=g??Aa,g.map(FA.from)}function SB(g={}){return{lookupTable:Ia(g.lookupTable),cycle:ga(g.cycle)}}const CE=new Set(["byte","short","int"]),Ba=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function Qa(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!CE.has(g.dataType)&&!Ba.has(g.dataType))throw new Error(`Image data type must be an integer, instead found: ${g.dataType}`);return g}function Ca(g){return CE.has(g.dataType)?"intLabelImage":"labelImage"}class EE extends Bg{worldToTexCoord=WA();outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new AE(A.width,A.height,1,1),this.setTexture(0,Qa(A.imageData));const I=SB(A.colorMap);this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable)),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName=Ca(A.imageData),this.depthProgramName="meshDepth"}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_worldToTexCoord:this.worldToTexCoord}}setColorMap(A){const I=SB(A);this.markStaleTexture(this.textures[1]),this.markStaleTexture(this.textures[2]),this.setTexture(1,this.makeColorCycleTexture(I.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(I.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new QE(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,FA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,FA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new QE(C,Q,2)}}class cQ extends Mg{type="LabelLayer";source_;sliceCoords_;axes_;planeRotation_;orientation_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new UQ;colorMap_;selectedValue_=null;policy_;chunkStoreView_;context_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:B,orientation:Q,colorMap:C={},onPickValue:E,outlineSelected:i=!1,...D}){super(D),this.setState("initialized"),this.source_=A,this.policy_=B??GB(),this.sliceCoords_=I,this.orientation_=Q??"XY",this.axes_=bI(this.orientation_),this.planeRotation_=PI(this.axes_),this.colorMap_=SB(C),this.onPickValue_=E,this.outlineSelected_=i}attach(A){if(this.context_=A,this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_,this.axes_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0,this.context_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera,B=I.type==="OrthographicCamera"?I.getWorldViewRect():this.chunkStoreView_.getWholePlaneRect();this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:B,bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[Q,C]of this.visibleChunks_)this.updateSlicePosition(C,Q)}get orientation(){return this.orientation_}setOrientation(A){A!==this.orientation_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.lastPresentationTimeStamp_=void 0,this.lastPresentationTimeCoord_=void 0,this.orientation_=A,this.axes_=bI(A),this.planeRotation_=PI(this.axes_),this.context_&&(this.chunkStoreView_=this.context_.chunkManager.addView(this.source_,this.policy_,this.axes_)))}updateChunks(){if(!this.chunkStoreView_)return;this.state!=="ready"&&this.setState("ready");const A=Array.from(this.visibleChunks_.keys()).every(C=>C.texture!==void 0);if(this.visibleChunks_.size>0&&A&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale())return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const I=this.chunkStoreView_.getChunksToRender(),B=new Set(I),Q=Array.from(this.visibleChunks_.keys()).filter(C=>!B.has(C));this.releaseAndRemoveChunks(Q),this.clearObjects();for(const C of I){const E=this.getLabelForChunk(C,C.texture);this.visibleChunks_.set(C,E),this.addObject(E,0)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>cQ.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=gE(A,this.pointerDownPos_,I=>this.pickAtRay(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async pickAtRay(A){const I=this.visibleChunks_.values().next();if(I.done)return null;const B=I.value.transform,Q=uQ(AA(),yA(0,0,1),B.rotation),C=CI.fromPointAndNormal(B.translation,Q),E=A.intersectWithPlane(C);if(!E)return null;const i=await this.getValueAtWorld(E);return i===null?null:{world:E,value:i}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=SB(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,zg))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const B of[!0,!1])for(const[Q,C]of this.visibleChunks_){if(Q.lod===I!==B)continue;const E=await this.readValueFromChunk(Q,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,B){const Q=YB(AA(),B,I.transform.inverse),{u:C,v:E,w:i}=this.axes_,D=Math.floor(Q[0]),a=Math.floor(Q[1]);if(D<0||D>=A.shape[C]||a<0||a>=A.shape[E])return null;const G={x:0,y:0,z:0};return G[C]=D,G[E]=a,G[i]=this.sliceIndexForChunk(A),await I.textures[0].readTexel?.(G.x,G.y,G.z)??null}getLabelForChunk(A,I){const B=this.visibleChunks_.get(A);if(B)return B;const Q=this.pool_.acquire(wB(A,this.axes_));return Q?(Q.setTexture(0,I),Q.setColorMap(this.colorMap_),Q.setSelectedValue(this.selectedValue_),this.updateLabelChunk(Q,A),Q):this.createLabel(A,I)}createLabel(A,I){const B=new EE({width:A.shape[this.axes_.u],height:A.shape[this.axes_.v],imageData:I,colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(B,A),B}updateSlicePosition(A,I){const{u:B,v:Q,w:C}=this.axes_,E=AA();E[RA[B]]=I.offset[B],E[RA[Q]]=I.offset[Q],E[RA[C]]=this.sliceCoords_[C]??I.offset[C],A.transform.setTranslation(E)}sliceIndexForChunk(A){const I=this.axes_.w,B=this.sliceCoords_[I];if(B===void 0)return 0;const Q=(B-A.offset[I])/A.scale[I];return EI(Math.round(Q),0,A.shape[I]-1)}updateLabelChunk(A,I){const{u:B,v:Q}=this.axes_;A.transform.setScale([I.scale[B],I.scale[Q],1]),A.transform.setRotation(this.planeRotation_),this.updateSlicePosition(A,I),A.worldToTexCoord=jQ(I,this.axes_)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(wB(I,this.axes_),B),this.visibleChunks_.delete(I))}}}class Ea extends lB{width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=dB(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}}const iE={circle:0,square:1,triangle:2};class ia extends Bg{constructor(A){super(),this.programName="points",this.depthProgramName="pointsDepth";const I=A.flatMap(Q=>{const C=FA.from(Q.color);return[Q.position[0],Q.position[1],Q.position[2],C.r,C.g,C.b,C.a,Q.size,iE[Q.marker]]}),B=new uI(I,[],"points");B.addAttribute({type:"position",itemSize:3,offset:0}),B.addAttribute({type:"color",itemSize:4,offset:B.strideBytes}),B.addAttribute({type:"size",itemSize:1,offset:B.strideBytes}),B.addAttribute({type:"marker",itemSize:1,offset:B.strideBytes}),this.geometry=B,this.setTexture(0,oa())}get type(){return"PointsRenderable"}}let LQ;function oa(){return LQ||(LQ=Da()),LQ}function Da(){const g=a=>{const G=new Float32Array(a*a);return G.fill(1),G},A=a=>{const G=new Float32Array(a*a);for(let R=0;R<a;R++)for(let U=0;U<a;U++)(R-a/2)**2+(U-a/2)**2<(a/2)**2&&(G[R*a+U]=1);return G},I=a=>{const G=new Float32Array(a*a);for(let R=0;R<a;R++)for(let U=0;U<a;U++)U>=(a-R)/2&&U<=(a+R)/2&&(G[R*a+U]=1);return G},C={circle:A(256),square:g(256),triangle:I(256)},E=Object.keys(C).length,i=new Float32Array(E*65536);for(const[a,G]of Object.entries(C))i.set(G,iE[a]*65536);const D=new Ea(i,256,256);return D.wrapR="clamp_to_edge",D.wrapS="clamp_to_edge",D.wrapT="clamp_to_edge",D}class oE{planes_;constructor(A){this.planes_=[new CI(AA(),0),new CI(AA(),0),new CI(AA(),0),new CI(AA(),0),new CI(AA(),0),new CI(AA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=AA();this.planes_[0].set(JI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(JI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(JI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(JI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(JI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(JI(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=AA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class JQ extends xg{transform_=new SQ;projectionMatrix_=WA();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get transform(){return this.transform_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return yA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return yA(A[4],A[5],A[6])}getViewProjection(){return Zg(WA(),this.projectionMatrix,this.viewMatrix)}get frustum(){return new oE(this.getViewProjection())}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=Og(A[0],A[1],A[2],1),B=Sg(WA(),this.projectionMatrix_),Q=Rg(ZI(),I,B);Ii(Q,Q,1/Q[3]);const C=Rg(ZI(),Q,this.transform.matrix);return yA(C[0],C[1],C[2])}}class DE{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return yA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const rQ=-1,aE=0,aa=1,sE=.009,sa=.001,ya=9e-4,ha=.5,Ga=60;class Fa{camera_;orbitVelocity_=new DE(0,0,0);panVelocity_=AA();currPos_;currCenter_=AA();dampingFactor_;scrollZoom_;currMouseButton_=rQ;constructor(A,I){this.camera_=A,this.currPos_=new DE(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&LB(this.currCenter_,I.target),this.dampingFactor_=EI(I?.dampingFactor??ha,0,1),this.scrollZoom_=I?.scrollZoom??"always",this.updateCamera()}get radius(){return this.currPos_.radius}get yaw(){return this.currPos_.phi}get pitch(){return this.currPos_.theta}get target(){return $A(this.currCenter_)}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&KB(this.panVelocity_,yA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,ug(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-wA;this.currPos_.theta=EI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const B=Math.pow(1-this.dampingFactor_,A*Ga);this.orbitVelocity_.phi*=B,this.orbitVelocity_.theta*=B,this.orbitVelocity_.radius*=B,rB(this.panVelocity_,this.panVelocity_,B),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==rQ)return;const I=A.event,B=I.movementX??0,Q=I.movementY??0,C=this.currMouseButton_===aE&&!I.shiftKey,E=this.currMouseButton_===aE&&I.shiftKey||this.currMouseButton_===aa;C&&this.orbit(B,Q),E&&this.pan(B,Q)}onWheel(A){const I=A.event;if(this.scrollZoom_==="never"||this.scrollZoom_==="modifier"&&!(I.ctrlKey||I.metaKey))return;I.preventDefault();const B=I.deltaY??0;this.zoom(B)}onPointerEnd(A){this.currMouseButton_=rQ;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*sE,this.orbitVelocity_.theta+=I*sE}pan(A,I){const B=this.currPos_.radius*sa,Q=AA();nB(Q,Q,this.camera_.right,A),nB(Q,Q,this.camera_.up,I),rB(Q,Q,B),MB(this.panVelocity_,this.panVelocity_,Q)}zoom(A){this.orbitVelocity_.radius+=A*ya}updateCamera(){const A=ug(AA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<wA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<wA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<wA&&(this.orbitVelocity_.radius=0),cB(this.panVelocity_)<wA&&zE(this.panVelocity_)}}const yE=1.77,hE=128,GE=128/yE,wa=-1e6,Sa=1e6;class Ra extends JQ{width_=hE;height_=GE;viewportAspectRatio_=yE;viewportSize_=[hE,GE];axes_;rotation_;orientation_;constructor(A){super(),this.near_=A.near??wa,this.far_=A.far??Sa,this.orientation_=A.orientation??"XY",this.axes_=bI(this.orientation_),this.rotation_=PI(this.axes_),this.setFrame(A),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame({left:A,right:I,top:B,bottom:Q}){this.width_=Math.abs(I-A),this.height_=Math.abs(B-Q),this.updateProjectionMatrix();const C=AA();C[RA[this.axes_.u]]=.5*(A+I),C[RA[this.axes_.v]]=.5*(Q+B),this.transform.setTranslation(C),this.transform.setScale([1,1,1]),this.transform.setRotation(this.rotation_)}get type(){return"OrthographicCamera"}get orientation(){return this.orientation_}setOrientation(A){if(A===this.orientation_)return;const I=this.transform.translation[RA[this.axes_.u]],B=this.transform.translation[RA[this.axes_.v]];this.orientation_=A,this.axes_=bI(A),this.rotation_=PI(this.axes_);const Q=AA();Q[RA[this.axes_.u]]=I,Q[RA[this.axes_.v]]=B,this.transform.setTranslation(Q),this.transform.setRotation(this.rotation_)}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=Og(-1,-1,0,1),I=Og(1,1,0,1);const B=Sg(WA(),this.getViewProjection());A=Rg(ZI(),A,B),I=Rg(ZI(),I,B);const Q=RA[this.axes_.u],C=RA[this.axes_.v];return new ZA(LA(A[Q],A[C]),LA(I[Q],I[C]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],OE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const FE=0;class Na{camera_;scrollZoom_;dragActive_=!1;dragStart_=AA();constructor(A,I){this.camera_=A,this.scrollZoom_=I?.scrollZoom??"always"}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;if(this.scrollZoom_==="never"||this.scrollZoom_==="modifier"&&!(I.ctrlKey||I.metaKey))return;I.preventDefault();const B=$A(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=MB(AA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==FE||(this.dragStart_=$A(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=MB(AA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==FE||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}const ta=60,Ua=1.77,RB=.1,nQ=180-RB;class ka extends JQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=ta,aspectRatio:B=Ua,near:Q=.1,far:C=1e4,position:E=yA(0,0,0)}=A;if(I<RB||I>nQ)throw new Error(`Invalid field of view: ${I}, must be in [${RB}, ${nQ}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(RB,Math.min(nQ,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){bE(this.projectionMatrix_,WE(this.fov),this.aspectRatio_,this.near_,this.far_)}}var YQ=(()=>{for(var g=new Uint8Array(128),A=0;A<64;A++)g[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var B=I.length,Q=new Uint8Array((B-(I[B-1]=="=")-(I[B-2]=="="))*3/4|0),C=0,E=0;C<B;){var i=g[I.charCodeAt(C++)],D=g[I.charCodeAt(C++)],a=g[I.charCodeAt(C++)],G=g[I.charCodeAt(C++)];Q[E++]=i<<2|D>>4,Q[E++]=D<<4|a>>2,Q[E++]=a<<6|G}return Q}})(),ca=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(g={}){var A=g,I,B;A.ready=new Promise((s,h)=>{I=s,B=h});var Q=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,Q),Q=null,A.thisProgram&&(C=A.thisProgram);var D;A.wasmBinary&&(D=A.wasmBinary),typeof WebAssembly!="object"&&EA("no native wasm support detected");var a,G=!1,R,U,J,r,H,K,l,O;function Z(){var s=a.buffer;A.HEAP8=R=new Int8Array(s),A.HEAP16=J=new Int16Array(s),A.HEAPU8=U=new Uint8Array(s),A.HEAPU16=r=new Uint16Array(s),A.HEAP32=H=new Int32Array(s),A.HEAPU32=K=new Uint32Array(s),A.HEAPF32=l=new Float32Array(s),A.HEAPF64=O=new Float64Array(s)}var W=[],p=[],T=[];function $(){var s=A.preRun.shift();W.unshift(s)}var QA=0,iA=null;function EA(s){throw A.onAbort?.(s),s="Aborted("+s+")",i(s),G=!0,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),B(s),s}var sA=s=>s.startsWith("data:application/octet-stream;base64,"),qA=s=>s.startsWith("file://"),kA;if(kA="blosc_codec.wasm",!sA(kA)){var aA=kA;kA=A.locateFile?A.locateFile(aA,""):""+aA}function oI(s){return Promise.resolve().then(()=>{if(s==kA&&D)var h=new Uint8Array(D);else throw"both async and sync fetching of the wasm failed";return h})}function II(s,h,S){return oI(s).then(c=>WebAssembly.instantiate(c,h)).then(c=>c).then(S,c=>{i(`failed to asynchronously prepare wasm: ${c}`),EA(c)})}function DI(s,h){var S=kA;return D||typeof WebAssembly.instantiateStreaming!="function"||sA(S)||qA(S)||typeof fetch!="function"?II(S,s,h):fetch(S,{credentials:"same-origin"}).then(c=>WebAssembly.instantiateStreaming(c,s).then(h,function(o){return i(`wasm streaming compile failed: ${o}`),i("falling back to ArrayBuffer instantiation"),II(S,s,h)}))}var RI=s=>{for(;0<s.length;)s.shift()(A)};function NI(s){this.H=s-24,this.N=function(h){K[this.H+4>>2]=h},this.M=function(h){K[this.H+8>>2]=h},this.I=function(h,S){this.J(),this.N(h),this.M(S)},this.J=function(){K[this.H+16>>2]=0}}var fA=0,nA,NA=s=>{for(var h="";U[s];)h+=nA[U[s++]];return h},eA={},SA={},cA={},YA,MI=s=>{throw new YA(s)},eI,XA=(s,h)=>{function S(t){if(t=h(t),t.length!==c.length)throw new eI("Mismatched type converter count");for(var N=0;N<c.length;++N)tA(c[N],t[N])}var c=[];c.forEach(function(t){cA[t]=s});var o=Array(s.length),y=[],w=0;s.forEach((t,N)=>{SA.hasOwnProperty(t)?o[N]=SA[t]:(y.push(t),eA.hasOwnProperty(t)||(eA[t]=[]),eA[t].push(()=>{o[N]=SA[t],++w,w===y.length&&S(o)}))}),y.length===0&&S(o)};function uA(s,h,S={}){var c=h.name;if(!s)throw new YA(`type "${c}" must have a positive integer typeid pointer`);if(SA.hasOwnProperty(s)){if(S.P)return;throw new YA(`Cannot register type '${c}' twice`)}SA[s]=h,delete cA[s],eA.hasOwnProperty(s)&&(h=eA[s],delete eA[s],h.forEach(o=>o()))}function tA(s,h,S={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");uA(s,h,S)}function bA(){this.F=[void 0],this.K=[]}var dA=new bA,aI=s=>{s>=dA.H&&--dA.get(s).L===0&&dA.J(s)},og=s=>{switch(s){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return dA.I({L:1,value:s})}};function tI(s){return this.fromWireType(H[s>>2])}var HI=(s,h)=>{switch(h){case 4:return function(S){return this.fromWireType(l[S>>2])};case 8:return function(S){return this.fromWireType(O[S>>3])};default:throw new TypeError(`invalid float width (${h}): ${s}`)}},UI=(s,h)=>Object.defineProperty(h,"name",{value:s}),Dg=s=>{for(;s.length;){var h=s.pop();s.pop()(h)}};function ag(s){for(var h=1;h<s.length;++h)if(s[h]!==null&&s[h].G===void 0)return!0;return!1}function Hg(s){var h=Function;if(!(h instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof h} which is not a function`);var S=UI(h.name||"unknownFunctionName",function(){});return S.prototype=h.prototype,S=new S,s=h.apply(S,s),s instanceof Object?s:S}var qg=(s,h)=>{if(A[s].C===void 0){var S=A[s];A[s]=function(){if(!A[s].C.hasOwnProperty(arguments.length))throw new YA(`Function '${h}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[s].C})!`);return A[s].C[arguments.length].apply(this,arguments)},A[s].C=[],A[s].C[S.O]=S}},qI=(s,h,S)=>{if(A.hasOwnProperty(s)){if(S===void 0||A[s].C!==void 0&&A[s].C[S]!==void 0)throw new YA(`Cannot register public name '${s}' twice`);if(qg(s,s),A.hasOwnProperty(S))throw new YA(`Cannot register multiple overloads of a function with the same number of arguments (${S})!`);A[s].C[S]=h}else A[s]=h,S!==void 0&&(A[s].S=S)},dI=(s,h)=>{for(var S=[],c=0;c<s;c++)S.push(K[h+4*c>>2]);return S},fI,sg=(s,h)=>{var S=[];return function(){if(S.length=0,Object.assign(S,arguments),s.includes("j")){var c=A["dynCall_"+s];c=S&&S.length?c.apply(null,[h].concat(S)):c.call(null,h)}else c=fI.get(h).apply(null,S);return c}},yg=(s,h)=>{s=NA(s);var S=s.includes("j")?sg(s,h):fI.get(h);if(typeof S!="function")throw new YA(`unknown function pointer with signature ${s}: ${h}`);return S},lI,pI=s=>{s=f(s);var h=NA(s);return n(s),h},dg=(s,h)=>{function S(y){o[y]||SA[y]||(cA[y]?cA[y].forEach(S):(c.push(y),o[y]=!0))}var c=[],o={};throw h.forEach(S),new lI(`${s}: `+c.map(pI).join([", "]))},fg=s=>{s=s.trim();const h=s.indexOf("(");return h!==-1?s.substr(0,h):s},hg=(s,h,S)=>{switch(h){case 1:return S?c=>R[c>>0]:c=>U[c>>0];case 2:return S?c=>J[c>>1]:c=>r[c>>1];case 4:return S?c=>H[c>>2]:c=>K[c>>2];default:throw new TypeError(`invalid integer width (${h}): ${s}`)}};function WI(s){return this.fromWireType(K[s>>2])}for(var kI=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,mI=(s,h,S)=>{var c=h+S;for(S=h;s[S]&&!(S>=c);)++S;if(16<S-h&&s.buffer&&kI)return kI.decode(s.subarray(h,S));for(c="";h<S;){var o=s[h++];if(o&128){var y=s[h++]&63;if((o&224)==192)c+=String.fromCharCode((o&31)<<6|y);else{var w=s[h++]&63;o=(o&240)==224?(o&15)<<12|y<<6|w:(o&7)<<18|y<<12|w<<6|s[h++]&63,65536>o?c+=String.fromCharCode(o):(o-=65536,c+=String.fromCharCode(55296|o>>10,56320|o&1023))}}else c+=String.fromCharCode(o)}return c},Gg=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,lg=(s,h)=>{for(var S=s>>1,c=S+h/2;!(S>=c)&&r[S];)++S;if(S<<=1,32<S-s&&Gg)return Gg.decode(U.subarray(s,S));for(S="",c=0;!(c>=h/2);++c){var o=J[s+2*c>>1];if(o==0)break;S+=String.fromCharCode(o)}return S},pg=(s,h,S)=>{if(S??=2147483647,2>S)return 0;S-=2;var c=h;S=S<2*s.length?S/2:s.length;for(var o=0;o<S;++o)J[h>>1]=s.charCodeAt(o),h+=2;return J[h>>1]=0,h-c},Wg=s=>2*s.length,Fg=(s,h)=>{for(var S=0,c="";!(S>=h/4);){var o=H[s+4*S>>2];if(o==0)break;++S,65536<=o?(o-=65536,c+=String.fromCharCode(55296|o>>10,56320|o&1023)):c+=String.fromCharCode(o)}return c},cI=(s,h,S)=>{if(S??=2147483647,4>S)return 0;var c=h;S=c+S-4;for(var o=0;o<s.length;++o){var y=s.charCodeAt(o);if(55296<=y&&57343>=y){var w=s.charCodeAt(++o);y=65536+((y&1023)<<10)|w&1023}if(H[h>>2]=y,h+=4,h+4>S)break}return H[h>>2]=0,h-c},TI=s=>{for(var h=0,S=0;S<s.length;++S){var c=s.charCodeAt(S);55296<=c&&57343>=c&&++S,h+=4}return h},TA={},gI=()=>{if(!xA){var s={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"},h;for(h in TA)TA[h]===void 0?delete s[h]:s[h]=TA[h];var S=[];for(h in s)S.push(`${h}=${s[h]}`);xA=S}return xA},xA,UA=[null,[],[]],BI=Array(256),HA=0;256>HA;++HA)BI[HA]=String.fromCharCode(HA);nA=BI,YA=A.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},eI=A.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Object.assign(bA.prototype,{get(s){return this.F[s]},has(s){return this.F[s]!==void 0},I(s){var h=this.K.pop()||this.F.length;return this.F[h]=s,h},J(s){this.F[s]=void 0,this.K.push(s)}}),dA.F.push({value:void 0},{value:null},{value:!0},{value:!1}),dA.H=dA.F.length,A.count_emval_handles=()=>{for(var s=0,h=dA.H;h<dA.F.length;++h)dA.F[h]!==void 0&&++s;return s},lI=A.UnboundTypeError=((s,h)=>{var S=UI(h,function(c){this.name=h,this.message=c,c=Error(c).stack,c!==void 0&&(this.stack=this.toString()+`
4123
4123
  `+c.replace(/^Error(:[^\n]*)?\n/,""))});return S.prototype=Object.create(s.prototype),S.prototype.constructor=S,S.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},S})(Error,"UnboundTypeError");var F={p:(s,h,S)=>{throw new NI(s).I(h,S),fA=s,fA},o:()=>{},l:(s,h,S,c)=>{h=NA(h),tA(s,{name:h,fromWireType:function(o){return!!o},toWireType:function(o,y){return y?S:c},argPackAdvance:8,readValueFromPointer:function(o){return this.fromWireType(U[o])},G:null})},k:(s,h)=>{h=NA(h),tA(s,{name:h,fromWireType:S=>{if(!S)throw new YA("Cannot use deleted val. handle = "+S);var c=dA.get(S).value;return aI(S),c},toWireType:(S,c)=>og(c),argPackAdvance:8,readValueFromPointer:tI,G:null})},i:(s,h,S)=>{h=NA(h),tA(s,{name:h,fromWireType:c=>c,toWireType:(c,o)=>o,argPackAdvance:8,readValueFromPointer:HI(h,S),G:null})},d:(s,h,S,c,o,y,w)=>{var t=dI(h,S);s=NA(s),s=fg(s),o=yg(c,o),qI(s,function(){dg(`Cannot call ${s} due to unbound types`,t)},h-1),XA(t,function(N){var Y=s,e=s;N=[N[0],null].concat(N.slice(1));var d=o,M=N.length;if(2>M)throw new YA("argTypes array size mismatch! Must at least get return value and 'this' types!");var X=N[1]!==null&&!1,j=ag(N),lA=N[0].name!=="void";d=[MI,d,y,Dg,N[0],N[1]];for(var IA=0;IA<M-2;++IA)d.push(N[IA+2]);if(!j)for(IA=X?1:2;IA<N.length;++IA)N[IA].G!==null&&d.push(N[IA].G);j=ag(N),IA=N.length;var KA="",_A="";for(M=0;M<IA-2;++M)KA+=(M!==0?", ":"")+"arg"+M,_A+=(M!==0?", ":"")+"arg"+M+"Wired";KA=`
4124
4124
  return function (${KA}) {
4125
4125
  if (arguments.length !== ${IA-2}) {