@fnndsc/argus 0.18.6 → 0.18.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{Settings-CuV3h6cB.js → Settings-Dh71PFqP.js} +1 -1
- package/dist/assets/{Texture-PfrmOwfm.js → Texture-BvC_ok8j.js} +1 -1
- package/dist/assets/{addVolumesToViewports-D9CKTGAr.js → addVolumesToViewports-BzJEa7FJ.js} +1 -1
- package/dist/assets/{cornerstoneEngine-Dd1A3l-l.js → cornerstoneEngine-DyH_C-Fw.js} +2 -2
- package/dist/assets/{index-C_044N76.js → index-Brcz7G5i.js} +1 -1
- package/dist/assets/{index-D_WB5hnv.js → index-CZHRg884.js} +1 -1
- package/dist/assets/{index-CUyQvuO9.js → index-D-DDRSRY.js} +4 -4
- package/dist/assets/{index-Ds7K0_di.js → index-DYZLKb9g.js} +1 -1
- package/dist/assets/{index-DwdyJFUH.js → index-PqTC2E5D.js} +1 -1
- package/dist/assets/{index-DgeYQ6Vy.js → index-af1edG3x.js} +1 -1
- package/dist/assets/{index-DSLwz04y.js → index-yOfm1DJe.js} +1 -1
- package/dist/assets/{niivueEngine-4fE28_PW.js → niivueEngine-DwasekQ0.js} +2 -2
- package/dist/assets/{slabScene-Bh-hkIAb.js → slabScene-BB_oW2TA.js} +1 -1
- package/dist/index.html +2 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./cornerstoneEngine-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./cornerstoneEngine-DyH_C-Fw.js","./_commonjsHelpers-CE1G-McA.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const r of i)if(r.type==="childList")for(const a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function t(i){const r={};return i.integrity&&(r.integrity=i.integrity),i.referrerPolicy&&(r.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?r.credentials="include":i.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(i){if(i.ep)return;i.ep=!0;const r=t(i);fetch(i.href,r)}})();const SM=["cold","cached","failed"];function AM(n){return n.state??(n.restored===!0?"cached":"cold")}const EM=["upload","download","pull","workflow","pipeline","group","task"],DM=["transfer","retrieve","workflow","inspection"],IM=["scanning","transferring","watching","retrying","reading","working","complete","failed"],TM=["files","bytes","series","jobs","nodes"],GM=["running","done","unconfirmed","stalled","timeout","error","unknown"],Hc=1;var Dt;(function(n){n.assertEqual=i=>{};function e(i){}n.assertIs=e;function t(i){throw new Error}n.assertNever=t,n.arrayToEnum=i=>{const r={};for(const a of i)r[a]=a;return r},n.getValidEnumValues=i=>{const r=n.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(const o of r)a[o]=i[o];return n.objectValues(a)},n.objectValues=i=>n.objectKeys(i).map(function(r){return i[r]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const r=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&r.push(a);return r},n.find=(i,r)=>{for(const a of i)if(r(a))return a},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,r=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(r)}n.joinValues=s,n.jsonStringifyReplacer=(i,r)=>typeof r=="bigint"?r.toString():r})(Dt||(Dt={}));var sh;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(sh||(sh={}));const ke=Dt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mi=n=>{switch(typeof n){case"undefined":return ke.undefined;case"string":return ke.string;case"number":return Number.isNaN(n)?ke.nan:ke.number;case"boolean":return ke.boolean;case"function":return ke.function;case"bigint":return ke.bigint;case"symbol":return ke.symbol;case"object":return Array.isArray(n)?ke.array:n===null?ke.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ke.promise:typeof Map<"u"&&n instanceof Map?ke.map:typeof Set<"u"&&n instanceof Set?ke.set:typeof Date<"u"&&n instanceof Date?ke.date:ke.object;default:return ke.unknown}},we=Dt.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 ei extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(r){return r.message},s={_errors:[]},i=r=>{for(const a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)s._errors.push(t(a));else{let o=s,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(a))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return i(this),s}static assert(e){if(!(e instanceof ei))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Dt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const i of this.issues)if(i.path.length>0){const r=i.path[0];t[r]=t[r]||[],t[r].push(e(i))}else s.push(e(i));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}ei.create=n=>new ei(n);const qc=(n,e)=>{let t;switch(n.code){case we.invalid_type:n.received===ke.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case we.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Dt.jsonStringifyReplacer)}`;break;case we.unrecognized_keys:t=`Unrecognized key(s) in object: ${Dt.joinValues(n.keys,", ")}`;break;case we.invalid_union:t="Invalid input";break;case we.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Dt.joinValues(n.options)}`;break;case we.invalid_enum_value:t=`Invalid enum value. Expected ${Dt.joinValues(n.options)}, received '${n.received}'`;break;case we.invalid_arguments:t="Invalid function arguments";break;case we.invalid_return_type:t="Invalid function return type";break;case we.invalid_date:t="Invalid date";break;case we.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Dt.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case we.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case we.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case we.custom:t="Invalid input";break;case we.invalid_intersection_types:t="Intersection results could not be merged";break;case we.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case we.not_finite:t="Number must be finite";break;default:t=e.defaultError,Dt.assertNever(n)}return{message:t}};let RM=qc;function BM(){return RM}const NM=n=>{const{data:e,path:t,errorMaps:s,issueData:i}=n,r=[...t,...i.path||[]],a={...i,path:r};if(i.message!==void 0)return{...i,path:r,message:i.message};let o="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)o=c(a,{data:e,defaultError:o}).message;return{...i,path:r,message:o}};function Ce(n,e){const t=BM(),s=NM({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===qc?void 0:qc].filter(i=>!!i)});n.common.issues.push(s)}class Cs{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const i of t){if(i.status==="aborted")return at;i.status==="dirty"&&e.dirty(),s.push(i.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const i of t){const r=await i.key,a=await i.value;s.push({key:r,value:a})}return Cs.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const i of t){const{key:r,value:a}=i;if(r.status==="aborted"||a.status==="aborted")return at;r.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(s[r.value]=a.value)}return{status:e.value,value:s}}}const at=Object.freeze({status:"aborted"}),Aa=n=>({status:"dirty",value:n}),on=n=>({status:"valid",value:n}),nh=n=>n.status==="aborted",ih=n=>n.status==="dirty",Ur=n=>n.status==="valid",Ko=n=>typeof Promise<"u"&&n instanceof Promise;var He;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(He||(He={}));class Tn{constructor(e,t,s,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=i}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 rh=(n,e)=>{if(Ur(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ei(n.common.issues);return this._error=t,this._error}}};function mt(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:i}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{const{message:l}=n;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??s??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},description:i}}class vt{get description(){return this._def.description}_getType(e){return mi(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:mi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Cs,ctx:{common:e.parent.common,data:e.data,parsedType:mi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ko(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mi(e)},i=this._parseSync({data:e,path:s.path,parent:s});return rh(s,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mi(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return Ur(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>Ur(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mi(e)},i=this._parse({data:e,path:s.path,parent:s}),r=await(Ko(i)?i:Promise.resolve(i));return rh(s,r)}refine(e,t){const s=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,r)=>{const a=e(i),o=()=>r.addIssue({code:we.custom,...s(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,i)=>e(s)?!0:(i.addIssue(typeof t=="function"?t(s,i):t),!1))}_refinement(e){return new Ki({schema:this,typeName:ot.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return Kn.create(this,this._def)}nullable(){return Zi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return En.create(this)}promise(){return nl.create(this,this._def)}or(e){return Qo.create([this,e],this._def)}and(e){return Jo.create(this,e,this._def)}transform(e){return new Ki({...mt(this._def),schema:this,typeName:ot.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new il({...mt(this._def),innerType:this,defaultValue:t,typeName:ot.ZodDefault})}brand(){return new hm({typeName:ot.ZodBranded,type:this,...mt(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new rl({...mt(this._def),innerType:this,catchValue:t,typeName:ot.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return du.create(this,e)}readonly(){return al.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const CM=/^c[^\s-]{8,}$/i,PM=/^[0-9a-z]+$/,LM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WM=/^[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,kM=/^[a-z0-9_-]{21}$/i,UM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,FM=/^[-+]?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)?)??$/,jM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$M="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ul;const VM=/^(?:(?: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])$/,HM=/^(?:(?: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])$/,qM=/^(([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]))$/,XM=/^(([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])$/,YM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KM=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cm="((\\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])))",ZM=new RegExp(`^${cm}$`);function dm(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function QM(n){return new RegExp(`^${dm(n)}$`)}function JM(n){let e=`${cm}T${dm(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function eb(n,e){return!!((e==="v4"||!e)&&VM.test(n)||(e==="v6"||!e)&&qM.test(n))}function tb(n,e){if(!UM.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function sb(n,e){return!!((e==="v4"||!e)&&HM.test(n)||(e==="v6"||!e)&&XM.test(n))}class Xn extends vt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ke.string){const r=this._getOrReturnCtx(e);return Ce(r,{code:we.invalid_type,expected:ke.string,received:r.parsedType}),at}const s=new Cs;let i;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty());else if(r.kind==="max")e.data.length>r.value&&(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty());else if(r.kind==="length"){const a=e.data.length>r.value,o=e.data.length<r.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?Ce(i,{code:we.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&Ce(i,{code:we.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),s.dirty())}else if(r.kind==="email")jM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"email",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="emoji")Ul||(Ul=new RegExp($M,"u")),Ul.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"emoji",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="uuid")WM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"uuid",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="nanoid")kM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"nanoid",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="cuid")CM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"cuid",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="cuid2")PM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"cuid2",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="ulid")LM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"ulid",code:we.invalid_string,message:r.message}),s.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Ce(i,{validation:"url",code:we.invalid_string,message:r.message}),s.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"regex",code:we.invalid_string,message:r.message}),s.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),s.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.invalid_string,validation:{startsWith:r.value},message:r.message}),s.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.invalid_string,validation:{endsWith:r.value},message:r.message}),s.dirty()):r.kind==="datetime"?JM(r).test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.invalid_string,validation:"datetime",message:r.message}),s.dirty()):r.kind==="date"?ZM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.invalid_string,validation:"date",message:r.message}),s.dirty()):r.kind==="time"?QM(r).test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.invalid_string,validation:"time",message:r.message}),s.dirty()):r.kind==="duration"?FM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"duration",code:we.invalid_string,message:r.message}),s.dirty()):r.kind==="ip"?eb(e.data,r.version)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"ip",code:we.invalid_string,message:r.message}),s.dirty()):r.kind==="jwt"?tb(e.data,r.alg)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"jwt",code:we.invalid_string,message:r.message}),s.dirty()):r.kind==="cidr"?sb(e.data,r.version)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"cidr",code:we.invalid_string,message:r.message}),s.dirty()):r.kind==="base64"?YM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"base64",code:we.invalid_string,message:r.message}),s.dirty()):r.kind==="base64url"?KM.test(e.data)||(i=this._getOrReturnCtx(e,i),Ce(i,{validation:"base64url",code:we.invalid_string,message:r.message}),s.dirty()):Dt.assertNever(r);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(i=>e.test(i),{validation:t,code:we.invalid_string,...He.errToObj(s)})}_addCheck(e){return new Xn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...He.errToObj(e)})}url(e){return this._addCheck({kind:"url",...He.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...He.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...He.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...He.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...He.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...He.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...He.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...He.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...He.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...He.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...He.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...He.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...He.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...He.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...He.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...He.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...He.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...He.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...He.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...He.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...He.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...He.errToObj(t)})}nonempty(e){return this.min(1,He.errToObj(e))}trim(){return new Xn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Xn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Xn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Xn.create=n=>new Xn({checks:[],typeName:ot.ZodString,coerce:n?.coerce??!1,...mt(n)});function nb(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,i=t>s?t:s,r=Number.parseInt(n.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return r%a/10**i}class Fr extends vt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ke.number){const r=this._getOrReturnCtx(e);return Ce(r,{code:we.invalid_type,expected:ke.number,received:r.parsedType}),at}let s;const i=new Cs;for(const r of this._def.checks)r.kind==="int"?Dt.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.invalid_type,expected:"integer",received:"float",message:r.message}),i.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()):r.kind==="multipleOf"?nb(e.data,r.value)!==0&&(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.not_finite,message:r.message}),i.dirty()):Dt.assertNever(r);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,He.toString(t))}gt(e,t){return this.setLimit("min",e,!1,He.toString(t))}lte(e,t){return this.setLimit("max",e,!0,He.toString(t))}lt(e,t){return this.setLimit("max",e,!1,He.toString(t))}setLimit(e,t,s,i){return new Fr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:He.toString(i)}]})}_addCheck(e){return new Fr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:He.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:He.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:He.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:He.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:He.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:He.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:He.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:He.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:He.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Dt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Fr.create=n=>new Fr({checks:[],typeName:ot.ZodNumber,coerce:n?.coerce||!1,...mt(n)});class Ca extends vt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ke.bigint)return this._getInvalidInput(e);let s;const i=new Cs;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),Ce(s,{code:we.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):Dt.assertNever(r);return{status:i.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Ce(t,{code:we.invalid_type,expected:ke.bigint,received:t.parsedType}),at}gte(e,t){return this.setLimit("min",e,!0,He.toString(t))}gt(e,t){return this.setLimit("min",e,!1,He.toString(t))}lte(e,t){return this.setLimit("max",e,!0,He.toString(t))}lt(e,t){return this.setLimit("max",e,!1,He.toString(t))}setLimit(e,t,s,i){return new Ca({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:He.toString(i)}]})}_addCheck(e){return new Ca({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:He.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:He.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:He.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:He.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:He.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Ca.create=n=>new Ca({checks:[],typeName:ot.ZodBigInt,coerce:n?.coerce??!1,...mt(n)});class Xc extends vt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ke.boolean){const s=this._getOrReturnCtx(e);return Ce(s,{code:we.invalid_type,expected:ke.boolean,received:s.parsedType}),at}return on(e.data)}}Xc.create=n=>new Xc({typeName:ot.ZodBoolean,coerce:n?.coerce||!1,...mt(n)});class Zo extends vt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ke.date){const r=this._getOrReturnCtx(e);return Ce(r,{code:we.invalid_type,expected:ke.date,received:r.parsedType}),at}if(Number.isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return Ce(r,{code:we.invalid_date}),at}const s=new Cs;let i;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),s.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(i=this._getOrReturnCtx(e,i),Ce(i,{code:we.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),s.dirty()):Dt.assertNever(r);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Zo({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:He.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:He.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Zo.create=n=>new Zo({checks:[],coerce:n?.coerce||!1,typeName:ot.ZodDate,...mt(n)});class ah extends vt{_parse(e){if(this._getType(e)!==ke.symbol){const s=this._getOrReturnCtx(e);return Ce(s,{code:we.invalid_type,expected:ke.symbol,received:s.parsedType}),at}return on(e.data)}}ah.create=n=>new ah({typeName:ot.ZodSymbol,...mt(n)});class Yc extends vt{_parse(e){if(this._getType(e)!==ke.undefined){const s=this._getOrReturnCtx(e);return Ce(s,{code:we.invalid_type,expected:ke.undefined,received:s.parsedType}),at}return on(e.data)}}Yc.create=n=>new Yc({typeName:ot.ZodUndefined,...mt(n)});class Kc extends vt{_parse(e){if(this._getType(e)!==ke.null){const s=this._getOrReturnCtx(e);return Ce(s,{code:we.invalid_type,expected:ke.null,received:s.parsedType}),at}return on(e.data)}}Kc.create=n=>new Kc({typeName:ot.ZodNull,...mt(n)});class oh extends vt{constructor(){super(...arguments),this._any=!0}_parse(e){return on(e.data)}}oh.create=n=>new oh({typeName:ot.ZodAny,...mt(n)});class Zc extends vt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return on(e.data)}}Zc.create=n=>new Zc({typeName:ot.ZodUnknown,...mt(n)});class Ai extends vt{_parse(e){const t=this._getOrReturnCtx(e);return Ce(t,{code:we.invalid_type,expected:ke.never,received:t.parsedType}),at}}Ai.create=n=>new Ai({typeName:ot.ZodNever,...mt(n)});class lh extends vt{_parse(e){if(this._getType(e)!==ke.undefined){const s=this._getOrReturnCtx(e);return Ce(s,{code:we.invalid_type,expected:ke.void,received:s.parsedType}),at}return on(e.data)}}lh.create=n=>new lh({typeName:ot.ZodVoid,...mt(n)});class En extends vt{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),i=this._def;if(t.parsedType!==ke.array)return Ce(t,{code:we.invalid_type,expected:ke.array,received:t.parsedType}),at;if(i.exactLength!==null){const a=t.data.length>i.exactLength.value,o=t.data.length<i.exactLength.value;(a||o)&&(Ce(t,{code:a?we.too_big:we.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(Ce(t,{code:we.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(Ce(t,{code:we.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>i.type._parseAsync(new Tn(t,a,t.path,o)))).then(a=>Cs.mergeArray(s,a));const r=[...t.data].map((a,o)=>i.type._parseSync(new Tn(t,a,t.path,o)));return Cs.mergeArray(s,r)}get element(){return this._def.type}min(e,t){return new En({...this._def,minLength:{value:e,message:He.toString(t)}})}max(e,t){return new En({...this._def,maxLength:{value:e,message:He.toString(t)}})}length(e,t){return new En({...this._def,exactLength:{value:e,message:He.toString(t)}})}nonempty(e){return this.min(1,e)}}En.create=(n,e)=>new En({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ot.ZodArray,...mt(e)});function Nr(n){if(n instanceof ls){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=Kn.create(Nr(s))}return new ls({...n._def,shape:()=>e})}else return n instanceof En?new En({...n._def,type:Nr(n.element)}):n instanceof Kn?Kn.create(Nr(n.unwrap())):n instanceof Zi?Zi.create(Nr(n.unwrap())):n instanceof Xi?Xi.create(n.items.map(e=>Nr(e))):n}class ls extends vt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=Dt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ke.object){const c=this._getOrReturnCtx(e);return Ce(c,{code:we.invalid_type,expected:ke.object,received:c.parsedType}),at}const{status:s,ctx:i}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ai&&this._def.unknownKeys==="strip"))for(const c in i.data)a.includes(c)||o.push(c);const l=[];for(const c of a){const d=r[c],u=i.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Tn(i,u,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Ai){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(c==="strict")o.length>0&&(Ce(i,{code:we.unrecognized_keys,keys:o}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of o){const u=i.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Tn(i,u,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const u=await d.key,h=await d.value;c.push({key:u,value:h,alwaysSet:d.alwaysSet})}return c}).then(c=>Cs.mergeObjectSync(s,c)):Cs.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return He.errToObj,new ls({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const i=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:He.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new ls({...this._def,unknownKeys:"strip"})}passthrough(){return new ls({...this._def,unknownKeys:"passthrough"})}extend(e){return new ls({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ls({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ot.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ls({...this._def,catchall:e})}pick(e){const t={};for(const s of Dt.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new ls({...this._def,shape:()=>t})}omit(e){const t={};for(const s of Dt.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new ls({...this._def,shape:()=>t})}deepPartial(){return Nr(this)}partial(e){const t={};for(const s of Dt.objectKeys(this.shape)){const i=this.shape[s];e&&!e[s]?t[s]=i:t[s]=i.optional()}return new ls({...this._def,shape:()=>t})}required(e){const t={};for(const s of Dt.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let r=this.shape[s];for(;r instanceof Kn;)r=r._def.innerType;t[s]=r}return new ls({...this._def,shape:()=>t})}keyof(){return um(Dt.objectKeys(this.shape))}}ls.create=(n,e)=>new ls({shape:()=>n,unknownKeys:"strip",catchall:Ai.create(),typeName:ot.ZodObject,...mt(e)});ls.strictCreate=(n,e)=>new ls({shape:()=>n,unknownKeys:"strict",catchall:Ai.create(),typeName:ot.ZodObject,...mt(e)});ls.lazycreate=(n,e)=>new ls({shape:n,unknownKeys:"strip",catchall:Ai.create(),typeName:ot.ZodObject,...mt(e)});class Qo extends vt{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function i(r){for(const o of r)if(o.result.status==="valid")return o.result;for(const o of r)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=r.map(o=>new ei(o.ctx.common.issues));return Ce(t,{code:we.invalid_union,unionErrors:a}),at}if(t.common.async)return Promise.all(s.map(async r=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let r;const a=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!r&&(r={result:d,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const o=a.map(l=>new ei(l));return Ce(t,{code:we.invalid_union,unionErrors:o}),at}}get options(){return this._def.options}}Qo.create=(n,e)=>new Qo({options:n,typeName:ot.ZodUnion,...mt(e)});const Fn=n=>n instanceof tl?Fn(n.schema):n instanceof Ki?Fn(n.innerType()):n instanceof sl?[n.value]:n instanceof Yi?n.options:n instanceof Jc?Dt.objectValues(n.enum):n instanceof il?Fn(n._def.innerType):n instanceof Yc?[void 0]:n instanceof Kc?[null]:n instanceof Kn?[void 0,...Fn(n.unwrap())]:n instanceof Zi?[null,...Fn(n.unwrap())]:n instanceof hm||n instanceof al?Fn(n.unwrap()):n instanceof rl?Fn(n._def.innerType):[];class cu extends vt{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ke.object)return Ce(t,{code:we.invalid_type,expected:ke.object,received:t.parsedType}),at;const s=this.discriminator,i=t.data[s],r=this.optionsMap.get(i);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(Ce(t,{code:we.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),at)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const i=new Map;for(const r of t){const a=Fn(r.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,r)}}return new cu({typeName:ot.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...mt(s)})}}function Qc(n,e){const t=mi(n),s=mi(e);if(n===e)return{valid:!0,data:n};if(t===ke.object&&s===ke.object){const i=Dt.objectKeys(e),r=Dt.objectKeys(n).filter(o=>i.indexOf(o)!==-1),a={...n,...e};for(const o of r){const l=Qc(n[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(t===ke.array&&s===ke.array){if(n.length!==e.length)return{valid:!1};const i=[];for(let r=0;r<n.length;r++){const a=n[r],o=e[r],l=Qc(a,o);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return t===ke.date&&s===ke.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Jo extends vt{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),i=(r,a)=>{if(nh(r)||nh(a))return at;const o=Qc(r.value,a.value);return o.valid?((ih(r)||ih(a))&&t.dirty(),{status:t.value,value:o.data}):(Ce(s,{code:we.invalid_intersection_types}),at)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([r,a])=>i(r,a)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Jo.create=(n,e,t)=>new Jo({left:n,right:e,typeName:ot.ZodIntersection,...mt(t)});class Xi extends vt{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ke.array)return Ce(s,{code:we.invalid_type,expected:ke.array,received:s.parsedType}),at;if(s.data.length<this._def.items.length)return Ce(s,{code:we.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),at;!this._def.rest&&s.data.length>this._def.items.length&&(Ce(s,{code:we.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...s.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new Tn(s,a,s.path,o)):null}).filter(a=>!!a);return s.common.async?Promise.all(r).then(a=>Cs.mergeArray(t,a)):Cs.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Xi({...this._def,rest:e})}}Xi.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xi({items:n,typeName:ot.ZodTuple,rest:null,...mt(e)})};class el extends vt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ke.object)return Ce(s,{code:we.invalid_type,expected:ke.object,received:s.parsedType}),at;const i=[],r=this._def.keyType,a=this._def.valueType;for(const o in s.data)i.push({key:r._parse(new Tn(s,o,s.path,o)),value:a._parse(new Tn(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?Cs.mergeObjectAsync(t,i):Cs.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof vt?new el({keyType:e,valueType:t,typeName:ot.ZodRecord,...mt(s)}):new el({keyType:Xn.create(),valueType:e,typeName:ot.ZodRecord,...mt(t)})}}class ch extends vt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ke.map)return Ce(s,{code:we.invalid_type,expected:ke.map,received:s.parsedType}),at;const i=this._def.keyType,r=this._def.valueType,a=[...s.data.entries()].map(([o,l],c)=>({key:i._parse(new Tn(s,o,s.path,[c,"key"])),value:r._parse(new Tn(s,l,s.path,[c,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return at;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(c.value,d.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of a){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return at;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(c.value,d.value)}return{status:t.value,value:o}}}}ch.create=(n,e,t)=>new ch({valueType:e,keyType:n,typeName:ot.ZodMap,...mt(t)});class Pa extends vt{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ke.set)return Ce(s,{code:we.invalid_type,expected:ke.set,received:s.parsedType}),at;const i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(Ce(s,{code:we.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(Ce(s,{code:we.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const r=this._def.valueType;function a(l){const c=new Set;for(const d of l){if(d.status==="aborted")return at;d.status==="dirty"&&t.dirty(),c.add(d.value)}return{status:t.value,value:c}}const o=[...s.data.values()].map((l,c)=>r._parse(new Tn(s,l,s.path,c)));return s.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,t){return new Pa({...this._def,minSize:{value:e,message:He.toString(t)}})}max(e,t){return new Pa({...this._def,maxSize:{value:e,message:He.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Pa.create=(n,e)=>new Pa({valueType:n,minSize:null,maxSize:null,typeName:ot.ZodSet,...mt(e)});class tl extends vt{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}tl.create=(n,e)=>new tl({getter:n,typeName:ot.ZodLazy,...mt(e)});class sl extends vt{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Ce(t,{received:t.data,code:we.invalid_literal,expected:this._def.value}),at}return{status:"valid",value:e.data}}get value(){return this._def.value}}sl.create=(n,e)=>new sl({value:n,typeName:ot.ZodLiteral,...mt(e)});function um(n,e){return new Yi({values:n,typeName:ot.ZodEnum,...mt(e)})}class Yi extends vt{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return Ce(t,{expected:Dt.joinValues(s),received:t.parsedType,code:we.invalid_type}),at}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return Ce(t,{received:t.data,code:we.invalid_enum_value,options:s}),at}return on(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Yi.create(e,{...this._def,...t})}exclude(e,t=this._def){return Yi.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}Yi.create=um;class Jc extends vt{_parse(e){const t=Dt.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ke.string&&s.parsedType!==ke.number){const i=Dt.objectValues(t);return Ce(s,{expected:Dt.joinValues(i),received:s.parsedType,code:we.invalid_type}),at}if(this._cache||(this._cache=new Set(Dt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=Dt.objectValues(t);return Ce(s,{received:s.data,code:we.invalid_enum_value,options:i}),at}return on(e.data)}get enum(){return this._def.values}}Jc.create=(n,e)=>new Jc({values:n,typeName:ot.ZodNativeEnum,...mt(e)});class nl extends vt{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ke.promise&&t.common.async===!1)return Ce(t,{code:we.invalid_type,expected:ke.promise,received:t.parsedType}),at;const s=t.parsedType===ke.promise?t.data:Promise.resolve(t.data);return on(s.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}}nl.create=(n,e)=>new nl({type:n,typeName:ot.ZodPromise,...mt(e)});class Ki extends vt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ot.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),i=this._def.effect||null,r={addIssue:a=>{Ce(s,a),a.fatal?t.abort():t.dirty()},get path(){return s.path}};if(r.addIssue=r.addIssue.bind(r),i.type==="preprocess"){const a=i.transform(s.data,r);if(s.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return at;const l=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return l.status==="aborted"?at:l.status==="dirty"||t.value==="dirty"?Aa(l.value):l});{if(t.value==="aborted")return at;const o=this._def.schema._parseSync({data:a,path:s.path,parent:s});return o.status==="aborted"?at:o.status==="dirty"||t.value==="dirty"?Aa(o.value):o}}if(i.type==="refinement"){const a=o=>{const l=i.refinement(o,r);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?at:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?at:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(i.type==="transform")if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Ur(a))return at;const o=i.transform(a.value,r);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>Ur(a)?Promise.resolve(i.transform(a.value,r)).then(o=>({status:t.value,value:o})):at);Dt.assertNever(i)}}Ki.create=(n,e,t)=>new Ki({schema:n,typeName:ot.ZodEffects,effect:e,...mt(t)});Ki.createWithPreprocess=(n,e,t)=>new Ki({schema:e,effect:{type:"preprocess",transform:n},typeName:ot.ZodEffects,...mt(t)});class Kn extends vt{_parse(e){return this._getType(e)===ke.undefined?on(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Kn.create=(n,e)=>new Kn({innerType:n,typeName:ot.ZodOptional,...mt(e)});class Zi extends vt{_parse(e){return this._getType(e)===ke.null?on(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Zi.create=(n,e)=>new Zi({innerType:n,typeName:ot.ZodNullable,...mt(e)});class il extends vt{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===ke.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}il.create=(n,e)=>new il({innerType:n,typeName:ot.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...mt(e)});class rl extends vt{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Ko(i)?i.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ei(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ei(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}rl.create=(n,e)=>new rl({innerType:n,typeName:ot.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...mt(e)});class dh extends vt{_parse(e){if(this._getType(e)!==ke.nan){const s=this._getOrReturnCtx(e);return Ce(s,{code:we.invalid_type,expected:ke.nan,received:s.parsedType}),at}return{status:"valid",value:e.data}}}dh.create=n=>new dh({typeName:ot.ZodNaN,...mt(n)});class hm extends vt{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class du extends vt{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?at:r.status==="dirty"?(t.dirty(),Aa(r.value)):this._def.out._parseAsync({data:r.value,path:s.path,parent:s})})();{const i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?at:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(e,t){return new du({in:e,out:t,typeName:ot.ZodPipeline})}}class al extends vt{_parse(e){const t=this._def.innerType._parse(e),s=i=>(Ur(i)&&(i.value=Object.freeze(i.value)),i);return Ko(t)?t.then(i=>s(i)):s(t)}unwrap(){return this._def.innerType}}al.create=(n,e)=>new al({innerType:n,typeName:ot.ZodReadonly,...mt(e)});var ot;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ot||(ot={}));const H=Xn.create,ge=Fr.create,is=Xc.create,uu=Zc.create;Ai.create;const At=En.create,_e=ls.create;Qo.create;const fm=cu.create;Jo.create;const pm=Xi.create,ib=el.create,rb=tl.create,It=sl.create,cs=Yi.create;nl.create;Kn.create;Zi.create;const ab=cs(["ok","error"]),ob=_e({type:cs(["error","warning"]),message:H()}),lb=_e({kind:H(),data:uu()}),cb=_e({input:H(),proposed:H(),validated:is(),executed:H().optional()}),mm=_e({status:ab,rendered:H(),renderedErr:H().optional(),model:lb.optional(),errors:At(ob).optional(),trace:cb.optional()}),db=cs(["data","err","status"]),ub=_e({shellCommands:is(),hiddenInput:is().optional(),color:is().optional(),fileDelivery:is().optional(),localFilesystem:is().optional()}),hb=_e({type:It("attach"),protocolVersion:ge().int(),token:H(),session:H().optional(),capabilities:ub.optional()}),fb=_e({type:It("execute"),id:H(),line:H(),instrument:is().optional()}),pb=_e({type:It("cancel"),id:H()}),mb=_e({type:It("complete"),id:H(),prefix:H()}),gb=_e({type:It("promptAnswer"),promptId:H(),answer:H()}),Mb=_e({type:It("promptError"),promptId:H(),reason:H()}),bb=_e({type:It("pipeResult"),pipeId:H(),output:H()}),zb=_e({type:It("pipeError"),pipeId:H(),reason:H()}),_b=_e({type:It("shellResult"),shellId:H(),exitCode:ge().int()}),wb=_e({type:It("shellError"),shellId:H(),reason:H()}),yb=_e({type:It("editResult"),editId:H(),content:H(),changed:is()}),vb=_e({type:It("editError"),editId:H(),reason:H()}),Ob=_e({type:It("deliverResult"),deliverId:H(),location:H(),bytes:ge().nonnegative()}),xb=_e({type:It("deliverError"),deliverId:H(),reason:H()}),Sb=_e({address:H(),modelKind:H().optional(),groupId:H(),paneId:H()}),gm=_e({type:It("regard"),regard:Sb}),Ab=_e({type:It("watch"),subject:H()}),Eb=_e({type:It("unwatch"),subject:H()}),Db=["live","settled","stale"],Ib=cs(Db),Tb=_e({type:It("watched"),subject:H(),state:Ib}),Gb=_e({type:It("numbered"),id:ge(),source:H(),rows:ge(),handles:At(_e({kind:H(),ordinal:ge(),address:H()}))});fm("type",[hb,fb,pb,mb,gb,Mb,bb,zb,_b,wb,yb,vb,Ob,xb,gm,Ab,Eb]);const Rb=_e({type:It("attached"),session:H(),protocolVersion:ge().int(),stack:_e({chell:H(),calypso:H(),build:H(),brasa:H().optional(),chili:H().optional(),salsa:H().optional(),cumin:H().optional()}).optional(),hostControl:At(H()).optional()}),Bb=_e({type:It("result"),id:H(),envelopes:At(mm)}),Nb=_e({type:It("complete"),id:H(),prefix:H(),candidates:At(H())}),Cb=_e({type:It("output"),id:H(),channel:db,chunk:H()}),Pb=cs(EM).catch("task"),Lb=cs(DM).catch(void 0),Wb=cs(IM).catch("working"),kb=cs(TM).catch(void 0),Ub=cs(GM).catch("unknown"),Fb=_e({type:It("progress"),id:H(),operation:Pb,kind:Lb.optional(),phase:Wb,label:H().optional(),itemId:H().optional(),current:ge().nonnegative().optional(),total:ge().nonnegative().optional(),percent:ge().min(0).max(100).optional(),unit:kb.optional(),status:Ub.optional(),path:H().optional()}),jb=_e({type:It("session"),surface:H(),envelope:mm}),$b=_e({type:It("error"),id:H().optional(),reason:H()}),Vb=["text","secret","confirm","path"],Hb=cs(Vb).catch("text"),qb=_e({anchor:H().optional(),wantsDirectory:is(),suggest:H().optional()}),Xb=_e({type:It("prompt"),promptId:H(),message:H(),hidden:is(),wants:Hb.optional(),path:qb.optional(),commit:H().optional()});function Yb(n){return n.wants!==void 0?n.wants:n.hidden===!0?"secret":"text"}const Kb=_e({user:H(),uri:H(),cwd:H(),pacsserver:H().nullable(),physicalMode:is(),lastExitCode:ge(),lastCommandDurationMs:ge(),procWarmup:_e({loaded:ge(),total:ge().optional(),restored:is().optional(),state:cs(SM).optional(),sweeping:is().optional(),feed:_e({id:ge(),loaded:ge(),total:ge(),failed:H().optional()}).optional(),feeds:At(_e({id:ge(),loaded:ge(),total:ge(),failed:H().optional()})).optional(),arrived:At(ge()).optional(),landed:At(_e({id:ge(),title:H().default(""),jobs:ge(),status:H(),chain:At(H()),groups:At(_e({plugin:H(),count:ge(),errored:ge().default(0),status:H(),parent:ge().nullable()})).default([])})).optional(),roster:cs(["delta","full"]).optional()}).optional(),procIndex:_e({jobs:ge(),feeds:ge()}).optional(),warmupFailures:At(_e({label:H(),message:H()})).optional()}),Zb=_e({type:It("promptline"),context:Kb}),Qb=_e({type:It("pipe"),pipeId:H(),command:H(),input:H()}),Jb=_e({type:It("shell"),shellId:H(),command:H()}),e0=_e({type:It("edit"),editId:H(),content:H(),extension:H().optional()}),t0=_e({type:It("deliver"),deliverId:H(),path:H(),filename:H(),destination:H().optional(),size:ge().nonnegative().optional(),contentType:H().optional()}),s0=_e({type:It("telemetry"),index:_e({jobs:ge(),feeds:ge()}),lane:_e({running:_e({line:H(),sinceMs:ge(),surface:H()}).nullable(),waiting:ge()}).optional(),cube:_e({msPerPage:ge(),samples:ge()}).optional(),state:_e({running:ge(),runningFeeds:ge(),scheduled:ge(),errored:ge(),erroredFeeds:ge()}).optional()}),Mm=fm("type",[Rb,Bb,Nb,Cb,Fb,jb,$b,Xb,Zb,s0,Qb,Jb,e0,t0,gm,Tb,Gb]);new Set(Mm.options.map(n=>n.shape.type.value));function n0(n){return n.issues.map(e=>{const t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}).join("; ")}function i0(n,e){const t=n.safeParse(e);return t.success?{ok:!0,value:t.data}:{ok:!1,error:n0(t.error)}}function r0(n){return i0(Mm,n)}const bm=_e({id:H(),label:H(),parentIds:At(H()),joinParentIds:At(H())}),a0=_e({name:H(),value:uu()}),o0=bm.extend({pluginName:H(),pluginVersion:H().optional(),arguments:At(a0).optional()}),ed=_e({name:H(),pipelineId:ge().optional(),nodes:At(o0)}),l0=["created","waiting","scheduled","started","registeringFiles","finishedSuccessfully","finishedWithError","cancelled","unknown"],zm=cs(l0).catch("unknown"),c0=_e({count:ge(),done:ge(),error:ge(),running:ge(),other:ge(),anomalies:At(_e({id:H(),status:zm})).optional()}),d0=_e({computeSeconds:ge().optional(),dataBytes:ge().optional()}),u0=bm.extend({instanceId:ge(),pluginName:H(),pluginVersion:H().optional(),status:zm,vfsPath:H(),metrics:d0.optional(),tally:c0.optional(),computeResource:H().optional()}),td=_e({feedId:ge(),feedName:H(),nodes:At(u0)}),h0=_e({feedId:ge(),loaded:ge(),total:ge(),failed:H().optional()}),zi={pipelineDiagram:"pipeline.diagram",feedDag:"feed.dag",feedIndexing:"feed.indexing"},f0=_e({id:ge(),title:H(),owner:H(),status:H(),createdAt:H(),sizeBytes:ge().optional(),wallSeconds:ge().optional(),jobsDone:ge().optional(),jobsTotal:ge().optional(),jobsErrored:ge().optional()}),_m=_e({feeds:At(f0)}),wm="feed.list",p0=_e({plugin:H(),count:ge(),errored:ge().default(0),status:H(),parent:ge().nullable()}),m0=_e({format:cs(["dicom","nifti","mgz","jpeg","png","other","unknown"]),modality:H().optional(),seriesDescription:H().optional(),reason:H().optional(),sourceFeed:ge().optional()}),g0=_e({id:ge(),title:H().default(""),jobs:ge(),status:H(),chain:At(H()),groups:At(p0).default([]),createdAt:H().default(""),data:m0.optional()}),ym=_e({feeds:At(g0),whole:is()}),vm="proc.universe",M0=_e({name:H(),positions:ib(H(),pm([ge(),ge(),ge()])).nullable(),writtenAt:H().nullable(),laying:_e({nodes:ge(),fraction:ge()}).nullable().optional()}),b0="proc.layout",z0=_e({name:H(),type:H(),optional:is(),default:uu().optional(),help:H().optional(),flag:H()}),_0=_e({id:ge().optional(),name:H(),version:H(),type:H(),title:H().optional(),description:H().optional(),authors:H().optional(),documentation:H().optional(),category:H().optional(),parameters:At(z0),command:H().optional()}),w0="plugin.info",y0=_e({seriesUID:H(),description:H(),modality:H(),fileCount:ge().optional(),vfsPath:H().optional(),pulled:is().optional(),pulledFiles:ge().optional(),folderPath:H().optional()}),v0=_e({studyUID:H().optional(),server:H().optional(),vfsPath:H().optional(),description:H(),patientName:H(),patientId:H(),date:H(),modalities:H(),accession:H(),series:At(y0)}),Om=_e({replayed:is(),answeredAt:H()}),O0=["found","none","unasked"],x0=cs(O0).catch("unasked"),S0=_e({patientId:H(),server:H().optional(),patientName:H().optional(),status:x0,studyCount:ge(),seriesCount:ge(),queryId:ge().optional(),provenance:Om.optional(),error:H().optional()}),A0=_e({queryId:ge(),vfsPath:H(),pacsName:H(),expression:H(),studies:At(v0),provenance:Om.optional(),patients:At(S0).optional()}),E0=_e({id:ge(),identifier:H(),active:is()}),D0=_e({servers:At(E0)}),I0="pacs.servers",T0="pacs.query";function G0(n){return`pacs:patient:${n.server??"-"}:${n.patientId}`}const R0=["patient","study","series","image","equipment","meta","private","other"],xm=cs(R0).catch("other"),Sm=rb(()=>_e({tag:H(),name:H(),vr:H(),value:H(),group:xm,phi:is(),decoded:H().optional(),items:At(At(Sm)).optional()})),B0=_e({tag:H(),name:H(),vr:H(),group:xm,phi:is(),distinct:ge(),first:H(),last:H(),values:At(_e({path:H(),value:H().nullable()}))}),uh=_e({path:H(),subject:cs(["file","folder"]),read:ge(),of:ge(),refused:At(H()),constant:At(Sm),varying:At(B0)}),N0=_e({rows:ge(),columns:ge(),pixelSpacing:pm([ge(),ge()]).optional(),sliceThickness:ge().optional(),spacingBetweenSlices:ge().optional()}),hh=_e({path:H(),seriesInstanceUID:H().optional(),studyInstanceUID:H().optional(),modality:H(),seriesDescription:H(),seriesNumber:ge().optional(),instances:ge(),frames:ge(),order:cs(["filename","unknown"]),geometry:N0.optional(),transferSyntax:_e({uid:H(),name:H().optional()}).optional(),bytes:ge(),header:H(),files:At(H()),annotations:At(H())}),Ha={tags:"dicom.tags",series:"dicom.series"},C0=_e({path:H(),target:cs(["series","volume"]),force:is().optional(),startAt:ge().int().positive().optional()}),P0={view:"image.view"},L0=_e({state:cs(["cold","warming","current"]),loaded:ge(),total:ge()});_e({user:H(),surface:H(),feeds:_e({total:ge(),own:ge(),shared:ge(),public:ge()}),jobs:_e({total:ge(),finished:ge(),errored:ge(),cancelled:ge(),running:ge(),scheduled:ge()}),failureRate:ge().nullable(),index:L0,fortune:H()});function Es(n){return n.groups.map(e=>`${e.parent??"r"}:${e.plugin}`).join(">")}function wi(n,e){return`feed:${n}:${e}`}function Am(n){return`shape:${n}`}function jr(n){return Math.log2(Math.max(1,n)+1)}function hu(n){if(!(n.errored<=0||n.count<=0))return Math.min(1,n.errored/n.count)}function Fa(n,e="jobs"){const t=[],s=new Set,i=[...n].sort((a,o)=>a.id-o.id),r=new Map;for(const a of i){if(a.groups.length===0)continue;const o=Es(a);r.set(o,(r.get(o)??0)+1)}for(const a of i){if(a.groups.length===0)continue;const o=Es(a),l=Am(o);s.has(o)||(s.add(o),t.push({id:l,label:vl(o),parentIds:[],joinParentIds:[],ghost:!0,halo:!0,metric:1,count:r.get(o)??1})),a.groups.forEach((c,d)=>{const u=hu(c);t.push({id:wi(a.id,d),label:c.plugin,parentIds:[c.parent===null?l:wi(a.id,c.parent)],joinParentIds:[],status:c.status,metric:e==="jobs"?jr(c.count):1,...c.count>1?{count:c.count}:{},...u!==void 0?{share:u}:{}})})}return{nodes:t}}const sd="plugin:";function W0(n){return`${sd}${n}`}function nd(n){return n.startsWith(sd)?n.slice(sd.length):null}function fu(n,e="jobs"){const t=[],s=new Map,i=[...n].sort((r,a)=>r.id-a.id);for(const r of i)if(r.groups.length!==0){for(const a of new Set(r.groups.map(o=>o.plugin)))s.set(a,(s.get(a)??0)+1);r.groups.forEach((a,o)=>{const l=hu(a);t.push({id:wi(r.id,o),label:a.plugin,parentIds:a.parent===null?[]:[wi(r.id,a.parent)],joinParentIds:[],status:a.status,metric:e==="jobs"?jr(a.count):1,attrs:{plugin:a.plugin},...a.count>1?{count:a.count}:{},...l!==void 0?{share:l}:{}})})}for(const[r,a]of[...s].sort((o,l)=>o[0]<l[0]?-1:1))t.push({id:W0(r),label:r,parentIds:[],joinParentIds:[],metric:1+Math.log(a),hue:"#e8f4ff",ring:!0,attrs:{kind:"star",plugin:r}});return{nodes:t}}function fh(n,e="jobs"){const t=new Map;for(const i of n){const r=i.createdAt===void 0?Number.NaN:Date.parse(i.createdAt);Number.isFinite(r)&&t.set(i.id,r)}return{nodes:fu(n,e).nodes.filter(i=>i.attrs?.kind!=="star").map(i=>{const r=t.get(Number(i.id.split(":")[1]));return r===void 0?i:{...i,attrs:{...i.attrs,createdAt:r}}})}}function vl(n){const e=[];for(const t of n.split(">")){const s=t.slice(t.indexOf(":")+1);s.length>0&&!e.includes(s)&&e.push(s)}return e.join(" > ")}const k0=.5,U0=5,F0=.02,id="data:",j0={dicom:"DICOM",nifti:"NIfTI",mgz:"MGZ",jpeg:"JPEG",png:"PNG",other:"OTHER",unknown:"UNREADABLE",unread:"NOT YET READ"};function $0(n){const e=n.toUpperCase().replace(/[_\-.,/\\()[\]:;+]+/g," ").split(/\s+/).filter(t=>t.length>0).filter(t=>!/^\d+$/.test(t)).filter(t=>!/^\d+X\d+$/.test(t)).filter(t=>!/^FOV\d*$/.test(t)).filter(t=>!/^\d+(\.\d+)?(MM|CM)$/.test(t));return[...new Set(e)]}function V0(n,e){if(n.length===0||e.length===0)return 0;const t=new Set(n);return e.filter(i=>t.has(i)).length/Math.min(n.length,e.length)}function Em(n){const e=new Map;for(const r of n)e.set(r,(e.get(r)??0)+1);const t=[...e.keys()].sort((r,a)=>(e.get(a)??0)-(e.get(r)??0)||(r<a?-1:1)),s=[],i=new Map;for(const r of t){const a=$0(r),o=a.length===0?void 0:s.find(l=>V0(l.words,a)>=k0);if(o!==void 0){i.set(r,o.name);continue}s.push({name:r,words:a}),i.set(r,r)}return i}function Dm(n,e){const t=n.data?.format??"unread",s=[{key:t,label:j0[t]??t.toUpperCase()}];if(t!=="dicom")return s;const i=n.data?.modality??"NO MODALITY";s.push({key:`${t}/${i}`,label:i});const r=n.data?.seriesDescription,a=r===void 0?"NO DESCRIPTION":e.get(r)??r;return s.push({key:`${t}/${i}/${a}`,label:a}),s}function Fl(n){return`${id}${n}`}function rd(n){return n.startsWith(id)?n.slice(id.length):null}function ph(n,e="jobs"){const t=[...n].filter(d=>d.groups.length>0).sort((d,u)=>d.id-u.id),s=Em(t.map(d=>d.data?.seriesDescription).filter(d=>d!==void 0)),i=new Map,r=[];for(const d of t){const u=Dm(d,s);let h=null;for(const p of u){const z=i.get(p.key);z===void 0?i.set(p.key,{label:p.label,feeds:1,parent:h}):z.feeds+=1,h=p.key}const g=Fl(h);d.groups.forEach((p,z)=>{const m=hu(p);r.push({id:wi(d.id,z),label:p.plugin,parentIds:[p.parent===null?g:wi(d.id,p.parent)],joinParentIds:[],status:p.status,metric:e==="jobs"?jr(p.count):1,...p.count>1?{count:p.count}:{},...m!==void 0?{share:m}:{}})})}const a=new Map;for(const d of t){const u=d.groups.findIndex(h=>h.parent===null);u>=0&&a.set(d.id,wi(d.id,u))}const o=new Map(r.map(d=>[d.id,d]));for(const d of t){const u=d.data?.sourceFeed,h=u===void 0||u===d.id?void 0:a.get(u),g=a.get(d.id);if(h===void 0||g===void 0)continue;const p=o.get(g);p!==void 0&&(p.joinParentIds=[...p.joinParentIds,h],p.joinFaint=!0)}const l=(d,u)=>d.split("/").length<3||u>=Math.max(U0,F0*t.length);return{graph:{nodes:[...[...i].map(([d,u])=>({id:Fl(d),label:u.label,parentIds:u.parent===null?[]:[Fl(u.parent)],joinParentIds:[],ghost:!0,halo:!0,metric:1,count:u.feeds,...l(d,u.feeds)?{caption:`${u.label} · ${u.feeds.toLocaleString("en-US")}`}:{}})),...r]},hubs:new Map([...i].map(([d,u])=>[d,{label:u.label,feeds:u.feeds}]))}}function H0(n,e){const t=rd(n);if(t===null)return null;const s=t.split("/"),i=s.map((a,o)=>e.get(s.slice(0,o+1).join("/"))?.label??s[o]??""),r=e.get(t)?.feeds??0;return`${i.join(" · ")} · ${r.toLocaleString("en-US")} feed${r===1?"":"s"}`}const ad=12,q0=240;function X0(n){return n<=q0?ad:void 0}function od(n,e){return`fold:${n}:${e}`}function Im(n){const e=n.match(/^fold:(.+):\d+$/);return e===null?null:e[1]}function Y0(n){const e=n.match(/^feed:(\d+):/);if(e!==null)return`feed:${e[1]}`;const t=Im(n);return t===null?null:`fold:${t}`}const pu="185",K0=0,mh=1,Z0=2,Po=1,Q0=2,Ea=3,Ei=0,ks=1,Hn=2,Zn=0,$i=1,Qi=2,gh=3,Mh=4,J0=5,Wi=100,ez=101,tz=102,sz=103,nz=104,iz=200,rz=201,az=202,oz=203,ld=204,cd=205,lz=206,cz=207,dz=208,uz=209,hz=210,fz=211,pz=212,mz=213,gz=214,dd=0,ud=1,hd=2,$r=3,fd=4,pd=5,md=6,gd=7,Tm=0,Mz=1,bz=2,Dn=0,Gm=1,Rm=2,Bm=3,Nm=4,Cm=5,Pm=6,Lm=7,Wm=300,Ji=301,Vr=302,jl=303,$l=304,Ol=306,Md=1e3,Yn=1001,bd=1002,ys=1003,zz=1004,qa=1005,Ds=1006,Vl=1007,Fi=1008,Zs=1009,km=1010,Um=1011,La=1012,mu=1013,Gn=1014,Mn=1015,ti=1016,gu=1017,Mu=1018,Wa=1020,Fm=35902,jm=35899,$m=1021,Vm=1022,bn=1023,si=1026,ji=1027,bu=1028,zu=1029,er=1030,_u=1031,wu=1033,Lo=33776,Wo=33777,ko=33778,Uo=33779,zd=35840,_d=35841,wd=35842,yd=35843,vd=36196,Od=37492,xd=37496,Sd=37488,Ad=37489,ol=37490,Ed=37491,Dd=37808,Id=37809,Td=37810,Gd=37811,Rd=37812,Bd=37813,Nd=37814,Cd=37815,Pd=37816,Ld=37817,Wd=37818,kd=37819,Ud=37820,Fd=37821,jd=36492,$d=36494,Vd=36495,Hd=36283,qd=36284,ll=36285,Xd=36286,_z=3200,Yd=0,wz=1,bi="",sn="srgb",cl="srgb-linear",dl="linear",kt="srgb",dr=7680,bh=519,yz=512,vz=513,Oz=514,yu=515,xz=516,Sz=517,vu=518,Az=519,Kd=35044,zh="300 es",An=2e3,ka=2001;function Ez(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function ul(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function Dz(){const n=ul("canvas");return n.style.display="block",n}const _h={};function hl(...n){const e="THREE."+n.shift();console.log(e,...n)}function Hm(n){const e=n[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=n[1];t&&t.isStackTrace?n[0]+=" "+t.getLocation():n[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return n}function st(...n){n=Hm(n);const e="THREE."+n.shift();{const t=n[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...n)}}function Ot(...n){n=Hm(n);const e="THREE."+n.shift();{const t=n[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...n)}}function Pr(...n){const e=n.join(" ");e in _h||(_h[e]=!0,st(...n))}function Iz(n,e,t){return new Promise(function(s,i){function r(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:i();break;case n.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:s()}}setTimeout(r,t)})}const Tz={[dd]:ud,[hd]:md,[fd]:gd,[$r]:pd,[ud]:dd,[md]:hd,[gd]:fd,[pd]:$r};class ir{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const s=this._listeners;s[e]===void 0&&(s[e]=[]),s[e].indexOf(t)===-1&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return s===void 0?!1:s[e]!==void 0&&s[e].indexOf(t)!==-1}removeEventListener(e,t){const s=this._listeners;if(s===void 0)return;const i=s[e];if(i!==void 0){const r=i.indexOf(t);r!==-1&&i.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const s=t[e.type];if(s!==void 0){e.target=this;const i=s.slice(0);for(let r=0,a=i.length;r<a;r++)i[r].call(this,e);e.target=null}}}const Ss=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Hl=Math.PI/180,Zd=180/Math.PI;function yi(){const n=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,s=Math.random()*4294967295|0;return(Ss[n&255]+Ss[n>>8&255]+Ss[n>>16&255]+Ss[n>>24&255]+"-"+Ss[e&255]+Ss[e>>8&255]+"-"+Ss[e>>16&15|64]+Ss[e>>24&255]+"-"+Ss[t&63|128]+Ss[t>>8&255]+"-"+Ss[t>>16&255]+Ss[t>>24&255]+Ss[s&255]+Ss[s>>8&255]+Ss[s>>16&255]+Ss[s>>24&255]).toLowerCase()}function St(n,e,t){return Math.max(e,Math.min(t,n))}function Gz(n,e){return(n%e+e)%e}function ql(n,e,t){return(1-t)*n+t*e}function xn(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function Ft(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const Yu=class Yu{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=St(this.x,e.x,t.x),this.y=St(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=St(this.x,e,t),this.y=St(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(St(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(St(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*s-a*i+e.x,this.y=r*i+a*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};Yu.prototype.isVector2=!0;let lt=Yu;class rr{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,r,a,o){let l=s[i+0],c=s[i+1],d=s[i+2],u=s[i+3],h=r[a+0],g=r[a+1],p=r[a+2],z=r[a+3];if(u!==z||l!==h||c!==g||d!==p){let m=l*h+c*g+d*p+u*z;m<0&&(h=-h,g=-g,p=-p,z=-z,m=-m);let f=1-o;if(m<.9995){const _=Math.acos(m),O=Math.sin(_);f=Math.sin(f*_)/O,o=Math.sin(o*_)/O,l=l*f+h*o,c=c*f+g*o,d=d*f+p*o,u=u*f+z*o}else{l=l*f+h*o,c=c*f+g*o,d=d*f+p*o,u=u*f+z*o;const _=1/Math.sqrt(l*l+c*c+d*d+u*u);l*=_,c*=_,d*=_,u*=_}}e[t]=l,e[t+1]=c,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,a){const o=s[i],l=s[i+1],c=s[i+2],d=s[i+3],u=r[a],h=r[a+1],g=r[a+2],p=r[a+3];return e[t]=o*p+d*u+l*g-c*h,e[t+1]=l*p+d*h+c*u-o*g,e[t+2]=c*p+d*g+o*h-l*u,e[t+3]=d*p-o*u-l*h-c*g,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(s/2),d=o(i/2),u=o(r/2),h=l(s/2),g=l(i/2),p=l(r/2);switch(a){case"XYZ":this._x=h*d*u+c*g*p,this._y=c*g*u-h*d*p,this._z=c*d*p+h*g*u,this._w=c*d*u-h*g*p;break;case"YXZ":this._x=h*d*u+c*g*p,this._y=c*g*u-h*d*p,this._z=c*d*p-h*g*u,this._w=c*d*u+h*g*p;break;case"ZXY":this._x=h*d*u-c*g*p,this._y=c*g*u+h*d*p,this._z=c*d*p+h*g*u,this._w=c*d*u-h*g*p;break;case"ZYX":this._x=h*d*u-c*g*p,this._y=c*g*u+h*d*p,this._z=c*d*p-h*g*u,this._w=c*d*u+h*g*p;break;case"YZX":this._x=h*d*u+c*g*p,this._y=c*g*u+h*d*p,this._z=c*d*p-h*g*u,this._w=c*d*u-h*g*p;break;case"XZY":this._x=h*d*u-c*g*p,this._y=c*g*u-h*d*p,this._z=c*d*p+h*g*u,this._w=c*d*u+h*g*p;break;default:st("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],a=t[1],o=t[5],l=t[9],c=t[2],d=t[6],u=t[10],h=s+o+u;if(h>0){const g=.5/Math.sqrt(h+1);this._w=.25/g,this._x=(d-l)*g,this._y=(r-c)*g,this._z=(a-i)*g}else if(s>o&&s>u){const g=2*Math.sqrt(1+s-o-u);this._w=(d-l)/g,this._x=.25*g,this._y=(i+a)/g,this._z=(r+c)/g}else if(o>u){const g=2*Math.sqrt(1+o-s-u);this._w=(r-c)/g,this._x=(i+a)/g,this._y=.25*g,this._z=(l+d)/g}else{const g=2*Math.sqrt(1+u-s-o);this._w=(a-i)/g,this._x=(r+c)/g,this._y=(l+d)/g,this._z=.25*g}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(St(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(s===0)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,a=e._w,o=t._x,l=t._y,c=t._z,d=t._w;return this._x=s*d+a*o+i*c-r*l,this._y=i*d+a*l+r*o-s*c,this._z=r*d+a*c+s*l-i*o,this._w=a*d-s*o-i*l-r*c,this._onChangeCallback(),this}slerp(e,t){let s=e._x,i=e._y,r=e._z,a=e._w,o=this.dot(e);o<0&&(s=-s,i=-i,r=-r,a=-a,o=-o);let l=1-t;if(o<.9995){const c=Math.acos(o),d=Math.sin(c);l=Math.sin(l*c)/d,t=Math.sin(t*c)/d,this._x=this._x*l+s*t,this._y=this._y*l+i*t,this._z=this._z*l+r*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+s*t,this._y=this._y*l+i*t,this._z=this._z*l+r*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}const Ku=class Ku{constructor(e=0,t=0,s=0){this.x=e,this.y=t,this.z=s}set(e,t,s){return s===void 0&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(wh.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(wh.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,a=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*a,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*a,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*a,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*i-o*s),d=2*(o*t-r*i),u=2*(r*s-a*t);return this.x=t+l*c+a*u-o*d,this.y=s+l*d+o*c-r*u,this.z=i+l*u+r*d-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=St(this.x,e.x,t.x),this.y=St(this.y,e.y,t.y),this.z=St(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=St(this.x,e,t),this.y=St(this.y,e,t),this.z=St(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(St(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,a=t.x,o=t.y,l=t.z;return this.x=i*l-r*o,this.y=r*a-s*l,this.z=s*o-i*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Xl.copy(this).projectOnVector(e),this.sub(Xl)}reflect(e){return this.sub(Xl.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(St(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};Ku.prototype.isVector3=!0;let F=Ku;const Xl=new F,wh=new rr,Zu=class Zu{constructor(e,t,s,i,r,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,s,i,r,a,o,l,c)}set(e,t,s,i,r,a,o,l,c){const d=this.elements;return d[0]=e,d[1]=i,d[2]=o,d[3]=t,d[4]=r,d[5]=l,d[6]=s,d[7]=a,d[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,a=s[0],o=s[3],l=s[6],c=s[1],d=s[4],u=s[7],h=s[2],g=s[5],p=s[8],z=i[0],m=i[3],f=i[6],_=i[1],O=i[4],w=i[7],x=i[2],S=i[5],I=i[8];return r[0]=a*z+o*_+l*x,r[3]=a*m+o*O+l*S,r[6]=a*f+o*w+l*I,r[1]=c*z+d*_+u*x,r[4]=c*m+d*O+u*S,r[7]=c*f+d*w+u*I,r[2]=h*z+g*_+p*x,r[5]=h*m+g*O+p*S,r[8]=h*f+g*w+p*I,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],d=e[8];return t*a*d-t*o*c-s*r*d+s*o*l+i*r*c-i*a*l}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],d=e[8],u=d*a-o*c,h=o*l-d*r,g=c*r-a*l,p=t*u+s*h+i*g;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const z=1/p;return e[0]=u*z,e[1]=(i*c-d*s)*z,e[2]=(o*s-i*a)*z,e[3]=h*z,e[4]=(d*t-i*l)*z,e[5]=(i*r-o*t)*z,e[6]=g*z,e[7]=(s*l-c*t)*z,e[8]=(a*t-s*r)*z,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,a,o){const l=Math.cos(r),c=Math.sin(r);return this.set(s*l,s*c,-s*(l*a+c*o)+a+e,-i*c,i*l,-i*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return Pr("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Yl.makeScale(e,t)),this}rotate(e){return Pr("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Yl.makeRotation(-e)),this}translate(e,t){return Pr("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Yl.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<9;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return new this.constructor().fromArray(this.elements)}};Zu.prototype.isMatrix3=!0;let ut=Zu;const Yl=new ut,yh=new ut().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),vh=new ut().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Rz(){const n={enabled:!0,workingColorSpace:cl,spaces:{},convert:function(i,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===kt&&(i.r=Qn(i.r),i.g=Qn(i.g),i.b=Qn(i.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(i.applyMatrix3(this.spaces[r].toXYZ),i.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===kt&&(i.r=Lr(i.r),i.g=Lr(i.g),i.b=Lr(i.b))),i},workingToColorSpace:function(i,r){return this.convert(i,this.workingColorSpace,r)},colorSpaceToWorking:function(i,r){return this.convert(i,r,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===bi?dl:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,r=this.workingColorSpace){return i.fromArray(this.spaces[r].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,r,a){return i.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,r){return Pr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(i,r)},toWorkingColorSpace:function(i,r){return Pr("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(i,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],s=[.3127,.329];return n.define({[cl]:{primaries:e,whitePoint:s,transfer:dl,toXYZ:yh,fromXYZ:vh,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:sn},outputColorSpaceConfig:{drawingBufferColorSpace:sn}},[sn]:{primaries:e,whitePoint:s,transfer:kt,toXYZ:yh,fromXYZ:vh,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:sn}}}),n}const xt=Rz();function Qn(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function Lr(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let ur;class Bz{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{ur===void 0&&(ur=ul("canvas")),ur.width=e.width,ur.height=e.height;const i=ur.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),s=ur}return s.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=ul("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let a=0;a<r.length;a++)r[a]=Qn(r[a]/255)*255;return s.putImageData(i,0,0),t}else if(e.data){const t=e.data.slice(0);for(let s=0;s<t.length;s++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[s]=Math.floor(Qn(t[s]/255)*255):t[s]=Qn(t[s]);return{data:t,width:e.width,height:e.height}}else return st("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Nz=0;class Ou{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Nz++}),this.uuid=yi(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(i!==null){let r;if(Array.isArray(i)){r=[];for(let a=0,o=i.length;a<o;a++)i[a].isDataTexture?r.push(Kl(i[a].image)):r.push(Kl(i[a]))}else r=Kl(i);s.url=r}return t||(e.images[this.uuid]=s),s}}function Kl(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&n instanceof ImageBitmap?Bz.getDataURL(n):n.data?{data:Array.from(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(st("Texture: Unable to serialize Texture."),{})}let Cz=0;const Zl=new F;class Is extends ir{constructor(e=Is.DEFAULT_IMAGE,t=Is.DEFAULT_MAPPING,s=Yn,i=Yn,r=Ds,a=Fi,o=bn,l=Zs,c=Is.DEFAULT_ANISOTROPY,d=bi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Cz++}),this.uuid=yi(),this.name="",this.source=new Ou(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=r,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new lt(0,0),this.repeat=new lt(1,1),this.center=new lt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ut,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Zl).x}get height(){return this.source.getSize(Zl).y}get depth(){return this.source.getSize(Zl).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const s=e[t];if(s===void 0){st(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){st(`Texture.setValues(): property '${t}' does not exist.`);continue}i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const s={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Wm)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Md:e.x=e.x-Math.floor(e.x);break;case Yn:e.x=e.x<0?0:1;break;case bd:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Md:e.y=e.y-Math.floor(e.y);break;case Yn:e.y=e.y<0?0:1;break;case bd:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Is.DEFAULT_IMAGE=null;Is.DEFAULT_MAPPING=Wm;Is.DEFAULT_ANISOTROPY=1;const Qu=class Qu{constructor(e=0,t=0,s=0,i=1){this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*s+a[8]*i+a[12]*r,this.y=a[1]*t+a[5]*s+a[9]*i+a[13]*r,this.z=a[2]*t+a[6]*s+a[10]*i+a[14]*r,this.w=a[3]*t+a[7]*s+a[11]*i+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const l=e.elements,c=l[0],d=l[4],u=l[8],h=l[1],g=l[5],p=l[9],z=l[2],m=l[6],f=l[10];if(Math.abs(d-h)<.01&&Math.abs(u-z)<.01&&Math.abs(p-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+z)<.1&&Math.abs(p+m)<.1&&Math.abs(c+g+f-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const O=(c+1)/2,w=(g+1)/2,x=(f+1)/2,S=(d+h)/4,I=(u+z)/4,b=(p+m)/4;return O>w&&O>x?O<.01?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(O),i=S/s,r=I/s):w>x?w<.01?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(w),s=S/i,r=b/i):x<.01?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(x),s=I/r,i=b/r),this.set(s,i,r,t),this}let _=Math.sqrt((m-p)*(m-p)+(u-z)*(u-z)+(h-d)*(h-d));return Math.abs(_)<.001&&(_=1),this.x=(m-p)/_,this.y=(u-z)/_,this.z=(h-d)/_,this.w=Math.acos((c+g+f-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=St(this.x,e.x,t.x),this.y=St(this.y,e.y,t.y),this.z=St(this.z,e.z,t.z),this.w=St(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=St(this.x,e,t),this.y=St(this.y,e,t),this.z=St(this.z,e,t),this.w=St(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(St(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};Qu.prototype.isVector4=!0;let ts=Qu;class Pz extends ir{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ds,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new ts(0,0,e,t),this.scissorTest=!1,this.viewport=new ts(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:s.depth},r=new Is(i),a=s.count;for(let o=0;o<a;o++)this.textures[o]=r.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview,this.useArrayDepthTexture=s.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:Ds,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let s=0;s<this.textures.length;s++)this.textures[s].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const i=Object.assign({},e.textures[t].image);this.textures[t].source=new Ou(i)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class In extends Pz{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class qm extends Is{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=ys,this.minFilter=ys,this.wrapR=Yn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Lz extends Is{constructor(e=null,t=1,s=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=ys,this.minFilter=ys,this.wrapR=Yn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const yl=class yl{constructor(e,t,s,i,r,a,o,l,c,d,u,h,g,p,z,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,s,i,r,a,o,l,c,d,u,h,g,p,z,m)}set(e,t,s,i,r,a,o,l,c,d,u,h,g,p,z,m){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=a,f[9]=o,f[13]=l,f[2]=c,f[6]=d,f[10]=u,f[14]=h,f[3]=g,f[7]=p,f[11]=z,f[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new yl().fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),s.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this)}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();const t=this.elements,s=e.elements,i=1/hr.setFromMatrixColumn(e,0).length(),r=1/hr.setFromMatrixColumn(e,1).length(),a=1/hr.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*a,t[9]=s[9]*a,t[10]=s[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,a=Math.cos(s),o=Math.sin(s),l=Math.cos(i),c=Math.sin(i),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=a*d,g=a*u,p=o*d,z=o*u;t[0]=l*d,t[4]=-l*u,t[8]=c,t[1]=g+p*c,t[5]=h-z*c,t[9]=-o*l,t[2]=z-h*c,t[6]=p+g*c,t[10]=a*l}else if(e.order==="YXZ"){const h=l*d,g=l*u,p=c*d,z=c*u;t[0]=h+z*o,t[4]=p*o-g,t[8]=a*c,t[1]=a*u,t[5]=a*d,t[9]=-o,t[2]=g*o-p,t[6]=z+h*o,t[10]=a*l}else if(e.order==="ZXY"){const h=l*d,g=l*u,p=c*d,z=c*u;t[0]=h-z*o,t[4]=-a*u,t[8]=p+g*o,t[1]=g+p*o,t[5]=a*d,t[9]=z-h*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const h=a*d,g=a*u,p=o*d,z=o*u;t[0]=l*d,t[4]=p*c-g,t[8]=h*c+z,t[1]=l*u,t[5]=z*c+h,t[9]=g*c-p,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const h=a*l,g=a*c,p=o*l,z=o*c;t[0]=l*d,t[4]=z-h*u,t[8]=p*u+g,t[1]=u,t[5]=a*d,t[9]=-o*d,t[2]=-c*d,t[6]=g*u+p,t[10]=h-z*u}else if(e.order==="XZY"){const h=a*l,g=a*c,p=o*l,z=o*c;t[0]=l*d,t[4]=-u,t[8]=c*d,t[1]=h*u+z,t[5]=a*d,t[9]=g*u-p,t[2]=p*u-g,t[6]=o*d,t[10]=z*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Wz,e,kz)}lookAt(e,t,s){const i=this.elements;return Hs.subVectors(e,t),Hs.lengthSq()===0&&(Hs.z=1),Hs.normalize(),ci.crossVectors(s,Hs),ci.lengthSq()===0&&(Math.abs(s.z)===1?Hs.x+=1e-4:Hs.z+=1e-4,Hs.normalize(),ci.crossVectors(s,Hs)),ci.normalize(),Xa.crossVectors(Hs,ci),i[0]=ci.x,i[4]=Xa.x,i[8]=Hs.x,i[1]=ci.y,i[5]=Xa.y,i[9]=Hs.y,i[2]=ci.z,i[6]=Xa.z,i[10]=Hs.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,a=s[0],o=s[4],l=s[8],c=s[12],d=s[1],u=s[5],h=s[9],g=s[13],p=s[2],z=s[6],m=s[10],f=s[14],_=s[3],O=s[7],w=s[11],x=s[15],S=i[0],I=i[4],b=i[8],A=i[12],B=i[1],N=i[5],k=i[9],L=i[13],j=i[2],P=i[6],W=i[10],X=i[14],Q=i[3],re=i[7],Me=i[11],oe=i[15];return r[0]=a*S+o*B+l*j+c*Q,r[4]=a*I+o*N+l*P+c*re,r[8]=a*b+o*k+l*W+c*Me,r[12]=a*A+o*L+l*X+c*oe,r[1]=d*S+u*B+h*j+g*Q,r[5]=d*I+u*N+h*P+g*re,r[9]=d*b+u*k+h*W+g*Me,r[13]=d*A+u*L+h*X+g*oe,r[2]=p*S+z*B+m*j+f*Q,r[6]=p*I+z*N+m*P+f*re,r[10]=p*b+z*k+m*W+f*Me,r[14]=p*A+z*L+m*X+f*oe,r[3]=_*S+O*B+w*j+x*Q,r[7]=_*I+O*N+w*P+x*re,r[11]=_*b+O*k+w*W+x*Me,r[15]=_*A+O*L+w*X+x*oe,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],a=e[1],o=e[5],l=e[9],c=e[13],d=e[2],u=e[6],h=e[10],g=e[14],p=e[3],z=e[7],m=e[11],f=e[15],_=l*g-c*h,O=o*g-c*u,w=o*h-l*u,x=a*g-c*d,S=a*h-l*d,I=a*u-o*d;return t*(z*_-m*O+f*w)-s*(p*_-m*x+f*S)+i*(p*O-z*x+f*I)-r*(p*w-z*S+m*I)}determinantAffine(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[1],a=e[5],o=e[9],l=e[2],c=e[6],d=e[10];return t*(a*d-o*c)-s*(r*d-o*l)+i*(r*c-a*l)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],d=e[8],u=e[9],h=e[10],g=e[11],p=e[12],z=e[13],m=e[14],f=e[15],_=t*o-s*a,O=t*l-i*a,w=t*c-r*a,x=s*l-i*o,S=s*c-r*o,I=i*c-r*l,b=d*z-u*p,A=d*m-h*p,B=d*f-g*p,N=u*m-h*z,k=u*f-g*z,L=h*f-g*m,j=_*L-O*k+w*N+x*B-S*A+I*b;if(j===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const P=1/j;return e[0]=(o*L-l*k+c*N)*P,e[1]=(i*k-s*L-r*N)*P,e[2]=(z*I-m*S+f*x)*P,e[3]=(h*S-u*I-g*x)*P,e[4]=(l*B-a*L-c*A)*P,e[5]=(t*L-i*B+r*A)*P,e[6]=(m*w-p*I-f*O)*P,e[7]=(d*I-h*w+g*O)*P,e[8]=(a*k-o*B+c*b)*P,e[9]=(s*B-t*k-r*b)*P,e[10]=(p*S-z*w+f*_)*P,e[11]=(u*w-d*S-g*_)*P,e[12]=(o*A-a*N-l*b)*P,e[13]=(t*N-s*A+i*b)*P,e[14]=(z*O-p*x-m*_)*P,e[15]=(d*x-u*O+h*_)*P,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,a=e.x,o=e.y,l=e.z,c=r*a,d=r*o;return this.set(c*a+s,c*o-i*l,c*l+i*o,0,c*o+i*l,d*o+s,d*l-i*a,0,c*l-i*o,d*l+i*a,r*l*l+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,a){return this.set(1,s,r,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,a=t._y,o=t._z,l=t._w,c=r+r,d=a+a,u=o+o,h=r*c,g=r*d,p=r*u,z=a*d,m=a*u,f=o*u,_=l*c,O=l*d,w=l*u,x=s.x,S=s.y,I=s.z;return i[0]=(1-(z+f))*x,i[1]=(g+w)*x,i[2]=(p-O)*x,i[3]=0,i[4]=(g-w)*S,i[5]=(1-(h+f))*S,i[6]=(m+_)*S,i[7]=0,i[8]=(p+O)*I,i[9]=(m-_)*I,i[10]=(1-(h+z))*I,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinantAffine();if(r===0)return s.set(1,1,1),t.identity(),this;let a=hr.set(i[0],i[1],i[2]).length();const o=hr.set(i[4],i[5],i[6]).length(),l=hr.set(i[8],i[9],i[10]).length();r<0&&(a=-a),dn.copy(this);const c=1/a,d=1/o,u=1/l;return dn.elements[0]*=c,dn.elements[1]*=c,dn.elements[2]*=c,dn.elements[4]*=d,dn.elements[5]*=d,dn.elements[6]*=d,dn.elements[8]*=u,dn.elements[9]*=u,dn.elements[10]*=u,t.setFromRotationMatrix(dn),s.x=a,s.y=o,s.z=l,this}makePerspective(e,t,s,i,r,a,o=An,l=!1){const c=this.elements,d=2*r/(t-e),u=2*r/(s-i),h=(t+e)/(t-e),g=(s+i)/(s-i);let p,z;if(l)p=r/(a-r),z=a*r/(a-r);else if(o===An)p=-(a+r)/(a-r),z=-2*a*r/(a-r);else if(o===ka)p=-a/(a-r),z=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=d,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=u,c[9]=g,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=z,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,s,i,r,a,o=An,l=!1){const c=this.elements,d=2/(t-e),u=2/(s-i),h=-(t+e)/(t-e),g=-(s+i)/(s-i);let p,z;if(l)p=1/(a-r),z=a/(a-r);else if(o===An)p=-2/(a-r),z=-(a+r)/(a-r);else if(o===ka)p=-1/(a-r),z=-r/(a-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=d,c[4]=0,c[8]=0,c[12]=h,c[1]=0,c[5]=u,c[9]=0,c[13]=g,c[2]=0,c[6]=0,c[10]=p,c[14]=z,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let i=0;i<16;i++)if(t[i]!==s[i])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}};yl.prototype.isMatrix4=!0;let Gt=yl;const hr=new F,dn=new Gt,Wz=new F(0,0,0),kz=new F(1,1,1),ci=new F,Xa=new F,Hs=new F,Oh=new Gt,xh=new rr;class Di{constructor(e=0,t=0,s=0,i=Di.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],a=i[4],o=i[8],l=i[1],c=i[5],d=i[9],u=i[2],h=i[6],g=i[10];switch(t){case"XYZ":this._y=Math.asin(St(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-d,g),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(h,c),this._z=0);break;case"YXZ":this._x=Math.asin(-St(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(o,g),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(St(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,g),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-St(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,g),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(St(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-d,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,g));break;case"XZY":this._z=Math.asin(-St(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(h,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-d,g),this._y=0);break;default:st("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,s===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return Oh.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Oh,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return xh.setFromEuler(this),this.setFromQuaternion(xh,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Di.DEFAULT_ORDER="XYZ";class xu{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let Uz=0;const Sh=new F,fr=new rr,Bn=new Gt,Ya=new F,ca=new F,Fz=new F,jz=new rr,Ah=new F(1,0,0),Eh=new F(0,1,0),Dh=new F(0,0,1),Ih={type:"added"},$z={type:"removed"},pr={type:"childadded",child:null},Ql={type:"childremoved",child:null};class ss extends ir{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Uz++}),this.uuid=yi(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ss.DEFAULT_UP.clone();const e=new F,t=new Di,s=new rr,i=new F(1,1,1);function r(){s.setFromEuler(t,!1)}function a(){t.setFromQuaternion(s,void 0,!1)}t._onChange(r),s._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Gt},normalMatrix:{value:new ut}}),this.matrix=new Gt,this.matrixWorld=new Gt,this.matrixAutoUpdate=ss.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ss.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new xu,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return fr.setFromAxisAngle(e,t),this.quaternion.multiply(fr),this}rotateOnWorldAxis(e,t){return fr.setFromAxisAngle(e,t),this.quaternion.premultiply(fr),this}rotateX(e){return this.rotateOnAxis(Ah,e)}rotateY(e){return this.rotateOnAxis(Eh,e)}rotateZ(e){return this.rotateOnAxis(Dh,e)}translateOnAxis(e,t){return Sh.copy(e).applyQuaternion(this.quaternion),this.position.add(Sh.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Ah,e)}translateY(e){return this.translateOnAxis(Eh,e)}translateZ(e){return this.translateOnAxis(Dh,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Bn.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?Ya.copy(e):Ya.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),ca.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Bn.lookAt(ca,Ya,this.up):Bn.lookAt(Ya,ca,this.up),this.quaternion.setFromRotationMatrix(Bn),i&&(Bn.extractRotation(i.matrixWorld),fr.setFromRotationMatrix(Bn),this.quaternion.premultiply(fr.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(Ot("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Ih),pr.child=e,this.dispatchEvent(pr),pr.child=null):Ot("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let s=0;s<arguments.length;s++)this.remove(arguments[s]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent($z),Ql.child=e,this.dispatchEvent(Ql),Ql.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Bn.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Bn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Bn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Ih),pr.child=e,this.dispatchEvent(pr),pr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let s=0,i=this.children.length;s<i;s++){const a=this.children[s].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let r=0,a=i.length;r<a;r++)i[r].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ca,e,Fz),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ca,jz,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(e!==null){const t=e.x,s=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*s-r[8]*i,r[13]+=s-r[1]*t-r[5]*s-r[9]*i,r[14]+=i-r[2]*t-r[6]*s-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].updateMatrixWorld(e)}updateWorldMatrix(e,t,s=!1){const i=this.parent;if(e===!0&&i!==null&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||s)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,s=!0),t===!0){const r=this.children;for(let a=0,o=r.length;a<o;a++)r[a].updateWorldMatrix(!1,!0,s)}}toJSON(e){const t=e===void 0||typeof e=="string",s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),this.static!==!1&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null&&(i.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(o=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function r(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,d=l.length;c<d;c++){const u=l[c];r(e.shapes,u)}else r(e.shapes,l)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(r(e.materials,this.material[l]));i.material=o}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){const l=this.animations[o];i.animations.push(r(e.animations,l))}}if(t){const o=a(e.geometries),l=a(e.materials),c=a(e.textures),d=a(e.images),u=a(e.shapes),h=a(e.skeletons),g=a(e.animations),p=a(e.nodes);o.length>0&&(s.geometries=o),l.length>0&&(s.materials=l),c.length>0&&(s.textures=c),d.length>0&&(s.images=d),u.length>0&&(s.shapes=u),h.length>0&&(s.skeletons=h),g.length>0&&(s.animations=g),p.length>0&&(s.nodes=p)}return s.object=i,s;function a(o){const l=[];for(const c in o){const d=o[c];delete d.metadata,l.push(d)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let s=0;s<e.children.length;s++){const i=e.children[s];this.add(i.clone())}return this}}ss.DEFAULT_UP=new F(0,1,0);ss.DEFAULT_MATRIX_AUTO_UPDATE=!0;ss.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Da extends ss{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Vz={type:"move"};class Jl{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Da,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Da,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new F,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new F),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Da,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new F,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new F,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,s){let i=null,r=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const z of e.hand.values()){const m=t.getJointPose(z,s),f=this._getHandJoint(c,z);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}const d=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],h=d.position.distanceTo(u.position),g=.02,p=.005;c.inputState.pinching&&h>g+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&h<=g-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(i=t.getPose(e.targetRaySpace,s),i===null&&r!==null&&(i=r),i!==null&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Vz)))}return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const s=new Da;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const Xm={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},di={h:0,s:0,l:0},Ka={h:0,s:0,l:0};function ec(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class Ye{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(t===void 0&&s===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=sn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,xt.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=xt.workingColorSpace){return this.r=e,this.g=t,this.b=s,xt.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=xt.workingColorSpace){if(e=Gz(e,1),t=St(t,0,1),s=St(s,0,1),t===0)this.r=this.g=this.b=s;else{const r=s<=.5?s*(1+t):s+t-s*t,a=2*s-r;this.r=ec(a,r,e+1/3),this.g=ec(a,r,e),this.b=ec(a,r,e-1/3)}return xt.colorSpaceToWorking(this,i),this}setStyle(e,t=sn){function s(r){r!==void 0&&parseFloat(r)<1&&st("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=i[1],o=i[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:st("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=i[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);st("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=sn){const s=Xm[e.toLowerCase()];return s!==void 0?this.setHex(s,t):st("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Qn(e.r),this.g=Qn(e.g),this.b=Qn(e.b),this}copyLinearToSRGB(e){return this.r=Lr(e.r),this.g=Lr(e.g),this.b=Lr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=sn){return xt.workingToColorSpace(As.copy(this),e),Math.round(St(As.r*255,0,255))*65536+Math.round(St(As.g*255,0,255))*256+Math.round(St(As.b*255,0,255))}getHexString(e=sn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=xt.workingColorSpace){xt.workingToColorSpace(As.copy(this),t);const s=As.r,i=As.g,r=As.b,a=Math.max(s,i,r),o=Math.min(s,i,r);let l,c;const d=(o+a)/2;if(o===a)l=0,c=0;else{const u=a-o;switch(c=d<=.5?u/(a+o):u/(2-a-o),a){case s:l=(i-r)/u+(i<r?6:0);break;case i:l=(r-s)/u+2;break;case r:l=(s-i)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=d,e}getRGB(e,t=xt.workingColorSpace){return xt.workingToColorSpace(As.copy(this),t),e.r=As.r,e.g=As.g,e.b=As.b,e}getStyle(e=sn){xt.workingToColorSpace(As.copy(this),e);const t=As.r,s=As.g,i=As.b;return e!==sn?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(s*255)},${Math.round(i*255)})`}offsetHSL(e,t,s){return this.getHSL(di),this.setHSL(di.h+e,di.s+t,di.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(di),e.getHSL(Ka);const s=ql(di.h,Ka.h,t),i=ql(di.s,Ka.s,t),r=ql(di.l,Ka.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const As=new Ye;Ye.NAMES=Xm;class Hz extends ss{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Di,this.environmentIntensity=1,this.environmentRotation=new Di,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const un=new F,Nn=new F,tc=new F,Cn=new F,mr=new F,gr=new F,Th=new F,sc=new F,nc=new F,ic=new F,rc=new ts,ac=new ts,oc=new ts;class an{constructor(e=new F,t=new F,s=new F){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),un.subVectors(e,t),i.cross(un);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){un.subVectors(i,t),Nn.subVectors(s,t),tc.subVectors(e,t);const a=un.dot(un),o=un.dot(Nn),l=un.dot(tc),c=Nn.dot(Nn),d=Nn.dot(tc),u=a*c-o*o;if(u===0)return r.set(0,0,0),null;const h=1/u,g=(c*l-o*d)*h,p=(a*d-o*l)*h;return r.set(1-g-p,p,g)}static containsPoint(e,t,s,i){return this.getBarycoord(e,t,s,i,Cn)===null?!1:Cn.x>=0&&Cn.y>=0&&Cn.x+Cn.y<=1}static getInterpolation(e,t,s,i,r,a,o,l){return this.getBarycoord(e,t,s,i,Cn)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Cn.x),l.addScaledVector(a,Cn.y),l.addScaledVector(o,Cn.z),l)}static getInterpolatedAttribute(e,t,s,i,r,a){return rc.setScalar(0),ac.setScalar(0),oc.setScalar(0),rc.fromBufferAttribute(e,t),ac.fromBufferAttribute(e,s),oc.fromBufferAttribute(e,i),a.setScalar(0),a.addScaledVector(rc,r.x),a.addScaledVector(ac,r.y),a.addScaledVector(oc,r.z),a}static isFrontFacing(e,t,s,i){return un.subVectors(s,t),Nn.subVectors(e,t),un.cross(Nn).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return un.subVectors(this.c,this.b),Nn.subVectors(this.a,this.b),un.cross(Nn).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return an.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return an.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return an.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return an.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return an.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let a,o;mr.subVectors(i,s),gr.subVectors(r,s),sc.subVectors(e,s);const l=mr.dot(sc),c=gr.dot(sc);if(l<=0&&c<=0)return t.copy(s);nc.subVectors(e,i);const d=mr.dot(nc),u=gr.dot(nc);if(d>=0&&u<=d)return t.copy(i);const h=l*u-d*c;if(h<=0&&l>=0&&d<=0)return a=l/(l-d),t.copy(s).addScaledVector(mr,a);ic.subVectors(e,r);const g=mr.dot(ic),p=gr.dot(ic);if(p>=0&&g<=p)return t.copy(r);const z=g*c-l*p;if(z<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(s).addScaledVector(gr,o);const m=d*p-g*u;if(m<=0&&u-d>=0&&g-p>=0)return Th.subVectors(r,i),o=(u-d)/(u-d+(g-p)),t.copy(i).addScaledVector(Th,o);const f=1/(m+z+h);return a=z*f,o=h*f,t.copy(s).addScaledVector(mr,a).addScaledVector(gr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class ar{constructor(e=new F(1/0,1/0,1/0),t=new F(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t+=3)this.expandByPoint(hn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(hn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=hn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const s=e.geometry;if(s!==void 0){const r=s.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,hn):hn.fromBufferAttribute(r,a),hn.applyMatrix4(e.matrixWorld),this.expandByPoint(hn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Za.copy(e.boundingBox)):(s.boundingBox===null&&s.computeBoundingBox(),Za.copy(s.boundingBox)),Za.applyMatrix4(e.matrixWorld),this.union(Za)}const i=e.children;for(let r=0,a=i.length;r<a;r++)this.expandByObject(i[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,hn),hn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(da),Qa.subVectors(this.max,da),Mr.subVectors(e.a,da),br.subVectors(e.b,da),zr.subVectors(e.c,da),ui.subVectors(br,Mr),hi.subVectors(zr,br),Ti.subVectors(Mr,zr);let t=[0,-ui.z,ui.y,0,-hi.z,hi.y,0,-Ti.z,Ti.y,ui.z,0,-ui.x,hi.z,0,-hi.x,Ti.z,0,-Ti.x,-ui.y,ui.x,0,-hi.y,hi.x,0,-Ti.y,Ti.x,0];return!lc(t,Mr,br,zr,Qa)||(t=[1,0,0,0,1,0,0,0,1],!lc(t,Mr,br,zr,Qa))?!1:(Ja.crossVectors(ui,hi),t=[Ja.x,Ja.y,Ja.z],lc(t,Mr,br,zr,Qa))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,hn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(hn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Pn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Pn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Pn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Pn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Pn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Pn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Pn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Pn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Pn),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Pn=[new F,new F,new F,new F,new F,new F,new F,new F],hn=new F,Za=new ar,Mr=new F,br=new F,zr=new F,ui=new F,hi=new F,Ti=new F,da=new F,Qa=new F,Ja=new F,Gi=new F;function lc(n,e,t,s,i){for(let r=0,a=n.length-3;r<=a;r+=3){Gi.fromArray(n,r);const o=i.x*Math.abs(Gi.x)+i.y*Math.abs(Gi.y)+i.z*Math.abs(Gi.z),l=e.dot(Gi),c=t.dot(Gi),d=s.dot(Gi);if(Math.max(-Math.max(l,c,d),Math.min(l,c,d))>o)return!1}return!0}const os=new F,eo=new lt;let qz=0;class ws extends ir{constructor(e,t,s=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:qz++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=s,this.usage=Kd,this.updateRanges=[],this.gpuType=Mn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,s=this.count;t<s;t++)eo.fromBufferAttribute(this,t),eo.applyMatrix3(e),this.setXY(t,eo.x,eo.y);else if(this.itemSize===3)for(let t=0,s=this.count;t<s;t++)os.fromBufferAttribute(this,t),os.applyMatrix3(e),this.setXYZ(t,os.x,os.y,os.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)os.fromBufferAttribute(this,t),os.applyMatrix4(e),this.setXYZ(t,os.x,os.y,os.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)os.fromBufferAttribute(this,t),os.applyNormalMatrix(e),this.setXYZ(t,os.x,os.y,os.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)os.fromBufferAttribute(this,t),os.transformDirection(e),this.setXYZ(t,os.x,os.y,os.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=xn(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Ft(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=xn(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=xn(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=xn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=xn(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(r,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Kd&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}}class Ym extends ws{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Km extends ws{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Xt extends ws{constructor(e,t,s){super(new Float32Array(e),t,s)}}const Xz=new ar,ua=new F,cc=new F;class or{constructor(e=new F,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;t!==void 0?s.copy(t):Xz.setFromPoints(e).getCenter(s);let i=0;for(let r=0,a=e.length;r<a;r++)i=Math.max(i,s.distanceToSquared(e[r]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const s=this.center.distanceToSquared(e);return t.copy(e),s>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ua.subVectors(e,this.center);const t=ua.lengthSq();if(t>this.radius*this.radius){const s=Math.sqrt(t),i=(s-this.radius)*.5;this.center.addScaledVector(ua,i/s),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(cc.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ua.copy(e.center).add(cc)),this.expandByPoint(ua.copy(e.center).sub(cc))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let Yz=0;const en=new Gt,dc=new ss,_r=new F,qs=new ar,ha=new ar,bs=new F;class ds extends ir{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Yz++}),this.uuid=yi(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ez(e)?Km:Ym)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(s!==void 0){const r=new ut().getNormalMatrix(e);s.applyNormalMatrix(r),s.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return en.makeRotationFromQuaternion(e),this.applyMatrix4(en),this}rotateX(e){return en.makeRotationX(e),this.applyMatrix4(en),this}rotateY(e){return en.makeRotationY(e),this.applyMatrix4(en),this}rotateZ(e){return en.makeRotationZ(e),this.applyMatrix4(en),this}translate(e,t,s){return en.makeTranslation(e,t,s),this.applyMatrix4(en),this}scale(e,t,s){return en.makeScale(e,t,s),this.applyMatrix4(en),this}lookAt(e){return dc.lookAt(e),dc.updateMatrix(),this.applyMatrix4(dc.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(_r).negate(),this.translate(_r.x,_r.y,_r.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const s=[];for(let i=0,r=e.length;i<r;i++){const a=e[i];s.push(a.x,a.y,a.z||0)}this.setAttribute("position",new Xt(s,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const r=e[i];t.setXYZ(i,r.x,r.y,r.z||0)}e.length>t.count&&st("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ar);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ot("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let s=0,i=t.length;s<i;s++){const r=t[s];qs.setFromBufferAttribute(r),this.morphTargetsRelative?(bs.addVectors(this.boundingBox.min,qs.min),this.boundingBox.expandByPoint(bs),bs.addVectors(this.boundingBox.max,qs.max),this.boundingBox.expandByPoint(bs)):(this.boundingBox.expandByPoint(qs.min),this.boundingBox.expandByPoint(qs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Ot('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new or);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ot("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new F,1/0);return}if(e){const s=this.boundingSphere.center;if(qs.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];ha.setFromBufferAttribute(o),this.morphTargetsRelative?(bs.addVectors(qs.min,ha.min),qs.expandByPoint(bs),bs.addVectors(qs.max,ha.max),qs.expandByPoint(bs)):(qs.expandByPoint(ha.min),qs.expandByPoint(ha.max))}qs.getCenter(s);let i=0;for(let r=0,a=e.count;r<a;r++)bs.fromBufferAttribute(e,r),i=Math.max(i,s.distanceToSquared(bs));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],l=this.morphTargetsRelative;for(let c=0,d=o.count;c<d;c++)bs.fromBufferAttribute(o,c),l&&(_r.fromBufferAttribute(e,c),bs.add(_r)),i=Math.max(i,s.distanceToSquared(bs))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Ot('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){Ot("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const s=t.position,i=t.normal,r=t.uv;let a=this.getAttribute("tangent");(a===void 0||a.count!==s.count)&&(a=new ws(new Float32Array(4*s.count),4),this.setAttribute("tangent",a));const o=[],l=[];for(let b=0;b<s.count;b++)o[b]=new F,l[b]=new F;const c=new F,d=new F,u=new F,h=new lt,g=new lt,p=new lt,z=new F,m=new F;function f(b,A,B){c.fromBufferAttribute(s,b),d.fromBufferAttribute(s,A),u.fromBufferAttribute(s,B),h.fromBufferAttribute(r,b),g.fromBufferAttribute(r,A),p.fromBufferAttribute(r,B),d.sub(c),u.sub(c),g.sub(h),p.sub(h);const N=1/(g.x*p.y-p.x*g.y);isFinite(N)&&(z.copy(d).multiplyScalar(p.y).addScaledVector(u,-g.y).multiplyScalar(N),m.copy(u).multiplyScalar(g.x).addScaledVector(d,-p.x).multiplyScalar(N),o[b].add(z),o[A].add(z),o[B].add(z),l[b].add(m),l[A].add(m),l[B].add(m))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let b=0,A=_.length;b<A;++b){const B=_[b],N=B.start,k=B.count;for(let L=N,j=N+k;L<j;L+=3)f(e.getX(L+0),e.getX(L+1),e.getX(L+2))}const O=new F,w=new F,x=new F,S=new F;function I(b){x.fromBufferAttribute(i,b),S.copy(x);const A=o[b];O.copy(A),O.sub(x.multiplyScalar(x.dot(A))).normalize(),w.crossVectors(S,A);const N=w.dot(l[b])<0?-1:1;a.setXYZW(b,O.x,O.y,O.z,N)}for(let b=0,A=_.length;b<A;++b){const B=_[b],N=B.start,k=B.count;for(let L=N,j=N+k;L<j;L+=3)I(e.getX(L+0)),I(e.getX(L+1)),I(e.getX(L+2))}this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let s=this.getAttribute("normal");if(s===void 0||s.count!==t.count)s=new ws(new Float32Array(t.count*3),3),this.setAttribute("normal",s);else for(let h=0,g=s.count;h<g;h++)s.setXYZ(h,0,0,0);const i=new F,r=new F,a=new F,o=new F,l=new F,c=new F,d=new F,u=new F;if(e)for(let h=0,g=e.count;h<g;h+=3){const p=e.getX(h+0),z=e.getX(h+1),m=e.getX(h+2);i.fromBufferAttribute(t,p),r.fromBufferAttribute(t,z),a.fromBufferAttribute(t,m),d.subVectors(a,r),u.subVectors(i,r),d.cross(u),o.fromBufferAttribute(s,p),l.fromBufferAttribute(s,z),c.fromBufferAttribute(s,m),o.add(d),l.add(d),c.add(d),s.setXYZ(p,o.x,o.y,o.z),s.setXYZ(z,l.x,l.y,l.z),s.setXYZ(m,c.x,c.y,c.z)}else for(let h=0,g=t.count;h<g;h+=3)i.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),a.fromBufferAttribute(t,h+2),d.subVectors(a,r),u.subVectors(i,r),d.cross(u),s.setXYZ(h+0,d.x,d.y,d.z),s.setXYZ(h+1,d.x,d.y,d.z),s.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)bs.fromBufferAttribute(e,t),bs.normalize(),e.setXYZ(t,bs.x,bs.y,bs.z)}toNonIndexed(){function e(o,l){const c=o.array,d=o.itemSize,u=o.normalized,h=new c.constructor(l.length*d);let g=0,p=0;for(let z=0,m=l.length;z<m;z++){o.isInterleavedBufferAttribute?g=l[z]*o.data.stride+o.offset:g=l[z]*d;for(let f=0;f<d;f++)h[p++]=c[g++]}return new ws(h,d,u)}if(this.index===null)return st("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ds,s=this.index.array,i=this.attributes;for(const o in i){const l=i[o],c=e(l,s);t.setAttribute(o,c)}const r=this.morphAttributes;for(const o in r){const l=[],c=r[o];for(let d=0,u=c.length;d<u;d++){const h=c[d],g=e(h,s);l.push(g)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,l=a.length;o<l;o++){const c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const l in s){const c=s[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],d=[];for(let u=0,h=c.length;u<h;u++){const g=c[u];d.push(g.toJSON(e.data))}d.length>0&&(i[l]=d,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;s!==null&&this.setIndex(s.clone());const i=e.attributes;for(const c in i){const d=i[c];this.setAttribute(c,d.clone(t))}const r=e.morphAttributes;for(const c in r){const d=[],u=r[c];for(let h=0,g=u.length;h<g;h++)d.push(u[h].clone(t));this.morphAttributes[c]=d}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let c=0,d=a.length;c<d;c++){const u=a[c];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Kz{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Kd,this.updateRanges=[],this.version=0,this.uuid=yi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[s+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=yi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=yi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Gs=new F;class fl{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,s=this.data.count;t<s;t++)Gs.fromBufferAttribute(this,t),Gs.applyMatrix4(e),this.setXYZ(t,Gs.x,Gs.y,Gs.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Gs.fromBufferAttribute(this,t),Gs.applyNormalMatrix(e),this.setXYZ(t,Gs.x,Gs.y,Gs.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Gs.fromBufferAttribute(this,t),Gs.transformDirection(e),this.setXYZ(t,Gs.x,Gs.y,Gs.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=xn(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Ft(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=xn(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=xn(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=xn(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=xn(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(e===void 0){hl("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return new ws(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new fl(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){hl("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let s=0;s<this.count;s++){const i=s*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let Zz=0;class ni extends ir{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Zz++}),this.uuid=yi(),this.name="",this.type="Material",this.blending=$i,this.side=Ei,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ld,this.blendDst=cd,this.blendEquation=Wi,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ye(0,0,0),this.blendAlpha=0,this.depthFunc=$r,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=bh,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=dr,this.stencilZFail=dr,this.stencilZPass=dr,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const s=e[t];if(s===void 0){st(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){st(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(s):i&&i.isVector2&&s&&s.isVector2||i&&i.isEuler&&s&&s.isEuler||i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),this.roughness!==void 0&&(s.roughness=this.roughness),this.metalness!==void 0&&(s.metalness=this.metalness),this.sheen!==void 0&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(s.shininess=this.shininess),this.clearcoat!==void 0&&(s.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(s.dispersion=this.dispersion),this.iridescence!==void 0&&(s.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(s.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(s.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(s.combine=this.combine)),this.envMapRotation!==void 0&&(s.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(s.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(s.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(s.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(s.size=this.size),this.shadowSide!==null&&(s.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(s.sizeAttenuation=this.sizeAttenuation),this.blending!==$i&&(s.blending=this.blending),this.side!==Ei&&(s.side=this.side),this.vertexColors===!0&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),this.transparent===!0&&(s.transparent=!0),this.blendSrc!==ld&&(s.blendSrc=this.blendSrc),this.blendDst!==cd&&(s.blendDst=this.blendDst),this.blendEquation!==Wi&&(s.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(s.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(s.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(s.blendAlpha=this.blendAlpha),this.depthFunc!==$r&&(s.depthFunc=this.depthFunc),this.depthTest===!1&&(s.depthTest=this.depthTest),this.depthWrite===!1&&(s.depthWrite=this.depthWrite),this.colorWrite===!1&&(s.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(s.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==bh&&(s.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(s.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==dr&&(s.stencilFail=this.stencilFail),this.stencilZFail!==dr&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==dr&&(s.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(s.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(s.rotation=this.rotation),this.polygonOffset===!0&&(s.polygonOffset=!0),this.polygonOffsetFactor!==0&&(s.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(s.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(s.linewidth=this.linewidth),this.dashSize!==void 0&&(s.dashSize=this.dashSize),this.gapSize!==void 0&&(s.gapSize=this.gapSize),this.scale!==void 0&&(s.scale=this.scale),this.dithering===!0&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),this.alphaHash===!0&&(s.alphaHash=!0),this.alphaToCoverage===!0&&(s.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(s.premultipliedAlpha=!0),this.forceSinglePass===!0&&(s.forceSinglePass=!0),this.allowOverride===!1&&(s.allowOverride=!1),this.wireframe===!0&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(s.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(s.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(s.flatShading=!0),this.visible===!1&&(s.visible=!1),this.toneMapped===!1&&(s.toneMapped=!1),this.fog===!1&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData);function i(r){const a=[];for(const o in r){const l=r[o];delete l.metadata,a.push(l)}return a}if(t){const r=i(e.textures),a=i(e.images);r.length>0&&(s.textures=r),a.length>0&&(s.images=a)}return s}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new Ye().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let s=e.normalScale;Array.isArray(s)===!1&&(s=[s,s]),this.normalScale=new lt().fromArray(s)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new lt().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(t!==null){const i=t.length;s=new Array(i);for(let r=0;r!==i;++r)s[r]=t[r].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class xl extends ni{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Ye(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}let wr;const fa=new F,yr=new F,vr=new F,Or=new lt,pa=new lt,Zm=new Gt,to=new F,ma=new F,so=new F,Gh=new lt,uc=new lt,Rh=new lt;class Su extends ss{constructor(e=new xl){if(super(),this.isSprite=!0,this.type="Sprite",wr===void 0){wr=new ds;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),s=new Kz(t,5);wr.setIndex([0,1,2,0,2,3]),wr.setAttribute("position",new fl(s,3,0,!1)),wr.setAttribute("uv",new fl(s,2,3,!1))}this.geometry=wr,this.material=e,this.center=new lt(.5,.5),this.count=1}raycast(e,t){e.camera===null&&Ot('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),yr.setFromMatrixScale(this.matrixWorld),Zm.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),vr.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&yr.multiplyScalar(-vr.z);const s=this.material.rotation;let i,r;s!==0&&(r=Math.cos(s),i=Math.sin(s));const a=this.center;no(to.set(-.5,-.5,0),vr,a,yr,i,r),no(ma.set(.5,-.5,0),vr,a,yr,i,r),no(so.set(.5,.5,0),vr,a,yr,i,r),Gh.set(0,0),uc.set(1,0),Rh.set(1,1);let o=e.ray.intersectTriangle(to,ma,so,!1,fa);if(o===null&&(no(ma.set(-.5,.5,0),vr,a,yr,i,r),uc.set(0,1),o=e.ray.intersectTriangle(to,so,ma,!1,fa),o===null))return;const l=e.ray.origin.distanceTo(fa);l<e.near||l>e.far||t.push({distance:l,point:fa.clone(),uv:an.getInterpolation(fa,to,ma,so,Gh,uc,Rh,new lt),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function no(n,e,t,s,i,r){Or.subVectors(n,t).addScalar(.5).multiply(s),i!==void 0?(pa.x=r*Or.x-i*Or.y,pa.y=i*Or.x+r*Or.y):pa.copy(Or),n.copy(e),n.x+=pa.x,n.y+=pa.y,n.applyMatrix4(Zm)}const Ln=new F,hc=new F,io=new F,fi=new F,fc=new F,ro=new F,pc=new F;class Sl{constructor(e=new F,t=new F(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Ln)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ln.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ln.copy(this.origin).addScaledVector(this.direction,t),Ln.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){hc.copy(e).add(t).multiplyScalar(.5),io.copy(t).sub(e).normalize(),fi.copy(this.origin).sub(hc);const r=e.distanceTo(t)*.5,a=-this.direction.dot(io),o=fi.dot(this.direction),l=-fi.dot(io),c=fi.lengthSq(),d=Math.abs(1-a*a);let u,h,g,p;if(d>0)if(u=a*l-o,h=a*o-l,p=r*d,u>=0)if(h>=-p)if(h<=p){const z=1/d;u*=z,h*=z,g=u*(u+a*h+2*o)+h*(a*u+h+2*l)+c}else h=r,u=Math.max(0,-(a*h+o)),g=-u*u+h*(h+2*l)+c;else h=-r,u=Math.max(0,-(a*h+o)),g=-u*u+h*(h+2*l)+c;else h<=-p?(u=Math.max(0,-(-a*r+o)),h=u>0?-r:Math.min(Math.max(-r,-l),r),g=-u*u+h*(h+2*l)+c):h<=p?(u=0,h=Math.min(Math.max(-r,-l),r),g=h*(h+2*l)+c):(u=Math.max(0,-(a*r+o)),h=u>0?r:Math.min(Math.max(-r,-l),r),g=-u*u+h*(h+2*l)+c);else h=a>0?-r:r,u=Math.max(0,-(a*h+o)),g=-u*u+h*(h+2*l)+c;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(hc).addScaledVector(io,h),g}intersectSphere(e,t){Ln.subVectors(e.center,this.origin);const s=Ln.dot(this.direction),i=Ln.dot(Ln)-s*s,r=e.radius*e.radius;if(i>r)return null;const a=Math.sqrt(r-i),o=s-a,l=s+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return s===null?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,a,o,l;const c=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return c>=0?(s=(e.min.x-h.x)*c,i=(e.max.x-h.x)*c):(s=(e.max.x-h.x)*c,i=(e.min.x-h.x)*c),d>=0?(r=(e.min.y-h.y)*d,a=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,a=(e.min.y-h.y)*d),s>a||r>i||((r>s||isNaN(s))&&(s=r),(a<i||isNaN(i))&&(i=a),u>=0?(o=(e.min.z-h.z)*u,l=(e.max.z-h.z)*u):(o=(e.max.z-h.z)*u,l=(e.min.z-h.z)*u),s>l||o>i)||((o>s||s!==s)&&(s=o),(l<i||i!==i)&&(i=l),i<0)?null:this.at(s>=0?s:i,t)}intersectsBox(e){return this.intersectBox(e,Ln)!==null}intersectTriangle(e,t,s,i,r){fc.subVectors(t,e),ro.subVectors(s,e),pc.crossVectors(fc,ro);let a=this.direction.dot(pc),o;if(a>0){if(i)return null;o=1}else if(a<0)o=-1,a=-a;else return null;fi.subVectors(this.origin,e);const l=o*this.direction.dot(ro.crossVectors(fi,ro));if(l<0)return null;const c=o*this.direction.dot(fc.cross(fi));if(c<0||l+c>a)return null;const d=-o*fi.dot(pc);return d<0?null:this.at(d/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Au extends ni{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ye(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Di,this.combine=Tm,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Bh=new Gt,Ri=new Sl,ao=new or,Nh=new F,oo=new F,lo=new F,co=new F,mc=new F,uo=new F,Ch=new F,ho=new F;class Us extends ss{constructor(e=new ds,t=new Au){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,s=Object.keys(t);if(s.length>0){const i=t[s[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=i.length;r<a;r++){const o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,r=s.morphAttributes.position,a=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const o=this.morphTargetInfluences;if(r&&o){uo.set(0,0,0);for(let l=0,c=r.length;l<c;l++){const d=o[l],u=r[l];d!==0&&(mc.fromBufferAttribute(u,e),a?uo.addScaledVector(mc,d):uo.addScaledVector(mc.sub(t),d))}t.add(uo)}return t}raycast(e,t){const s=this.geometry,i=this.material,r=this.matrixWorld;i!==void 0&&(s.boundingSphere===null&&s.computeBoundingSphere(),ao.copy(s.boundingSphere),ao.applyMatrix4(r),Ri.copy(e.ray).recast(e.near),!(ao.containsPoint(Ri.origin)===!1&&(Ri.intersectSphere(ao,Nh)===null||Ri.origin.distanceToSquared(Nh)>(e.far-e.near)**2))&&(Bh.copy(r).invert(),Ri.copy(e.ray).applyMatrix4(Bh),!(s.boundingBox!==null&&Ri.intersectsBox(s.boundingBox)===!1)&&this._computeIntersections(e,t,Ri)))}_computeIntersections(e,t,s){let i;const r=this.geometry,a=this.material,o=r.index,l=r.attributes.position,c=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,g=r.drawRange;if(o!==null)if(Array.isArray(a))for(let p=0,z=h.length;p<z;p++){const m=h[p],f=a[m.materialIndex],_=Math.max(m.start,g.start),O=Math.min(o.count,Math.min(m.start+m.count,g.start+g.count));for(let w=_,x=O;w<x;w+=3){const S=o.getX(w),I=o.getX(w+1),b=o.getX(w+2);i=fo(this,f,e,s,c,d,u,S,I,b),i&&(i.faceIndex=Math.floor(w/3),i.face.materialIndex=m.materialIndex,t.push(i))}}else{const p=Math.max(0,g.start),z=Math.min(o.count,g.start+g.count);for(let m=p,f=z;m<f;m+=3){const _=o.getX(m),O=o.getX(m+1),w=o.getX(m+2);i=fo(this,a,e,s,c,d,u,_,O,w),i&&(i.faceIndex=Math.floor(m/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(a))for(let p=0,z=h.length;p<z;p++){const m=h[p],f=a[m.materialIndex],_=Math.max(m.start,g.start),O=Math.min(l.count,Math.min(m.start+m.count,g.start+g.count));for(let w=_,x=O;w<x;w+=3){const S=w,I=w+1,b=w+2;i=fo(this,f,e,s,c,d,u,S,I,b),i&&(i.faceIndex=Math.floor(w/3),i.face.materialIndex=m.materialIndex,t.push(i))}}else{const p=Math.max(0,g.start),z=Math.min(l.count,g.start+g.count);for(let m=p,f=z;m<f;m+=3){const _=m,O=m+1,w=m+2;i=fo(this,a,e,s,c,d,u,_,O,w),i&&(i.faceIndex=Math.floor(m/3),t.push(i))}}}}function Qz(n,e,t,s,i,r,a,o){let l;if(e.side===ks?l=s.intersectTriangle(a,r,i,!0,o):l=s.intersectTriangle(i,r,a,e.side===Ei,o),l===null)return null;ho.copy(o),ho.applyMatrix4(n.matrixWorld);const c=t.ray.origin.distanceTo(ho);return c<t.near||c>t.far?null:{distance:c,point:ho.clone(),object:n}}function fo(n,e,t,s,i,r,a,o,l,c){n.getVertexPosition(o,oo),n.getVertexPosition(l,lo),n.getVertexPosition(c,co);const d=Qz(n,e,t,s,oo,lo,co,Ch);if(d){const u=new F;an.getBarycoord(Ch,oo,lo,co,u),i&&(d.uv=an.getInterpolatedAttribute(i,o,l,c,u,new lt)),r&&(d.uv1=an.getInterpolatedAttribute(r,o,l,c,u,new lt)),a&&(d.normal=an.getInterpolatedAttribute(a,o,l,c,u,new F),d.normal.dot(s.direction)>0&&d.normal.multiplyScalar(-1));const h={a:o,b:l,c,normal:new F,materialIndex:0};an.getNormal(oo,lo,co,h.normal),d.face=h,d.barycoord=u}return d}class Qm extends Is{constructor(e=null,t=1,s=1,i,r,a,o,l,c=ys,d=ys,u,h){super(null,a,o,l,c,d,i,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class vi extends ws{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const xr=new Gt,Ph=new Gt,po=[],Lh=new ar,Jz=new Gt,ga=new Us,Ma=new or;class Eu extends Us{constructor(e,t,s){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new vi(new Float32Array(s*16),16),this.instanceColor=null,this.morphTexture=null,this.count=s,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<s;i++)this.setMatrixAt(i,Jz)}computeBoundingBox(){const e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new ar),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let s=0;s<t;s++)this.getMatrixAt(s,xr),Lh.copy(e.boundingBox).applyMatrix4(xr),this.boundingBox.union(Lh)}computeBoundingSphere(){const e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new or),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let s=0;s<t;s++)this.getMatrixAt(s,xr),Ma.copy(e.boundingSphere).applyMatrix4(xr),this.boundingSphere.union(Ma)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){return this.instanceColor===null?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){const s=t.morphTargetInfluences,i=this.morphTexture.source.data.data,r=s.length+1,a=e*r+1;for(let o=0;o<s.length;o++)s[o]=i[a+o]}raycast(e,t){const s=this.matrixWorld,i=this.count;if(ga.geometry=this.geometry,ga.material=this.material,ga.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Ma.copy(this.boundingSphere),Ma.applyMatrix4(s),e.ray.intersectsSphere(Ma)!==!1))for(let r=0;r<i;r++){this.getMatrixAt(r,xr),Ph.multiplyMatrices(s,xr),ga.matrixWorld=Ph,ga.raycast(e,po);for(let a=0,o=po.length;a<o;a++){const l=po[a];l.instanceId=r,l.object=this,t.push(l)}po.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new vi(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,e*16),this}setMorphAt(e,t){const s=t.morphTargetInfluences,i=s.length+1;this.morphTexture===null&&(this.morphTexture=new Qm(new Float32Array(i*this.count),i,this.count,bu,Mn));const r=this.morphTexture.source.data.data;let a=0;for(let c=0;c<s.length;c++)a+=s[c];const o=this.geometry.morphTargetsRelative?1:1-a,l=i*e;return r[l]=o,r.set(s,l+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const gc=new F,e_=new F,t_=new ut;class gi{constructor(e=new F(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=gc.subVectors(s,t).cross(e_.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,s=!0){const i=e.delta(gc),r=this.normal.dot(i);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const a=-(e.start.dot(this.normal)+this.constant)/r;return s===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||t_.getNormalMatrix(e),i=this.coplanarPoint(gc).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Bi=new or,s_=new lt(.5,.5),mo=new F;class Du{constructor(e=new gi,t=new gi,s=new gi,i=new gi,r=new gi,a=new gi){this.planes=[e,t,s,i,r,a]}set(e,t,s,i,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=An,s=!1){const i=this.planes,r=e.elements,a=r[0],o=r[1],l=r[2],c=r[3],d=r[4],u=r[5],h=r[6],g=r[7],p=r[8],z=r[9],m=r[10],f=r[11],_=r[12],O=r[13],w=r[14],x=r[15];if(i[0].setComponents(c-a,g-d,f-p,x-_).normalize(),i[1].setComponents(c+a,g+d,f+p,x+_).normalize(),i[2].setComponents(c+o,g+u,f+z,x+O).normalize(),i[3].setComponents(c-o,g-u,f-z,x-O).normalize(),s)i[4].setComponents(l,h,m,w).normalize(),i[5].setComponents(c-l,g-h,f-m,x-w).normalize();else if(i[4].setComponents(c-l,g-h,f-m,x-w).normalize(),t===An)i[5].setComponents(c+l,g+h,f+m,x+w).normalize();else if(t===ka)i[5].setComponents(l,h,m,w).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Bi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Bi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Bi)}intersectsSprite(e){Bi.center.set(0,0,0);const t=s_.distanceTo(e.center);return Bi.radius=.7071067811865476+t,Bi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Bi)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(s)<i)return!1;return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(mo.x=i.normal.x>0?e.max.x:e.min.x,mo.y=i.normal.y>0?e.max.y:e.min.y,mo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(mo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Hr extends ni{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ye(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const pl=new F,ml=new F,Wh=new Gt,ba=new Sl,go=new or,Mc=new F,kh=new F;class Qd extends ss{constructor(e=new ds,t=new Hr){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,s=[0];for(let i=1,r=t.count;i<r;i++)pl.fromBufferAttribute(t,i-1),ml.fromBufferAttribute(t,i),s[i]=s[i-1],s[i]+=pl.distanceTo(ml);e.setAttribute("lineDistance",new Xt(s,1))}else st("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const s=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,a=s.drawRange;if(s.boundingSphere===null&&s.computeBoundingSphere(),go.copy(s.boundingSphere),go.applyMatrix4(i),go.radius+=r,e.ray.intersectsSphere(go)===!1)return;Wh.copy(i).invert(),ba.copy(e.ray).applyMatrix4(Wh);const o=r/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=this.isLineSegments?2:1,d=s.index,h=s.attributes.position;if(d!==null){const g=Math.max(0,a.start),p=Math.min(d.count,a.start+a.count);for(let z=g,m=p-1;z<m;z+=c){const f=d.getX(z),_=d.getX(z+1),O=Mo(this,e,ba,l,f,_,z);O&&t.push(O)}if(this.isLineLoop){const z=d.getX(p-1),m=d.getX(g),f=Mo(this,e,ba,l,z,m,p-1);f&&t.push(f)}}else{const g=Math.max(0,a.start),p=Math.min(h.count,a.start+a.count);for(let z=g,m=p-1;z<m;z+=c){const f=Mo(this,e,ba,l,z,z+1,z);f&&t.push(f)}if(this.isLineLoop){const z=Mo(this,e,ba,l,p-1,g,p-1);z&&t.push(z)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,s=Object.keys(t);if(s.length>0){const i=t[s[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=i.length;r<a;r++){const o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function Mo(n,e,t,s,i,r,a){const o=n.geometry.attributes.position;if(pl.fromBufferAttribute(o,i),ml.fromBufferAttribute(o,r),t.distanceSqToSegment(pl,ml,Mc,kh)>s)return;Mc.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(Mc);if(!(c<e.near||c>e.far))return{distance:c,point:kh.clone().applyMatrix4(n.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:n}}const Uh=new F,Fh=new F;class Jm extends Qd{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,s=[];for(let i=0,r=t.count;i<r;i+=2)Uh.fromBufferAttribute(t,i),Fh.fromBufferAttribute(t,i+1),s[i]=i===0?0:s[i-1],s[i+1]=s[i]+Uh.distanceTo(Fh);e.setAttribute("lineDistance",new Xt(s,1))}else st("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class n_ extends ni{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Ye(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const jh=new Gt,Jd=new Sl,bo=new or,zo=new F;class i_ extends ss{constructor(e=new ds,t=new n_){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const s=this.geometry,i=this.matrixWorld,r=e.params.Points.threshold,a=s.drawRange;if(s.boundingSphere===null&&s.computeBoundingSphere(),bo.copy(s.boundingSphere),bo.applyMatrix4(i),bo.radius+=r,e.ray.intersectsSphere(bo)===!1)return;jh.copy(i).invert(),Jd.copy(e.ray).applyMatrix4(jh);const o=r/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=s.index,u=s.attributes.position;if(c!==null){const h=Math.max(0,a.start),g=Math.min(c.count,a.start+a.count);for(let p=h,z=g;p<z;p++){const m=c.getX(p);zo.fromBufferAttribute(u,m),$h(zo,m,l,i,e,t,this)}}else{const h=Math.max(0,a.start),g=Math.min(u.count,a.start+a.count);for(let p=h,z=g;p<z;p++)zo.fromBufferAttribute(u,p),$h(zo,p,l,i,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,s=Object.keys(t);if(s.length>0){const i=t[s[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=i.length;r<a;r++){const o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function $h(n,e,t,s,i,r,a){const o=Jd.distanceSqToPoint(n);if(o<t){const l=new F;Jd.closestPointToPoint(n,l),l.applyMatrix4(s);const c=i.ray.origin.distanceTo(l);if(c<i.near||c>i.far)return;r.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class eg extends Is{constructor(e=[],t=Ji,s,i,r,a,o,l,c,d){super(e,t,s,i,r,a,o,l,c,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class tg extends Is{constructor(e,t,s,i,r,a,o,l,c){super(e,t,s,i,r,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class qr extends Is{constructor(e,t,s=Gn,i,r,a,o=ys,l=ys,c,d=si,u=1){if(d!==si&&d!==ji)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,i,r,a,o,l,d,s,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Ou(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class r_ extends qr{constructor(e,t=Gn,s=Ji,i,r,a=ys,o=ys,l,c=si){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,s,i,r,a,o,l,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class sg extends Is{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ja extends ds{constructor(e=1,t=1,s=1,i=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:a};const o=this;i=Math.floor(i),r=Math.floor(r),a=Math.floor(a);const l=[],c=[],d=[],u=[];let h=0,g=0;p("z","y","x",-1,-1,s,t,e,a,r,0),p("z","y","x",1,-1,s,t,-e,a,r,1),p("x","z","y",1,1,e,s,t,i,a,2),p("x","z","y",1,-1,e,s,-t,i,a,3),p("x","y","z",1,-1,e,t,s,i,r,4),p("x","y","z",-1,-1,e,t,-s,i,r,5),this.setIndex(l),this.setAttribute("position",new Xt(c,3)),this.setAttribute("normal",new Xt(d,3)),this.setAttribute("uv",new Xt(u,2));function p(z,m,f,_,O,w,x,S,I,b,A){const B=w/I,N=x/b,k=w/2,L=x/2,j=S/2,P=I+1,W=b+1;let X=0,Q=0;const re=new F;for(let Me=0;Me<W;Me++){const oe=Me*N-L;for(let Oe=0;Oe<P;Oe++){const Ke=Oe*B-k;re[z]=Ke*_,re[m]=oe*O,re[f]=j,c.push(re.x,re.y,re.z),re[z]=0,re[m]=0,re[f]=S>0?1:-1,d.push(re.x,re.y,re.z),u.push(Oe/I),u.push(1-Me/b),X+=1}}for(let Me=0;Me<b;Me++)for(let oe=0;oe<I;oe++){const Oe=h+oe+P*Me,Ke=h+oe+P*(Me+1),nt=h+(oe+1)+P*(Me+1),je=h+(oe+1)+P*Me;l.push(Oe,Ke,je),l.push(Ke,nt,je),Q+=6}o.addGroup(g,Q,A),g+=Q,h+=X}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ja(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Iu extends ds{constructor(e=1,t=32,s=0,i=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:s,thetaLength:i},t=Math.max(3,t);const r=[],a=[],o=[],l=[],c=new F,d=new lt;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let u=0,h=3;u<=t;u++,h+=3){const g=s+u/t*i;c.x=e*Math.cos(g),c.y=e*Math.sin(g),a.push(c.x,c.y,c.z),o.push(0,0,1),d.x=(a[h]/e+1)/2,d.y=(a[h+1]/e+1)/2,l.push(d.x,d.y)}for(let u=1;u<=t;u++)r.push(u,u+1,0);this.setIndex(r),this.setAttribute("position",new Xt(a,3)),this.setAttribute("normal",new Xt(o,3)),this.setAttribute("uv",new Xt(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Iu(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class Tu extends ds{constructor(e=1,t=1,s=1,i=32,r=1,a=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:a,thetaStart:o,thetaLength:l};const c=this;i=Math.floor(i),r=Math.floor(r);const d=[],u=[],h=[],g=[];let p=0;const z=[],m=s/2;let f=0;_(),a===!1&&(e>0&&O(!0),t>0&&O(!1)),this.setIndex(d),this.setAttribute("position",new Xt(u,3)),this.setAttribute("normal",new Xt(h,3)),this.setAttribute("uv",new Xt(g,2));function _(){const w=new F,x=new F;let S=0;const I=(t-e)/s;for(let b=0;b<=r;b++){const A=[],B=b/r,N=B*(t-e)+e;for(let k=0;k<=i;k++){const L=k/i,j=L*l+o,P=Math.sin(j),W=Math.cos(j);x.x=N*P,x.y=-B*s+m,x.z=N*W,u.push(x.x,x.y,x.z),w.set(P,I,W).normalize(),h.push(w.x,w.y,w.z),g.push(L,1-B),A.push(p++)}z.push(A)}for(let b=0;b<i;b++)for(let A=0;A<r;A++){const B=z[A][b],N=z[A+1][b],k=z[A+1][b+1],L=z[A][b+1];(e>0||A!==0)&&(d.push(B,N,L),S+=3),(t>0||A!==r-1)&&(d.push(N,k,L),S+=3)}c.addGroup(f,S,0),f+=S}function O(w){const x=p,S=new lt,I=new F;let b=0;const A=w===!0?e:t,B=w===!0?1:-1;for(let k=1;k<=i;k++)u.push(0,m*B,0),h.push(0,B,0),g.push(.5,.5),p++;const N=p;for(let k=0;k<=i;k++){const j=k/i*l+o,P=Math.cos(j),W=Math.sin(j);I.x=A*W,I.y=m*B,I.z=A*P,u.push(I.x,I.y,I.z),h.push(0,B,0),S.x=P*.5+.5,S.y=W*.5*B+.5,g.push(S.x,S.y),p++}for(let k=0;k<i;k++){const L=x+k,j=N+k;w===!0?d.push(j,j+1,L):d.push(j+1,j,L),b+=3}c.addGroup(f,b,w===!0?1:2),f+=b}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Tu(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Gu extends ds{constructor(e=[],t=[],s=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:s,detail:i};const r=[],a=[];o(i),c(s),d(),this.setAttribute("position",new Xt(r,3)),this.setAttribute("normal",new Xt(r.slice(),3)),this.setAttribute("uv",new Xt(a,2)),i===0?this.computeVertexNormals():this.normalizeNormals();function o(_){const O=new F,w=new F,x=new F;for(let S=0;S<t.length;S+=3)g(t[S+0],O),g(t[S+1],w),g(t[S+2],x),l(O,w,x,_)}function l(_,O,w,x){const S=x+1,I=[];for(let b=0;b<=S;b++){I[b]=[];const A=_.clone().lerp(w,b/S),B=O.clone().lerp(w,b/S),N=S-b;for(let k=0;k<=N;k++)k===0&&b===S?I[b][k]=A:I[b][k]=A.clone().lerp(B,k/N)}for(let b=0;b<S;b++)for(let A=0;A<2*(S-b)-1;A++){const B=Math.floor(A/2);A%2===0?(h(I[b][B+1]),h(I[b+1][B]),h(I[b][B])):(h(I[b][B+1]),h(I[b+1][B+1]),h(I[b+1][B]))}}function c(_){const O=new F;for(let w=0;w<r.length;w+=3)O.x=r[w+0],O.y=r[w+1],O.z=r[w+2],O.normalize().multiplyScalar(_),r[w+0]=O.x,r[w+1]=O.y,r[w+2]=O.z}function d(){const _=new F;for(let O=0;O<r.length;O+=3){_.x=r[O+0],_.y=r[O+1],_.z=r[O+2];const w=m(_)/2/Math.PI+.5,x=f(_)/Math.PI+.5;a.push(w,1-x)}p(),u()}function u(){for(let _=0;_<a.length;_+=6){const O=a[_+0],w=a[_+2],x=a[_+4],S=Math.max(O,w,x),I=Math.min(O,w,x);S>.9&&I<.1&&(O<.2&&(a[_+0]+=1),w<.2&&(a[_+2]+=1),x<.2&&(a[_+4]+=1))}}function h(_){r.push(_.x,_.y,_.z)}function g(_,O){const w=_*3;O.x=e[w+0],O.y=e[w+1],O.z=e[w+2]}function p(){const _=new F,O=new F,w=new F,x=new F,S=new lt,I=new lt,b=new lt;for(let A=0,B=0;A<r.length;A+=9,B+=6){_.set(r[A+0],r[A+1],r[A+2]),O.set(r[A+3],r[A+4],r[A+5]),w.set(r[A+6],r[A+7],r[A+8]),S.set(a[B+0],a[B+1]),I.set(a[B+2],a[B+3]),b.set(a[B+4],a[B+5]),x.copy(_).add(O).add(w).divideScalar(3);const N=m(x);z(S,B+0,_,N),z(I,B+2,O,N),z(b,B+4,w,N)}}function z(_,O,w,x){x<0&&_.x===1&&(a[O]=_.x-1),w.x===0&&w.z===0&&(a[O]=x/2/Math.PI+.5)}function m(_){return Math.atan2(_.z,-_.x)}function f(_){return Math.atan2(-_.y,Math.sqrt(_.x*_.x+_.z*_.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Gu(e.vertices,e.indices,e.radius,e.detail)}}class Ru extends Gu{constructor(e=1,t=0){const s=(1+Math.sqrt(5))/2,i=[-1,s,0,1,s,0,-1,-s,0,1,-s,0,0,-1,s,0,1,s,0,-1,-s,0,1,-s,s,0,-1,s,0,1,-s,0,-1,-s,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(i,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Ru(e.radius,e.detail)}}class Al extends ds{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const r=e/2,a=t/2,o=Math.floor(s),l=Math.floor(i),c=o+1,d=l+1,u=e/o,h=t/l,g=[],p=[],z=[],m=[];for(let f=0;f<d;f++){const _=f*h-a;for(let O=0;O<c;O++){const w=O*u-r;p.push(w,-_,0),z.push(0,0,1),m.push(O/o),m.push(1-f/l)}}for(let f=0;f<l;f++)for(let _=0;_<o;_++){const O=_+c*f,w=_+c*(f+1),x=_+1+c*(f+1),S=_+1+c*f;g.push(O,w,S),g.push(w,x,S)}this.setIndex(g),this.setAttribute("position",new Xt(p,3)),this.setAttribute("normal",new Xt(z,3)),this.setAttribute("uv",new Xt(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Al(e.width,e.height,e.widthSegments,e.heightSegments)}}class El extends ds{constructor(e=1,t=32,s=16,i=0,r=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const l=Math.min(a+o,Math.PI);let c=0;const d=[],u=new F,h=new F,g=[],p=[],z=[],m=[];for(let f=0;f<=s;f++){const _=[],O=f/s,w=a+O*o,x=e*Math.cos(w),S=Math.sqrt(e*e-x*x);let I=0;f===0&&a===0?I=.5/t:f===s&&l===Math.PI&&(I=-.5/t);for(let b=0;b<=t;b++){const A=b/t,B=i+A*r;u.x=-S*Math.cos(B),u.y=x,u.z=S*Math.sin(B),p.push(u.x,u.y,u.z),h.copy(u).normalize(),z.push(h.x,h.y,h.z),m.push(A+I,1-O),_.push(c++)}d.push(_)}for(let f=0;f<s;f++)for(let _=0;_<t;_++){const O=d[f][_+1],w=d[f][_],x=d[f+1][_],S=d[f+1][_+1];(f!==0||a>0)&&g.push(O,w,S),(f!==s-1||l<Math.PI)&&g.push(w,x,S)}this.setIndex(g),this.setAttribute("position",new Xt(p,3)),this.setAttribute("normal",new Xt(z,3)),this.setAttribute("uv",new Xt(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new El(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}function Xr(n){const e={};for(const t in n){e[t]={};for(const s in n[t]){const i=n[t][s];if(Vh(i))i.isRenderTargetTexture?(st("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][s]=null):e[t][s]=i.clone();else if(Array.isArray(i))if(Vh(i[0])){const r=[];for(let a=0,o=i.length;a<o;a++)r[a]=i[a].clone();e[t][s]=r}else e[t][s]=i.slice();else e[t][s]=i}}return e}function Bs(n){const e={};for(let t=0;t<n.length;t++){const s=Xr(n[t]);for(const i in s)e[i]=s[i]}return e}function Vh(n){return n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)}function a_(n){const e=[];for(let t=0;t<n.length;t++)e.push(n[t].clone());return e}function ng(n){const e=n.getRenderTarget();return e===null?n.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:xt.workingColorSpace}const o_={clone:Xr,merge:Bs};var l_=`void main() {
|
|
3
3
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
4
4
|
}`,c_=`void main() {
|
|
@@ -4226,9 +4226,9 @@ void main() {
|
|
|
4226
4226
|
`){l(),c(),a+=2;continue}if(d===`
|
|
4227
4227
|
`||d==="\r"){l(),c(),a+=1;continue}s+=d,a+=1}return(s!==""||o||i.length>0)&&(l(),c()),t}function JA(n){if(n.length===0)return!1;const e=new Set;for(const t of n){const s=t.trim();if(s===""||e.has(s.toLowerCase())||s!==""&&Number.isFinite(Number(s)))return!1;e.add(s.toLowerCase())}return!0}function eE(n,e){const t=/\.tsv$/i.test(e)?" ":",",s=QA(n,t);if(s.length===0)return{caps:[],rows:[],headed:!1};const i=s[0],r=JA(i),a=r?s.slice(1):s,o=s.reduce((d,u)=>Math.max(d,u.length),0),l=r?Array.from({length:o},(d,u)=>(i[u]??`COLUMN ${u+1}`).trim()):Array.from({length:o},(d,u)=>`COLUMN ${u+1}`),c=a.map(d=>Array.from({length:o},(u,h)=>d[h]??""));return{caps:l,rows:c,headed:r}}const pp=/\.json$/i,tE=4*1024*1024,Bc=/("(?:\\.|[^"\\])*")(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b/g;function mp(n){if(n.length>tE)return null;let e;try{e=JSON.parse(n)}catch{return null}const t=JSON.stringify(e,null,2),s=document.createDocumentFragment();let i=0;Bc.lastIndex=0;for(let r=Bc.exec(t);r!==null;r=Bc.exec(t)){r.index>i&&s.append(t.slice(i,r.index));const a=document.createElement("span"),[o,l,c,d,u]=r;l!==void 0?(a.className=c!==void 0?"json-key":"json-string",a.textContent=l,s.append(a),c!==void 0&&s.append(c)):d!==void 0?(a.className="json-number",a.textContent=d,s.append(a)):(a.className="json-literal",a.textContent=u??o,s.append(a)),i=r.index+o.length}return i<t.length&&s.append(t.slice(i)),s}function gp(n){return/-v(\d+(?:\.\d+)*)$/.exec(n)?.[1]??""}const Mp="",sE="/bin",bp="/bin/recent",Ao={dir:"",file:"",link:"",plugin:"",pipeline:"",vfs:"",job:""},Nc=["list","cards","preview"],nE=5e3,iE=new Set(["png","jpg","jpeg","gif","svg","webp","bmp"]),rE=new Set(["txt","md","adoc","rst","json","csv","tsv","log","yaml","yml","toml","ini","cfg","xml","html","py","sh","ts","js","mjs","r","c","h","cpp","java","go","rs","sql","tex","bib"]),zp=160,_p=100,Eo=10,aE=30,oE=256*1024,lE=4e3,cE=12*1024*1024,dE=400;function Yo(n){return iE.has(Zg(n))}function Zg(n){const e=n.split("/").pop()??"",t=e.lastIndexOf(".");return t>0?e.slice(t+1).toLowerCase():""}function uE(n){if(n.includes("\0"))return!0;const e=(n.match(/\uFFFD/g)??[]).length;return e>0&&e/n.length>.02}const hE=80;function wp(n,e){if(n===null)return[];const t=document.createElement("button");return t.className="files-close-pill files-download-pill",t.textContent="DOWNLOAD",t.title="save this file to your disk",t.addEventListener("click",()=>n.download(e)),[t]}function yp(n){const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"svg");t.setAttribute("viewBox",`0 0 ${zp} ${_p}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");const s=Dg(n),i=Math.max(s.width,1),r=Math.max(s.tierCount-1,1),a=new Map;for(const o of s.placements)a.set(o.id,{x:Eo+o.x/i*(zp-2*Eo),y:Eo+o.tier/r*(_p-2*Eo)});for(const o of n){const l=a.get(o.id);if(l)for(const c of o.parentIds){const d=a.get(c);if(!d)continue;const u=document.createElementNS(e,"line");u.setAttribute("x1",String(d.x)),u.setAttribute("y1",String(d.y)),u.setAttribute("x2",String(l.x)),u.setAttribute("y2",String(l.y)),u.setAttribute("stroke","currentColor"),u.setAttribute("stroke-width","1"),u.setAttribute("opacity","0.6"),t.appendChild(u)}}for(const[,o]of a){const l=document.createElementNS(e,"circle");l.setAttribute("cx",String(o.x)),l.setAttribute("cy",String(o.y)),l.setAttribute("r",n.length>aE?"2.2":"4"),l.setAttribute("fill","currentColor"),t.appendChild(l)}return t}function Do(n){return n.type==="dir"||n.type==="vfs"||n.type==="link"||n.type==="job"?"dir":n.type==="file"?"file":n.type==="plugin"||n.type==="pipeline"?n.type:null}class vp{container;recent=null;activate;listing;lastListings=[];contentShown=!1;denied=new Set;following=!1;viewMode="list";viewPill;modeSpan;preview;catalogue;runStrip=null;feedOpen=null;headCache=new Map;thumbObserver=null;frameTopObserver=null;stale=!1;home=null;ceiling=null;stateSpan;indicate=null;selectionVerbs=null;constructor(e,t,s=null,i={}){this.container=e,this.activate=t,this.preview=s,this.catalogue=i.catalogue===!0,this.catalogue&&e.parentElement?.classList.add("files-catalogue");const r=e.closest(".pane-files")??e.parentElement;this.viewPill=e.parentElement?.querySelector(".files-view")??null,this.modeSpan=e.closest(".pane-files")?.querySelector(".pane-mode")??null,this.stateSpan=r?.querySelector(".pane-state")??null,this.viewPill?.addEventListener("click",()=>{this.view_set(Nc[(Nc.indexOf(this.viewMode)+1)%Nc.length]??"list")});const a=e.parentElement?.querySelector(":scope > .mode-frame")!==null;this.listing=new Qr({mount:e,traits:this.traits_declare(),key:o=>o.home===!0?"~":o.path,address:o=>o.path,chrome:r===null?void 0:{root:r,prefix:"files"},control:"control",activate:o=>this.row_activate(o),activatable:o=>o.updir||Do(o.entry)!==null,indicated:o=>this.indicate?.(o.entry,o.path),row:{className:o=>`files-row files-type-${o.entry.type}${o.home===!0?" files-lead-home":o.updir?" files-lead-up":""}${!o.updir&&this.denied.has(o.path)?" files-denied":""}`,decorate:(o,l)=>{o.dataset.path=l.path,!l.updir&&this.denied.has(l.path)&&(o.title="listed but not readable — CUBE refused this identity access to the contents")}},...a?{selection:{verbs:o=>this.selectionVerbs?.(o.map(([l,c])=>[l,c.entry]))??[]}}:{},state:o=>this.stateLine_compose(o),defaultSort:{key:"name",dir:"asc"}}),this.empty_render()}traits_declare(){return this.catalogue?this.catalogueTraits_declare():this.browserTraits_declare()}browserTraits_declare(){return[{key:"control",label:"",className:"files-control",capped:!1,width:"2.4em",cell:e=>{const t=document.createElement("span"),s=e.updir?"dir":e.entry.type,i=e.updir||Do(e.entry)!==null;return t.className=`files-control files-glyph files-glyph-${s}${i?" files-capsule":""}`,t.textContent=e.home===!0?Mp:!e.updir&&this.denied.has(e.path)?"⃠":Ao[s],t}},{key:"name",label:"NAME",className:"files-name",width:"minmax(12em, 1fr)",cell:e=>{const t=document.createElement("span");if(t.className="files-name",t.textContent=e.home===!0?"~":e.entry.name,e.home===!0){const s=document.createElement("span");s.className="files-target",s.textContent=e.path,t.appendChild(s),t.title=`home: ${e.path}`}if(!e.updir&&e.entry.type==="link"&&e.entry.target!==void 0){const s=document.createElement("span");s.className="files-target",s.textContent=`→ ${e.entry.target}`,t.appendChild(s),t.title=e.entry.target}return t},compare:e=>e.entry.name},{key:"type",label:"TYPE",className:"files-type",width:"6em",cell:e=>e.updir?"":e.entry.type},{key:"size",label:"SIZE",className:"files-size",width:"6em",cell:e=>e.updir||e.entry.type==="dir"?"":xp(e.entry.size),compare:e=>e.entry.size},{key:"date",label:"DATE",className:"files-date",width:"7em",cell:e=>e.updir?"":e.entry.date.slice(0,10),compare:e=>e.entry.date},{key:"owner",label:"OWNER",className:"files-owner",width:"10em",cell:e=>e.updir?"":e.entry.owner}]}row_activate(e){if(e.updir){this.activate({kind:"dir",path:e.path});return}const t=Do(e.entry);t!==null&&this.activate({kind:t,path:e.path})}envelope_observe(e){if(e.model?.kind!=="fs.listing")return;const t=Op(e.model.data);if(t===null||t.length===0)return;this.lastListings=t;const s=t[0]?.path??"";this.container.closest(".workspace-pane")?.classList.toggle("files-projection",/^\/(proc|net|etc|usr)(\/|$)/.test(s)),!this.contentShown&&this.listings_render(t)}ambient_observe(e){if(e.model?.kind!=="fs.listing")return;const t=Op(e.model.data);if(t===null||this.lastListings.length===0)return;let s=!1;const i=this.lastListings.map(r=>{const a=t.find(o=>o.path===r.path);return a===void 0?r:(s=!0,a)});if(s){if(this.contentShown){this.lastListings=i;return}this.listings_render(i)}}contentTable_show(e,t){const s=eE(t,e);if(s.caps.length===0){this.content_show(e,t);return}const i=s.rows.slice(0,nE),r=s.rows.length>i.length;this.contentRelease?.(),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren(),this.diagram_declare(!1);const a=document.createElement("section");a.className="files-content-view files-table-view";const o=document.createElement("header");o.className="files-path files-content-header";const l=document.createElement("span");l.textContent=e;const c=document.createElement("span");c.className="pane-state",o.append(l,c);const d=document.createElement("div");d.className="files-table-field";const u=document.createElement("span");u.className="field-rule";const h=document.createElement("button");h.className="mode-strip",h.title="display modes";const g=document.createElement("span");g.className="mode-elbow";const p=document.createElement("aside");p.className="mode-frame";const z=document.createElement("button");z.className="strategy-pill csv-filter rail-off",z.textContent="FILTER OFF",z.title="filter the table";const m=document.createElement("button");m.className="strategy-pill csv-raw",m.textContent="RAW",m.title="the bytes as written",m.addEventListener("click",()=>this.content_show(e,t));const f=document.createElement("button");f.className="strategy-pill csv-close",f.textContent="CLOSE",f.title="leave the table; the listing beneath returns",f.addEventListener("click",()=>this.listing_restore());const _=document.createElement("span");_.className="mode-fill",p.append(z,m,_);const O=this.preview;if(O!==null){const I=document.createElement("button");I.className="strategy-pill csv-download",I.textContent="DOWNLOAD",I.title="save this file to your disk",I.addEventListener("click",()=>O.download(e)),p.append(I)}p.append(f);const w=document.createElement("div");w.className="files-table-rows",d.append(u,h,g,p,w),a.append(o,d),this.container.appendChild(a);const x=s.caps.map((I,b)=>({key:`c${b}`,label:I.toUpperCase(),className:"files-table-cell",cell:A=>A.cells[b]??"",width:"minmax(6em, 1fr)"}));new Qr({mount:w,traits:x,key:I=>String(I.index),chrome:{root:a,prefix:"csv"},state:I=>{const b=[];return I.filter!==""?b.push(`${I.filter} ROWS`):b.push(r?`SHOWING ${i.length} OF ${s.rows.length} ROWS`:`${s.rows.length} ROWS`),s.headed||b.push("NO HEADER: COLUMNS NUMBERED"),b.join(" · ")},empty:()=>{const I=document.createElement("div");return I.className="files-note",I.textContent="NO ROWS",I}}).rows_set([{key:e,rows:i.map((I,b)=>({index:b,cells:I}))}],{field:e}),this.contentRelease=()=>{w.replaceChildren()}}content_show(e,t,s=!1){this.diagram_declare(!1),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const i=document.createElement("header");i.className="files-path files-content-header";const r=document.createElement("span");r.textContent=e;const a=document.createElement("button");a.className="files-close-pill",a.textContent="CLOSE",a.addEventListener("click",()=>this.listing_restore());const o=document.createElement("pre");o.className="files-content";const l=s||!pp.test(e)?null:mp(t),c=[];if(l!==null||s&&pp.test(e)&&mp(t)!==null){const d=document.createElement("button");d.className="files-close-pill",d.textContent=l!==null?"RAW":"PRETTY",d.addEventListener("click",()=>this.content_show(e,t,l!==null)),c.push(d)}i.append(r,...wp(this.preview,e),...c,a),l!==null?(o.classList.add("files-json"),o.append(l)):o.textContent=t,this.container.append(i,o)}contentRefused_show(e,t){this.diagram_declare(!1),this.denied.add(e),this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const s=document.createElement("header");s.className="files-path files-content-header files-content-refused";const i=document.createElement("span");i.textContent=e;const r=document.createElement("button");r.className="files-close-pill",r.textContent="CLOSE",r.addEventListener("click",()=>this.listing_restore()),s.append(i,r);const a=document.createElement("div");a.className="files-refused";const o=document.createElement("p");o.className="files-refused-lede",o.textContent="READ REFUSED";const l=document.createElement("pre");l.className="files-refused-said",l.textContent=t,a.append(o,l),this.container.append(s,a)}contentImage_show(e,t){this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const s=document.createElement("header");s.className="files-path files-content-header";const i=document.createElement("span");i.textContent=e;const r=document.createElement("button");r.className="files-close-pill",r.textContent="CLOSE",r.addEventListener("click",()=>this.listing_restore()),s.append(i,...wp(this.preview,e),r);const a=document.createElement("img");a.className="files-image",a.src=t,a.alt=e,this.container.append(s,a)}rowVerbs_declare(e,t){this.indicate=t??null,this.listing.actions_declare({of:s=>s.updir?[]:e(s.entry,s.path).map(i=>({label:i.label,run:()=>i.run(s.entry),...i.offered!==void 0?{offered:()=>i.offered(s.entry)}:{},...i.disabled!==void 0?{disabled:()=>i.disabled(s.entry)}:{}}))})}catalogueTraits_declare(){return[...this.browserTraits_declare().filter(s=>s.key==="control"||s.key==="name"),{key:"type",label:"TYPE",className:"files-type",width:"6em",cell:s=>s.updir?"":s.entry.type},{key:"version",label:"VERSION",className:"files-version",width:"7em",cell:s=>s.updir?"":gp(s.entry.name),compare:s=>gp(s.entry.name)}]}catalogue_is(){return this.catalogue}binding_set(e){if(this.runStrip===null){const s=document.createElement("div");s.className="files-run-strip";const i=document.createElement("span");i.className="files-binding";const r=document.createElement("input");r.className="files-command",r.spellcheck=!1,r.autocomplete="off",r.placeholder="the line RUN will run",s.append(i,r),this.container.parentElement?.insertBefore(s,this.container),this.runStrip=s;const a=this.container.closest(".pane-files")?.querySelector(".pane-title");a!=null&&(a.textContent="CATALOGUE")}const t=this.runStrip.querySelector(".files-binding");t!==null&&(t.textContent=`INPUT ${e.input} → ${e.place}`),this.frameTop_track()}commandLine_get(){return this.runStrip?.querySelector(".files-command")?.value.trim()??""}commandLine_set(e){const t=this.runStrip?.querySelector(".files-command")??null;t!==null&&(t.value=e)}indicated_get(){return this.listing.indicated_get()}feedOpen_declare(e){this.feedOpen=e}run_show(e){if(this.runStrip===null)return;this.runStrip.querySelector(".files-feed")?.remove();const t=document.createElement("button");t.className="files-feed listing-capsule listing-action-selected",t.textContent=`FEED ${e}`,t.title="open this run's graph beside the catalogue",t.addEventListener("click",()=>this.feedOpen?.(e)),this.runStrip.appendChild(t)}row_indicate(e){this.listing.row_indicate(e)}rowReadout_show(e,t){this.listing.readout_show(e,t)}selectionVerbs_declare(e){this.selectionVerbs=e}select_toggle(e){this.listing.select_toggle(e)}select_isOn(){return this.listing.select_isOn()}selection_get(){return this.listing.selection_get()}path_current(){return this.lastListings[0]?.path??null}content_isShown(){return this.contentShown}contentRelease=null;contentHtml_show(e,t,s={}){this.contentRelease?.(),this.contentRelease=s.release??null,this.contentShown=!0,this.container.parentElement?.classList.add("content-view"),this.container.replaceChildren();const i=document.createElement("section");i.className="files-content-view";const r=document.createElement("header");r.className="files-path files-content-header";const a=document.createElement("span");a.textContent=e;const o=document.createElement("button");if(o.className="files-close-pill",o.textContent="CLOSE",o.addEventListener("click",()=>this.listing_restore()),r.append(a,o),i.appendChild(r),t!==""){const c=document.createElement("pre");c.className="files-content",c.innerHTML=t,i.appendChild(c)}let l=null;return s.diagram===!0&&(l=document.createElement("div"),l.className="files-diagram",i.appendChild(l)),this.diagram_declare(s.diagram===!0),this.container.appendChild(i),l}contentText_set(e){const t=this.container.querySelector(".files-content-view");if(t===null)return;const s=t.querySelector(".files-content"),i=s??document.createElement("pre");i.className="files-content",i.innerHTML=e,s===null&&t.querySelector(".files-content-header")?.after(i)}recent_set(e){this.recent=e===null?null:[...e],this.lastListings.length>0&&!this.contentShown&&this.listings_render(this.lastListings)}listing_restore(){this.contentRelease?.(),this.contentRelease=null,this.lastListings.length>0?this.listings_render(this.lastListings):this.empty_render()}empty_render(){this.diagram_declare(!1),this.container.replaceChildren();const e=document.createElement("p");e.className="files-empty",e.textContent="AWAITING LISTING — TYPE ls IN THE CONSOLE",this.container.appendChild(e)}listings_render(e){this.diagram_declare(!1),this.contentShown=!1,this.container.parentElement?.classList.remove("content-view"),this.lastListings=e,this.thumbObserver?.disconnect(),this.thumbObserver=null,this.stale=e.some(i=>i.fresh===!1),this.stateSpan?.classList.toggle("state-stale",this.stale),this.listing.painter_set(this.viewMode==="list"?null:(i,r)=>this.cards_paint(i,r));const t=e.map(i=>this.block_of(i)),s=e.find(i=>i.path===sE);if(this.recent!==null&&this.recent.length>0&&s!==void 0){const i=this.recentBlock_of(s);i!==null&&t.unshift(i)}this.listing.rows_set(t,{field:e[0]?.path??""}),this.frameTop_track()}crumbs_build(e){const t=document.createElement("header");t.className="files-path files-crumbs";const s=[],i=this.home;let r;i!==null&&(e===i||e.startsWith(`${i}/`))?(s.push({label:"~",path:i}),r=e.slice(i.length)):(s.push({label:"/",path:"/"}),r=e);let a=s[0]?.path??"/";for(const o of r.split("/").filter(l=>l.length>0))a=a==="/"?`/${o}`:`${a}/${o}`,s.push({label:o,path:a});return s.forEach((o,l)=>{l>0&&s[l-1]?.label!=="/"&&t.append("/");const c=l===s.length-1,d=document.createElement(c?"span":"button");d.className=c?"files-crumb files-crumb-here":"files-crumb",d.textContent=o.label,d.dataset.path=o.path,c||(d.title=`go to ${o.path}`,d.addEventListener("click",u=>{u.stopPropagation(),this.activate({kind:"dir",path:o.path})})),t.appendChild(d)}),t}ceiling_set(e,t=".."){this.ceiling=e===null?null:{path:e.replace(/\/+$/,"")||"/",word:t}}home_set(e){e!==this.home&&(this.home=e,!this.contentShown&&this.lastListings.length>0&&this.listings_render(this.lastListings))}block_of(e){const t=this.crumbs_build(e.path),s=e.items.map(r=>({entry:r,path:Io(e.path,r.name),updir:!1})),i=[];if(!this.catalogue&&this.home!==null&&e.path!==this.home&&i.push({entry:{name:"~",type:"dir",size:0,owner:"",date:""},path:this.home,updir:!0,home:!0}),e.path!=="/"){const r=this.ceiling!==null&&this.ceiling.path===e.path?this.ceiling.word:"..";i.push({entry:{name:r,type:"dir",size:0,owner:"",date:""},path:fE(e.path),updir:!0})}return{key:e.path,header:t,lead:i,rows:s}}recentBlock_of(e){const t=new Map(e.items.map(r=>[r.name,r])),s=[];for(const r of this.recent??[]){const a=t.get(r);a!==void 0&&s.push({entry:a,path:Io(bp,r),updir:!1})}if(s.length===0)return null;const i=document.createElement("header");return i.className="files-path files-recent",i.textContent="RECENT",{key:bp,header:i,lead:[],rows:s}}cards_paint(e,t){const s=this.viewMode==="preview",i=document.createElement("div");i.className=s?"files-cards files-previews":"files-cards";for(const a of e.lead??[]){const o=document.createElement("article");o.className=a.home===!0?"files-card files-card-up files-card-home files-activatable":"files-card files-card-up files-activatable",o.textContent=a.home===!0?`${Mp} ~`:"▴ ..",o.addEventListener("click",()=>this.activate({kind:"dir",path:a.path})),i.appendChild(o)}const r=e.key;for(const a of e.rows)i.appendChild(this.card_build(r,a.entry,s));t.appendChild(i)}frameTop_track(){const e=this.container.parentElement,t=this.container.querySelector(".roster-order"),s=this.container.querySelector(".files-path");if(this.frameTopObserver?.disconnect(),this.frameTopObserver=null,e===null)return;if(t===null||s===null){e.style.removeProperty("--mode-frame-top"),e.style.removeProperty("--roster-frame-h");return}const i=()=>{const r=e.getBoundingClientRect().top,a=Math.ceil(t.getBoundingClientRect().bottom-r);e.style.setProperty("--roster-frame-h",`${a}px`),e.style.setProperty("--mode-frame-top",`${Math.ceil(s.getBoundingClientRect().bottom-r)}px`)};i(),this.frameTopObserver=new ResizeObserver(i),this.frameTopObserver.observe(t),this.frameTopObserver.observe(s)}follow_set(e){this.following=e,this.listing.state_refresh()}follow_get(){return this.following}view_set(e){this.viewMode=e,this.viewPill!==null&&(this.viewPill.textContent=e.toUpperCase()),this.modeSpan!==null&&(this.modeSpan.textContent=e==="list"?"":e.toUpperCase()),this.lastListings.length>0&&!this.contentShown&&this.listings_render(this.lastListings)}view_get(){return this.viewMode}body_get(){return this.container.closest(".files-body")}diagram_declare(e){this.body_get()?.classList.toggle("diagram-shown",e),e||this.mode_annunciate(this.viewMode==="list"?"":this.viewMode.toUpperCase())}mode_annunciate(e){this.modeSpan!==null&&(this.modeSpan.textContent=e)}stateLine_compose(e){const t=[];return this.following&&t.push("CWD"),e.selecting&&t.push("SELECT"),t.push(this.stale?"STALE":e.filter),e.selected>0&&t.push(e.shown===e.selected?`${e.selected} SELECTED`:`${e.selected} SELECTED · ${e.shown} SHOWN`),t.filter(s=>s!=="").join(" · ")}card_build(e,t,s=!1){const i=document.createElement("article");i.className=`files-card files-type-${t.type}`,s&&i.appendChild(this.thumb_build(Io(e,t.name),t));const r=document.createElement("div");r.className="files-card-head";const a=document.createElement("span");a.className="files-card-badge",a.textContent=t.type.toUpperCase();const o=document.createElement("span");o.className="files-card-size",o.textContent=t.type==="dir"||t.size===0?"":xp(t.size),r.append(a,o);const l=document.createElement("div");l.className="files-card-title",l.textContent=t.name;const c=document.createElement("div");c.className="files-card-meta";const d=document.createElement("span");d.textContent=t.owner;const u=document.createElement("span");if(u.textContent=t.date.slice(0,10),c.append(d,u),i.append(r,l,c),t.type==="link"&&t.target!==void 0){const p=document.createElement("div");p.className="files-card-target",p.textContent=`→ ${t.target}`,p.title=t.target,i.appendChild(p)}const h=Io(e,t.name),g=Do(t);return g!==null&&(i.classList.add("files-activatable"),i.addEventListener("click",()=>this.activate({kind:g,path:h}))),i}thumb_build(e,t){const s=document.createElement("div");s.className="files-card-thumb";const i=()=>{s.textContent=Ao[t.type]};if(Kg.test(t.name)||Xo.test(t.name)){s.classList.add("thumb-series");const u=document.createElement("span");u.className="thumb-series-mark",u.textContent="DCM";const h=/^\d+-(.*)-[0-9a-f]{7}$/.exec(t.name)?.[1];if(s.replaceChildren(u),h!==void 0){const g=document.createElement("span");g.className="thumb-series-text",g.textContent=h.replace(/_/g," "),s.appendChild(g)}return s}if(this.preview===null||!(t.type==="file"||t.type==="plugin"||t.type==="pipeline"))return i(),s;if(t.type==="plugin")return s.replaceChildren(yp([{id:e,parentIds:[]}])),s;if(t.type==="pipeline"){const u=this.preview;s.classList.add("thumb-wait"),s.textContent=Ao[t.type];const h=()=>{u.pipelineGlimpse(e).then(g=>{if(s.classList.remove("thumb-wait"),g===null||g.length===0){i();return}if(g.length>hE){s.textContent=`${g.length} NODES`,s.classList.add("thumb-count");return}s.replaceChildren(yp(g))}).catch(()=>{s.classList.remove("thumb-wait"),i()})};return this.thumbObserver_get().observe(s),s.addEventListener("files:thumb-seen",h,{once:!0}),s}const r=this.headCache.get(e);if(r!==void 0){const u=document.createElement("pre");return u.textContent=r,s.appendChild(u),s}const a=Yo(e)&&t.size<=cE,o=Zg(e),l=(o===""||rE.has(o))&&t.size<=oE;if(!a&&!l)return i(),s;s.classList.add("thumb-wait"),s.textContent=Ao.file;const c=this.preview,d=()=>{if(a){const u=document.createElement("img");u.alt=t.name,u.addEventListener("load",()=>{s.classList.remove("thumb-wait")}),u.addEventListener("error",()=>{s.classList.remove("thumb-wait"),i()}),u.src=c.imageUrl(e),s.replaceChildren(u);return}c.textHead(e,lE).then(u=>{if(this.headCache.size>=dE&&this.headCache.clear(),this.headCache.set(e,u),s.classList.remove("thumb-wait"),u.trim()===""||uE(u)){i();return}const h=document.createElement("pre");h.textContent=u,s.replaceChildren(h)}).catch(()=>{s.classList.remove("thumb-wait"),i()})};return this.thumbObserver_get().observe(s),s.addEventListener("files:thumb-seen",d,{once:!0}),s}thumbObserver_get(){return this.thumbObserver===null&&(this.thumbObserver=new IntersectionObserver(e=>{for(const t of e)t.isIntersecting&&(this.thumbObserver?.unobserve(t.target),t.target.dispatchEvent(new CustomEvent("files:thumb-seen")))},{root:this.container,rootMargin:"25%"})),this.thumbObserver}filter_toggle(e){this.listing.filter_toggle(e)}}function Op(n){if(!Array.isArray(n))return null;for(const e of n){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.path!="string"||!Array.isArray(t.items))return null}return n}function Io(n,e){return n.endsWith("/")?`${n}${e}`:`${n}/${e}`}function fE(n){const e=n.endsWith("/")?n.slice(0,-1):n,t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function xp(n){if(n<1024)return String(n);const e=["K","M","G","T"];let t=n,s=-1;for(;t>=1024&&s<e.length-1;)t=t/1024,s=s+1;return`${t<10?t.toFixed(1):Math.round(t)}${e[s]}`}const Qg={listing:"files.row",rules:[{name:"image",label:()=>"IMAGE",offered:n=>n.kind==="seriesFolder"},{name:"gather",label:()=>"GATHER",offered:n=>n.kind!=="catalogue"&&n.projection!==!0},{name:"process",label:()=>"PROCESS",offered:n=>(n.kind==="directory"||n.kind==="seriesFolder")&&(n.feed===null||(n.node??null)!==null)},{name:"run",label:()=>"RUN",offered:n=>n.kind==="catalogue"&&n.bound===!0},{name:"download",label:()=>"DOWNLOAD",offered:n=>n.kind==="file"},{name:"move",label:()=>"MOVE",offered:n=>n.kind!=="catalogue"&&n.projection!==!0},{name:"copy",label:()=>"COPY",offered:n=>n.kind!=="catalogue"&&n.projection!==!0},{name:"delete",label:()=>"DELETE",offered:n=>n.kind!=="catalogue"&&n.projection!==!0},{name:"share",label:n=>`SHARE FEED ${n.feed??""}`,offered:n=>n.kind!=="catalogue"&&n.feed!==null&&n.projection!==!0}],states:[{name:"a plain file outside a feed",facts:{kind:"file",feed:null}},{name:"a file inside a feed",facts:{kind:"file",feed:12}},{name:"a directory",facts:{kind:"directory",feed:null}},{name:"a directory inside a feed that is not a node",facts:{kind:"directory",feed:12,node:null}},{name:"a node's data inside a feed",facts:{kind:"directory",feed:12,node:456}},{name:"a DICOM series folder",facts:{kind:"seriesFolder",feed:null}},{name:"a catalogue entry",facts:{kind:"catalogue",feed:null}},{name:"a catalogue entry in a bound catalogue",facts:{kind:"catalogue",feed:null,bound:!0}},{name:"a node's data seen through /proc",facts:{kind:"directory",feed:12,node:456,projection:!0}},{name:"a file seen through /proc",facts:{kind:"file",feed:12,projection:!0}}]},Jg={listing:"files.selection",rules:[{name:"delete",label:n=>`DELETE ${n.count}`,offered:()=>!0},{name:"move",label:n=>`MOVE ${n.count}`,offered:()=>!0},{name:"copy",label:n=>`COPY ${n.count}`,offered:()=>!0},{name:"share",label:n=>n.feeds.length===1?`SHARE FEED ${n.feeds[0]}`:`SHARE ${n.feeds.length} FEEDS`,offered:n=>n.feeds.length>0}],states:[{name:"a selection outside any feed",facts:{count:3,feeds:[]}},{name:"a selection in one feed",facts:{count:2,feeds:[12]}},{name:"a selection spanning feeds",facts:{count:5,feeds:[12,13]}}]},eM={listing:"runs.row",rules:[{name:"share",label:()=>"SHARE",offered:()=>!0},{name:"delete",label:()=>"DELETE",offered:()=>!0}],states:[{name:"any feed",facts:{feedId:12}}]},Ra={listing:"pacs.study",rules:[{name:"pullStudy",label:()=>"PULL STUDY",offered:n=>n.addressable},{name:"gather",label:()=>"GATHER",offered:n=>n.addressable},{name:"process",label:()=>"PROCESS",offered:n=>n.allInCube}],states:[{name:"a study with a path",facts:{addressable:!0,allInCube:!1}},{name:"a study with none",facts:{addressable:!1,allInCube:!1}},{name:"a study wholly home",facts:{addressable:!0,allInCube:!0,anyInCube:!0}},{name:"a study partly home",facts:{addressable:!0,allInCube:!1,anyInCube:!0}}]},Ui={listing:"pacs.series",rules:[{name:"gather",label:()=>"GATHER",offered:n=>n.addressable||n.inCube},{name:"image",label:()=>"IMAGE",offered:n=>n.inCube&&n.folderKnown},{name:"dir",label:()=>"DIR",offered:n=>n.inCube&&n.folderKnown},{name:"process",label:()=>"PROCESS",offered:n=>n.inCube&&n.folderKnown},{name:"pull",label:()=>"PULL",offered:n=>!n.inCube}],states:[{name:"not yet retrieved",facts:{inCube:!1,folderKnown:!1,addressable:!0}},{name:"not retrieved and unaddressable",facts:{inCube:!1,folderKnown:!1,addressable:!1}},{name:"home, folder not yet named",facts:{inCube:!0,folderKnown:!1,addressable:!0}},{name:"home, folder named",facts:{inCube:!0,folderKnown:!0,addressable:!0}}]},tM={listing:"gather.series",rules:[{name:"remove",label:()=>"REMOVE",offered:()=>!0},{name:"pull",label:()=>"PULL",offered:n=>n.pullable===!0},{name:"image",label:()=>"IMAGE",offered:n=>n.folderKnown&&n.imagery!==!1},{name:"process",label:()=>"PROCESS",offered:()=>!0}],states:[{name:"folder named",facts:{folderKnown:!0}},{name:"a place that is not imagery",facts:{folderKnown:!0,imagery:!1}},{name:"folder not yet named",facts:{folderKnown:!1}},{name:"not retrieved yet",facts:{folderKnown:!1,pullable:!0}}]},sM={listing:"gather.cohort",rules:[{name:"save",label:()=>"SAVE",offered:n=>n.count>0},{name:"export",label:()=>"EXPORT CSV",offered:n=>n.count>0},{name:"feed",label:()=>"CREATE FEED",offered:n=>n.count>0&&n.feed===null},{name:"process",label:()=>"PROCESS",offered:n=>n.count>0},{name:"dismiss",label:()=>"DISMISS",offered:()=>!0}],states:[{name:"holding series",facts:{count:2,feed:null}},{name:"holding series, rooted in a feed",facts:{count:2,feed:4501}},{name:"emptied",facts:{count:0,feed:null}}]};function Ci(n){return{listing:n.listing,visit(e){return e(n)}}}Ci(Qg),Ci(Jg),Ci(eM),Ci(Ra),Ci(Ui),Ci(sM),Ci(tM);function vn(n,e){const t=n.rules.find(s=>s.name===e);if(t===void 0)throw new Error(`${n.listing} declares no verb '${e}'`);return t}function pE(n){return{inCube:n.pulled===!0,folderKnown:n.folderPath!==void 0,addressable:n.vfsPath!==void 0}}function Sp(n){if(n.series.length===0)return null;const e=[];for(const s of n.series){if(s.pulled!==!0||s.folderPath===void 0)return null;e.push(s.folderPath.replace(/\/[^/]+\/?$/,""))}const t=e[0]??"";return e.every(s=>s===t)&&t!==""?t:null}function kn(n){const e=pE(n),t=s=>vn(Ui,s).offered(e);return{gather:t("gather"),image:t("image"),dir:t("dir"),pull:t("pull")}}function mE(n,e,t,s){let i=!1;for(const r of n.studies)for(const a of r.series)a.seriesUID===e&&(s!==void 0&&a.folderPath!==s&&(a.folderPath=s,i=!0),a.pulled!==!0&&(a.pulled=!0,t!==void 0&&t>0&&(a.pulledFiles=t),i=!0));return i}const Ap=[{id:"pacs-f-name",term:"PatientName"},{id:"pacs-f-mrn",term:"PatientID"},{id:"pacs-f-date",term:"StudyDate"},{id:"pacs-f-accession",term:"AccessionNumber"},{id:"pacs-f-modality",term:"Modality"}],To={running:"RETRIEVING",done:"✓ PULLED",error:"✗ ERROR",unconfirmed:"? UNCONFIRMED",stalled:"STALLED",queued:"QUEUED",idle:"NOT RETRIEVED"},gE="--fresh",Ep="--anon",ME=/\s*--anon\b/,bE=["pacs-f-name","pacs-f-mrn","pacs-f-accession","pacs-f-date"],Dp=/\s*--fresh\b/;function Ip(n){const e=Date.parse(n);if(Number.isNaN(e))return null;const t=Math.max(0,Math.round((Date.now()-e)/1e3)),s=[{limit:60,size:1,name:"SECOND"},{limit:3600,size:60,name:"MINUTE"},{limit:86400,size:3600,name:"HOUR"},{limit:2592e3,size:86400,name:"DAY"},{limit:31536e3,size:2592e3,name:"MONTH"},{limit:1/0,size:31536e3,name:"YEAR"}];for(const i of s){if(t>=i.limit)continue;const r=Math.max(1,Math.floor(t/i.size));return`${r} ${i.name}${r===1?"":"S"} AGO`}return null}const zl=new Map;function nM(n,e){const t=zl.get(n)??new Set;t.add(e),zl.set(n,t)}const iM=new Map;function rM(n,e){n.replaceChildren(),n.dataset.state=e.status;const t=document.createElement("span");if(t.className="pacs-badge-note",e.status==="idle"){t.textContent=To.idle,n.append(bl({done:0,total:0}),t);return}if(e.status==="done"){const o=document.createElement("span");o.className="pacs-bar-full",t.textContent=e.total!==void 0&&e.total>0?`✓ ${e.total} IN CUBE`:"✓ IN CUBE",n.append(o,t);return}if(e.status!=="running"&&e.status!=="queued"){n.textContent=To[e.status]??e.status.toUpperCase();return}const s=e.total!==void 0?` ${e.current??0}/${e.total}`:"",i=e.status==="queued"||e.total===void 0||e.total===0?null:Math.min(1,(e.current??0)/e.total),r=document.createElement("span");r.className=i===null?"pacs-bar pacs-bar-pacing":"pacs-bar";const a=document.createElement("span");a.className="pacs-bar-fill",i!==null&&(a.style.width=`${Math.round(i*100)}%`),r.appendChild(a),t.textContent=e.status==="queued"?To.queued:`${To.running}${s}`,n.append(r,t)}function zE(n,e){const t=zl.get(n);if(t!==void 0){for(const s of[...t]){if(!s.isConnected){t.delete(s);continue}e(s)}t.size===0&&zl.delete(n)}}function _E(n){const e=document.createElement("span");if(e.className="pacs-badge",n.pulled===!0){const r=document.createElement("span");r.className="pacs-bar-full";const a=document.createElement("span");return a.className="pacs-badge-note",a.textContent=n.pulledFiles!==void 0?`✓ ${n.pulledFiles} IN CUBE`:"✓ IN CUBE",e.append(r,a),e.dataset.state="done",e}const t=document.createElement("span");t.className="pacs-bar";const s=document.createElement("span");s.className="pacs-badge-note",s.textContent="NOT RETRIEVED",e.append(t,s),e.dataset.state="idle",nM(n.seriesUID,e);const i=iM.get(n.seriesUID);return i!==void 0&&rM(e,i),e}function aM(n,e){return[{key:"series",label:"SERIES",className:"pacs-series-desc",width:"35.5em",cell:t=>n(t).description},{key:"state",label:"STATE",className:"pacs-badge",width:"1fr",cell:t=>e(n(t)),compare:t=>n(t).pulled===!0?"done":"idle"},{key:"modality",label:"MODALITY",className:"pacs-series-modality",width:"4em",cell:t=>n(t).modality},{key:"files",label:"FILES",className:"pacs-series-files",width:"6em",cell:t=>{const s=n(t).fileCount;return s!==void 0?`${s} FILES`:""},compare:t=>n(t).fileCount??-1}]}class wE{root;command;results;handlers;litFolders=new Map;badgeStates=new Map;seriesProgress=new Map;studyTracks=new Map;traits;actions;studyTraits;studyActions;patientTraits;listing;patientTracks=new Map;provenance;run;model=null;anon=!1;revealed=!1;anonPill;revealPill;replayed=!1;serverCell;serverStrip;servers=[];chosen=new Set;constructor(e,t){this.root=e,this.handlers=t,this.command=Go(e,"#pacs-command"),this.results=mn(e,"#pacs-results"),this.traits=this.traits_declare(),this.actions=this.actions_declare(),this.studyTraits=this.studyTraits_declare(),this.studyActions=this.studyActions_declare(),this.patientTraits=this.patientTraits_declare(),this.listing=new Qr({mount:this.results,traits:this.patientTraits,key:s=>s.key,chrome:{root:e,prefix:"pacs"},activatable:s=>s.studies.length>0,address:s=>s.studies.length>0?G0(s.patient):void 0,control:"fold",row:{className:()=>"pacs-patient-row",groupClassName:s=>s.patient.status==="unasked"?"pacs-patient pacs-patient-unasked":"pacs-patient",decorate:(s,i)=>{i.studies.length>0&&(s.title="unfold this patient's studies (the patient keeps its place)")}},child:kr(s=>s.studies.map((i,r)=>({study:i,key:Tp(i,r)})),{traits:this.studyTraits,key:s=>s.key,address:s=>s.study.vfsPath,control:"fold",actions:{of:()=>this.studyActions},row:{className:()=>"pacs-study-row",groupClassName:()=>"pacs-study",decorate:s=>{s.title="unfold this study's series (the study keeps its place)"}},child:kr(s=>s.study.series.map(i=>({study:s.study,studyKey:s.key,series:i})),{traits:this.traits,key:s=>s.series.seriesUID,address:s=>s.series.vfsPath,actions:{of:()=>this.actions},row:{className:()=>"pacs-series",decorate:(s,i)=>{s.dataset.seriesuid=i.series.seriesUID}}})}),state:s=>this.stateLine_compose(s),empty:()=>Rp("NO STUDIES FOUND")}),e.style.setProperty("--roster-cols",this.listing.template_get(1)),this.listing.rows_set([],{field:"pacs"});for(const{id:s}of Ap){const i=Go(e,`#${s}`);i.addEventListener("input",()=>this.command_regenerate()),i.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),this.query_run())})}this.serverCell=mn(e,"#pacs-f-server"),this.serverStrip=mn(e,"#pacs-server-strip"),this.serverCell.addEventListener("click",()=>this.serverStrip_toggle()),this.serverCell_sync(),this.provenance=mn(e,"#pacs-provenance"),this.anonPill=mn(e,"#pacs-anon"),this.revealPill=mn(e,"#pacs-reveal"),this.anonPill.addEventListener("click",()=>this.anon_set(!this.anon)),this.revealPill.addEventListener("click",()=>this.reveal_set(!this.revealed)),this.run=mn(e,"#pacs-run"),this.run.addEventListener("click",()=>this.query_run(this.replayed)),this.command.addEventListener("keydown",s=>{s.key==="Enter"&&this.query_run()}),mn(e,"#pacs-export").addEventListener("click",()=>this.answer_export()),mn(e,"#pacs-gather-shown").addEventListener("click",()=>this.shown_gather()),mn(e,"#pacs-pull-shown").addEventListener("click",()=>this.shown_pull())}patientTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:"5.2em",cell:e=>{const t=document.createElement("span");return t.className=e.studies.length===0?"pacs-fold pacs-fold-none":"pacs-fold",t}},{key:"patient",label:"PATIENT",className:"pacs-patient-name",width:"13em",cell:e=>e.patient.patientName||"(unknown)"},{key:"mrn",label:"MRN",className:"pacs-patient-mrn",width:"7.5em",cell:e=>e.patient.patientId||"—"},{key:"answered",label:"ANSWERED",className:"pacs-patient-answered",width:"12em",cell:e=>{const t=document.createElement("span");if(t.className=e.patient.status==="unasked"?"pacs-patient-answered pacs-unasked":"pacs-patient-answered",e.patient.status==="unasked")return t.textContent="UNASKED",e.patient.error!==void 0&&(t.title=e.patient.error),t;const s=e.patient.provenance?.answeredAt;return t.textContent=s===void 0?"—":Ip(s)??"—",s!==void 0&&(t.title=s),t},compare:e=>{const t=e.patient.provenance?.answeredAt;if(t===void 0)return Number.MAX_SAFE_INTEGER;const s=Date.parse(t);return Number.isNaN(s)?Number.MAX_SAFE_INTEGER:s}},{key:"progress",label:"PROGRESS",className:"pacs-patient-progress",width:"1fr",cell:e=>{const t=document.createElement("span");return t.className="pacs-patient-progress",this.patientTracks.set(e.key,{mount:t,uids:e.studies.flatMap(s=>s.series.map(i=>i.seriesUID))}),this.patientTrack_paint(e.key),t},compare:e=>{const t=this.patientProgress_of(e);return t.total===0?-1:t.done/t.total}},{key:"studies",label:"STUDIES",className:"pacs-patient-count",width:"6em",cell:e=>e.patient.status==="unasked"?"—":String(e.patient.studyCount),compare:e=>e.patient.status==="unasked"?-1:e.patient.studyCount},{key:"series",label:"SERIES",className:"pacs-patient-count",width:"5em",cell:e=>e.patient.status==="unasked"?"—":String(e.patient.seriesCount),compare:e=>e.patient.status==="unasked"?-1:e.patient.seriesCount},{key:"server",label:"SERVER",className:"pacs-patient-server",width:"9em",cell:e=>e.patient.server??this.model?.pacsName??"—"}]}patientProgress_of(e){return So(e.studies.flatMap(t=>t.series.map(s=>this.seriesProgress.get(s.seriesUID)??{done:0,total:0})))}patientTrack_paint(e){const t=this.patientTracks.get(e);if(t===void 0)return;const s=t.uids.map(i=>this.seriesProgress.get(i)??{done:0,total:0});t.mount.replaceChildren(bl(So(s)))}patientRows_build(e){const t=(r,a)=>e.studies.filter(o=>o.patientId===r&&(a===void 0||o.server===void 0||o.server===a));if(e.patients!==void 0&&e.patients.length>0)return e.patients.map((r,a)=>({patient:r,key:`${r.patientId}::${r.server??""}::${a}`,studies:t(r.patientId,r.server)}));const s=[],i=new Map;for(const r of e.studies){const a=r.patientId;i.has(a)||(i.set(a,[]),s.push(a)),i.get(a).push(r)}return s.map((r,a)=>{const o=i.get(r)??[];return{key:`${r}::${a}`,studies:o,patient:{patientId:r,...o[0]?.patientName?{patientName:o[0].patientName}:{},status:"found",studyCount:o.length,seriesCount:o.reduce((l,c)=>l+c.series.length,0),...e.provenance===void 0?{}:{provenance:e.provenance}}}})}studyTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:"5.2em",cell:()=>{const e=document.createElement("span");return e.className="pacs-fold",e}},{key:"patient",label:"PATIENT",className:"pacs-study-patient",width:"13em",cell:e=>e.study.patientName||"(unknown)"},{key:"mrn",label:"MRN",className:"pacs-study-mrn",width:"7.5em",cell:e=>e.study.patientId||"—"},{key:"study",label:"STUDY",className:"pacs-study-desc",width:"12em",cell:e=>e.study.description||"(no description)"},{key:"progress",label:"PROGRESS",className:"pacs-study-progress",width:"1fr",cell:e=>{const t=document.createElement("span");return t.className="pacs-study-progress",this.studyTracks.set(e.key,{mount:t,uids:e.study.series.map(s=>s.seriesUID)}),this.studyTrack_paint(e.key),t},compare:e=>{const t=this.studyProgress_of(e);return t.total===0?-1:t.done/t.total}},{key:"date",label:"DATE",className:"pacs-study-date",width:"7.5em",cell:e=>e.study.date},{key:"accession",label:"ACCESSION",className:"pacs-study-accession",width:"9em",cell:e=>e.study.accession||"—"},{key:"modality",label:"MODALITY",className:"pacs-study-modalities",width:"6.5em",cell:e=>e.study.modalities},{key:"server",label:"SERVER",className:"pacs-study-server",width:"9em",cell:e=>e.study.server??this.model?.pacsName??"—"},{key:"series",label:"SERIES",className:"pacs-study-count",width:"6.5em",cell:e=>String(e.study.series.length),compare:e=>e.study.series.length}]}studyActions_declare(){return[{label:vn(Ra,"pullStudy").label({addressable:!0,allInCube:!1}),offered:e=>vn(Ra,"pullStudy").offered({addressable:e.study.vfsPath!==void 0,allInCube:!1}),run:e=>{const t=e.study.vfsPath;if(t!==void 0){this.handlers.command_run(`pull ${t}`);for(const s of e.study.series)s.vfsPath!==void 0&&s.pulled!==!0&&this.badgeState_set(s.seriesUID,{status:"queued"})}}},{label:vn(Ra,"gather").label({addressable:!0,allInCube:!1,anyInCube:!0}),offered:e=>e.study.series.some(t=>kn(t).gather),run:e=>{const t=e.study.series.filter(i=>kn(i).gather);for(const i of t)this.gather_note(e.study,i);const s=e.study.series.length-t.length;this.handlers.note(`gather: ${t.length} series gathered${s>0?`, ${s} not in CUBE (pull them first)`:""}`)}},{label:vn(Ra,"process").label({addressable:!0,allInCube:!0}),offered:e=>Sp(e.study)!==null,run:e=>{const t=Sp(e.study);t!==null&&this.handlers.process_open(t)}}]}studyProgress_of(e){return So(e.study.series.map(t=>this.seriesProgress.get(t.seriesUID)??{done:0,total:0}))}traits_declare(){return aM(e=>e.series,e=>this.badge_build(e))}actions_declare(){return[{label:vn(Ui,"gather").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>kn(e.series).gather,selected:e=>this.handlers.gathered_is(e.series.seriesUID),run:e=>this.gather_note(e.study,e.series)},{label:vn(Ui,"image").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>kn(e.series).image,selected:e=>e.series.folderPath!==void 0&&(this.litFolders.get(Gp(e.series.folderPath))?.viewer??!1),run:e=>{e.series.folderPath!==void 0&&this.handlers.image_open(e.series.folderPath)}},{label:vn(Ui,"dir").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>kn(e.series).dir,selected:e=>e.series.folderPath!==void 0&&(this.litFolders.get(Gp(e.series.folderPath))?.browser??!1),run:e=>{e.series.folderPath!==void 0&&this.handlers.dir_open(e.series.folderPath)}},{label:vn(Ui,"process").label({inCube:!0,folderKnown:!0,addressable:!0}),offered:e=>kn(e.series).image,run:e=>{e.series.folderPath!==void 0&&this.handlers.process_open(e.series.folderPath)}},{label:vn(Ui,"pull").label({inCube:!1,folderKnown:!1,addressable:!0}),offered:e=>kn(e.series).pull,disabled:e=>e.series.vfsPath===void 0,run:e=>{const t=e.series.vfsPath;t!==void 0&&(this.handlers.command_run(`pull ${t}`),this.badgeState_set(e.series.seriesUID,{status:"queued"}))}}]}state_name(e){return e.pulled===!0?"pulled":this.badgeStates.get(e.seriesUID)?.status??"idle"}command_regenerate(){const e=[];for(const{id:i,term:r}of Ap){const a=Go(this.root,`#${i}`).value.trim();a.length>0&&e.push(`${r}:${a}`)}const t=this.chosen.size>1?` --pacsserver ${[...this.chosen].join(",")}`:"",s=this.anon?` ${Ep}`:"";this.command.value=e.length>0||t!==""?`pacs query ${e.join(",")}${t}${s}`:""}anon_set(e){e!==this.anon&&(this.anon=e,this.revealed=!1,this.anonPill.textContent=e?"ANON ON":"ANON OFF",this.anonPill.classList.toggle("pacs-capsule-off",!e),this.revealPill.hidden=!e,this.model=null,this.listing.rows_set([],{field:"pending"}),this.provenance_show(void 0),this.command.value=e?`${this.command.value.trim()} ${Ep}`.trim():this.command.value.replace(ME,"").trimEnd(),this.masking_apply())}reveal_set(e){this.revealed=e,this.revealPill.textContent=e?"HIDE":"REVEAL",this.revealPill.classList.toggle("pacs-capsule-off",!e),this.masking_apply()}masking_apply(){const e=this.anon&&!this.revealed;for(const t of bE)Go(this.root,`#${t}`).type=e?"password":"text";this.command.type=e?"password":"text"}serverStrip_toggle(e){const t=e??this.serverStrip.hidden;this.serverStrip.hidden=!t,this.serverCell.classList.toggle("pacs-server-open",t),t&&this.servers.length===0&&this.servers_ask(),t&&this.serverStrip_paint()}query_get(){return this.model===null?null:`pacs query ${this.model.expression}`}serverStrip_isOpen(){return!this.serverStrip.hidden}serverStrip_close(){this.serverStrip_toggle(!1)}servers_ask(){this.handlers.command_run("pacs list")}servers_take(e){this.servers=e,this.serverStrip_paint(),this.serverCell_sync()}serverStrip_paint(){if(this.serverStrip.replaceChildren(),this.servers.length===0){this.serverStrip.appendChild(Rp("ASKING THE SESSION FOR REGISTERED SERVERS"));return}for(const e of this.servers){const t=document.createElement("button");t.className=this.chosen.has(e.identifier)?"pacs-server-segment pacs-server-chosen":"pacs-server-segment",t.dataset.server=e.identifier,t.textContent=e.identifier,e.active&&(t.title="the session is connected to this server"),t.addEventListener("click",()=>this.server_choose(e.identifier)),this.serverStrip.appendChild(t)}}server_choose(e){if(this.chosen.has(e)?this.chosen.delete(e):this.chosen.add(e),this.chosen.size===1){const t=[...this.chosen][0];this.handlers.command_show(`pacs connect ${t}`)}this.serverStrip_paint(),this.serverCell_sync(),this.command_regenerate()}serverCell_sync(){const e=[...this.chosen];if(e.length===0){const t=this.servers.find(s=>s.active);this.serverCell.textContent=t?.identifier??"—",this.serverCell.classList.remove("pacs-server-many");return}this.serverCell.textContent=e.length===1?e[0]:`${e[0]} +${e.length-1}`,this.serverCell.classList.toggle("pacs-server-many",e.length>1)}wrote_show(e){const t=this.root.querySelector("#pacs-wrote");t!==null&&(t.textContent=`WROTE ${e}`,t.title="open the folder this landed in",t.classList.add("pacs-wrote-opens"),t.onclick=()=>{const s=e.lastIndexOf("/");this.handlers.dir_open(s<=0?e:e.slice(0,s))},t.hidden=!1)}answer_export(){if(this.model===null)return;const e=this.command.value.trim(),t=e===""?`pacs query ${this.model.expression}`:e;this.handlers.command_show(`${t} --csv-to`)}query_run(e=!1){e&&!Dp.test(this.command.value)&&(this.command.value=`${this.command.value.trim()} ${gE}`);const t=this.command.value.trim();t.length!==0&&(this.model=null,this.listing.rows_set([],{field:"pending"}),this.listing.field_get()?.appendChild(this.waiting_build()),this.handlers.command_run(t))}provenance_show(e){if(this.replayed=e?.replayed===!0,this.run.textContent=this.replayed?"RE-QUERY":"QUERY",this.run.classList.toggle("pacs-capsule-requery",this.replayed),this.provenance.hidden=!this.replayed,!this.replayed){this.provenance.textContent="",this.command.value=this.command.value.replace(Dp,"").trimEnd();return}const t=e?.answeredAt??"",s=Ip(t),i=t.slice(0,10);this.provenance.textContent=s===null?`RESULTS ${i}`:`RESULTS ${i} · ${s}`,this.provenance.title=t}waiting_build(){const e=document.createElement("div");e.className="pacs-waiting";const t=document.createElement("span");t.className="pacs-bar pacs-bar-pacing";const s=document.createElement("span");s.className="pacs-bar-fill",t.appendChild(s);const i=document.createElement("span");return i.className="pacs-waiting-note",i.textContent="QUERYING THE PACS…",e.append(t,i),e}envelope_observe(e){const t=/✓ wrote (\S+)/.exec((e.rendered??"").replace(/\x1b\[[0-9;]*m/g,""));if(t!==null&&this.wrote_show(t[1]),e.model?.kind===I0){const i=D0.safeParse(e.model.data);i.success&&this.servers_take(i.data.servers);return}if(e.model?.kind!==T0)return;const s=A0.safeParse(e.model.data);s.success&&this.results_render(s.data)}progress_observe(e){if(e.operation!=="pull"||e.itemId===void 0)return;const t=e.status??"running",s={status:t};e.current!==void 0&&(s.current=e.current),e.total!==void 0&&(s.total=e.total),this.badgeState_set(e.itemId,s),t==="done"&&this.model!==null&&mE(this.model,e.itemId,e.current??e.total,e.path)&&this.results_repaint()}badgeState_set(e,t){this.badgeStates.set(e,t),iM.set(e,t),this.seriesProgress.set(e,vE(t,this.seriesProgress.get(e))),zE(e,s=>this.badge_paint(s,t));for(const[s,i]of this.studyTracks)i.uids.includes(e)&&this.studyTrack_paint(s);for(const[s,i]of this.patientTracks)i.uids.includes(e)&&this.patientTrack_paint(s)}badge_build(e){const t=document.createElement("span");if(t.className="pacs-badge",e.pulled===!0){const s=document.createElement("span");s.className="pacs-bar-full";const i=document.createElement("span");return i.className="pacs-badge-note",i.textContent=e.pulledFiles!==void 0?`✓ ${e.pulledFiles} IN CUBE`:"✓ IN CUBE",t.append(s,i),t.dataset.state="done",t}return nM(e.seriesUID,t),this.badge_paint(t,this.badgeStates.get(e.seriesUID)??{status:"idle"}),t}badge_paint(e,t){rM(e,t)}results_render(e){const t=this.model!==null&&this.model.queryId===e.queryId;if(this.model=e,this.provenance_show(e.provenance),!t){this.listing.open_clear(),this.badgeStates.clear();const s=this.patientRows_build(e),i=s.length===1?s[0]:void 0;i!==void 0&&i.studies.length>0&&this.listing.open_set(0,[i.key]),e.studies.length===1&&this.listing.open_set(1,[Tp(e.studies[0],0)])}for(const s of e.studies)for(const i of s.series)t&&this.badgeStates.has(i.seriesUID)||this.seriesProgress.set(i.seriesUID,yE(i));this.results_repaint()}results_repaint(){const e=this.model;if(this.studyTracks.clear(),this.patientTracks.clear(),e===null){this.listing.rows_set([],{field:"pacs"});return}this.listing.rows_set([{key:String(e.queryId),rows:this.patientRows_build(e)}],{field:String(e.queryId)})}studyTrack_paint(e){const t=this.studyTracks.get(e);if(t===void 0)return;const s=t.uids.map(i=>this.seriesProgress.get(i)??{done:0,total:0});t.mount.replaceChildren(bl(So(s)))}stateLine_compose(e){queueMicrotask(()=>{this.shownGather_render(),this.shownPull_render()});const t=[],s=this.model?.patients??[];if(s.length>0){const i=r=>s.filter(a=>a.status===r).length;t.push(`FOUND ${i("found")} · NONE ${i("none")} · UNASKED ${i("unasked")}`)}return e.filter!==""&&t.push(e.filter),t.join(" · ")}filter_toggle(e){this.listing.filter_toggle(e)}shown_candidates(){const e=[];if(!this.filtering()){for(const t of this.model?.studies??[])for(const s of t.series)e.push({study:t,series:s});return e}for(const t of this.root.querySelectorAll("#pacs-results .pacs-series")){const s=t.dataset.seriesuid;if(s!==void 0)for(const i of this.model?.studies??[]){const r=i.series.find(a=>a.seriesUID===s);r!==void 0&&e.push({study:i,series:r})}}return e}filtering(){return this.listing.filterText_get()!==""}shown_gatherable(){return this.shown_candidates().filter(({series:e})=>kn(e).gather&&!this.handlers.gathered_is(e.seriesUID))}shownGather_render(){const e=this.root.querySelector("#pacs-gather-shown");if(e===null)return;const t=this.shown_gatherable().length;e.hidden=t===0,e.textContent=this.filtering()?`GATHER ${t} SHOWN`:`GATHER ${t}`}shown_pullable(){return this.shown_candidates().map(({series:e})=>e).filter(e=>kn(e).pull&&e.vfsPath!==void 0)}shownPull_render(){const e=this.root.querySelector("#pacs-pull-shown");if(e===null)return;const t=this.shown_pullable().length;e.hidden=t===0,e.textContent=this.filtering()?`PULL ${t} SHOWN`:`PULL ${t}`}shown_pull(){const e=this.shown_pullable();if(e.length===0)return;const t=e.map(s=>`"${s.vfsPath}"`).join(" ");this.handlers.command_show(`pull ${t}`);for(const s of e)this.badgeState_set(s.seriesUID,{status:"queued"});this.handlers.note(`pull: ${e.length} series asked for`),this.shownPull_render()}shown_gather(){const e=this.shown_gatherable();if(e.length!==0){for(const{study:t,series:s}of e)this.gather_note(t,s);this.handlers.note(this.filtering()?`gather: ${e.length} series gathered from what the filter left showing`:`gather: ${e.length} series gathered from the whole answer`),this.shownGather_render()}}gather_note(e,t){t.vfsPath!==void 0&&(this.handlers.gather_add({seriesUID:t.seriesUID,description:t.description,modality:t.modality,series:t,patient:e.patientId||e.patientName,...e.description===void 0||e.description===""?{}:{study:e.description},vfsPath:t.vfsPath,...t.folderPath!==void 0?{folderPath:t.folderPath}:{},...t.fileCount!==void 0?{files:t.fileCount}:{}}),this.selected_refresh())}stage_lit(e){this.litFolders=e,this.selected_refresh()}selected_refresh(){this.listing.indication_refresh()}}function Tp(n,e){return n.studyUID??`study-${e}`}function Gp(n){return n.replace(/\/$/,"")}function yE(n){const e=n.pulledFiles??0,t=Math.max(n.fileCount??0,e);return n.pulled===!0?{done:t,total:t}:{done:e,total:t}}function vE(n,e){const t=n.total??e?.total??0;return n.status==="error"?{done:n.current??e?.done??0,total:t,failed:!0}:n.status==="done"?{done:t,total:t}:{done:n.current??e?.done??0,total:t}}function mn(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`PACS workspace is missing '${e}'`);return t}function Go(n,e){const t=mn(n,e);if(!(t instanceof HTMLInputElement))throw new Error(`'${e}' is not an input`);return t}function Rp(n){const e=document.createElement("p");return e.className="files-empty",e.textContent=n,e}function Bp(n){return(n.kind??"series")==="series"?void 0:n.vfsPath}const Cc="cohort";function OE(n){return/[",\n\r]/.test(n)?`"${n.split('"').join('""')}"`:n}function xE(n){const e=document.createElement("p");return e.className="files-empty",e.textContent=n,e}class Np{handlers;title;cohort;greeted=!1;listing;cohortActions;seriesActions;constructor(e,t,s,i){this.handlers=s,this.cohort=i,i.watch(()=>{this.unsaved=!0,this.render()}),this.title=e.querySelector(".gather-title"),this.cohortActions=this.cohortActions_declare(),this.seriesActions=this.seriesActions_declare(),this.listing=new Qr({mount:t,traits:this.cohortTraits_declare(),key:r=>r.key,chrome:{root:e,prefix:"gather"},control:"fold",actions:{of:()=>this.cohortActions},row:{className:()=>"gather-cohort-row",groupClassName:()=>"gather-cohort",decorate:r=>{r.title="the cohort: click for its verbs, the fold cell folds its series"}},child:kr(()=>[...this.cohort.members_get()].map(r=>({entry:r})),{traits:this.seriesTraits_declare(),key:r=>r.entry.seriesUID,address:r=>r.entry.vfsPath,actions:{of:()=>this.seriesActions},row:{className:()=>"gather-series",decorate:(r,a)=>{r.dataset.seriesuid=a.entry.seriesUID}}}),state:r=>this.stateLine_compose(r),empty:()=>xE("NOTHING GATHERED")}),this.pullBlock=e.querySelector(".gather-pull"),this.pullBlock?.addEventListener("click",()=>this.cohort_pull()),this.emptyBlock=e.querySelector(".gather-remove"),this.emptyBlock?.addEventListener("click",()=>{this.cohort_clear()}),this.processBlock=e.querySelector(".gather-process"),this.processBlock?.addEventListener("click",()=>{this.cohort_process()}),this.render()}pullBlock=null;emptyBlock=null;unsaved=!1;processBlock=null;cohort_empty(){this.cohort.size()!==0&&(this.cohort.clear(),this.handlers.changed(),this.render())}async cohort_clear(){if(this.cohort.size()!==0){if(this.unsaved){const e=await this.handlers.confirm_ask(`Save the cohort first? (${this.cohort.size()} ${this.cohort.size()===1?"member":"members"}, unsaved)`);if(e===null||e==="y"&&!await this.manifest_save())return}this.handlers.command_show("gather clear"),this.cohort_empty()}}away(){return[...this.cohort.members_get()].filter(e=>e.folderPath===void 0&&e.series?.pulled!==!0)}cohort_pull(){const e=this.away();if(e.length===0)return;const t=e.map(s=>`"${s.vfsPath}"`).join(" ");this.handlers.command_show(`pull ${t}`)}render_now(){this.render()}has(e){return this.cohort.has(e)}entries_get(){return[...this.cohort.members_get()]}name_get(){return this.cohort.name_get()}feed_get(){return this.cohort.feed_get()}feed_set(e){e!==null&&this.cohort.feed_set(e),this.render()}name_set(e){e!==null&&this.cohort.name_set(e),this.render()}series_add(e){this.cohort.take(e),this.render(),this.handlers.changed()}series_remove(e){this.cohort.drop(e)&&(this.render(),this.handlers.changed())}render(){if(this.title!==null&&(this.title.textContent=this.cohort.name_get()===null?"GATHER":`GATHER · ${this.cohort.name_get()??""}`.toUpperCase()),this.listing.rows_set([{key:"gather",rows:[{key:Cc}]}],{field:"gather"}),this.cohort.size()>0&&this.listing.open_set(0,[Cc]),this.pullBlock!==null){const e=this.away().length;this.pullBlock.hidden=e===0,this.pullBlock.textContent=`PULL ${e}`}this.emptyBlock!==null&&(this.emptyBlock.hidden=this.cohort.size()===0,this.emptyBlock.textContent=`CLEAR ${this.cohort.size()}`),this.processBlock!==null&&(this.processBlock.hidden=this.cohort.size()===0),this.greeted||(this.greeted=!0,this.listing.row_indicate(Cc))}cohortTraits_declare(){return[{key:"fold",label:"",className:"pacs-fold",capped:!1,width:"5.2em",cell:()=>{const e=document.createElement("span");return e.className="pacs-fold",e}},{key:"name",label:"COHORT",className:"gather-cohort-name",width:"1fr",cell:()=>this.cohort.name_get()??"(unnamed — SAVE names it)"},{key:"series",label:"SERIES",className:"gather-cohort-count",width:"6em",cell:()=>String(this.series_count()),compare:()=>this.series_count()},{key:"patients",label:"PATIENTS",className:"gather-cohort-patients",width:"7em",cell:()=>String(this.patients_count()),compare:()=>this.patients_count()},{key:"feed",label:"FEED",className:"gather-cohort-feed",width:"7em",cell:()=>{if(this.cohort.feed_get()===null)return"—";const e=document.createElement("button");e.className="gather-feed listing-capsule listing-action-selected",e.textContent=`FEED ${this.cohort.feed_get()?.feedId??0}`,e.title="open the feed's graph beside the cohort";const t=this.cohort.feed_get()?.feedId??0;return e.addEventListener("click",s=>{s.stopPropagation(),this.handlers.feed_open(t)}),e},compare:()=>this.cohort.feed_get()?.feedId??-1}]}seriesTraits_declare(){const e=aM(i=>i.entry.series??{seriesUID:i.entry.seriesUID,description:i.entry.description,modality:i.entry.modality,...i.entry.files===void 0?{}:{fileCount:i.entry.files},...i.entry.folderPath===void 0?{}:{pulled:!0,folderPath:i.entry.folderPath}},_E),t={key:"patient",label:"MRN",className:"gather-series-patient",width:"8em",cell:i=>i.entry.patient||"—"},s={key:"study",label:"STUDY",className:"gather-series-study",width:"14em",cell:i=>i.entry.study??"—"};return[...e.slice(0,1),s,t,...e.slice(1)]}cohortActions_declare(){const e=()=>({count:this.cohort.size(),feed:this.cohort.feed_get()?.feedId??null}),t={save:()=>{this.manifest_save()},export:()=>{this.cohort_export()},feed:()=>{this.feed_ensure()},process:()=>{this.cohort_process()},dismiss:()=>this.handlers.dismiss()};return sM.rules.map(s=>({label:s.label(e()),offered:()=>s.offered(e()),run:()=>t[s.name]?.()}))}seriesActions_declare(){const e=s=>({folderKnown:(s.entry.kind??"series")!=="series"||s.entry.folderPath!==void 0,imagery:(s.entry.kind??"series")==="series"||s.entry.imagery===!0,pullable:(s.entry.kind??"series")==="series"&&s.entry.folderPath===void 0&&s.entry.series?.pulled!==!0&&s.entry.vfsPath!==""}),t={remove:s=>this.series_remove(s.entry.seriesUID),pull:s=>this.handlers.command_show(`pull "${s.entry.vfsPath}"`),image:s=>{const i=s.entry.folderPath??Bp(s.entry);i!==void 0&&this.handlers.image_open(i)},process:s=>{const i=s.entry.folderPath??Bp(s.entry);if(i!==void 0){this.handlers.process_open(i);return}this.handlers.note(`gather: ${s.entry.description||s.entry.seriesUID} is not in CUBE yet — PULL it first, then PROCESS it.`)}};return tM.rules.map(s=>({label:s.label({folderKnown:!0,pullable:!0}),offered:i=>s.offered(e(i)),run:i=>t[s.name]?.(i)}))}patients_count(){return new Set(this.cohort.members_get().filter(e=>(e.kind??"series")==="series").map(e=>e.patient)).size}series_count(){return this.cohort.members_get().filter(e=>(e.kind??"series")==="series").length}stateLine_compose(e){const t=this.cohort.members_get(),s=t.filter(o=>(o.kind??"series")!=="series").length,i=t.length-s,r=[];(i>0||s===0)&&r.push(`${i} SERIES`),s>0&&r.push(`${s} ${s===1?"PLACE":"PLACES"}`),s===0&&r.push(`${this.patients_count()} PATIENTS`);const a=[r.join(" · ")];return e.filter!==""&&a.push(e.filter),a.join(" · ")}async name_ensure(){if(this.cohort.name_get()!==null)return this.cohort.name_get();const t=(await this.handlers.name_ask(`gather-${new Date().toISOString().slice(0,10)}`)??"").trim();return t===""?null:(this.cohort.name_set(t),this.render(),t)}async manifest_save(){if(this.cohort.size()===0)return!1;const e=await this.name_ensure();if(e===null)return!1;const t=JSON.stringify({name:e,gatheredAt:new Date().toISOString(),series:[...this.cohort.members_get()].map(s=>({seriesUID:s.seriesUID,description:s.description,modality:s.modality,patient:s.patient,vfsPath:s.vfsPath}))});return this.handlers.command_run("mkdir -p ~/gather"),this.handlers.command_show(`touch --withContents '${t}' ~/gather/${e}.json`),this.unsaved=!1,!0}async cohort_export(){if(this.cohort.size()===0)return;const e=await this.name_ensure();if(e===null)return;const t=[["patient","series","modality","seriesUID","path"].join(","),...[...this.cohort.members_get()].map(s=>[s.patient,s.description,s.modality,s.seriesUID,s.vfsPath].map(OE).join(","))];this.handlers.command_run("mkdir -p ~/gather"),this.handlers.command_show(`touch --withContents '${t.join(`
|
|
4228
4228
|
`)}' ~/gather/${e}.csv`)}async feed_ensure(){const e=this.cohort.feed_get();if(e!==null)return e;if(this.cohort.size()===0)return null;const t=this.cohort.members_get().filter(a=>(a.kind??"series")!=="series");if(t.length>0)return this.handlers.note(`gather: this cohort holds ${t.length} ${t.length===1?"place":"places"} as well as series, and a feed is rooted by pulling its members — a place is already in ChRIS. PROCESS one place from its own row, or remove them to make a feed of the series. (Rooting a feed on the whole cohort, places included, is coming: CUBE takes the list.)`),null;const s=await this.name_ensure();if(s===null)return null;const i=[...this.cohort.members_get()].map(a=>a.vfsPath).join(" "),r=await this.handlers.feed_create(`pull --new-feed "${s}" ${i}`);return r!==null&&this.feed_set(r),r}async cohort_process(){const e=await this.feed_ensure();e!==null&&this.handlers.cohort_process({input:e.path,feed:e.feedId,node:e.rootInstanceId})}}class SE{members=new Map;title=null;landed=null;watchers=new Set;watch(e){return this.watchers.add(e),()=>{this.watchers.delete(e)}}changed(){for(const e of[...this.watchers])e()}members_get(){return[...this.members.values()]}size(){return this.members.size}has(e){return this.members.has(e)}take(e){const t=this.members.get(e.seriesUID);this.members.set(e.seriesUID,t===void 0?e:{...t,...e}),this.changed()}drop(e){const t=this.members.delete(e);return t&&this.changed(),t}clear(){this.members.size!==0&&(this.members.clear(),this.changed())}name_get(){return this.title}name_set(e){this.title=e,this.changed()}feed_get(){return this.landed}feed_set(e){this.landed=e,this.changed()}}class AE{grid;startHere;host;paintId=0;constructor(e,t){this.host=t,this.grid=e.querySelector(".launcher-grid"),this.startHere=e.querySelector(".launcher-start"),this.startHere.addEventListener("click",()=>{this.host.startHere_set(!this.host.startHere_get()),this.startHere_render()}),this.startHere_render()}render(){const e=++this.paintId;this.host.tiles().then(t=>{e!==this.paintId||!this.grid.isConnected||(this.grid.replaceChildren(...t.map((s,i)=>this.tile_build(s,i===0))),this.startHere_render())}).catch(()=>{e!==this.paintId||!this.grid.isConnected||this.grid.replaceChildren()})}numeral_press(e){const t=this.grid.querySelector(`[data-numeral="${e}"]`);return t===null?!1:(t.click(),!0)}startHere_render(){const e=this.host.startHere_get();this.startHere.textContent=e?"START HERE · ON":"START HERE · OFF",this.startHere.classList.toggle("pacs-capsule-off",!e)}tile_build(e,t){const s=document.createElement("button");s.className=`launcher-tile${t?" launcher-tile-wide":""}`,s.style.setProperty("--tile-hue",`var(${e.hue})`),s.dataset.numeral=e.numeral,s.title=e.verb,s.addEventListener("click",d=>{d.target instanceof Element&&d.target.closest(".launcher-row, .launcher-figure")!==null||e.enter()});const i=document.createElement("span");i.className="launcher-head";const r=document.createElement("span");r.className="launcher-name",r.textContent=e.name;const a=document.createElement("span");a.className="launcher-numeral",a.textContent=e.numeral,i.append(r);for(const d of e.figures){const u=document.createElement(d.open===void 0?"span":"button");if(u.className=`launcher-figure${d.errored===!0?" launcher-figure-errored":""}`,u.textContent=d.text,d.open!==void 0){const h=d.open;u.addEventListener("click",g=>{g.stopPropagation(),h()})}i.appendChild(u)}i.appendChild(a);const o=document.createElement("span");o.className="launcher-rule";const l=document.createElement("span");l.className="launcher-rows";for(const d of e.rows){const u=document.createElement(d.open===void 0?"span":"button");u.className=`launcher-row${d.arrived===!0?" launcher-row-arrived":""}`;const h=document.createElement("span");h.className=`launcher-dot${d.errored===!0?" launcher-dot-errored":""}`;const g=document.createElement("span");if(g.className="launcher-row-text",g.textContent=d.text,u.append(h,g),d.open!==void 0){const p=d.open,z=document.createElement("span");z.className="launcher-go",z.textContent="›",u.appendChild(z),u.addEventListener("click",m=>{m.stopPropagation(),p()})}l.appendChild(u)}const c=document.createElement("span");return c.className="launcher-verb",c.textContent=e.verb,s.append(i,o,l,c),s}}const EE=/\s--(?:\s|$)/;function Bl(n){const e=EE.exec(n),t=e===null?n:n.slice(0,e.index),s=e===null?"":n.slice(e.index),i=t.lastIndexOf(";"),r=i===-1?0:i+1,a=t.slice(r),o=/^\s*\S+/.exec(a),l=r+(o===null?a.length:o[0].length);return{head:t.slice(0,l),args:t.slice(l),tail:s}}function Cp(n,e){return`cd "${n}"; ${e}`}function DE(n){return/^[A-Za-z0-9_./:@+=,-]+$/.test(n)?n:`"${n.replace(/(["\\])/g,"\\$1")}"`}function oM(n){const e=[],t=/"(?:[^"\\]|\\.)*"|\S+/g;let s=t.exec(n);for(;s!==null;)e.push(s[0]),s=t.exec(n);return e}function Pp(n){return n.length>=2&&n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1).replace(/\\(["\\])/g,"$1"):n}function lM(n){return n.startsWith("-")&&n!=="-"&&!/^-\d/.test(n)}function IE(n,e){const t=oM(Bl(n).args);for(let s=0;s<t.length;s++){const i=t[s]??"";if(i===e){const r=t[s+1];return r===void 0||lM(r)?!0:Pp(r)}if(i.startsWith(`${e}=`))return Pp(i.slice(e.length+1))}return null}function Lp(n,e,t){const s=Bl(n),i=oM(s.args),r=[];let a=!1;const o=t===null||t===""?[]:t===!0?[e]:[e,DE(t)];for(let c=0;c<i.length;c++){const d=i[c]??"";if(d===e||d.startsWith(`${e}=`)){if(d===e){const u=i[c+1];u!==void 0&&!lM(u)&&c++}a||(r.push(...o),a=!0);continue}r.push(d)}a||r.push(...o);const l=r.length===0?"":` ${r.join(" ")}`;return`${s.head}${l}${s.tail}`}function TE(n){return/\bfeed_title=/.test(Bl(n).tail)}function GE(n,e){return`${n} -- feed_title="${e.replace(/(["\\])/g,"\\$1")}"`}function Wp(n){return Bl(n).head.replace(/^.*;\s*/,"").trim()}function RE(n,e,t){return/^[A-Za-z0-9_-]+$/.test(n)&&t.filter(i=>i===n).length===1?n:`@${e}`}function BE(n){return(n.replace(/\[[0-9;]*m/g,"").split(`
|
|
4229
|
-
`).find(s=>s.trim().length>0)?.trim()??"").replace(/\s*\((?:[\d,]+\/[\d,]+(?:,\s*\d+%)?|initializing)\)(?=\.?$)/,"")}function Pc(n,e){const t=nd(n);if(t===null)return null;let s=0,i=0,r=0;for(const o of e.all()){const l=o.groups.filter(c=>c.plugin===t);if(l.length!==0){s+=1;for(const c of l)i+=c.count,r+=c.errored}}const a=i===0?0:Math.round(r/i*100);return`${t} · ${s.toLocaleString("en-US")} feed${s===1?"":"s"} · ${a}% errored`}class cM{byId=new Map;take(e){let t=!1;for(const s of e){const i=this.byId.get(s.id);i!==void 0&&i.status===s.status&&i.jobs===s.jobs&&JSON.stringify(i.groups)===JSON.stringify(s.groups)||(this.byId.set(s.id,{...s,chain:[...s.chain],groups:s.groups.map(r=>({...r}))}),t=!0)}return t}size(){return this.byId.size}shapes(){return new Set([...this.byId.values()].map(Es)).size}all(){return[...this.byId.values()]}get(e){return this.byId.get(e)}clear(){this.byId.clear()}}function dM(n,e){const t=n.match(/^feed:(\d+):(\d+)$/);if(t===null)return null;const s=e.get(Number(t[1])),i=s?.groups[Number(t[2])];if(s===void 0||i===void 0)return null;const r=i.count>1?` ×${i.count.toLocaleString("en-US")}`:"",a=s.title.length>0?` · ${s.title}`:"",o=i.errored>0&&i.count>1?`${i.errored.toLocaleString("en-US")} errored`:i.status;return`${i.plugin}${r} · ${o} · feed ${s.id}${a}`}function NE(n,e){return`argus.universe.${n}@${e}`}const Mi={draw:"stars",view:"feeds",scale:"jobs",density:"shape",arrangement:"galaxy",captions:!0};function CE(n,e,t,s,i=Mi.arrangement,r=Mi.captions){return{draw:n,view:e,scale:t,density:s,arrangement:i,captions:r}}function PE(n){let e={};try{const s=n===null?null:JSON.parse(n);s!==null&&typeof s=="object"&&!Array.isArray(s)&&(e=s)}catch{}const t=(s,i,r)=>typeof s=="string"&&i.includes(s)?s:r;return{draw:t(e.draw,["stars","spheres"],Mi.draw),view:t(e.view,["feeds","shapes"],Mi.view),scale:t(e.scale,["jobs","feeds"],Mi.scale),density:t(e.density,["shape","census"],Mi.density),arrangement:t(e.arrangement,["galaxy","spokes","clumps","constellations","data","accretion"],Mi.arrangement),captions:typeof e.captions=="boolean"?e.captions:Mi.captions}}function kp(n){if(n===null||n.length===0)return{};try{const e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[s,i]of Object.entries(e))Array.isArray(i)&&i.length===3&&i.every(r=>typeof r=="number"&&Number.isFinite(r))&&(t[s]=[i[0],i[1],i[2]]);return t}catch{return{}}}function Lc(n,e){return`inst:${n}:${e}`}function LE(n){const e=new Set(n.nodes.map(i=>i.id)),t=[],s=new Map;for(const i of n.nodes){const r=Lc(n.feedId,i.id),a=i.parentIds.filter(d=>e.has(d)).map(d=>Lc(n.feedId,d)),o=i.tally?.count??1,l=i.tally?.error??(i.status==="finishedWithError"?1:0),c=l>0&&o>0?Math.min(1,l/o):void 0;t.push({id:r,label:i.pluginName,parentIds:a,joinParentIds:i.joinParentIds.filter(d=>e.has(d)).map(d=>Lc(n.feedId,d)),status:i.status,metric:jr(o),...o>1?{count:o}:{},...c!==void 0?{share:c}:{}}),s.set(r,i)}return{nodes:t,payloads:s}}function WE(n,e,t,s="jobs",i=!1,r){const a=r??(i?fu(n,s):Fa(n,s)),o=`feed:${e}:`;return{nodes:[...a.nodes.filter(c=>!c.id.startsWith(o)).map(c=>({...c,dim:!0})),...t.nodes]}}function uM(n,e){return e.groups.map((t,s)=>wi(n,s))}function hM(n,e=3){const t=vl(n).split(" > ");return t.length<=e?t.join(" > "):`${t.slice(0,e).join(" > ")} … +${t.length-e}`}function kE(n,e){if(!n.startsWith("shape:"))return null;const t=n.slice(6),s=e.all().filter(i=>Es(i)===t).length;return`${vl(t)} · ${s} feed${s===1?"":"s"}`}function UE(n,e){const t=[];for(const s of e.all())Es(s)===n&&t.push(...uM(s.id,s));return t}function FE(n,e,t="jobs"){const s=Fa(n,t),i=new Set(n.filter(a=>Es(a)===e).map(a=>a.id));return{nodes:s.nodes.map(a=>{if(a.ghost===!0)return a.id===Am(e)?a:{...a,dim:!0};const o=a.id.match(/^feed:(\d+):/);return o!==null&&i.has(Number(o[1]))?a:{...a,dim:!0}})}}function fM(n,e="jobs"){const t=new Map;for(const i of[...n].sort((r,a)=>r.id-a.id)){if(i.groups.length===0)continue;const r=Es(i),a=t.get(r)??[];a.push(i),t.set(r,a)}const s=[];for(const[i,r]of t)r[0].groups.forEach((o,l)=>{let c=0,d=0;for(const h of r){const g=h.groups[l];g!==void 0&&(c+=g.count,g.errored>0&&(d+=1))}const u=d>0?Math.min(1,d/r.length):void 0;s.push({id:od(i,l),label:o.plugin,parentIds:o.parent===null?[]:[od(i,o.parent)],joinParentIds:[],status:d===r.length?"finishedWithError":"finishedSuccessfully",metric:jr(e==="feeds"?r.length:c),...r.length>1?{count:r.length}:{},...u!==void 0?{share:u}:{}})});return{nodes:s}}function jE(n,e){const t=n.match(/^fold:(.+):(\d+)$/);if(t===null)return null;const s=t[1],i=Number(t[2]),r=e.all().filter(d=>Es(d)===s),a=r[0]?.groups[i]?.plugin;if(a===void 0)return null;const o=r.filter(d=>(d.groups[i]?.errored??0)>0).length,l=`${r.length.toLocaleString("en-US")} feed${r.length===1?"":"s"}`,c=o>0?` · ${o.toLocaleString("en-US")} with errors`:"";return`${a} · ${l}${c} · ${hM(s)}`}function Up(n,e){const t=e.all().find(s=>Es(s)===n);return t===void 0?[]:t.groups.map((s,i)=>od(n,i))}function Fp(n,e,t="jobs"){const s=n.filter(l=>Es(l)===e),i=n.filter(l=>Es(l)!==e),r=fM(i,t),a=Fa(s,t),o=a.nodes.filter(l=>l.ghost!==!0).map(l=>l.id);return{graph:{nodes:[...r.nodes.map(l=>({...l,dim:!0})),...a.nodes]},memberIds:o}}const $E=6e4,jp=1e4,VE=new Set(["running","scheduled","created","started"]),HE=[/\/proc\/jobs\/feed_(\d+)(?:\/|$)/,/\/feeds?\/feed_(\d+)(?:\/|$)/],qE={running:"started",done:"finishedSuccessfully",error:"finishedWithError"};function $p(n){if(n.jobsTotal===void 0||n.jobsDone===void 0)return null;const e=n.status==="finishedWithError"||n.status==="cancelled",t=n.jobsErrored===void 0?void 0:n.jobsDone-n.jobsErrored;return{done:n.jobsDone,total:n.jobsTotal,...e?{failed:!0}:{},...t!==void 0?{succeeded:t}:{}}}function XE(n){const e=[];return n.layout==="molecule"&&e.push("dag layout molecule"),n.projection==="2d"&&e.push("dag projection 2d"),n.scale==="size"&&e.push("dag scale size"),n.hue==="compute"&&e.push("dag hue compute"),n.census==="census"&&e.push("dag census"),e}const YE=[{key:"control",label:"",className:"feedlist-control",capped:!1,width:"5.2em",cell:()=>{const n=document.createElement("span");return n.className="feedlist-control listing-capsule",n.textContent="OPEN",n}},{key:"id",label:"ID",className:"feedlist-id",width:"4em",cell:n=>String(n.id),compare:n=>n.id},{key:"title",label:"TITLE",className:"feedlist-title",width:"24em",cell:n=>n.title||"(untitled)",compare:n=>n.title},{key:"progress",label:"PROGRESS",className:"feedlist-progress",width:"1fr",cell:n=>bl($p(n)),compare:n=>{const e=$p(n);return e===null||e.total===0?-1:e.done/e.total}},{key:"status",label:"STATUS",className:"feedlist-status",width:"8em",cell:n=>n.status.toUpperCase(),compare:n=>n.status},{key:"nodes",label:"NODES",className:"feedlist-nodes",width:"4em",cell:n=>n.jobsTotal===void 0?"—":String(n.jobsTotal),compare:n=>n.jobsTotal??-1},{key:"sizeBytes",label:"SIZE",className:"feedlist-size",width:"5.5em",cell:n=>n.sizeBytes===void 0?"—":mM(n.sizeBytes),compare:n=>n.sizeBytes??-1},{key:"wallSeconds",label:"TIME",className:"feedlist-time",width:"6em",cell:n=>n.wallSeconds===void 0?"—":pM(n.wallSeconds),compare:n=>n.wallSeconds??-1},{key:"owner",label:"OWNER",className:"feedlist-owner",width:"7em",cell:n=>n.owner},{key:"createdAt",label:"CREATED",className:"feedlist-created",width:"7em",cell:n=>n.createdAt.slice(0,10),compare:n=>n.createdAt}];function Vp(n,e){return n.nodes.length===e.nodes.length&&e.nodes.every((t,s)=>{const i=n.nodes[s];return i!==void 0&&i.id===t.id&&(i.tally?.count??1)===(t.tally?.count??1)&&i.parentIds.length===t.parentIds.length&&i.joinParentIds.length===t.joinParentIds.length})}class KE{scene;canvas;title;facts;empty;strategyPill;feedList;handlers;rosterTimer=null;shownFeedId=null;pinnedFeedId=null;requestedFeedId=null;defaultTitle;metricMode="time";lastModel=null;lastRoster=[];arrivals=new Set;arrivalsKey="";listing;stateSpan;watchedFeedId=null;liveState=null;pendingFeedId=null;lastCwd=null;constructor(e,t,s,i,r,a,o){this.feedList=a,this.canvas=e,e.style.display="none",this.title=t,this.defaultTitle=t.textContent??"",this.facts=s,this.empty=i,this.strategyPill=r,this.handlers=o;const l=r.closest(".pane-dag");this.stateSpan=l?.querySelector(".pane-state")??null,this.modeSpan=l?.querySelector(".pane-mode")??null;const c=o.feed_verbs;this.listing=new Qr({mount:this.feedList,traits:YE,key:f=>String(f.id),chrome:l===null?void 0:{root:l,prefix:"runs"},actions:c===void 0?void 0:{of:f=>c(f)},control:"control",activate:f=>this.feed_activate(f),indicated:f=>this.handlers.feed_indicated?.(f),row:{className:f=>`feedlist-row feedlist-${f.status}${this.arrivals.has(f.id)?" feedlist-arrived":""}`,decorate:(f,_)=>{f.dataset.feed=String(_.id),f.title=c===void 0?"enter the feed (Esc returns to this list)":"click to indicate, double-click to enter (Esc returns to this list)"}},state:f=>this.canvas.style.display==="block"?null:f.filter,defaultSort:{key:"createdAt",dir:"desc"}}),this.rosterTimer=setInterval(()=>{if(!this.feedList.isConnected||!this.rosterShown||this.rosterPending||document.visibilityState!=="visible")return;const _=this.lastRoster.some(O=>VE.has(O.status))?jp:$E;Date.now()-this.rosterAskedAt<_||(this.rosterAskedAt=Date.now(),this.handlers.command_run("proc feeds"))},jp),this.scene=new Rl(e,{select:f=>this.facts_show(f),activate:f=>this.node_activate(f),deselect:()=>this.facts.replaceChildren(),tip:f=>this.universeShown?dM(f.id,this.landed):null}),r.addEventListener("click",()=>{const f=this.scene.strategy_get()==="ranked"?"molecule":"ranked";this.scene.strategy_set(f),r.textContent=f.toUpperCase(),this.modes_render()});const d=r.parentElement?.querySelector(".dag-projection")??null;d?.addEventListener("click",()=>{const f=this.scene.projection_get()==="3d"?"2d":"3d";this.scene.projection_set(f),d.textContent=f.toUpperCase(),this.modes_render()});const u=r.parentElement?.querySelector(".dag-pulse")??null;u?.classList.add("rail-off"),u?.addEventListener("click",()=>{const f=!this.scene.waveLoop_get();this.scene.waveLoop_set(f),u.textContent=f?"PULSE ON":"PULSE OFF",u.classList.toggle("rail-off",!f),this.modes_render()});const h=r.parentElement?.querySelector(".dag-scale")??null;h?.addEventListener("click",()=>{this.metricMode=this.metricMode==="time"?"size":"time",h.textContent=this.metricMode==="time"?"TIME":"SIZE",this.lastModel!==null&&this.graph_show(this.lastModel,!1),this.modes_render()}),this.scalePill=h;const g=r.parentElement?.querySelector(".dag-census")??null;g?.addEventListener("click",()=>{const f=!this.scene.census_get();this.scene.census_set(f),g.textContent=f?"CENSUS":"SHAPE",this.modes_render()});const p=r.parentElement?.querySelector(".dag-gravity")??null;p?.classList.add("rail-off"),p?.addEventListener("click",()=>{const f=!this.scene.physics_get().gravity;this.scene.physics_set({gravity:f}),p.textContent=f?"GRAVITY ON":"GRAVITY OFF",p.classList.toggle("rail-off",!f),this.modes_render()});const z=r.parentElement?.querySelector(".dag-hue")??null;z?.addEventListener("click",()=>{this.hueMode=this.hueMode==="status"?"compute":"status",z.textContent=this.hueMode.toUpperCase(),this.lastModel!==null&&this.graph_show(this.lastModel,!1),this.hueMode==="compute"&&!this.computeKnown&&this.shownFeedId!==null&&this.canvas.style.display!=="none"&&(this.computeRereading=!0,this.handlers.command_run(`proc refresh ${this.shownFeedId}`),this.refresh()),this.modes_render()}),this.huePill=z,r.closest(".pane-dag")?.addEventListener("argus:dag-physics",f=>{const _=f.detail;if(_==="reset"){this.scene.physics_set({charge:!0,link:!0,collide:!0});return}if(_.term==="gravity"){this.scene.physics_get().gravity!==_.on&&p?.click();return}this.scene.physics_set({[_.term]:_.on})}),new MutationObserver(()=>this.scene.palette_refresh()).observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),window.addEventListener("resize",()=>this.scene.size_fit()),new MutationObserver(()=>{window.setTimeout(()=>this.scene.size_fit(),600)}).observe(document.body,{attributes:!0,attributeFilter:["data-zoom"]})}envelope_observe(e){if(e.model?.kind===vm){const r=ym.safeParse(e.model.data);r.success&&this.universe_show(r.data);return}if(e.model?.kind===wm){this.rosterPending=!1;const r=_m.safeParse(e.model.data);r.success&&(this.universe_end(!0),this.chooser_show(r.data.feeds));return}if(this.pendingFeedId!==null&&e.status==="error"&&e.model===void 0){this.feedRequest_refuse(e.renderedErr??e.rendered??"");return}if(this.rosterPending&&e.status==="error"){this.rosterPending=!1,this.rosterRefusal_show(e),this.universe_request();return}if(e.model?.kind===zi.feedIndexing){const r=h0.safeParse(e.model.data);if(!r.success)return;this.requestedFeedId===r.data.feedId?this.requestedFeedId=null:this.pendingFeedId!==r.data.feedId&&(this.pinnedFeedId=r.data.feedId,this.pendingFeedId=r.data.feedId),this.feedIndexing_show(r.data);return}if(e.model?.kind!==zi.feedDag)return;const t=td.safeParse(e.model.data);if(!t.success)return;const s=t.data;this.requestedFeedId===s.feedId?this.requestedFeedId=null:this.pinnedFeedId=s.feedId,this.universe_end(!1),this.shownFeedId=s.feedId,this.pendingFeedId=null,this.stateSpan?.classList.remove("state-wait"),this.title.textContent=`DAG · FEED ${s.feedId} — ${s.feedName}`.toUpperCase(),this.empty.style.display="none",this.roster_show(!1),this.canvas.style.display="block",this.lastModel!==null&&this.lastModel.feedId!==s.feedId&&(this.facts.replaceChildren(),this.scene.selection_clear());const i=this.lastModel;this.lastModel=s,i!==null&&i.feedId===s.feedId&&Vp(i,s)?this.statuses_patch(s):this.graph_show(s),this.watch_open(s.feedId),this.handlers.feed_shown?.()}watch_open(e){this.watchedFeedId!==e&&(this.watch_release(),this.watchedFeedId=e,this.liveState_show(null),this.handlers.watch_set?.(`/proc/jobs/feed_${e}`,!0))}watch_release(){this.watchedFeedId!==null&&(this.handlers.watch_set?.(`/proc/jobs/feed_${this.watchedFeedId}`,!1),this.watchedFeedId=null,this.liveState_show(null))}modeSpan=null;hueMode="status";huePill=null;hueLegend=new Map;computeKnown=!1;computeRereading=!1;hueLegend_build(e){const t=getComputedStyle(document.documentElement),s=["--harvestgold","--daybreak","--orange","--honey","--butter","--october-sunset"].map(r=>t.getPropertyValue(r).trim()).filter(r=>r!==""),i=new Map;for(const r of e.nodes){const a=r.computeResource;a===void 0||a==="mixed"||i.has(a)||i.set(a,s[i.size%Math.max(1,s.length)]??"#888")}return i}modes_render(){if(this.modeSpan===null)return;const e=[];if(this.scene.strategy_get()!=="ranked"&&e.push("MOLECULE"),this.scene.projection_get()!=="3d"&&e.push("2D"),this.metricMode!=="time"&&e.push("SIZE"),this.scene.census_get()&&e.push("CENSUS"),this.scene.waveLoop_get()&&e.push("PULSE"),this.scene.physics_get().gravity&&e.push("GRAVITY"),this.modeSpan.replaceChildren(document.createTextNode(e.join(" · "))),this.hueMode==="compute"){const t=document.createElement("span");t.className="pane-legend",t.append(document.createTextNode(e.length>0?" · COMPUTE":"COMPUTE"));for(const[s,i]of this.hueLegend){const r=document.createElement("span");r.className="legend-swatch",r.style.backgroundColor=i;const a=document.createElement("span");a.textContent=s,t.append(document.createTextNode(" "),r,a)}this.hueLegend.size===0&&t.append(document.createTextNode(this.computeRereading?" (re-reading the feed…)":" (none reported)")),this.modeSpan.appendChild(t)}}liveState_show(e){if(this.liveState=e,this.stateSpan!==null){if(this.stateSpan.classList.remove("state-live","state-settled","state-stale"),e===null){this.canvas.style.display!=="none"&&(this.stateSpan.textContent="");return}this.stateSpan.textContent=e.toUpperCase(),this.stateSpan.classList.add(`state-${e}`)}}liveState_get(){return this.liveState}feed_get(){return this.pendingFeedId??this.shownFeedId}graph_isShown(){return this.canvas.style.display==="block"}feedTitle_get(){return(this.title.textContent??"").replace(/^DAG\s*·\s*/i,"").trim()}view_lines(){const e=this.strategyPill.parentElement,t=s=>e?.querySelector(s)?.textContent?.trim().toLowerCase()??"";return XE({layout:t(".dag-strategy"),projection:t(".dag-projection"),scale:t(".dag-scale"),hue:t(".dag-hue"),census:t(".dag-census")})}watched_observe(e,t){const s=/feed_(\d+)$/.exec(e);!s||Number(s[1])!==this.watchedFeedId||this.liveState_show(t)}model_refresh(e){if(this.pendingFeedId===e.feedId&&this.canvas.style.display==="none"){this.envelope_observe({status:"ok",rendered:"",model:{kind:zi.feedDag,data:e}});return}if(this.shownFeedId!==e.feedId||this.canvas.style.display==="none")return;const t=this.lastModel;if(this.lastModel=e,t!==null&&Vp(t,e)){this.statuses_patch(e);return}this.graph_show(e,!1)}statuses_patch(e){for(const t of e.nodes)this.scene.status_update(t.id,t.status),this.factsPayloads.set(t.id,t);this.factsShown!==null&&this.facts_show(this.factsShown)}refresh(){this.shownFeedId===null||this.canvas.style.display==="none"||(this.requestedFeedId=this.shownFeedId,this.handlers.command_run(`feed diagram feed_${this.shownFeedId}`))}scalePill=null;graph_show(e,t=!0){const s=o=>this.metricMode==="time"?o.metrics?.computeSeconds:o.metrics?.dataBytes,i=e.nodes.some(o=>s(o)!==void 0);this.scalePill?.classList.toggle("rail-na",!i),this.scalePill!==null&&(this.scalePill.title=i?"molecule node size: wall time or output bytes":`no ${this.metricMode==="time"?"wall-time":"output-size"} data in this feed's cache yet`),this.hueLegend=this.hueLegend_build(e);const r=e.nodes.some(o=>o.computeResource!==void 0);this.computeKnown=r,r&&(this.computeRereading=!1),this.huePill?.classList.toggle("rail-na",!r),this.huePill!==null&&(this.huePill.title=r?"what colors a node: its status, or the compute resource it ran on":"no compute resource reported for this feed's nodes yet");const a=o=>{if(this.hueMode==="compute")return o.computeResource===void 0?"#555":this.hueLegend.get(o.computeResource)??"#555"};this.scene.graph_set({nodes:e.nodes.map(o=>{const l=a(o);return{id:o.id,label:o.label,parentIds:o.parentIds,joinParentIds:o.joinParentIds,status:o.status,metric:s(o),count:o.tally?.count,...l!==void 0?{hue:l}:{}}})},{wave:t}),this.scene.size_fit(),this.hueMode==="compute"&&this.modes_render(),this.factsPayloads.clear();for(const o of e.nodes)this.factsPayloads.set(o.id,o);this.factsShown!==null&&(this.factsPayloads.has(this.factsShown.id)?this.facts_show(this.factsShown):this.factsShown=null)}factsPayloads=new Map;factsShown=null;promptContext_observe(e){const t=e.procWarmup?.landed??[];if(t.length>0&&this.universeLandings_take(t),this.universeShown&&this.universeLive){const o=e.procWarmup;if(o?.total!==void 0&&o.total>0&&o.sweeping!==!1){const l=Math.floor(o.loaded/o.total*100),c=`INDEX WARMING ${o.loaded.toLocaleString()}/${o.total.toLocaleString()} (${l}%)`;c!==this.universeWarming&&(this.universeWarming=c,this.universeTitle_paint())}else(o===void 0||o.sweeping===!1||o.state==="cached")&&(this.universeLive=!1,this.universeWarming="",this.universe_request())}if(this.rosterProgress!==null&&this.rosterProgress.isConnected){const o=e.procWarmup;if(o?.total!==void 0&&o.total>0&&o.sweeping!==!1){const l=Math.floor(o.loaded/o.total*100);this.rosterProgress.textContent=`INDEX WARMING — ${o.loaded}/${o.total} (${l}%). The roster opens when the index is whole.`}(o===void 0||o.sweeping===!1||o.state==="cached")&&(this.rosterProgress=null,this.feedsChooser_request())}this.arrivals_observe(e.procWarmup?.arrived??[]);const i=(e.procWarmup?.feeds??(e.procWarmup?.feed!==void 0?[e.procWarmup.feed]:[])).find(o=>o.id===this.pendingFeedId);if(i!==void 0&&this.feedIndexing_show({feedId:i.id,loaded:i.loaded,total:i.total,...i.failed!==void 0?{failed:i.failed}:{}}),!this.canvas.isConnected||this.rosterShown||this.pendingFeedId!==null)return;const r=this.lastCwd!==null&&e.cwd!==this.lastCwd;if(this.lastCwd=e.cwd,!r)return;const a=QE(e.cwd);a!==null&&a!==this.shownFeedId&&(this.pinnedFeedId!==null&&a===this.pinnedFeedId||(this.pinnedFeedId=null,this.requestedFeedId=a,this.handlers.command_run(`feed diagram feed_${a}`)))}progress_observe(e){if(e.itemId===void 0)return;const t=e.status!==void 0?qE[e.status]:void 0;t!==void 0&&this.scene.status_update(String(e.itemId),t)}size_fit(){this.scene.size_fit()}dispose(){this.watch_release(),this.rosterTimer!==null&&clearInterval(this.rosterTimer),this.scene.dispose()}feed_enter(e){this.pinnedFeedId=e,this.requestedFeedId=null,this.feedRequest_show(e),this.handlers.command_run(`feed diagram feed_${e}`)}feedRequest_show(e){this.pendingFeedId=e,this.roster_show(!1),this.canvas.style.display="none",this.facts.replaceChildren(),this.title.textContent=`DAG · FEED ${e}`,this.empty.textContent=`RETRIEVING FEED ${e}…`,this.empty.style.display="block",this.stateSpan!==null&&(this.stateSpan.classList.remove("state-live","state-settled","state-stale"),this.stateSpan.classList.add("state-wait"),this.stateSpan.textContent="LOADING")}feedIndexing_show(e){this.pendingFeedId===null&&(this.pendingFeedId=e.feedId),this.roster_show(!1),this.canvas.style.display="none",this.title.textContent=`DAG · FEED ${e.feedId}`;const t=e.total>0?`${e.loaded.toLocaleString()} / ${e.total.toLocaleString()}`:`${e.loaded.toLocaleString()} / ?`;this.empty.textContent=e.failed!==void 0?`INDEXING FEED ${e.feedId} FAILED AT ${t} — ${e.failed.toUpperCase()} — REFRESH RETRIES`:`INDEXING FEED ${e.feedId} — ${t}`,this.empty.style.display="block",this.stateSpan!==null&&(this.stateSpan.classList.remove("state-live","state-settled","state-stale"),this.stateSpan.classList.add("state-wait"),this.stateSpan.textContent=e.failed!==void 0?"FAILED":"LOADING"),e.failed===void 0&&this.watch_open(e.feedId)}feedRequest_refuse(e){const t=this.pendingFeedId;this.pendingFeedId=null,this.empty.textContent=`FEED ${t??"?"}: ${e.trim()||"not available"}`.toUpperCase(),this.empty.style.display="block",this.roster_show(!0),this.title.textContent=this.defaultTitle,this.stateSpan?.classList.remove("state-wait"),this.listing.state_refresh()}feedsChooser_request(){const e=document.createElement("div");e.className="feedlist-loading",e.textContent="RETRIEVING FEED ROSTER…",this.feedList.replaceChildren(e),this.roster_show(!0),this.rosterPending=!0,this.rosterAskedAt=Date.now(),this.handlers.command_run("proc feeds")}rosterPending=!1;rosterShown=!1;rosterAskedAt=0;rosterProgress=null;landed=new cM;universeShown=!1;universeLive=!1;universeRepaint=null;universeStrategyWas=null;universeWarming="";universe_request(){this.handlers.command_run("proc universe")}universe_show(e){this.landed.clear(),this.landed.take(e.feeds),this.universeLive=!e.whole,this.universeShown||(this.universeShown=!0,this.universeStrategyWas=this.scene.strategy_get(),this.scene.strategy_set("molecule"),this.scene.physics_set({gravity:!0})),this.roster_show(!1),this.pendingFeedId=null,this.pinnedFeedId=null,this.empty.style.display="none",this.canvas.style.display="block",this.universe_paint()}universe_paint(){this.lastModel=null,this.scene.graph_set(Fa(this.landed.all()),{wave:!1}),this.universeTitle_paint()}universeTitle_paint(){const e=`${this.landed.size()} FEEDS · ${this.landed.shapes()} SHAPES`;this.title.textContent=this.universeLive?`UNIVERSE — ${e}${this.universeWarming.length>0?` · ${this.universeWarming}`:" · INDEX WARMING"}`:`UNIVERSE — ${e}`,this.stateSpan!==null&&(this.stateSpan.classList.remove("state-live","state-settled","state-stale","state-wait"),this.stateSpan.classList.add(this.universeLive?"state-wait":"state-settled"),this.stateSpan.textContent=this.universeLive?"LANDING":"WHOLE")}universeLandings_take(e){!this.universeShown||!this.universeLive||!this.landed.take(e)||this.universeRepaint!==null||(this.universeRepaint=window.setTimeout(()=>{this.universeRepaint=null,this.universeShown&&this.universe_paint()},1e3))}universe_end(e){this.universeShown&&(this.universeShown=!1,this.universeLive=!1,this.universeWarming="",this.universeRepaint!==null&&(window.clearTimeout(this.universeRepaint),this.universeRepaint=null),this.landed.clear(),this.universeStrategyWas!==null&&(this.scene.strategy_set(this.universeStrategyWas),this.universeStrategyWas=null),this.scene.selection_clear(),e&&(this.canvas.style.display="none"))}rosterRefusal_show(e){const t=BE(e.renderedErr||e.rendered||""),s=t.length>0?t:"the roster request was refused",i=document.createElement("div");i.className="feedlist-refusal",i.textContent=s;const r=document.createElement("div");r.className="feedlist-warming",r.textContent="INDEX WARMING… the roster opens when the index is whole.",this.feedList.replaceChildren(i,r),this.roster_show(!0),this.rosterProgress=r}list_reset(){this.pendingFeedId=null,this.stateSpan?.classList.remove("state-wait"),this.watch_release(),this.facts.replaceChildren(),this.scene.selection_clear(),this.canvas.style.display="none",this.pinnedFeedId=null,this.requestedFeedId=null,this.title.textContent=this.defaultTitle,this.empty.style.display="none"}nav_pop(){return this.pendingFeedId!==null&&this.feedList.childElementCount>0?(this.pendingFeedId=null,this.pinnedFeedId=null,this.requestedFeedId=null,this.empty.style.display="none",this.roster_show(!0),this.title.textContent=this.defaultTitle,this.stateSpan?.classList.remove("state-wait"),this.listing.state_refresh(),!0):this.canvas.style.display==="none"||this.feedList.childElementCount===0?!1:(this.watch_release(),this.canvas.style.display="none",this.pinnedFeedId=null,this.requestedFeedId=null,this.title.textContent=this.defaultTitle,this.facts.replaceChildren(),this.scene.selection_clear(),this.roster_show(!0),this.listing.state_refresh(),!0)}arrivals_observe(e){const t=e.join(",");if(t===this.arrivalsKey)return;this.arrivalsKey=t,this.arrivals=new Set(e);for(const r of this.lastRoster)this.listing.row_element(String(r.id))?.classList.toggle("feedlist-arrived",this.arrivals.has(r.id));const s=new Set(this.lastRoster.map(r=>r.id));e.some(r=>!s.has(r))&&this.rosterShown&&this.feedsChooser_request()}chooser_show(e){this.lastRoster=e,this.empty.style.display="none",this.roster_show(!0),this.listing.rows_set([{key:"roster",rows:e}],{field:"roster"}),this.rosterFrame_track()}feed_activate(e){this.pinnedFeedId=e.id,this.requestedFeedId=null,this.handlers.feed_regard?.(`/proc/jobs/feed_${e.id}`),this.feedRequest_show(e.id),this.handlers.command_run(`feed diagram feed_${e.id}`)}row_indicate(e){this.listing.row_indicate(e===null?null:String(e.id))}rowReadout_show(e,t){this.listing.readout_show(String(e),t)}filter_toggle(e){this.listing.filter_toggle(e)}roster_filter(e){this.listing.filter_toggle(e!==""),this.listing.filter_set(e)}rosterFrameObserver=null;rosterFrame_track(){const e=this.feedList.parentElement,t=this.feedList.querySelector(".roster-order");if(this.rosterFrameObserver?.disconnect(),this.rosterFrameObserver=null,e===null)return;if(t===null){e.style.removeProperty("--mode-frame-top");return}const s=()=>{e.style.setProperty("--mode-frame-top",`${Math.ceil(t.getBoundingClientRect().bottom-e.getBoundingClientRect().top)}px`)};s(),this.rosterFrameObserver=new ResizeObserver(s),this.rosterFrameObserver.observe(t)}roster_show(e){this.rosterShown=e,this.feedList.style.display=e?"flex":"none",this.feedList.parentElement?.classList.toggle("roster-shown",e)}facts_show(e){this.factsShown=e;const t=this.factsPayloads.get(e.id);if(!t){this.facts.textContent=e.label;return}this.handlers.node_regard?.(t.vfsPath),this.facts.replaceChildren();const i=t.status==="finishedSuccessfully"||t.status==="finishedWithError"||t.status==="cancelled"?"awaiting warmup":"in flight",r=t.tally,a=[["PLUGIN",t.pluginName],[r?"REP. INSTANCE":"INSTANCE",String(t.instanceId)],["STATUS",t.status],...r?[["COUNT",`×${r.count} — ${r.done} done, ${r.error} err, ${r.running} live, ${r.other} other`]]:[],...r?.anomalies!==void 0&&r.anomalies.length>0?[["FAULTS",r.anomalies.map(o=>o.id).join(" ")+(r.count>r.done+r.anomalies.length?" …":"")]]:[],["WALL",t.metrics?.computeSeconds!==void 0?pM(t.metrics.computeSeconds):i],["SIZE",t.metrics?.dataBytes!==void 0?mM(t.metrics.dataBytes):i],["DATA",t.vfsPath]];for(const[o,l]of a){const c=document.createElement("div");c.className="telemetry-row";const d=document.createElement("span");d.className="telemetry-label",d.textContent=o;const u=document.createElement("span");u.className="telemetry-value",u.textContent=l,c.append(d,u),this.facts.appendChild(c)}if(this.facts.appendChild(ZE(t.status)),this.handlers.node_process!==void 0){const o=this.handlers.node_process,l=document.createElement("button");l.className="pacs-capsule dag-process",r!==void 0?(l.textContent="PROCESS",l.disabled=!0,l.title=`${r.count} instances stand here: open one to process it`,l.classList.add("pacs-capsule-off")):(l.textContent="PROCESS",l.title=`open /bin bound to ${t.label} — a run appends to this node`,l.addEventListener("click",()=>o({vfsPath:t.vfsPath,instanceId:t.instanceId,label:t.label}))),this.facts.appendChild(l)}}node_activate(e){const t=this.factsPayloads.get(e.id);if(t)if(this.handlers.node_dive!==void 0){const s=this.handlers.node_dive;this.scene.flight_into(e.id,()=>s(t.vfsPath))}else this.handlers.node_enter(t.vfsPath)}detail_clear(){this.scene.selection_clear(),this.facts.replaceChildren()}wave_start(){this.scene.wave_start()}inside_isHeld(){return this.scene.holding_get()}flight_back(e){this.scene.flight_back(e)}node_flyTo(e){for(const[t,s]of this.factsPayloads){if(s.instanceId!==e)continue;if(this.handlers.node_dive===void 0)return!1;const i=this.handlers.node_dive;return this.facts_show({id:t,label:s.label,parentIds:[],joinParentIds:[]}),this.scene.flight_into(t,()=>i(s.vfsPath)),!0}return!1}}function pM(n){const e=Math.round(n);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h ${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}function mM(n){if(n<1024)return`${n}B`;const e=["K","M","G","T"];let t=n,s=-1;for(;t>=1024&&s<e.length-1;)t=t/1024,s=s+1;return`${t<10?t.toFixed(1):Math.round(t)}${e[s]}`}const Wc=[{key:"created",label:"CREATED"},{key:"waiting",label:"WAITING"},{key:"scheduled",label:"SCHEDULED"},{key:"started",label:"STARTED"},{key:"registeringFiles",label:"REGISTERING"}];function ZE(n){const e=document.createElement("div");e.className="dag-subway";const t=n==="finishedSuccessfully",s=n==="finishedWithError"||n==="cancelled",i=Wc.findIndex(l=>l.key===n),r=t||s?Wc.length:i;!t&&!s&&e.classList.add("dag-subway-live");const a=(l,c,d)=>{const u=document.createElement("span");u.className=`subway-step${d?" subway-step-here":""}`;const h=document.createElement("span");h.className=c;const g=document.createElement("span");return g.className="subway-label",g.textContent=l,u.append(h,g),u};Wc.forEach((l,c)=>{if(c>0){const u=document.createElement("span");u.className="subway-link"+(c<=r?" subway-passed":""),e.appendChild(u)}const d=c===i&&!t&&!s;e.appendChild(a(l.label,"subway-stop"+(c<r?" subway-passed":"")+(d?" subway-here":""),d))});const o=document.createElement("span");return o.className="subway-link"+(t||s?" subway-passed":""),e.appendChild(o),e.appendChild(a(t?"FINISHED":s?n==="cancelled"?"CANCELLED":"ERROR":"FINISHED","subway-stop subway-terminal"+(t?" subway-done":"")+(s?" subway-failed":""),!1)),e}function QE(n){for(const e of HE){const t=n.match(e);if(t?.[1]!==void 0)return parseInt(t[1],10)}return null}class JE{root;label;fill;constructor(e){this.root=document.createElement("div"),this.root.className="wait-progress",this.root.hidden=!0,this.root.setAttribute("role","progressbar"),this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax","100"),this.label=document.createElement("span"),this.label.className="wait-progress-label";const t=document.createElement("span");t.className="wait-progress-track",this.fill=document.createElement("span"),this.fill.className="wait-progress-fill",t.appendChild(this.fill),this.root.append(this.label,t),e.appendChild(this.root)}show(e,t){this.root.hidden=!1,this.label.textContent=t===null?e:`${e} · ${Math.floor(t*100)}%`,this.root.classList.toggle("wait-progress-indeterminate",t===null),this.fill.style.width=t===null?"":`${Math.max(0,Math.min(1,t))*100}%`,t===null?this.root.removeAttribute("aria-valuenow"):this.root.setAttribute("aria-valuenow",String(Math.floor(t*100)))}hide(){this.root.hidden=!0}shown(){return!this.root.hidden}}function eD(n){const e={...tr,gravity:!0};return n.charge===e.charge&&n.link===e.link&&n.collide===e.collide&&n.gravity===e.gravity}function Hp(n){let e=0;for(const t of Object.values(n))e+=t[0]*1.3+t[1]*1.7+t[2]*1.9;return`${Object.keys(n).length}:${e.toFixed(2)}`}function kc(n){return n==="constellations"||n==="data"||n==="accretion"}const tD=18e4,sD=1500,nD=1e3,iD=5e3,rD=3e3,Tr=650,aD=650,oD=1.5;class lD{scene;wait;asking=!1;spaceKey="";landed=new cM;canvas;title;state;empty;handlers;store;whole=!1;shown=!1;warming="";repaintTimer=null;lastReask=0;rememberTimer=null;putSignatures=new Map;sessionPlaces=new Map;sessionWait=null;storeKey=null;arrivalsKey="";feedsCount=null;disposed=!1;scale="jobs";view="feeds";inside=null;cluster=null;flying=!1;framedAt=null;entering=null;facts;viewPill=null;gravityPill=null;densityPill=null;density="shape";drawMode="stars";drawPill=null;captionsPill=null;captions=!0;arrangement="galaxy";arrangementPill=null;scalePill=null;physics={...tr,gravity:!0};backPill;openPill;pane;escape_listen;lit=null;dataHubs=new Map;litHub=null;replayPill=null;replayDay="";reach=null;constructor(e,t,s){this.canvas=e.canvas,this.title=e.title,this.state=e.state,this.empty=e.empty,this.handlers=t,this.store=s,this.facts=e.facts,this.backPill=e.backPill,this.openPill=e.openPill,this.pane=e.canvas.closest(".workspace-pane"),this.wait=new JE(e.canvas),this.scene=new Rl(e.canvas,{progress:(i,r,a)=>this.settle_progress(i,r,a),handoffKey:i=>Y0(i.id),tip:i=>this.inside===null?H0(i.id,this.dataHubs)??Pc(i.id,this.landed)??jE(i.id,this.landed)??dM(i.id,this.landed)??kE(i.id,this.landed):null,select:i=>this.node_select(i),activate:i=>{const r=this.inside===null?nd(i.id):null;r!==null?this.plugin_frame(r):this.node_dive(i)},deselect:()=>{this.facts_clear(),this.lit!==null&&this.plugin_light(null)},replay:()=>this.replay_paint(),gesture_end:()=>this.pinch_leave()}),e.backPill?.addEventListener("click",()=>this.ascend()),e.openPill?.addEventListener("click",()=>{this.inside!==null&&this.handlers.feed_open?.(this.inside.feedId)}),this.escape_listen=i=>{if(i.key==="Escape"&&this.scene.replay_state()!==null&&(this.pane===null||this.pane.offsetParent!==null)){this.replay_end();return}i.key!=="Escape"||this.inside===null&&this.cluster===null||this.flying||this.scene.holding_get()||this.pane!==null&&this.pane.offsetParent===null||this.ascend()},window.addEventListener("keydown",this.escape_listen),this.scene.strategy_set("molecule"),this.scene.physics_set(this.physics),e.projectionPill?.addEventListener("click",()=>{const i=this.scene.projection_get()==="3d"?"2d":"3d";this.scene.projection_set(i),e.projectionPill!==null&&(e.projectionPill.textContent=i.toUpperCase())}),e.refreshPill?.addEventListener("click",()=>this.request()),this.replayPill=e.replayPill??null,e.replayPill?.addEventListener("click",()=>{const i=this.scene.replay_state();i===null?this.handlers.note?.(this.replay_start(1)):i.playing?this.scene.replay_pause():this.scene.replay_play(),this.replay_paint()}),e.scalePill?.addEventListener("click",()=>{this.scale=this.scale==="jobs"?"feeds":"jobs",e.scalePill!==null&&(e.scalePill.textContent=this.scale==="jobs"?"JOBS":"ALIKE"),this.shown&&this.paint(!0,"full"),this.settings_save()}),e.viewPill?.addEventListener("click",()=>this.view_set(this.view==="feeds"?"shapes":"feeds")),this.viewPill=e.viewPill,this.gravityPill=e.gravityPill,e.gravityPill?.addEventListener("click",()=>{this.physics_set("gravity",!this.physics.gravity)}),this.densityPill=e.densityPill,e.densityPill?.addEventListener("click",()=>{this.density_set(this.density==="shape"?"census":"shape")}),this.drawPill=e.drawPill??null,this.scalePill=e.scalePill,e.drawPill?.addEventListener("click",()=>{this.draw_set(this.drawMode==="stars"?"spheres":"stars")}),this.captionsPill=e.captionsPill??null,e.captionsPill?.addEventListener("click",()=>{this.handlers.note?.(this.captions_set(!this.captions))}),this.arrangementPill=e.arrangementPill??null,e.arrangementPill?.addEventListener("click",()=>{const i=["galaxy","spokes","clumps","constellations","data","accretion"];this.handlers.note?.(this.arrangement_set(i[(i.indexOf(this.arrangement)+1)%i.length]))}),this.scene.draw_set(this.drawMode),this.canvas.style.display="none",this.title_paint()}request(){this.asking=!0,this.shown||this.wait.show("ASKING THE SESSION FOR THE SPACE",null),this.title_paint(),this.shown||this.handlers.command_run(`proc layout ${this.sessionLayoutName_of(this.arrangement)}`),this.handlers.command_run("proc universe")}settle_progress(e,t,s){if(e>=t){this.wait.hide(),this.remember_later();return}this.wait.show(`SETTLING ${s.toLocaleString("en-US")} SPHERES`,t===0?1:e/t)}envelope_observe(e){if(e.model?.kind===b0){const s=M0.safeParse(e.model.data);s.success&&this.sessionLayout_take(s.data.name,s.data.positions,s.data.laying??null);return}if(e.model?.kind!==vm)return;const t=ym.safeParse(e.model.data);t.success&&this.space_show(t.data)}promptContext_observe(e){if(this.disposed)return;this.identity_note(e.user,e.uri);const t=e.procWarmup?.landed??[];t.length>0&&this.shown&&this.landings_take(t);const s=e.procWarmup;if(s?.total!==void 0&&s.total>0&&s.sweeping!==!1&&!this.whole){const i=Math.floor(s.loaded/s.total*100),r=`INDEX WARMING ${s.loaded.toLocaleString()}/${s.total.toLocaleString()} (${i}%)`;r!==this.warming&&(this.warming=r,this.title_paint())}else this.shown&&!this.whole&&(s===void 0||s.sweeping===!1||s.state==="cached")&&(this.warming="",this.request());if(this.shown&&this.whole){const i=(s?.arrived??[]).join(","),r=e.procIndex?.feeds??null,a=i.length>0&&i!==this.arrivalsKey||r!==null&&this.feedsCount!==null&&r!==this.feedsCount;this.arrivalsKey=i,r!==null&&(this.feedsCount=r),a&&Date.now()-this.lastReask>iD&&(this.lastReask=Date.now(),this.request())}}size_fit(){this.scene.size_fit()}control(e,t){if(e==="enter"){const s=parseInt(t[0]??"",10);return Number.isFinite(s)?this.landed.get(s)===void 0?`universe enter: feed ${s} has not landed here`:this.inside!==null?`universe enter: already inside feed ${this.inside.feedId}; universe back first`:(this.descend(s),`entering feed ${s}`):"universe enter <feed id>"}if(e==="node"){const s=parseInt(t[0]??"",10);return Number.isFinite(s)?this.inside===null?"universe node: not inside a feed (universe enter <feed> first)":this.node_flyTo(s)?`flying into instance ${s}`:`universe node: no node of feed ${this.inside.feedId} hosts instance ${s}`:"universe node <instance id>: fly into the entered feed's node that hosts it"}if(e==="state"){const s=this.scene.state_get(),i=(()=>{const r=this.settingsKey_get();try{return r===null||this.store===void 0?null:this.store.getItem(r)}catch{return null}})();return[`universe: ${this.inside!==null?`inside feed ${this.inside.feedId}`:this.cluster!==null?"in a cluster":"the whole space"}; view ${this.view}, scale ${this.scale}, density ${this.density}`,`scene: ${Object.entries(s).map(([r,a])=>`${r}=${String(a)}`).join(" ")}`,`kept settings: ${i??"(none)"}`,`lit: ${this.lit??"none"}`,`captions: ${this.captions?"on":"off"}`,`session layout: ${(()=>{const r=this.sessionPlaces.get(this.sessionLayoutName_of(this.arrangement));return r===void 0?"not asked":r===null?"none kept":`${r} places kept`})()}`,`replay: ${(()=>{const r=this.scene.replay_state();return r===null?"none":`${r.playing?"playing":"paused"} at ${new Date(r.at).toISOString().slice(0,10)} of ${new Date(r.span[0]).toISOString().slice(0,10)}..${new Date(r.span[1]).toISOString().slice(0,10)}`})()}`].join(`
|
|
4229
|
+
`).find(s=>s.trim().length>0)?.trim()??"").replace(/\s*\((?:[\d,]+\/[\d,]+(?:,\s*\d+%)?|initializing)\)(?=\.?$)/,"")}function Pc(n,e){const t=nd(n);if(t===null)return null;let s=0,i=0,r=0;for(const o of e.all()){const l=o.groups.filter(c=>c.plugin===t);if(l.length!==0){s+=1;for(const c of l)i+=c.count,r+=c.errored}}const a=i===0?0:Math.round(r/i*100);return`${t} · ${s.toLocaleString("en-US")} feed${s===1?"":"s"} · ${a}% errored`}class cM{byId=new Map;take(e){let t=!1;for(const s of e){const i=this.byId.get(s.id);i!==void 0&&i.status===s.status&&i.jobs===s.jobs&&JSON.stringify(i.groups)===JSON.stringify(s.groups)||(this.byId.set(s.id,{...s,chain:[...s.chain],groups:s.groups.map(r=>({...r}))}),t=!0)}return t}size(){return this.byId.size}shapes(){return new Set([...this.byId.values()].map(Es)).size}all(){return[...this.byId.values()]}get(e){return this.byId.get(e)}clear(){this.byId.clear()}}function dM(n,e){const t=n.match(/^feed:(\d+):(\d+)$/);if(t===null)return null;const s=e.get(Number(t[1])),i=s?.groups[Number(t[2])];if(s===void 0||i===void 0)return null;const r=i.count>1?` ×${i.count.toLocaleString("en-US")}`:"",a=s.title.length>0?` · ${s.title}`:"",o=i.errored>0&&i.count>1?`${i.errored.toLocaleString("en-US")} errored`:i.status;return`${i.plugin}${r} · ${o} · feed ${s.id}${a}`}function NE(n,e){return`argus.universe.${n}@${e}`}const Mi={draw:"stars",view:"feeds",scale:"jobs",density:"shape",arrangement:"galaxy",captions:!0};function CE(n,e,t,s,i=Mi.arrangement,r=Mi.captions){return{draw:n,view:e,scale:t,density:s,arrangement:i,captions:r}}function PE(n){let e={};try{const s=n===null?null:JSON.parse(n);s!==null&&typeof s=="object"&&!Array.isArray(s)&&(e=s)}catch{}const t=(s,i,r)=>typeof s=="string"&&i.includes(s)?s:r;return{draw:t(e.draw,["stars","spheres"],Mi.draw),view:t(e.view,["feeds","shapes"],Mi.view),scale:t(e.scale,["jobs","feeds"],Mi.scale),density:t(e.density,["shape","census"],Mi.density),arrangement:t(e.arrangement,["galaxy","spokes","clumps","constellations","data","accretion"],Mi.arrangement),captions:typeof e.captions=="boolean"?e.captions:Mi.captions}}function kp(n){if(n===null||n.length===0)return{};try{const e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[s,i]of Object.entries(e))Array.isArray(i)&&i.length===3&&i.every(r=>typeof r=="number"&&Number.isFinite(r))&&(t[s]=[i[0],i[1],i[2]]);return t}catch{return{}}}function Lc(n,e){return`inst:${n}:${e}`}function LE(n){const e=new Set(n.nodes.map(i=>i.id)),t=[],s=new Map;for(const i of n.nodes){const r=Lc(n.feedId,i.id),a=i.parentIds.filter(d=>e.has(d)).map(d=>Lc(n.feedId,d)),o=i.tally?.count??1,l=i.tally?.error??(i.status==="finishedWithError"?1:0),c=l>0&&o>0?Math.min(1,l/o):void 0;t.push({id:r,label:i.pluginName,parentIds:a,joinParentIds:i.joinParentIds.filter(d=>e.has(d)).map(d=>Lc(n.feedId,d)),status:i.status,metric:jr(o),...o>1?{count:o}:{},...c!==void 0?{share:c}:{}}),s.set(r,i)}return{nodes:t,payloads:s}}function WE(n,e,t,s="jobs",i=!1,r){const a=r??(i?fu(n,s):Fa(n,s)),o=`feed:${e}:`;return{nodes:[...a.nodes.filter(c=>!c.id.startsWith(o)).map(c=>({...c,dim:!0})),...t.nodes]}}function uM(n,e){return e.groups.map((t,s)=>wi(n,s))}function hM(n,e=3){const t=vl(n).split(" > ");return t.length<=e?t.join(" > "):`${t.slice(0,e).join(" > ")} … +${t.length-e}`}function kE(n,e){if(!n.startsWith("shape:"))return null;const t=n.slice(6),s=e.all().filter(i=>Es(i)===t).length;return`${vl(t)} · ${s} feed${s===1?"":"s"}`}function UE(n,e){const t=[];for(const s of e.all())Es(s)===n&&t.push(...uM(s.id,s));return t}function FE(n,e,t="jobs"){const s=Fa(n,t),i=new Set(n.filter(a=>Es(a)===e).map(a=>a.id));return{nodes:s.nodes.map(a=>{if(a.ghost===!0)return a.id===Am(e)?a:{...a,dim:!0};const o=a.id.match(/^feed:(\d+):/);return o!==null&&i.has(Number(o[1]))?a:{...a,dim:!0}})}}function fM(n,e="jobs"){const t=new Map;for(const i of[...n].sort((r,a)=>r.id-a.id)){if(i.groups.length===0)continue;const r=Es(i),a=t.get(r)??[];a.push(i),t.set(r,a)}const s=[];for(const[i,r]of t)r[0].groups.forEach((o,l)=>{let c=0,d=0;for(const h of r){const g=h.groups[l];g!==void 0&&(c+=g.count,g.errored>0&&(d+=1))}const u=d>0?Math.min(1,d/r.length):void 0;s.push({id:od(i,l),label:o.plugin,parentIds:o.parent===null?[]:[od(i,o.parent)],joinParentIds:[],status:d===r.length?"finishedWithError":"finishedSuccessfully",metric:jr(e==="feeds"?r.length:c),...r.length>1?{count:r.length}:{},...u!==void 0?{share:u}:{}})});return{nodes:s}}function jE(n,e){const t=n.match(/^fold:(.+):(\d+)$/);if(t===null)return null;const s=t[1],i=Number(t[2]),r=e.all().filter(d=>Es(d)===s),a=r[0]?.groups[i]?.plugin;if(a===void 0)return null;const o=r.filter(d=>(d.groups[i]?.errored??0)>0).length,l=`${r.length.toLocaleString("en-US")} feed${r.length===1?"":"s"}`,c=o>0?` · ${o.toLocaleString("en-US")} with errors`:"";return`${a} · ${l}${c} · ${hM(s)}`}function Up(n,e){const t=e.all().find(s=>Es(s)===n);return t===void 0?[]:t.groups.map((s,i)=>od(n,i))}function Fp(n,e,t="jobs"){const s=n.filter(l=>Es(l)===e),i=n.filter(l=>Es(l)!==e),r=fM(i,t),a=Fa(s,t),o=a.nodes.filter(l=>l.ghost!==!0).map(l=>l.id);return{graph:{nodes:[...r.nodes.map(l=>({...l,dim:!0})),...a.nodes]},memberIds:o}}const $E=6e4,jp=1e4,VE=new Set(["running","scheduled","created","started"]),HE=[/\/proc\/jobs\/feed_(\d+)(?:\/|$)/,/\/feeds?\/feed_(\d+)(?:\/|$)/],qE={running:"started",done:"finishedSuccessfully",error:"finishedWithError"};function $p(n){if(n.jobsTotal===void 0||n.jobsDone===void 0)return null;const e=n.status==="finishedWithError"||n.status==="cancelled",t=n.jobsErrored===void 0?void 0:n.jobsDone-n.jobsErrored;return{done:n.jobsDone,total:n.jobsTotal,...e?{failed:!0}:{},...t!==void 0?{succeeded:t}:{}}}function XE(n){const e=[];return n.layout==="molecule"&&e.push("dag layout molecule"),n.projection==="2d"&&e.push("dag projection 2d"),n.scale==="size"&&e.push("dag scale size"),n.hue==="compute"&&e.push("dag hue compute"),n.census==="census"&&e.push("dag census"),e}const YE=[{key:"control",label:"",className:"feedlist-control",capped:!1,width:"5.2em",cell:()=>{const n=document.createElement("span");return n.className="feedlist-control listing-capsule",n.textContent="OPEN",n}},{key:"id",label:"ID",className:"feedlist-id",width:"4em",cell:n=>String(n.id),compare:n=>n.id},{key:"title",label:"TITLE",className:"feedlist-title",width:"24em",cell:n=>n.title||"(untitled)",compare:n=>n.title},{key:"progress",label:"PROGRESS",className:"feedlist-progress",width:"1fr",cell:n=>bl($p(n)),compare:n=>{const e=$p(n);return e===null||e.total===0?-1:e.done/e.total}},{key:"status",label:"STATUS",className:"feedlist-status",width:"8em",cell:n=>n.status.toUpperCase(),compare:n=>n.status},{key:"nodes",label:"NODES",className:"feedlist-nodes",width:"4em",cell:n=>n.jobsTotal===void 0?"—":String(n.jobsTotal),compare:n=>n.jobsTotal??-1},{key:"sizeBytes",label:"SIZE",className:"feedlist-size",width:"5.5em",cell:n=>n.sizeBytes===void 0?"—":mM(n.sizeBytes),compare:n=>n.sizeBytes??-1},{key:"wallSeconds",label:"TIME",className:"feedlist-time",width:"6em",cell:n=>n.wallSeconds===void 0?"—":pM(n.wallSeconds),compare:n=>n.wallSeconds??-1},{key:"owner",label:"OWNER",className:"feedlist-owner",width:"7em",cell:n=>n.owner},{key:"createdAt",label:"CREATED",className:"feedlist-created",width:"7em",cell:n=>n.createdAt.slice(0,10),compare:n=>n.createdAt}];function Vp(n,e){return n.nodes.length===e.nodes.length&&e.nodes.every((t,s)=>{const i=n.nodes[s];return i!==void 0&&i.id===t.id&&(i.tally?.count??1)===(t.tally?.count??1)&&i.parentIds.length===t.parentIds.length&&i.joinParentIds.length===t.joinParentIds.length})}class KE{scene;canvas;title;facts;empty;strategyPill;backPill=null;feedList;handlers;rosterTimer=null;shownFeedId=null;pinnedFeedId=null;requestedFeedId=null;defaultTitle;metricMode="time";lastModel=null;lastRoster=[];arrivals=new Set;arrivalsKey="";listing;stateSpan;watchedFeedId=null;liveState=null;pendingFeedId=null;lastCwd=null;constructor(e,t,s,i,r,a,o){this.feedList=a,this.canvas=e,e.style.display="none",this.title=t,this.defaultTitle=t.textContent??"",this.facts=s,this.empty=i,this.strategyPill=r,this.handlers=o;const l=r.closest(".pane-dag");this.stateSpan=l?.querySelector(".pane-state")??null,this.modeSpan=l?.querySelector(".pane-mode")??null;const c=o.feed_verbs;this.listing=new Qr({mount:this.feedList,traits:YE,key:f=>String(f.id),chrome:l===null?void 0:{root:l,prefix:"runs"},actions:c===void 0?void 0:{of:f=>c(f)},control:"control",activate:f=>this.feed_activate(f),indicated:f=>this.handlers.feed_indicated?.(f),row:{className:f=>`feedlist-row feedlist-${f.status}${this.arrivals.has(f.id)?" feedlist-arrived":""}`,decorate:(f,_)=>{f.dataset.feed=String(_.id),f.title=c===void 0?"enter the feed (Esc returns to this list)":"click to indicate, double-click to enter (Esc returns to this list)"}},state:f=>this.canvas.style.display==="block"?null:f.filter,defaultSort:{key:"createdAt",dir:"desc"}}),this.rosterTimer=setInterval(()=>{if(!this.feedList.isConnected||!this.rosterShown||this.rosterPending||document.visibilityState!=="visible")return;const _=this.lastRoster.some(O=>VE.has(O.status))?jp:$E;Date.now()-this.rosterAskedAt<_||(this.rosterAskedAt=Date.now(),this.handlers.command_run("proc feeds"))},jp),this.scene=new Rl(e,{select:f=>this.facts_show(f),activate:f=>this.node_activate(f),deselect:()=>this.facts.replaceChildren(),tip:f=>this.universeShown?dM(f.id,this.landed):null}),r.addEventListener("click",()=>{const f=this.scene.strategy_get()==="ranked"?"molecule":"ranked";this.scene.strategy_set(f),r.textContent=f.toUpperCase(),this.modes_render()}),this.backPill=r.parentElement?.querySelector(".dag-back")??null,this.backPill?.addEventListener("click",()=>{this.nav_pop()||this.feedsChooser_request()}),this.facts.addEventListener("click",f=>{f.target instanceof Element&&f.target.closest("button, a, input")===null&&(this.facts.classList.contains("dag-facts-immersed")||(this.scene.selection_clear(),this.factsShown=null,this.facts.replaceChildren()))});const d=r.parentElement?.querySelector(".dag-projection")??null;d?.addEventListener("click",()=>{const f=this.scene.projection_get()==="3d"?"2d":"3d";this.scene.projection_set(f),d.textContent=f.toUpperCase(),this.modes_render()});const u=r.parentElement?.querySelector(".dag-pulse")??null;u?.classList.add("rail-off"),u?.addEventListener("click",()=>{const f=!this.scene.waveLoop_get();this.scene.waveLoop_set(f),u.textContent=f?"PULSE ON":"PULSE OFF",u.classList.toggle("rail-off",!f),this.modes_render()});const h=r.parentElement?.querySelector(".dag-scale")??null;h?.addEventListener("click",()=>{this.metricMode=this.metricMode==="time"?"size":"time",h.textContent=this.metricMode==="time"?"TIME":"SIZE",this.lastModel!==null&&this.graph_show(this.lastModel,!1),this.modes_render()}),this.scalePill=h;const g=r.parentElement?.querySelector(".dag-census")??null;g?.addEventListener("click",()=>{const f=!this.scene.census_get();this.scene.census_set(f),g.textContent=f?"CENSUS":"SHAPE",this.modes_render()});const p=r.parentElement?.querySelector(".dag-gravity")??null;p?.classList.add("rail-off"),p?.addEventListener("click",()=>{const f=!this.scene.physics_get().gravity;this.scene.physics_set({gravity:f}),p.textContent=f?"GRAVITY ON":"GRAVITY OFF",p.classList.toggle("rail-off",!f),this.modes_render()});const z=r.parentElement?.querySelector(".dag-hue")??null;z?.addEventListener("click",()=>{this.hueMode=this.hueMode==="status"?"compute":"status",z.textContent=this.hueMode.toUpperCase(),this.lastModel!==null&&this.graph_show(this.lastModel,!1),this.hueMode==="compute"&&!this.computeKnown&&this.shownFeedId!==null&&this.canvas.style.display!=="none"&&(this.computeRereading=!0,this.handlers.command_run(`proc refresh ${this.shownFeedId}`),this.refresh()),this.modes_render()}),this.huePill=z,r.closest(".pane-dag")?.addEventListener("argus:dag-physics",f=>{const _=f.detail;if(_==="reset"){this.scene.physics_set({charge:!0,link:!0,collide:!0});return}if(_.term==="gravity"){this.scene.physics_get().gravity!==_.on&&p?.click();return}this.scene.physics_set({[_.term]:_.on})}),new MutationObserver(()=>this.scene.palette_refresh()).observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),window.addEventListener("resize",()=>this.scene.size_fit()),new MutationObserver(()=>{window.setTimeout(()=>this.scene.size_fit(),600)}).observe(document.body,{attributes:!0,attributeFilter:["data-zoom"]})}envelope_observe(e){if(e.model?.kind===vm){const r=ym.safeParse(e.model.data);r.success&&this.universe_show(r.data);return}if(e.model?.kind===wm){this.rosterPending=!1;const r=_m.safeParse(e.model.data);r.success&&(this.universe_end(!0),this.chooser_show(r.data.feeds));return}if(this.pendingFeedId!==null&&e.status==="error"&&e.model===void 0){this.feedRequest_refuse(e.renderedErr??e.rendered??"");return}if(this.rosterPending&&e.status==="error"){this.rosterPending=!1,this.rosterRefusal_show(e),this.universe_request();return}if(e.model?.kind===zi.feedIndexing){const r=h0.safeParse(e.model.data);if(!r.success)return;this.requestedFeedId===r.data.feedId?this.requestedFeedId=null:this.pendingFeedId!==r.data.feedId&&(this.pinnedFeedId=r.data.feedId,this.pendingFeedId=r.data.feedId),this.feedIndexing_show(r.data);return}if(e.model?.kind!==zi.feedDag)return;const t=td.safeParse(e.model.data);if(!t.success)return;const s=t.data;this.requestedFeedId===s.feedId?this.requestedFeedId=null:this.pinnedFeedId=s.feedId,this.universe_end(!1),this.shownFeedId=s.feedId,this.pendingFeedId=null,this.stateSpan?.classList.remove("state-wait"),this.title.textContent=`DAG · FEED ${s.feedId} — ${s.feedName}`.toUpperCase(),this.empty.style.display="none",this.roster_show(!1),this.canvas.style.display="block",this.lastModel!==null&&this.lastModel.feedId!==s.feedId&&(this.facts.replaceChildren(),this.scene.selection_clear());const i=this.lastModel;this.lastModel=s,i!==null&&i.feedId===s.feedId&&Vp(i,s)?this.statuses_patch(s):this.graph_show(s),this.watch_open(s.feedId),this.handlers.feed_shown?.()}watch_open(e){this.watchedFeedId!==e&&(this.watch_release(),this.watchedFeedId=e,this.liveState_show(null),this.handlers.watch_set?.(`/proc/jobs/feed_${e}`,!0))}watch_release(){this.watchedFeedId!==null&&(this.handlers.watch_set?.(`/proc/jobs/feed_${this.watchedFeedId}`,!1),this.watchedFeedId=null,this.liveState_show(null))}modeSpan=null;hueMode="status";huePill=null;hueLegend=new Map;computeKnown=!1;computeRereading=!1;hueLegend_build(e){const t=getComputedStyle(document.documentElement),s=["--harvestgold","--daybreak","--orange","--honey","--butter","--october-sunset"].map(r=>t.getPropertyValue(r).trim()).filter(r=>r!==""),i=new Map;for(const r of e.nodes){const a=r.computeResource;a===void 0||a==="mixed"||i.has(a)||i.set(a,s[i.size%Math.max(1,s.length)]??"#888")}return i}modes_render(){if(this.modeSpan===null)return;const e=[];if(this.scene.strategy_get()!=="ranked"&&e.push("MOLECULE"),this.scene.projection_get()!=="3d"&&e.push("2D"),this.metricMode!=="time"&&e.push("SIZE"),this.scene.census_get()&&e.push("CENSUS"),this.scene.waveLoop_get()&&e.push("PULSE"),this.scene.physics_get().gravity&&e.push("GRAVITY"),this.modeSpan.replaceChildren(document.createTextNode(e.join(" · "))),this.hueMode==="compute"){const t=document.createElement("span");t.className="pane-legend",t.append(document.createTextNode(e.length>0?" · COMPUTE":"COMPUTE"));for(const[s,i]of this.hueLegend){const r=document.createElement("span");r.className="legend-swatch",r.style.backgroundColor=i;const a=document.createElement("span");a.textContent=s,t.append(document.createTextNode(" "),r,a)}this.hueLegend.size===0&&t.append(document.createTextNode(this.computeRereading?" (re-reading the feed…)":" (none reported)")),this.modeSpan.appendChild(t)}}liveState_show(e){if(this.liveState=e,this.stateSpan!==null){if(this.stateSpan.classList.remove("state-live","state-settled","state-stale"),e===null){this.canvas.style.display!=="none"&&(this.stateSpan.textContent="");return}this.stateSpan.textContent=e.toUpperCase(),this.stateSpan.classList.add(`state-${e}`)}}liveState_get(){return this.liveState}feed_get(){return this.pendingFeedId??this.shownFeedId}graph_isShown(){return this.canvas.style.display==="block"}feedTitle_get(){return(this.title.textContent??"").replace(/^DAG\s*·\s*/i,"").trim()}view_lines(){const e=this.strategyPill.parentElement,t=s=>e?.querySelector(s)?.textContent?.trim().toLowerCase()??"";return XE({layout:t(".dag-strategy"),projection:t(".dag-projection"),scale:t(".dag-scale"),hue:t(".dag-hue"),census:t(".dag-census")})}watched_observe(e,t){const s=/feed_(\d+)$/.exec(e);!s||Number(s[1])!==this.watchedFeedId||this.liveState_show(t)}model_refresh(e){if(this.pendingFeedId===e.feedId&&this.canvas.style.display==="none"){this.envelope_observe({status:"ok",rendered:"",model:{kind:zi.feedDag,data:e}});return}if(this.shownFeedId!==e.feedId||this.canvas.style.display==="none")return;const t=this.lastModel;if(this.lastModel=e,t!==null&&Vp(t,e)){this.statuses_patch(e);return}this.graph_show(e,!1)}statuses_patch(e){for(const t of e.nodes)this.scene.status_update(t.id,t.status),this.factsPayloads.set(t.id,t);this.factsShown!==null&&this.facts_show(this.factsShown)}refresh(){this.shownFeedId===null||this.canvas.style.display==="none"||(this.requestedFeedId=this.shownFeedId,this.handlers.command_run(`feed diagram feed_${this.shownFeedId}`))}scalePill=null;graph_show(e,t=!0){const s=o=>this.metricMode==="time"?o.metrics?.computeSeconds:o.metrics?.dataBytes,i=e.nodes.some(o=>s(o)!==void 0);this.scalePill?.classList.toggle("rail-na",!i),this.scalePill!==null&&(this.scalePill.title=i?"molecule node size: wall time or output bytes":`no ${this.metricMode==="time"?"wall-time":"output-size"} data in this feed's cache yet`),this.hueLegend=this.hueLegend_build(e);const r=e.nodes.some(o=>o.computeResource!==void 0);this.computeKnown=r,r&&(this.computeRereading=!1),this.huePill?.classList.toggle("rail-na",!r),this.huePill!==null&&(this.huePill.title=r?"what colors a node: its status, or the compute resource it ran on":"no compute resource reported for this feed's nodes yet");const a=o=>{if(this.hueMode==="compute")return o.computeResource===void 0?"#555":this.hueLegend.get(o.computeResource)??"#555"};this.scene.graph_set({nodes:e.nodes.map(o=>{const l=a(o);return{id:o.id,label:o.label,parentIds:o.parentIds,joinParentIds:o.joinParentIds,status:o.status,metric:s(o),count:o.tally?.count,...l!==void 0?{hue:l}:{}}})},{wave:t}),this.scene.size_fit(),this.hueMode==="compute"&&this.modes_render(),this.factsPayloads.clear();for(const o of e.nodes)this.factsPayloads.set(o.id,o);this.factsShown!==null&&(this.factsPayloads.has(this.factsShown.id)?this.facts_show(this.factsShown):this.factsShown=null)}factsPayloads=new Map;factsShown=null;promptContext_observe(e){const t=e.procWarmup?.landed??[];if(t.length>0&&this.universeLandings_take(t),this.universeShown&&this.universeLive){const o=e.procWarmup;if(o?.total!==void 0&&o.total>0&&o.sweeping!==!1){const l=Math.floor(o.loaded/o.total*100),c=`INDEX WARMING ${o.loaded.toLocaleString()}/${o.total.toLocaleString()} (${l}%)`;c!==this.universeWarming&&(this.universeWarming=c,this.universeTitle_paint())}else(o===void 0||o.sweeping===!1||o.state==="cached")&&(this.universeLive=!1,this.universeWarming="",this.universe_request())}if(this.rosterProgress!==null&&this.rosterProgress.isConnected){const o=e.procWarmup;if(o?.total!==void 0&&o.total>0&&o.sweeping!==!1){const l=Math.floor(o.loaded/o.total*100);this.rosterProgress.textContent=`INDEX WARMING — ${o.loaded}/${o.total} (${l}%). The roster opens when the index is whole.`}(o===void 0||o.sweeping===!1||o.state==="cached")&&(this.rosterProgress=null,this.feedsChooser_request())}this.arrivals_observe(e.procWarmup?.arrived??[]);const i=(e.procWarmup?.feeds??(e.procWarmup?.feed!==void 0?[e.procWarmup.feed]:[])).find(o=>o.id===this.pendingFeedId);if(i!==void 0&&this.feedIndexing_show({feedId:i.id,loaded:i.loaded,total:i.total,...i.failed!==void 0?{failed:i.failed}:{}}),!this.canvas.isConnected||this.rosterShown||this.pendingFeedId!==null)return;const r=this.lastCwd!==null&&e.cwd!==this.lastCwd;if(this.lastCwd=e.cwd,!r)return;const a=QE(e.cwd);a!==null&&a!==this.shownFeedId&&(this.pinnedFeedId!==null&&a===this.pinnedFeedId||(this.pinnedFeedId=null,this.requestedFeedId=a,this.handlers.command_run(`feed diagram feed_${a}`)))}progress_observe(e){if(e.itemId===void 0)return;const t=e.status!==void 0?qE[e.status]:void 0;t!==void 0&&this.scene.status_update(String(e.itemId),t)}size_fit(){this.scene.size_fit()}dispose(){this.watch_release(),this.rosterTimer!==null&&clearInterval(this.rosterTimer),this.scene.dispose()}feed_enter(e){this.pinnedFeedId=e,this.requestedFeedId=null,this.feedRequest_show(e),this.handlers.command_run(`feed diagram feed_${e}`)}feedRequest_show(e){this.pendingFeedId=e,this.roster_show(!1),this.canvas.style.display="none",this.facts.replaceChildren(),this.title.textContent=`DAG · FEED ${e}`,this.empty.textContent=`RETRIEVING FEED ${e}…`,this.empty.style.display="block",this.stateSpan!==null&&(this.stateSpan.classList.remove("state-live","state-settled","state-stale"),this.stateSpan.classList.add("state-wait"),this.stateSpan.textContent="LOADING")}feedIndexing_show(e){this.pendingFeedId===null&&(this.pendingFeedId=e.feedId),this.roster_show(!1),this.canvas.style.display="none",this.title.textContent=`DAG · FEED ${e.feedId}`;const t=e.total>0?`${e.loaded.toLocaleString()} / ${e.total.toLocaleString()}`:`${e.loaded.toLocaleString()} / ?`;this.empty.textContent=e.failed!==void 0?`INDEXING FEED ${e.feedId} FAILED AT ${t} — ${e.failed.toUpperCase()} — REFRESH RETRIES`:`INDEXING FEED ${e.feedId} — ${t}`,this.empty.style.display="block",this.stateSpan!==null&&(this.stateSpan.classList.remove("state-live","state-settled","state-stale"),this.stateSpan.classList.add("state-wait"),this.stateSpan.textContent=e.failed!==void 0?"FAILED":"LOADING"),e.failed===void 0&&this.watch_open(e.feedId)}feedRequest_refuse(e){const t=this.pendingFeedId;this.pendingFeedId=null,this.empty.textContent=`FEED ${t??"?"}: ${e.trim()||"not available"}`.toUpperCase(),this.empty.style.display="block",this.roster_show(!0),this.title.textContent=this.defaultTitle,this.stateSpan?.classList.remove("state-wait"),this.listing.state_refresh()}feedsChooser_request(){const e=document.createElement("div");e.className="feedlist-loading",e.textContent="RETRIEVING FEED ROSTER…",this.feedList.replaceChildren(e),this.roster_show(!0),this.rosterPending=!0,this.rosterAskedAt=Date.now(),this.handlers.command_run("proc feeds")}rosterPending=!1;rosterShown=!1;rosterAskedAt=0;rosterProgress=null;landed=new cM;universeShown=!1;universeLive=!1;universeRepaint=null;universeStrategyWas=null;universeWarming="";universe_request(){this.handlers.command_run("proc universe")}universe_show(e){this.landed.clear(),this.landed.take(e.feeds),this.universeLive=!e.whole,this.universeShown||(this.universeShown=!0,this.universeStrategyWas=this.scene.strategy_get(),this.scene.strategy_set("molecule"),this.scene.physics_set({gravity:!0})),this.roster_show(!1),this.pendingFeedId=null,this.pinnedFeedId=null,this.empty.style.display="none",this.canvas.style.display="block",this.universe_paint()}universe_paint(){this.lastModel=null,this.scene.graph_set(Fa(this.landed.all()),{wave:!1}),this.universeTitle_paint()}universeTitle_paint(){const e=`${this.landed.size()} FEEDS · ${this.landed.shapes()} SHAPES`;this.title.textContent=this.universeLive?`UNIVERSE — ${e}${this.universeWarming.length>0?` · ${this.universeWarming}`:" · INDEX WARMING"}`:`UNIVERSE — ${e}`,this.stateSpan!==null&&(this.stateSpan.classList.remove("state-live","state-settled","state-stale","state-wait"),this.stateSpan.classList.add(this.universeLive?"state-wait":"state-settled"),this.stateSpan.textContent=this.universeLive?"LANDING":"WHOLE")}universeLandings_take(e){!this.universeShown||!this.universeLive||!this.landed.take(e)||this.universeRepaint!==null||(this.universeRepaint=window.setTimeout(()=>{this.universeRepaint=null,this.universeShown&&this.universe_paint()},1e3))}universe_end(e){this.universeShown&&(this.universeShown=!1,this.universeLive=!1,this.universeWarming="",this.universeRepaint!==null&&(window.clearTimeout(this.universeRepaint),this.universeRepaint=null),this.landed.clear(),this.universeStrategyWas!==null&&(this.scene.strategy_set(this.universeStrategyWas),this.universeStrategyWas=null),this.scene.selection_clear(),e&&(this.canvas.style.display="none"))}rosterRefusal_show(e){const t=BE(e.renderedErr||e.rendered||""),s=t.length>0?t:"the roster request was refused",i=document.createElement("div");i.className="feedlist-refusal",i.textContent=s;const r=document.createElement("div");r.className="feedlist-warming",r.textContent="INDEX WARMING… the roster opens when the index is whole.",this.feedList.replaceChildren(i,r),this.roster_show(!0),this.rosterProgress=r}list_reset(){this.pendingFeedId=null,this.stateSpan?.classList.remove("state-wait"),this.watch_release(),this.facts.replaceChildren(),this.scene.selection_clear(),this.canvas.style.display="none",this.pinnedFeedId=null,this.requestedFeedId=null,this.title.textContent=this.defaultTitle,this.empty.style.display="none"}nav_pop(){return this.pendingFeedId!==null&&this.feedList.childElementCount>0?(this.pendingFeedId=null,this.pinnedFeedId=null,this.requestedFeedId=null,this.empty.style.display="none",this.roster_show(!0),this.title.textContent=this.defaultTitle,this.stateSpan?.classList.remove("state-wait"),this.listing.state_refresh(),!0):this.canvas.style.display==="none"||this.feedList.childElementCount===0?!1:(this.watch_release(),this.canvas.style.display="none",this.pinnedFeedId=null,this.requestedFeedId=null,this.title.textContent=this.defaultTitle,this.facts.replaceChildren(),this.scene.selection_clear(),this.roster_show(!0),this.listing.state_refresh(),!0)}arrivals_observe(e){const t=e.join(",");if(t===this.arrivalsKey)return;this.arrivalsKey=t,this.arrivals=new Set(e);for(const r of this.lastRoster)this.listing.row_element(String(r.id))?.classList.toggle("feedlist-arrived",this.arrivals.has(r.id));const s=new Set(this.lastRoster.map(r=>r.id));e.some(r=>!s.has(r))&&this.rosterShown&&this.feedsChooser_request()}chooser_show(e){this.lastRoster=e,this.empty.style.display="none",this.roster_show(!0),this.listing.rows_set([{key:"roster",rows:e}],{field:"roster"}),this.rosterFrame_track()}feed_activate(e){this.pinnedFeedId=e.id,this.requestedFeedId=null,this.handlers.feed_regard?.(`/proc/jobs/feed_${e.id}`),this.feedRequest_show(e.id),this.handlers.command_run(`feed diagram feed_${e.id}`)}row_indicate(e){this.listing.row_indicate(e===null?null:String(e.id))}rowReadout_show(e,t){this.listing.readout_show(String(e),t)}filter_toggle(e){this.listing.filter_toggle(e)}roster_filter(e){this.listing.filter_toggle(e!==""),this.listing.filter_set(e)}rosterFrameObserver=null;rosterFrame_track(){const e=this.feedList.parentElement,t=this.feedList.querySelector(".roster-order");if(this.rosterFrameObserver?.disconnect(),this.rosterFrameObserver=null,e===null)return;if(t===null){e.style.removeProperty("--mode-frame-top");return}const s=()=>{e.style.setProperty("--mode-frame-top",`${Math.ceil(t.getBoundingClientRect().bottom-e.getBoundingClientRect().top)}px`)};s(),this.rosterFrameObserver=new ResizeObserver(s),this.rosterFrameObserver.observe(t)}roster_show(e){this.rosterShown=e,this.backPill!==null&&(this.backPill.hidden=e),this.feedList.style.display=e?"flex":"none",this.feedList.parentElement?.classList.toggle("roster-shown",e)}facts_show(e){this.factsShown=e;const t=this.factsPayloads.get(e.id);if(!t){this.facts.textContent=e.label;return}this.handlers.node_regard?.(t.vfsPath),this.facts.replaceChildren();const i=t.status==="finishedSuccessfully"||t.status==="finishedWithError"||t.status==="cancelled"?"awaiting warmup":"in flight",r=t.tally,a=[["PLUGIN",t.pluginName],[r?"REP. INSTANCE":"INSTANCE",String(t.instanceId)],["STATUS",t.status],...r?[["COUNT",`×${r.count} — ${r.done} done, ${r.error} err, ${r.running} live, ${r.other} other`]]:[],...r?.anomalies!==void 0&&r.anomalies.length>0?[["FAULTS",r.anomalies.map(o=>o.id).join(" ")+(r.count>r.done+r.anomalies.length?" …":"")]]:[],["WALL",t.metrics?.computeSeconds!==void 0?pM(t.metrics.computeSeconds):i],["SIZE",t.metrics?.dataBytes!==void 0?mM(t.metrics.dataBytes):i],["DATA",t.vfsPath]];for(const[o,l]of a){const c=document.createElement("div");c.className="telemetry-row";const d=document.createElement("span");d.className="telemetry-label",d.textContent=o;const u=document.createElement("span");u.className="telemetry-value",u.textContent=l,c.append(d,u),this.facts.appendChild(c)}if(this.facts.appendChild(ZE(t.status)),this.handlers.node_process!==void 0){const o=this.handlers.node_process,l=document.createElement("button");l.className="pacs-capsule dag-process",r!==void 0?(l.textContent="PROCESS",l.disabled=!0,l.title=`${r.count} instances stand here: open one to process it`,l.classList.add("pacs-capsule-off")):(l.textContent="PROCESS",l.title=`open /bin bound to ${t.label} — a run appends to this node`,l.addEventListener("click",()=>o({vfsPath:t.vfsPath,instanceId:t.instanceId,label:t.label}))),this.facts.appendChild(l)}}node_activate(e){const t=this.factsPayloads.get(e.id);if(t)if(this.handlers.node_dive!==void 0){const s=this.handlers.node_dive;this.scene.flight_into(e.id,()=>s(t.vfsPath))}else this.handlers.node_enter(t.vfsPath)}detail_clear(){this.scene.selection_clear(),this.facts.replaceChildren()}wave_start(){this.scene.wave_start()}inside_isHeld(){return this.scene.holding_get()}flight_back(e){this.scene.flight_back(e)}node_flyTo(e){for(const[t,s]of this.factsPayloads){if(s.instanceId!==e)continue;if(this.handlers.node_dive===void 0)return!1;const i=this.handlers.node_dive;return this.facts_show({id:t,label:s.label,parentIds:[],joinParentIds:[]}),this.scene.flight_into(t,()=>i(s.vfsPath)),!0}return!1}}function pM(n){const e=Math.round(n);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h ${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}function mM(n){if(n<1024)return`${n}B`;const e=["K","M","G","T"];let t=n,s=-1;for(;t>=1024&&s<e.length-1;)t=t/1024,s=s+1;return`${t<10?t.toFixed(1):Math.round(t)}${e[s]}`}const Wc=[{key:"created",label:"CREATED"},{key:"waiting",label:"WAITING"},{key:"scheduled",label:"SCHEDULED"},{key:"started",label:"STARTED"},{key:"registeringFiles",label:"REGISTERING"}];function ZE(n){const e=document.createElement("div");e.className="dag-subway";const t=n==="finishedSuccessfully",s=n==="finishedWithError"||n==="cancelled",i=Wc.findIndex(l=>l.key===n),r=t||s?Wc.length:i;!t&&!s&&e.classList.add("dag-subway-live");const a=(l,c,d)=>{const u=document.createElement("span");u.className=`subway-step${d?" subway-step-here":""}`;const h=document.createElement("span");h.className=c;const g=document.createElement("span");return g.className="subway-label",g.textContent=l,u.append(h,g),u};Wc.forEach((l,c)=>{if(c>0){const u=document.createElement("span");u.className="subway-link"+(c<=r?" subway-passed":""),e.appendChild(u)}const d=c===i&&!t&&!s;e.appendChild(a(l.label,"subway-stop"+(c<r?" subway-passed":"")+(d?" subway-here":""),d))});const o=document.createElement("span");return o.className="subway-link"+(t||s?" subway-passed":""),e.appendChild(o),e.appendChild(a(t?"FINISHED":s?n==="cancelled"?"CANCELLED":"ERROR":"FINISHED","subway-stop subway-terminal"+(t?" subway-done":"")+(s?" subway-failed":""),!1)),e}function QE(n){for(const e of HE){const t=n.match(e);if(t?.[1]!==void 0)return parseInt(t[1],10)}return null}class JE{root;label;fill;constructor(e){this.root=document.createElement("div"),this.root.className="wait-progress",this.root.hidden=!0,this.root.setAttribute("role","progressbar"),this.root.setAttribute("aria-valuemin","0"),this.root.setAttribute("aria-valuemax","100"),this.label=document.createElement("span"),this.label.className="wait-progress-label";const t=document.createElement("span");t.className="wait-progress-track",this.fill=document.createElement("span"),this.fill.className="wait-progress-fill",t.appendChild(this.fill),this.root.append(this.label,t),e.appendChild(this.root)}show(e,t){this.root.hidden=!1,this.label.textContent=t===null?e:`${e} · ${Math.floor(t*100)}%`,this.root.classList.toggle("wait-progress-indeterminate",t===null),this.fill.style.width=t===null?"":`${Math.max(0,Math.min(1,t))*100}%`,t===null?this.root.removeAttribute("aria-valuenow"):this.root.setAttribute("aria-valuenow",String(Math.floor(t*100)))}hide(){this.root.hidden=!0}shown(){return!this.root.hidden}}function eD(n){const e={...tr,gravity:!0};return n.charge===e.charge&&n.link===e.link&&n.collide===e.collide&&n.gravity===e.gravity}function Hp(n){let e=0;for(const t of Object.values(n))e+=t[0]*1.3+t[1]*1.7+t[2]*1.9;return`${Object.keys(n).length}:${e.toFixed(2)}`}function kc(n){return n==="constellations"||n==="data"||n==="accretion"}const tD=18e4,sD=1500,nD=1e3,iD=5e3,rD=3e3,Tr=650,aD=650,oD=1.5;class lD{scene;wait;asking=!1;spaceKey="";landed=new cM;canvas;title;state;empty;handlers;store;whole=!1;shown=!1;warming="";repaintTimer=null;lastReask=0;rememberTimer=null;putSignatures=new Map;sessionPlaces=new Map;sessionWait=null;storeKey=null;arrivalsKey="";feedsCount=null;disposed=!1;scale="jobs";view="feeds";inside=null;cluster=null;flying=!1;framedAt=null;entering=null;facts;viewPill=null;gravityPill=null;densityPill=null;density="shape";drawMode="stars";drawPill=null;captionsPill=null;captions=!0;arrangement="galaxy";arrangementPill=null;scalePill=null;physics={...tr,gravity:!0};backPill;openPill;pane;escape_listen;lit=null;dataHubs=new Map;litHub=null;replayPill=null;replayDay="";reach=null;constructor(e,t,s){this.canvas=e.canvas,this.title=e.title,this.state=e.state,this.empty=e.empty,this.handlers=t,this.store=s,this.facts=e.facts,this.backPill=e.backPill,this.openPill=e.openPill,this.pane=e.canvas.closest(".workspace-pane"),this.wait=new JE(e.canvas),this.scene=new Rl(e.canvas,{progress:(i,r,a)=>this.settle_progress(i,r,a),handoffKey:i=>Y0(i.id),tip:i=>this.inside===null?H0(i.id,this.dataHubs)??Pc(i.id,this.landed)??jE(i.id,this.landed)??dM(i.id,this.landed)??kE(i.id,this.landed):null,select:i=>this.node_select(i),activate:i=>{const r=this.inside===null?nd(i.id):null;r!==null?this.plugin_frame(r):this.node_dive(i)},deselect:()=>{this.facts_clear(),this.lit!==null&&this.plugin_light(null)},replay:()=>this.replay_paint(),gesture_end:()=>this.pinch_leave()}),e.backPill?.addEventListener("click",()=>this.ascend()),e.openPill?.addEventListener("click",()=>{this.inside!==null&&this.handlers.feed_open?.(this.inside.feedId)}),this.escape_listen=i=>{if(i.key==="Escape"&&this.scene.replay_state()!==null&&(this.pane===null||this.pane.offsetParent!==null)){this.replay_end();return}i.key!=="Escape"||this.inside===null&&this.cluster===null||this.flying||this.scene.holding_get()||this.pane!==null&&this.pane.offsetParent===null||this.ascend()},window.addEventListener("keydown",this.escape_listen),this.scene.strategy_set("molecule"),this.scene.physics_set(this.physics),e.projectionPill?.addEventListener("click",()=>{const i=this.scene.projection_get()==="3d"?"2d":"3d";this.scene.projection_set(i),e.projectionPill!==null&&(e.projectionPill.textContent=i.toUpperCase())}),e.refreshPill?.addEventListener("click",()=>this.request()),this.replayPill=e.replayPill??null,e.replayPill?.addEventListener("click",()=>{const i=this.scene.replay_state();i===null?this.handlers.note?.(this.replay_start(1)):i.playing?this.scene.replay_pause():this.scene.replay_play(),this.replay_paint()}),e.scalePill?.addEventListener("click",()=>{this.scale=this.scale==="jobs"?"feeds":"jobs",e.scalePill!==null&&(e.scalePill.textContent=this.scale==="jobs"?"JOBS":"ALIKE"),this.shown&&this.paint(!0,"full"),this.settings_save()}),e.viewPill?.addEventListener("click",()=>this.view_set(this.view==="feeds"?"shapes":"feeds")),this.viewPill=e.viewPill,this.gravityPill=e.gravityPill,e.gravityPill?.addEventListener("click",()=>{this.physics_set("gravity",!this.physics.gravity)}),this.densityPill=e.densityPill,e.densityPill?.addEventListener("click",()=>{this.density_set(this.density==="shape"?"census":"shape")}),this.drawPill=e.drawPill??null,this.scalePill=e.scalePill,e.drawPill?.addEventListener("click",()=>{this.draw_set(this.drawMode==="stars"?"spheres":"stars")}),this.captionsPill=e.captionsPill??null,e.captionsPill?.addEventListener("click",()=>{this.handlers.note?.(this.captions_set(!this.captions))}),this.arrangementPill=e.arrangementPill??null,e.arrangementPill?.addEventListener("click",()=>{const i=["galaxy","spokes","clumps","constellations","data","accretion"];this.handlers.note?.(this.arrangement_set(i[(i.indexOf(this.arrangement)+1)%i.length]))}),this.scene.draw_set(this.drawMode),this.canvas.style.display="none",this.title_paint()}request(){this.asking=!0,this.shown||this.wait.show("ASKING THE SESSION FOR THE SPACE",null),this.title_paint(),this.shown||this.handlers.command_run(`proc layout ${this.sessionLayoutName_of(this.arrangement)}`),this.handlers.command_run("proc universe")}settle_progress(e,t,s){if(e>=t){this.wait.hide(),this.remember_later();return}this.wait.show(`SETTLING ${s.toLocaleString("en-US")} SPHERES`,t===0?1:e/t)}envelope_observe(e){if(e.model?.kind===b0){const s=M0.safeParse(e.model.data);s.success&&this.sessionLayout_take(s.data.name,s.data.positions,s.data.laying??null);return}if(e.model?.kind!==vm)return;const t=ym.safeParse(e.model.data);t.success&&this.space_show(t.data)}promptContext_observe(e){if(this.disposed)return;this.identity_note(e.user,e.uri);const t=e.procWarmup?.landed??[];t.length>0&&this.shown&&this.landings_take(t);const s=e.procWarmup;if(s?.total!==void 0&&s.total>0&&s.sweeping!==!1&&!this.whole){const i=Math.floor(s.loaded/s.total*100),r=`INDEX WARMING ${s.loaded.toLocaleString()}/${s.total.toLocaleString()} (${i}%)`;r!==this.warming&&(this.warming=r,this.title_paint())}else this.shown&&!this.whole&&(s===void 0||s.sweeping===!1||s.state==="cached")&&(this.warming="",this.request());if(this.shown&&this.whole){const i=(s?.arrived??[]).join(","),r=e.procIndex?.feeds??null,a=i.length>0&&i!==this.arrivalsKey||r!==null&&this.feedsCount!==null&&r!==this.feedsCount;this.arrivalsKey=i,r!==null&&(this.feedsCount=r),a&&Date.now()-this.lastReask>iD&&(this.lastReask=Date.now(),this.request())}}size_fit(){this.scene.size_fit()}control(e,t){if(e==="enter"){const s=parseInt(t[0]??"",10);return Number.isFinite(s)?this.landed.get(s)===void 0?`universe enter: feed ${s} has not landed here`:this.inside!==null?`universe enter: already inside feed ${this.inside.feedId}; universe back first`:(this.descend(s),`entering feed ${s}`):"universe enter <feed id>"}if(e==="node"){const s=parseInt(t[0]??"",10);return Number.isFinite(s)?this.inside===null?"universe node: not inside a feed (universe enter <feed> first)":this.node_flyTo(s)?`flying into instance ${s}`:`universe node: no node of feed ${this.inside.feedId} hosts instance ${s}`:"universe node <instance id>: fly into the entered feed's node that hosts it"}if(e==="state"){const s=this.scene.state_get(),i=(()=>{const r=this.settingsKey_get();try{return r===null||this.store===void 0?null:this.store.getItem(r)}catch{return null}})();return[`universe: ${this.inside!==null?`inside feed ${this.inside.feedId}`:this.cluster!==null?"in a cluster":"the whole space"}; view ${this.view}, scale ${this.scale}, density ${this.density}`,`scene: ${Object.entries(s).map(([r,a])=>`${r}=${String(a)}`).join(" ")}`,`kept settings: ${i??"(none)"}`,`lit: ${this.lit??"none"}`,`captions: ${this.captions?"on":"off"}`,`session layout: ${(()=>{const r=this.sessionPlaces.get(this.sessionLayoutName_of(this.arrangement));return r===void 0?"not asked":r===null?"none kept":`${r} places kept`})()}`,`replay: ${(()=>{const r=this.scene.replay_state();return r===null?"none":`${r.playing?"playing":"paused"} at ${new Date(r.at).toISOString().slice(0,10)} of ${new Date(r.span[0]).toISOString().slice(0,10)}..${new Date(r.span[1]).toISOString().slice(0,10)}`})()}`].join(`
|
|
4230
4230
|
`)}if(e==="plugin"){const s=t[0]??"";return s===""?"universe plugin <name> | off":this.arrangement!=="constellations"||this.inside!==null||this.cluster!==null?"universe plugin: the CONSTELLATIONS layout only (universe layout constellations)":s.toLowerCase()==="off"?(this.plugin_light(null),"no plugin lit"):this.landed.all().some(i=>i.groups.some(r=>r.plugin===s))?(this.plugin_light(s),Pc(`plugin:${s}`,this.landed)??s):`universe plugin: no feed here ran ${s}`}if(e==="replay"){const s=(t[0]??"").toLowerCase();if(s==="stop")return this.scene.replay_state()===null?"universe replay: none is running":(this.replay_end(),"replay stopped; the space is whole");if(s==="pause")return this.scene.replay_state()===null?"universe replay: none is running":(this.scene.replay_pause(),this.replay_paint(),"replay paused");if(s==="at"){if(this.scene.replay_state()===null)return"universe replay: none is running (universe replay first)";const r=Date.parse(t[1]??"");return Number.isFinite(r)?(this.scene.replay_pause(),this.scene.replay_seek(r),this.replay_paint(),`replay at ${new Date(this.scene.replay_state()?.at??r).toISOString().slice(0,10)}`):"universe replay at <YYYY-MM-DD>"}const i=s===""?1:Number(s);return!Number.isFinite(i)||i<=0?"universe replay [speed] | pause | stop | at <YYYY-MM-DD>":this.scene.replay_state()!==null?(this.scene.replay_play(i),this.replay_paint(),`replaying at ×${i}`):this.replay_start(i)}if(e==="layout"){const s=(t[0]??"").toLowerCase();return s!=="galaxy"&&s!=="spokes"&&s!=="clumps"&&s!=="constellations"&&s!=="data"&&s!=="accretion"?"universe layout galaxy|spokes|clumps|constellations|data|accretion":this.arrangement_set(s)}if(e==="draw"){const s=(t[0]??"").toLowerCase();return s!=="stars"&&s!=="spheres"?"universe draw stars|spheres":this.draw_set(s)}if(e==="regrow"){if(this.arrangement!=="accretion"||this.inside!==null||this.cluster!==null)return"universe regrow: the ACCRETION layout only (universe layout accretion)";this.replay_end();const s=this.positionsKey_of("accretion");try{s!==null&&this.store?.setItem(s,"{}")}catch{}return this.paint(!0,"full"),"the space regrown from its first feed"}if(e==="captions"){const s=(t[0]??"").toLowerCase();return s!=="on"&&s!=="off"?"universe captions on|off":this.captions_set(s==="on")}if(e==="density"){const s=(t[0]??"").toLowerCase();return s!=="shape"&&s!=="census"?"universe density shape|census":this.density_set(s)}if(e==="physics"){const s=(t[0]??"").toLowerCase();if(s==="reset")return this.physics_reset();if(!["charge","link","collide","gravity"].includes(s))return"universe physics charge|link|collide|gravity [on|off] | reset";const i=(t[1]??"on").toLowerCase()!=="off";return this.physics_set(s,i)}if(e==="view"){const s=(t[0]??"").toLowerCase();return s!=="feeds"&&s!=="shapes"?"universe view feeds|shapes":this.inside!==null||this.cluster!==null?"universe view: climb out first (universe back)":(this.view_set(s),s==="feeds"?"every feed its own molecule":"the shapes folded, one molecule each")}if(this.flying&&(e==="enter"||e==="cluster"||e==="back"))return"universe: still moving; ask again";if(e==="cluster"){const s=parseInt(t[0]??"",10),i=Number.isFinite(s)?this.landed.get(s):void 0;return i===void 0?"universe cluster <feed id>: the cluster of a feed that landed here":this.inside!==null?`universe cluster: inside feed ${this.inside.feedId}; universe back first`:(this.cluster_enter(Es(i)),`viewing the cluster of feed ${s}: ${vl(Es(i))}`)}return e==="back"?this.inside===null&&this.cluster===null?"universe back: not inside a feed or a cluster":(this.ascend(),"climbing out"):e==="open"?this.inside===null?"universe open: not inside a feed":(this.handlers.feed_open?.(this.inside.feedId),`opening feed ${this.inside.feedId}`):"universe enter <feed>|node <instance>|cluster <feed>|view feeds|shapes|density shape|census|draw stars|spheres|captions on|off|layout galaxy|spokes|clumps|constellations|data|accretion|regrow|plugin <name>|off|replay [speed]|pause|stop|at <date>|state|physics <term> on|off|reset|back|open"}physics_set(e,t){return this.inside!==null||this.cluster!==null?"universe physics: climb out first (universe back)":e==="reach"?"universe physics: reach is the pane's own":(this.physics={...this.physics,[e]:t},this.physics_apply(),`physics ${e} ${t?"on":"off"}`)}draw_set(e){return this.replay_end(),this.drawMode=e,this.drawPill!==null&&(this.drawPill.textContent=e.toUpperCase()),this.scene.draw_set(e),this.settings_save(),e==="stars"?"every sphere a point of light":"every sphere lit and solid"}captions_set(e){return this.captions=e,this.captionsPill!==null&&(this.captionsPill.textContent=e?"CAPTIONS ON":"CAPTIONS OFF"),this.scene.captions_set(e),this.settings_save(),e?"captions on: each hub names itself and its count":"captions off: a hub names itself on hover"}arrangement_set(e){if(kc(e)&&this.view!=="feeds")return`universe layout ${e}: the FEEDS view only (universe view feeds)`;this.replay_end();const t=i=>kc(i)?i:"hubs",s=t(e)!==t(this.arrangement);return this.litHub=null,this.remember_now(),this.arrangement=e,this.arrangementPill!==null&&(this.arrangementPill.textContent=e.toUpperCase()),this.positions_recalled(e)===void 0&&this.handlers.command_run(`proc layout ${this.sessionLayoutName_of(e)}`),this.inside===null&&this.cluster===null&&(this.scene.arrangement_set(e==="data"?"hubs":e,this.positions_recalled(e),!s),s&&this.paint(!0,this.positions_recalled(e)===void 0?"full":"hold")),this.settings_save(),e==="galaxy"?"the space finds its own shape: every sphere pushing, every edge holding":e==="spokes"?"each molecule a spoke round its hub":e==="clumps"?"molecules packed round their hub":e==="constellations"?"every plugin a star, placed by what runs with what; every feed pulled to the stars it ran":e==="data"?"every feed hung from what it began from: its format, its modality, its series":"the space grown in the order it was made: each feed wandering until it sticks, to its kin more readily than to strangers"}settingsKey_get(){return this.storeKey===null?null:this.storeKey.replace(/^argus\.universe\./,"argus.universe.settings.")}settings_save(){const e=this.settingsKey_get();if(!(this.store===void 0||e===null))try{this.store.setItem(e,JSON.stringify(CE(this.drawMode,this.view,this.scale,this.density,this.arrangement,this.captions)))}catch{}}settings_recall(){const e=this.settingsKey_get();if(this.store===void 0||e===null)return!1;let t=null;try{t=this.store.getItem(e)}catch{return!1}const s=PE(t),i=s.view!==this.view||s.scale!==this.scale;return this.drawMode=s.draw,this.view=s.view,this.scale=s.scale,this.density=s.density,this.arrangement=s.arrangement,this.arrangementPill!==null&&(this.arrangementPill.textContent=s.arrangement.toUpperCase()),this.scene.arrangement_set(s.arrangement==="data"?"hubs":s.arrangement,this.positions_recalled(s.arrangement)),this.drawPill!==null&&(this.drawPill.textContent=s.draw.toUpperCase()),this.viewPill!==null&&(this.viewPill.textContent=s.view.toUpperCase()),this.scalePill!==null&&(this.scalePill.textContent=s.scale==="jobs"?"JOBS":"ALIKE"),this.densityPill!==null&&(this.densityPill.textContent=s.density.toUpperCase()),this.scene.draw_set(s.draw),this.scene.census_set(s.density==="census"),this.captions=s.captions,this.captionsPill!==null&&(this.captionsPill.textContent=s.captions?"CAPTIONS ON":"CAPTIONS OFF"),this.scene.captions_set(s.captions),i}density_set(e){return this.replay_end(),this.density=e,this.densityPill!==null&&(this.densityPill.textContent=e.toUpperCase()),this.scene.census_set(e==="census"),this.settings_save(),e==="census"?"every job its own point":"a stage one sphere, with its count"}physics_reset(){return this.inside!==null||this.cluster!==null?"universe physics: climb out first (universe back)":(this.physics={...tr,gravity:!0},this.physics_apply(),"physics reset")}physics_apply(){this.gravityPill!==null&&(this.gravityPill.textContent=this.physics.gravity?"GRAVITY ON":"GRAVITY OFF"),this.scene.physics_set({...this.physics,reach:this.reach??void 0}),this.title_paint()}view_set(e){if(this.replay_end(),e==="shapes"&&kc(this.arrangement)&&(this.arrangement="galaxy",this.arrangementPill!==null&&(this.arrangementPill.textContent="GALAXY"),this.scene.arrangement_set("galaxy",this.positions_recalled("galaxy"),!1)),this.remember_now(),this.view=e,this.viewPill!==null&&(this.viewPill.textContent=e.toUpperCase()),this.shown&&this.inside===null&&this.cluster===null){const t=this.positions_recalled(this.arrangement);t!==void 0?(this.scene.positions_seed(t),this.paint(!0,"new")):this.paint(!0,"full")}this.settings_save()}inside_get(){return this.inside?.feedId??null}shown_get(){return this.shown}dispose(){this.disposed=!0,window.removeEventListener("keydown",this.escape_listen),this.repaintTimer!==null&&window.clearTimeout(this.repaintTimer),this.rememberTimer!==null&&window.clearTimeout(this.rememberTimer),this.remember_now(),this.scene.dispose()}space_show(e){this.asking=!1;const t=`${e.whole?"W":"L"}|${e.feeds.map(s=>`${s.id}:${s.jobs}:${s.status}`).join(",")}`;if(this.shown&&t===this.spaceKey){this.title_paint();return}this.spaceKey=t,this.wait.hide(),this.whole=e.whole,this.shown||(this.shown=!0,this.seed_recall()),this.landed.clear(),this.landed.take(e.feeds),this.whole&&(this.warming=""),this.empty.style.display="none",this.canvas.style.display="block",this.inside===null&&this.cluster===null&&this.entering===null&&!this.flying?this.paint(!this.scene.camera_touched()):this.title_paint()}landings_take(e){!this.landed.take(e)||this.repaintTimer!==null||this.inside!==null||this.cluster!==null||this.entering!==null||(this.repaintTimer=window.setTimeout(()=>{this.repaintTimer=null,!(this.disposed||this.entering!==null||this.inside!==null||this.cluster!==null||this.flying)&&this.paint(!this.scene.camera_touched())},nD))}paint(e=!0,t="new"){if(this.sessionWait_holds()){this.title_paint();return}const s=this.view==="shapes"?fM(this.landed.all(),this.scale):this.arrangement==="constellations"?fu(this.landed.all(),this.scale):this.arrangement==="data"?this.dataGraph_paint():this.arrangement==="accretion"?fh(this.landed.all(),this.scale):Fa(this.landed.all(),this.scale),i=this.arrangement==="constellations"?this.lit:null,r=i===null?s:{nodes:s.nodes.map(o=>o.attrs?.kind==="star"||o.attrs?.plugin===i?o:{...o,dim:!0})},a=X0(r.nodes.length);a!==this.reach&&(this.reach=a,this.scene.physics_set({reach:a},!1)),this.scene.graph_set(r,{wave:!1,fit:e,settle:t}),this.title_paint(),this.remember_later()}descend(e,t){this.replay_end();const s=this.landed.get(e),i=this.handlers.feed_dag;if(s===void 0||i===void 0||this.flying||this.inside!==null)return;this.flying=!0,this.facts_clear();const r=uM(e,s);this.entering=e,this.title_paint();const a=Date.now();(l=>{t!==void 0?this.scene.camera_flyToward(t,14,Tr,l):this.scene.camera_flyToFit(r,Tr,l)})(()=>{i(e).then(l=>{if(this.disposed)return;if(this.entering=null,l===null){this.flying=!1,this.title_paint(),this.handlers.note?.(`universe: feed ${e}: the session gave no graph for it (feed diagram feed_${e} refused or answered nothing after ${Math.round((Date.now()-a)/1e3)}s)`);return}const c=LE(l);for(const f of c.nodes)f.solid=!0;const d=this.scene.positions_get(),u=[0,0,0];let h=0;for(const f of[...r,...Up(Es(s),this.landed)]){const _=d[f];if(_!==void 0&&(u[0]+=_[0],u[1]+=_[1],u[2]+=_[2],h+=1,h===r.length&&r.some(O=>d[O]!==void 0)))break}h>0&&(u[0]/=h,u[1]/=h,u[2]/=h);for(const f of c.nodes)d[f.id]=[u[0]+(Math.random()-.5)*.5,u[1]+(Math.random()-.5)*.5,u[2]+(Math.random()-.5)*.5];this.scene.positions_seed(d);const g=`feed:${e}:`,p=this.view==="feeds"?WE(this.landed.all(),e,c,this.scale,this.arrangement==="constellations",this.arrangement==="data"?ph(this.landed.all(),this.scale).graph:this.arrangement==="accretion"?fh(this.landed.all(),this.scale):void 0):{nodes:[...Fp(this.landed.all(),Es(s),this.scale).graph.nodes.filter(f=>!f.id.startsWith(g)).map(f=>({...f,dim:!0})),...c.nodes]},z=new Set(c.nodes.map(f=>f.id)),m=p.nodes.filter(f=>!z.has(f.id)).map(f=>f.id);this.scene.graph_set(p,{wave:!1,fit:!1,frozen:m,physics:{reach:ad,gravity:!1}}),this.inside={feedId:e,title:l.feedName,entered:c,ids:new Set(c.nodes.map(f=>f.id))},this.pane?.classList.add("universe-inside"),this.title_paint(),this.scene.camera_flyToFit([...this.inside.ids],Tr,()=>this.landed_note(),1,.95)})})}ascend(){if(!this.flying){if(this.framedAt=null,this.inside!==null){if(this.inside=null,this.facts_clear(),this.pane?.classList.remove("universe-inside"),this.cluster!==null){this.cluster_show(this.cluster.shape);return}}else{if(this.cluster===null)return;this.cluster=null,this.pane?.classList.remove("universe-cluster")}this.flying=!0,this.paint(!1),this.scene.camera_flyToFit([],aD,()=>{this.flying=!1})}}cluster_enter(e){this.replay_end(),!(this.flying||this.inside!==null)&&this.cluster_show(e)}cluster_show(e){if(this.view==="feeds"){const d=UE(e,this.landed);if(d.length===0)return;this.flying=!0,this.cluster={shape:e,ids:d},this.pane?.classList.add("universe-cluster");const u=FE(this.landed.all(),e,this.scale);this.scene.graph_set(u,{wave:!1,fit:!1,frozen:u.nodes.map(h=>h.id)}),this.title_paint(),this.scene.camera_flyToFit(d,Tr,()=>this.landed_note());return}const{graph:t,memberIds:s}=Fp(this.landed.all(),e,this.scale);if(s.length===0)return;this.flying=!0,this.cluster={shape:e,ids:s},this.pane?.classList.add("universe-cluster");const i=this.scene.positions_get(),r=Up(e,this.landed),a=[0,0,0];let o=0;for(const d of r){const u=i[d];u!==void 0&&(a[0]+=u[0],a[1]+=u[1],a[2]+=u[2],o+=1)}o>0&&(a[0]/=o,a[1]/=o,a[2]/=o);const l=new Set(s);for(const d of t.nodes)(l.has(d.id)||d.ghost===!0)&&(i[d.id]=[a[0]+(Math.random()-.5)*.5,a[1]+(Math.random()-.5)*.5,a[2]+(Math.random()-.5)*.5]);this.scene.positions_seed(i);const c=t.nodes.filter(d=>!l.has(d.id)&&d.ghost!==!0).map(d=>d.id);this.scene.graph_set(t,{wave:!1,fit:!1,frozen:c,physics:{reach:ad,gravity:!1}}),this.title_paint(),this.scene.camera_flyToFit(s,Tr,()=>this.landed_note())}landed_note(){this.flying=!1,this.framedAt=this.scene.camera_distance()}pinch_leave(){this.inside===null&&this.cluster===null||this.flying||this.scene.holding_get()||this.framedAt===null||this.scene.camera_distance()<=this.framedAt*oD||this.ascend()}node_dive(e){const t=this.inside?.entered.payloads.get(e.id),s=this.handlers.node_dive;t===void 0||s===void 0||this.flying||this.scene.flight_into(e.id,()=>s(t.vfsPath))}flight_back(e){this.scene.flight_back(e)}node_flyTo(e){if(this.inside===null)return!1;for(const[t,s]of this.inside.entered.payloads){if(s.instanceId!==e)continue;const i=this.handlers.node_dive;return i===void 0?!1:(this.scene.flight_into(t,()=>i(s.vfsPath)),!0)}return!1}node_select(e){if(this.flying)return;if(this.inside===null){const s=nd(e.id);if(s!==null){this.plugin_light(this.lit===s?null:s);return}const i=rd(e.id);if(i!==null){this.litHub=this.litHub===i?null:i,this.paint(!1,"hold");return}const r=e.id.match(/^feed:(\d+):\d+$/),a=Im(e.id);r!==null?this.descend(Number(r[1]),e.id):a!==null?this.cluster_enter(a):e.id.startsWith("shape:")&&this.cluster_enter(e.id.slice(6));return}const t=this.inside.entered.payloads.get(e.id);t!==void 0&&this.facts_show(e,t)}facts_show(e,t){if(this.facts===null)return;this.facts.replaceChildren();const s=t.tally,i=[["PLUGIN",t.pluginName],[s?"REP. INSTANCE":"INSTANCE",String(t.instanceId)],["STATUS",t.status],...s?[["COUNT",`×${s.count} — ${s.done} done, ${s.error} err, ${s.running} live`]]:[],["DATA",t.vfsPath]];for(const[l,c]of i){const d=document.createElement("div");d.className="telemetry-row";const u=document.createElement("span");u.className="telemetry-label",u.textContent=l;const h=document.createElement("span");h.className="telemetry-value",h.textContent=c,d.append(u,h),this.facts.append(d)}const r=document.createElement("div");r.className="universe-node-verbs";const a=document.createElement("button");a.className="pacs-capsule universe-node-enter",a.textContent="ENTER NODE",a.title="fly into the node: its data, browsable inside (Esc flies out)",a.addEventListener("click",()=>{this.handlers.node_dive!==void 0?this.node_dive(e):this.handlers.node_enter?.(t.vfsPath)});const o=document.createElement("button");o.className="pacs-capsule universe-node-process",o.textContent="PROCESS",o.title="a catalogue bound to this node's data",o.addEventListener("click",()=>this.handlers.node_process?.({vfsPath:t.vfsPath,instanceId:t.instanceId,label:e.label})),r.append(a,o),this.facts.append(r),this.facts.hidden=!1}facts_clear(){this.facts!==null&&(this.facts.replaceChildren(),this.facts.hidden=!0)}title_paint(){if(this.entering!==null&&this.inside===null){const t=this.landed.get(this.entering);this.title.textContent=`UNIVERSE — ENTERING FEED ${this.entering}${t!==void 0&&t.title.length>0?` · ${t.title}`:""} …`,this.state!==null&&(this.state.classList.remove("state-live","state-settled","state-stale","state-wait"),this.state.classList.add("state-wait"),this.state.textContent="ASKING");return}if(this.inside!==null){const t=this.inside.entered.nodes.reduce((s,i)=>s+(i.count??1),0);this.title.textContent=`UNIVERSE — INSIDE FEED ${this.inside.feedId} · ${this.inside.title} · ${t.toLocaleString("en-US")} JOBS`,this.state!==null&&(this.state.classList.remove("state-live","state-settled","state-stale","state-wait"),this.state.classList.add("state-live"),this.state.textContent="INSIDE");return}if(this.cluster!==null){const t=this.landed.all().filter(s=>Es(s)===this.cluster?.shape).length;this.title.textContent=`UNIVERSE — SHAPE ${hM(this.cluster.shape)} · ${t} FEED${t===1?"":"S"}`,this.state!==null&&(this.state.classList.remove("state-live","state-settled","state-stale","state-wait"),this.state.classList.add("state-live"),this.state.textContent="CLUSTER");return}if(this.asking&&!this.shown){this.title.textContent="UNIVERSE — ASKING THE SESSION …",this.state!==null&&(this.state.classList.remove("state-live","state-settled","state-stale","state-wait"),this.state.classList.add("state-wait"),this.state.textContent="ASKING");return}const e=`${this.landed.size()} FEEDS · ${this.landed.shapes()} SHAPES`;this.title.textContent=this.whole?`UNIVERSE — ${e}`:`UNIVERSE — ${e}${this.warming.length>0?` · ${this.warming}`:" · INDEX WARMING"}`,this.state!==null&&(this.state.classList.remove("state-live","state-settled","state-stale","state-wait"),this.state.classList.add(this.whole?"state-settled":"state-wait"),this.state.textContent=this.whole?"WHOLE":"LANDING"),this.scene.replay_state()!==null&&this.replay_paint()}replay_start(e){if(this.inside!==null||this.cluster!==null)return"universe replay: climb out first (universe back)";if(this.view!=="feeds")return"universe replay: the FEEDS view only (universe view feeds)";if(this.density!=="shape")return"universe replay: SHAPE density only (universe density shape)";if(this.drawMode!=="stars")return"universe replay: it draws stars (universe draw stars)";const t=new Map;for(const o of this.landed.all()){const l=Date.parse(o.createdAt??"");Number.isFinite(l)&&t.set(o.id,l)}if(t.size===0)return"universe replay: the session does not say when its feeds were made (a daemon from before the replay: restart it)";const s=new Map;for(const o of Object.keys(this.scene.positions_get())){const l=o.match(/^feed:(\d+):/),c=l===null?void 0:t.get(Number(l[1]));c!==void 0&&s.set(o,c)}this.facts_clear(),this.replayDay="",this.scene.replay_begin(s,e),this.replay_paint();const i=this.scene.replay_state(),r=new Date(i?.span[0]??0).toISOString().slice(0,10),a=new Date(i?.span[1]??0).toISOString().slice(0,10);return`replaying ${t.size} feeds, ${r} to ${a}, at ×${e} (universe replay pause | stop | at <date>; Esc stops)`}plugin_light(e){this.lit=e,e===null?this.facts_clear():this.pluginFacts_show(e),this.shown&&this.inside===null&&this.cluster===null&&this.paint(!1,"hold")}plugin_frame(e){this.lit!==e&&this.plugin_light(e);const t=[];for(const s of this.landed.all())s.groups.forEach((i,r)=>{i.plugin===e&&t.push(`feed:${s.id}:${r}`)});t.length===0||this.flying||(this.flying=!0,this.scene.camera_flyToFit(t,Tr,()=>{this.flying=!1},.9))}pluginFacts_show(e){if(this.facts===null)return;this.facts.replaceChildren();const t=Pc(`plugin:${e}`,this.landed)??e,[,s="",i=""]=t.split(" · ");for(const[o,l]of[["PLUGIN",e],["FEEDS",s.replace(/ feeds?$/,"")],["ERRORED",i.replace(/ errored$/,"")]]){const c=document.createElement("div");c.className="telemetry-row";const d=document.createElement("span");d.className="telemetry-label",d.textContent=o;const u=document.createElement("span");u.className="telemetry-value",u.textContent=l,c.append(d,u),this.facts.append(c)}const r=document.createElement("div");r.className="universe-node-verbs";const a=document.createElement("button");a.className="pacs-capsule universe-plugin-open",a.textContent="OPEN IN /BIN",a.title="the plugin in the files browser: its one-node graph, its parameters",a.addEventListener("click",()=>this.handlers.plugin_open?.(e)),r.append(a),this.facts.append(r),this.facts.hidden=!1}dataGraph_paint(){const{graph:e,hubs:t}=ph(this.landed.all(),this.scale);this.dataHubs=t;const s=this.litHub;if(s===null)return e;const i=Em(this.landed.all().map(a=>a.data?.seriesDescription).filter(a=>a!==void 0)),r=new Set(this.landed.all().filter(a=>Dm(a,i).some(o=>o.key===s)).map(a=>a.id));return{nodes:e.nodes.map(a=>{if(rd(a.id)!==null)return a;const o=a.id.match(/^feed:(\d+):/);return o!==null&&r.has(Number(o[1]))?a:{...a,dim:!0}})}}replay_end(){this.scene.replay_state()!==null&&(this.scene.replay_stop(),this.replayDay="",this.title_paint(),this.replay_paint())}replay_paint(){const e=this.scene.replay_state();if(this.replayPill!==null){const s=e!==null&&!e.playing&&e.at>=e.span[1];this.replayPill.textContent=e===null?"REPLAY":e.playing?"PLAYING":s?"REPLAYED":"PAUSED",this.replayPill.classList.toggle("rail-off",e===null)}if(e===null||this.state===null)return;const t=`${e.playing?"REPLAY":"PAUSED"} ${new Date(e.at).toISOString().slice(0,10)}`;t!==this.replayDay&&(this.replayDay=t,this.state.classList.remove("state-live","state-settled","state-stale","state-wait"),this.state.classList.add("state-live"),this.state.textContent=t)}identity_note(e,t){const s=NE(e,t);if(s===this.storeKey)return;this.storeKey=s;const i=this.settings_recall();if(this.shown){const r=this.seed_recall();(i||r)&&this.inside===null&&this.cluster===null&&this.paint(!1)}}positionsKey_of(e){if(this.storeKey===null)return null;const t=e==="galaxy"?this.storeKey:`${this.storeKey}.${e}`;return this.view==="shapes"?`${t}.shapes`:t}positions_recalled(e){const t=this.positionsKey_of(e);if(!(this.store===void 0||t===null))try{const s=kp(this.store.getItem(t));return Object.keys(s).length>0?s:void 0}catch{return}}seed_recall(){const e=this.positionsKey_of(this.arrangement);if(this.store===void 0||e===null)return!1;const t=kp(this.store.getItem(e));return Object.keys(t).length===0?!1:(this.scene.positions_seed(t),!0)}remember_later(){this.rememberTimer===null&&(this.rememberTimer=window.setTimeout(()=>{this.rememberTimer=null,this.remember_now()},rD))}remember_now(){if(!(this.store===void 0||this.storeKey===null||!this.shown)&&this.positions_matchView(this.scene.positions_get())){try{const e=this.positionsKey_of(this.arrangement);e!==null&&this.store.setItem(e,JSON.stringify(this.scene.positions_get()))}catch{}this.sessionLayout_put()}}positions_matchView(e){const t=Object.keys(e),s=t.some(r=>r.startsWith("fold:")),i=t.some(r=>r.startsWith("feed:"));return this.view==="shapes"?s&&!i:!s}sessionLayoutName_of(e){return`${e}${this.view==="shapes"?"-shapes":""}${this.scale==="feeds"?"-alike":""}`}sessionLayout_take(e,t,s=null){if((t!==null||!this.sessionPlaces.has(e))&&this.sessionPlaces.set(e,t===null?null:Object.keys(t).length),t===null&&s!==null){this.sessionWait_hold(e,s);return}const i=this.sessionWait?.name===e;if(i&&this.sessionWait_end(),t===null||this.store===void 0){i&&this.shown&&this.paint(!0,"full");return}const r=["galaxy","spokes","clumps","constellations","data","accretion"].find(o=>this.sessionLayoutName_of(o)===e);if(r===void 0||this.positions_recalled(r)!==void 0)return;const a=this.positionsKey_of(r);if(a!==null){try{this.store.setItem(a,JSON.stringify(t))}catch{return}this.putSignatures.set(e,Hp(t)),r===this.arrangement&&this.shown&&this.inside===null&&this.cluster===null&&this.entering===null&&(this.scene.positions_seed(t),this.paint(i,"new"))}}sessionWait_hold(e,t){if(e!==this.sessionLayoutName_of(this.arrangement)||this.positions_recalled(this.arrangement)!==void 0)return;const s=this.sessionWait?.name===e?this.sessionWait.until:Date.now()+tD;if(this.sessionWait?.timer!==void 0&&this.sessionWait?.timer!==null&&window.clearTimeout(this.sessionWait.timer),Date.now()>=s){this.sessionWait_end(),this.shown&&this.paint(!0,"full");return}this.wait.show(`LAYING OUT ${t.nodes.toLocaleString("en-US")} SPHERES · THE SESSION`,t.fraction);const i=window.setTimeout(()=>{this.handlers.command_run(`proc layout ${e}`)},sD);this.sessionWait={name:e,until:s,timer:i}}sessionWait_end(){this.sessionWait?.timer!==void 0&&this.sessionWait?.timer!==null&&window.clearTimeout(this.sessionWait.timer),this.sessionWait=null,this.wait.hide()}sessionWait_holds(){return this.sessionWait!==null&&this.sessionWait.name===this.sessionLayoutName_of(this.arrangement)&&Date.now()<this.sessionWait.until&&this.inside===null&&this.cluster===null}sessionLayout_put(){if(this.inside!==null||this.cluster!==null||this.scene.replay_state()!==null||!this.whole||!eD(this.physics))return;const e={};for(const[i,r]of Object.entries(this.scene.positions_get()))r.every(a=>Number.isFinite(a))&&(e[i]=[Math.round(r[0]*100)/100,Math.round(r[1]*100)/100,Math.round(r[2]*100)/100]);if(Object.keys(e).length===0)return;const t=this.sessionLayoutName_of(this.arrangement),s=Hp(e);this.putSignatures.get(t)!==s&&(this.putSignatures.set(t,s),this.sessionPlaces.set(t,Object.keys(e).length),this.handlers.command_run(`proc layout put ${t} '${JSON.stringify(e).replace(/'/g,"'\\''")}'`))}}const Na=[];function cD(){const n=Na[Na.length-1];return n===void 0?!1:(n(),!0)}function dD(n){const e=n.querySelector(":scope > .pane-drawer");if(e!==null)return e.nextElementSibling;const t=n.querySelector(":scope > .lcars-terminal-header-bar");return t===null?n.firstElementChild:t.nextElementSibling}function Uc(n,e){if(n.querySelector(":scope > .ask-bar")!==null)return Promise.resolve(null);const t=document.createElement("div");t.className="ask-bar";const s=document.createElement("span");s.className="ask-bar-glyph",s.textContent="?";const i=document.createElement("span");i.className="ask-bar-caption",i.textContent=e.message.trim(),t.append(s,i);const r=document.createElement("input"),a=document.createElement("button"),o=document.createElement("button"),l=document.createElement("button"),c=document.createElement("button");c.className="pacs-capsule ask-bar-abandon",c.textContent="ABANDON",c.title="abandon the question (Esc)",e.kind==="confirm"?(a.className="pacs-capsule ask-bar-yes",a.textContent="YES",o.className="pacs-capsule ask-bar-no",o.textContent="NO",t.append(a,o,c)):(r.className="ask-bar-field",r.spellcheck=!1,e.kind==="secret"?r.type="password":e.suggest!==void 0&&(r.value=e.suggest),l.className="pacs-capsule ask-bar-commit",l.textContent=e.commit??"ANSWER",t.append(r,l,c));const d=dD(n);return d===null?n.appendChild(t):n.insertBefore(t,d),window.requestAnimationFrame(()=>t.classList.add("ask-bar-shown")),new Promise(u=>{let h=!1;const g=m=>{if(h)return;h=!0;const f=Na.indexOf(p);f>=0&&Na.splice(f,1),t.remove(),u(m)},p=()=>g(null);Na.push(p);const z=()=>{const m=r.value.trim();g(m===""?null:m)};l.addEventListener("click",z),a.addEventListener("click",()=>g("y")),o.addEventListener("click",()=>g("n")),c.addEventListener("click",p),t.addEventListener("keydown",m=>{if(m.key==="Escape"){m.stopPropagation(),p();return}if(e.kind==="confirm"){m.key==="y"||m.key==="Y"?(m.stopPropagation(),g("y")):m.key==="n"||m.key==="N"||m.key==="Enter"&&m.target===o?(m.stopPropagation(),g("n")):m.key==="Enter"&&(m.stopPropagation(),g("y"));return}m.key==="Enter"&&(m.stopPropagation(),z())}),e.kind==="confirm"?a.focus():(r.focus(),r.select())})}const uD={"fs.listing":"files","feed.dag":"dag","feed.list":"dag","pacs.query":"pacs","dicom.series":"image","dicom.tags":"tags"};class hD{result;handlers;constructor(e,t){this.handlers=t,this.result=xa(e,".empty-result");const s=xa(e,".empty-prompt");s.addEventListener("keydown",i=>{i.key==="Enter"&&s.value.trim().length>0&&(this.line_run(s.value.trim()),s.value="")}),xa(e,".empty-go-files").addEventListener("click",()=>{this.line_run("ls .")}),xa(e,".empty-go-dag").addEventListener("click",()=>{this.line_run("proc feeds")}),xa(e,".empty-go-pacs").addEventListener("click",()=>{this.handlers.claim("pacs",[])}),window.setTimeout(()=>s.focus(),0)}async line_run(e){this.result.textContent="…";let t;try{t=await this.handlers.execute(e)}catch(i){this.result.textContent=i instanceof Error?i.message:String(i);return}for(const i of t.envelopes){const r=i.model?.kind!==void 0?uD[i.model.kind]:void 0;if(r!==void 0){this.handlers.claim(r,t.envelopes);return}}const s=t.envelopes.map(i=>i.rendered).join(`
|
|
4231
|
-
`);this.result.textContent=fD(s)||"(no output)"}}function xa(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`empty pane template is missing ${e}`);return t}function fD(n){return n.replace(/\x1b\[[0-9;:]*[A-Za-z]/g,"")}class pD{container;title;handlers;currentAddress=null;constructor(e,t,s){this.container=e,this.title=t,this.handlers=s,this.awaiting_render()}regard_show(e){if(this.currentAddress=e.address,this.title.textContent=`VIEWER — ${e.address}`.toUpperCase(),this.handlers.path_isImage(e.address)){this.container.replaceChildren();const t=document.createElement("img");t.className="files-image",t.src=this.handlers.imageUrl_build(e.address),t.alt=e.address,this.container.appendChild(t);return}this.handlers.content_fetch(e.address).then(t=>{if(this.currentAddress!==e.address)return;if(this.container.replaceChildren(),t.trim().length===0){const i=document.createElement("p");i.className="files-empty",i.textContent=`NO PREVIEW — ${e.address.toUpperCase()}`,this.container.appendChild(i);return}const s=document.createElement("pre");s.className="files-content",s.textContent=t,this.container.appendChild(s)})}awaiting_render(){this.container.replaceChildren();const e=document.createElement("p");e.className="files-empty",e.textContent="NO REGARD — INDICATE A FILE OR NODE IN THIS PANE’S GROUP",this.container.appendChild(e)}}const mD="modulepreload",gD=function(n,e){return new URL(n,e).href},qp={},Xp=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");i=c(t.map(d=>{if(d=gD(d,s),d in qp)return;qp[d]=!0;const u=d.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(s)for(let p=a.length-1;p>=0;p--){const z=a[p];if(z.href===d&&(!u||z.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":mD,u||(g.as="script"),g.crossOrigin="",g.href=d,l&&g.setAttribute("nonce",l),document.head.appendChild(g),u)return new Promise((p,z)=>{g.addEventListener("load",p),g.addEventListener("error",()=>z(new Error(`Unable to preload CSS for ${d}`)))})}))}function r(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&r(o.reason);return e().catch(r)})},MD=[{label:"",tag:"PatientName"},{label:"MRN",tag:"PatientID"},{label:"ACC",tag:"AccessionNumber"},{label:"",tag:"StudyDescription"},{label:"",tag:"SeriesDescription"},{label:"",tag:"StudyDate"},{label:"",tag:"PatientAge"},{label:"",tag:"PatientSex"}],bD=256*1024*1024;function Ro(n){const e=["B","KB","MB","GB","TB"];let t=n,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s++;return s===0?`${n} B`:`${t.toFixed(1)} ${e[s]}`}function zD(n){const e=n.toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}class _D{pane;field;title;modeSpan;stateSpan;layoutPills=new Map;overlayPill;colormapPill;savePill;loadPill;retryPill;presetPill;focusMark;guardBytes=bD;forced=!1;pendingLayout=null;progressNote=null;overlayNote=null;probeNote=null;overlay=!1;overlayLines=[];presetIndex=-1;toolPills=new Map;handlers;engine=null;series=null;siblings=[];colormap="gray";tool="wl";constructor(e,t){this.handlers=t,this.pane=e,this.field=Xs(e,".image-field"),this.title=Xs(e,".pane-title"),this.modeSpan=Xs(e,".pane-mode"),this.stateSpan=Xs(e,".pane-state");for(const s of e.querySelectorAll(".image-layout")){const i=s.dataset.layout??"single";this.layoutPills.set(i,s),s.addEventListener("click",()=>{this.layout_set(i)})}this.overlayPill=Xs(e,".image-overlay"),this.overlayPill.addEventListener("click",()=>{this.overlay_set(!this.overlay)}),this.colormapPill=Xs(e,".image-colormap"),this.savePill=Xs(e,".image-save"),this.loadPill=Xs(e,".image-load"),this.retryPill=Xs(e,".image-retry"),this.presetPill=Xs(e,".image-preset"),this.focusMark=Xs(e,".image-focus"),this.field.tabIndex=0,this.colormapPill.addEventListener("click",()=>{this.colormap_cycle()}),this.savePill.addEventListener("click",()=>{this.annotations_save()}),this.loadPill.addEventListener("click",()=>{this.load_press()}),this.retryPill.addEventListener("click",()=>{this.retry_press()}),this.presetPill.addEventListener("click",()=>this.preset_cycle()),Xs(e,".image-tags").addEventListener("click",()=>this.handlers.tags_open());for(const s of hp){const i=Xs(e,`.image-tool[data-tool="${s}"]`);this.toolPills.set(s,i),i.addEventListener("click",()=>{this.tool_set(s)})}this.toolPills_paint(),this.field.addEventListener("mousedown",()=>{this.field.focus(),this.focusMark_paint(!0)}),this.field.addEventListener("focusin",()=>this.focusMark_paint(!0)),this.field.addEventListener("focusout",s=>{(!(s.relatedTarget instanceof Node)||!this.field.contains(s.relatedTarget))&&this.focusMark_paint(!1)}),this.field.addEventListener("keydown",s=>{if(s.key==="Escape"){this.field_release(),s.stopPropagation();return}s.stopPropagation()})}field_hasFocus(){return document.activeElement instanceof Node&&this.field.contains(document.activeElement)}field_release(){return this.field_hasFocus()?(document.activeElement.blur(),this.focusMark_paint(!1),!0):!1}async series_show(e,t={}){if(this.engine_dispose(),this.series=e,this.forced=t.force===!0,this.pendingLayout=null,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint(e.modality),this.siblings=t.siblings??[],this.pane.dataset.modality=zD(e.modality),this.title.textContent=`IMAGE ${e.modality.toUpperCase()} ${e.seriesDescription}`.trim(),this.title.title=this.title.textContent,this.siblings.length>1){const r=this.siblings.findIndex(a=>a.path===e.path)+1;this.handlers.note(`image: series ${r} of ${this.siblings.length} in this study; image series <n> switches`)}const{CornerstoneEngine:s}=await Xp(async()=>{const{CornerstoneEngine:r}=await import("./cornerstoneEngine-Dd1A3l-l.js").then(a=>a.b2);return{CornerstoneEngine:r}},__vite__mapDeps([0,1]),import.meta.url),i=new s(this.engineHost_get(),e,t.startAt??1);await this.engine_open(i),this.engine===i&&(this.guard_trips()?(this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${Ro(e.bytes)} · LOAD FOR STACK`,this.handlers.note(`image: ${Ro(e.bytes)} to fetch before the stack scrolls; press LOAD, image load, or image --force <path>`)):i.slices_fill(),await this.annotations_reload(i,e))}async annotations_reload(e,t){let s=0;for(const i of t.annotations.filter(r=>/\.dcm$/i.test(r))){if(this.engine!==e)return;const r=i.split("/").pop()??i;try{const a=await fetch(this.handlers.source.url_of(i));if(!a.ok){this.handlers.note(`image: ${r}: HTTP ${a.status}`);continue}const o=await e.annotations_import(await a.arrayBuffer());s+=o,this.handlers.note(o>0?`image: ${o} measurement${o===1?"":"s"} from ${r}`:`image: ${r}: no measurements this engine can place`)}catch(a){this.handlers.note(`image: ${r}: ${a instanceof Error?a.message:String(a)}`)}}this.pane.dataset.annotations=String(s)}async volume_show(e){this.engine_dispose(),this.series=null,this.siblings=[],this.pane.dataset.modality="NIFTI",this.title.textContent=`IMAGE ${e.split("/").pop()??""}`,this.title.title=e,this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint("NIFTI");const{NiivueEngine:t}=await Xp(async()=>{const{NiivueEngine:s}=await import("./niivueEngine-4fE28_PW.js");return{NiivueEngine:s}},[],import.meta.url);await this.engine_open(new t(this.engineHost_get(),e))}opening_show(e){const t=e.replace(/\/$/,"").split("/").pop()??e;this.stateSpan.textContent="OPENING",this.progress_show({label:`OPENING ${t}`,done:0,total:0})}opening_fail(e,t){this.stateSpan.textContent=t,this.progress_show({label:t,done:0,total:0});const s=this.progressNote;s!==null&&(s.classList.add("image-working-failed"),s.querySelector(".image-working-count").textContent=e)}siblings_get(){return this.siblings}series_get(){return this.series}state_get(){return this.engine===null?null:{...this.engine.state_get(),colormap:this.colormap,path:this.series?.path??null,guard:this.guardBytes,waiting:this.pendingLayout}}async layout_set(e){if(this.engine===null)return!1;if(e!=="single"&&this.guard_trips())return this.pendingLayout=e,this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${Ro(this.series?.bytes??0)} · LOAD FOR ${e.toUpperCase()}`,this.handlers.note(`image: ${Ro(this.series?.bytes??0)} to fetch for ${e}; press LOAD, image load, or image --force <path>`),!1;const t=this.engine.state_get().layout;return this.layoutPills_paint(e),this.modeSpan.textContent=e==="single"?"":e.toUpperCase(),this.overlay_hide(),await this.engine.layout_set(e)?(this.progress_show(null),this.overlay_paint(),this.toolPills_paint(),!0):(this.progress_show(null),this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),this.handlers.note(`image: layout ${e}: not offered by ${this.engine.name}`),!1)}layoutPills_paint(e){for(const[t,s]of this.layoutPills)s.classList.toggle("rail-off",t!==e)}guard_trips(){return this.guardBytes!==null&&!this.forced&&this.engine?.name==="cornerstone"&&(this.series?.bytes??0)>this.guardBytes}async load_press(){this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0;const e=this.pendingLayout;return this.pendingLayout=null,e!==null?this.layout_set(e):this.engine===null||this.engine.state_get().filled?!1:this.engine.slices_fill()}guard_set(e){this.guardBytes=e}guard_get(){return this.guardBytes}preset_cycle(){const e=this.presets_for(this.series?.modality??"NIFTI");if(e.length===0)return;this.presetIndex=(this.presetIndex+1)%e.length;const t=e[this.presetIndex];t!==void 0&&this.wl_set(t.lower,t.upper)&&(this.presetPill.textContent=t.name.toUpperCase())}presets_for(e){const t=e.toUpperCase();return Yg.filter(s=>s.modalities.length===0||s.modalities.includes(t))}presets_paint(e){this.presetIndex=-1;const t=this.presets_for(e);this.presetPill.hidden=t.length===0,this.presetPill.textContent="PRESET"}slice_set(e){if(this.engine===null)return!1;const t=this.engine.slice_set(e);return t||this.handlers.note(`image: slice ${e}: not offered in ${this.engine.state_get().layout} layout by ${this.engine.name}`),t}wl_set(e,t){if(this.engine===null)return!1;const s=this.engine.wl_set(e,t);return s||this.handlers.note(`image: wl: not offered by ${this.engine.name}`),s}ghost_set(e){if(this.engine===null)return!1;const t=this.engine.ghost_set(e);return t||this.handlers.note("image: ghost applies to the SLAB layout"),t}wlPreset_set(e){const t=this.series?.modality??"NIFTI",s=ZA(e,t);return s===void 0?(this.handlers.note(`image: wl preset ${e}: none for ${t}`),!1):this.wl_set(s.lower,s.upper)}colormap_set(e){return this.engine===null?!1:this.engine.colormap_set(e)?(this.colormap=e,this.colormapPill.textContent=e.toUpperCase(),!0):(this.handlers.note(`image: colormap ${e}: not offered by ${this.engine.name}`),!1)}tool_set(e){return this.engine===null?!1:this.engine.tool_set(e)?(this.tool=e,this.toolPills_paint(),!0):(this.handlers.note(`image: ${e}: not offered by ${this.engine.name}`),!1)}async annotations_save(){if(this.engine===null)return!1;const e=this.series?.seriesInstanceUID,t=/^(\/home\/[^/]+)\//.exec(this.series?.path??"")?.[1];if(e===void 0||t===void 0)return this.handlers.note("image: save: this series has no UID to file an annotation under"),!1;const s=await this.engine.annotations_export();if(s===null)return this.handlers.note(`image: save: nothing measured, or ${this.engine.name} writes no report`),!1;const i=`${t}/annotations/${e}/measurements.dcm`,r=await this.handlers.file_put(i,s);return this.handlers.note(r===200?`✓ ${i}`:`image: save: ${i}: HTTP ${r}`),r===200}dispose(){this.engine_dispose()}async colormap_cycle(){const e=qo[(qo.indexOf(this.colormap)+1)%qo.length]??"gray";this.colormap_set(e)}async engine_open(e){this.engine=e,this.field.replaceChildren(),this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.layoutPills_paint("single"),this.modeSpan.textContent="",this.colormapPill.textContent=this.colormap.toUpperCase();try{await e.open(this.field)}catch(s){this.stateSpan.textContent="REFUSED",this.handlers.note(`image: ${s instanceof Error?s.message:String(s)}`);return}const t=e.state_get().layout;this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),e.tool_set(this.tool),this.toolPills_paint(),this.progress_show(null),this.overlay_fill()}engine_dispose(){this.engine?.dispose(),this.engine=null,this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.field.replaceChildren(),this.stateSpan.textContent=""}retryPill_paint(){const e=this.engine===null?0:this.engine.state_get().refused,t=this.engine?.refused_retry!==void 0;this.retryPill.hidden=!t||e===0,this.retryPill.disabled||(this.retryPill.textContent=`RETRY ${e}`)}async retry_press(){if(!(this.engine?.refused_retry===void 0||this.retryPill.disabled)){this.retryPill.disabled=!0,this.retryPill.textContent="ASKING…";try{await this.engine.refused_retry()}finally{this.retryPill.disabled=!1,this.retryPill_paint()}}}engineHost_get(){return{source:this.handlers.source,readout_set:e=>{this.stateSpan.textContent=e,this.retryPill_paint()},progress_set:e=>this.progress_show(e),note:this.handlers.note,regard:e=>{this.handlers.regard(e),this.overlaySlice_paint()},probe_set:e=>this.probe_show(e)}}probe_show(e){if(e===null){this.probeNote?.remove(),this.probeNote=null;return}if(this.probeNote===null||this.probeNote.parentElement===null){const t=document.createElement("div");t.className="image-probe-note",this.field.appendChild(t),this.probeNote=t}this.probeNote.textContent=e}overlaySlice_paint(){const e=this.overlayNote?.querySelector(".image-overlay-slice")??null;if(e===null||this.engine===null)return;const t=this.engine.state_get();e.textContent=t.slices>1?`SLICE ${Math.max(1,t.slice)} OF ${t.slices}`:"",e.hidden=t.slices<=1}progress_show(e){if(e===null){this.progressNote?.remove(),this.progressNote=null;return}if(this.progressNote===null||this.progressNote.parentElement===null){const a=document.createElement("div");a.className="image-working",a.innerHTML='<span class="image-working-label"></span><span class="image-working-track"><span class="image-working-fill"></span></span><span class="image-working-count"></span>',this.field.appendChild(a),this.progressNote=a}const t=this.progressNote;t.classList.remove("image-working-failed");const s=e.total>0,i=s?Math.min(1,e.done/e.total):0;t.querySelector(".image-working-label").textContent=e.label,t.querySelector(".image-working-count").textContent=s?`${e.done} / ${e.total} · ${Math.round(i*100)}%`:"";const r=t.querySelector(".image-working-fill");r.classList.toggle("image-working-pacing",!s),r.style.width=s?`${Math.round(i*100)}%`:""}async overlay_set(e){if(this.overlay=e,this.overlayPill.textContent=e?"OVERLAY ON":"OVERLAY OFF",this.overlayPill.classList.toggle("rail-off",!e),!e){this.overlay_hide();return}await this.overlay_fill()}overlay_hide(){this.overlayNote?.remove(),this.overlayNote=null}async overlay_fill(){if(!this.overlay||this.series===null)return;const e=this.series.files[0]??this.series.path,t=await this.handlers.tags_read(e);if(t===null){this.handlers.note(`image: overlay: ${e}: no header to read`);return}this.overlayLines=MD.flatMap(s=>{const r=(t.constant.find(a=>a.name===s.tag)?.value??"").trim();return r===""?[]:[s.label===""?r:`${s.label} ${r}`]}),this.overlay_paint()}overlay_paint(){if(!this.overlay||this.overlayLines.length===0)return;this.overlay_hide();const e=document.createElement("div");e.className="image-overlay-note";const t=document.createElement("span");t.className="image-overlay-slice",e.appendChild(t);for(const s of this.overlayLines){const i=document.createElement("span");i.textContent=s,e.appendChild(i)}this.field.appendChild(e),this.overlayNote=e,this.overlaySlice_paint()}toolPills_paint(){const e=new Set(this.engine?.toolsOffered_get()??hp),t=this.engine!==null?this.engine.state_get().primaryTool:this.tool;for(const[s,i]of this.toolPills){const r=e.has(s);i.classList.toggle("rail-na",!r),i.classList.toggle("rail-off",r&&s!==t),i.disabled=!r}}focusMark_paint(e){this.focusMark.hidden=!e,this.pane.classList.toggle("image-field-focused",e)}}function Xs(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`image pane: missing ${e}`);return t}const gM=["patient","study","series","image","equipment","meta","private","other","varying"],wD=new Set(["meta","private"]),Yp="••••";class yD{pane;title;modeSpan;redactBlock;listing;handlers;redact=!0;model=null;groups=[];constructor(e,t){this.handlers=t,this.pane=e,this.title=Bo(e,".pane-title"),this.modeSpan=Bo(e,".pane-mode"),this.redactBlock=Bo(e,".tags-redact"),this.redactBlock.addEventListener("click",()=>this.redact_set(!this.redact));const s=Bo(e,".tags-panel");this.listing=new Qr({mount:s,traits:this.groupTraits_declare(),key:i=>i.group,chrome:{root:e,prefix:"tags"},caps:"root",row:{className:()=>"tags-group-row",groupClassName:i=>`tags-group tags-group-${i.group}`,decorate:i=>{i.title="fold this group open or shut (it keeps its place)"}},child:kr(i=>i.rows,{traits:this.tagTraits_declare(),key:i=>i.key,activatable:i=>i.items.length>0,row:{className:i=>`tags-row${i.phi?" tags-phi":""}`,groupClassName:()=>"tags-sequence",decorate:(i,r)=>{i.title=r.items.length>0?`${r.name}: fold the sequence open or shut`:`${r.tag} ${r.name}`}},child:kr(i=>i.items,{traits:this.itemTraits_declare(),key:i=>i.key,row:{className:()=>"tags-item-row",groupClassName:()=>"tags-item"},child:kr(i=>i.rows,{traits:this.tagTraits_declare(),key:i=>i.key,activatable:()=>!1,row:{className:i=>`tags-row tags-row-deep${i.phi?" tags-phi":""}`}})})}),state:i=>this.stateLine_compose(i),empty:()=>SD("NO TAGS")}),this.redactBlock_paint(),this.listing.rows_set([],{field:"tags"})}model_show(e){this.model=e,this.title.textContent=`TAGS ${OD(e)}`,this.pane.dataset.modality=xD(e),this.groups=vD(e),this.listing.rows_set([{key:e.path,rows:this.groups}],{field:e.path}),this.listing.open_set(0,this.groups.map(t=>t.group).filter(t=>!wD.has(t))),this.modeSpan.textContent=e.subject==="folder"?"FOLDER":""}path_get(){return this.model?.path??null}redact_get(){return this.redact}redact_set(e){this.redact=e,this.redactBlock_paint(),this.model!==null&&this.listing.rows_set([{key:this.model.path,rows:this.groups}],{field:this.model.path})}filter_set(e){if(e===null){this.listing.filter_toggle(!1);return}this.listing.filter_toggle(!0),this.listing.filter_set(e)}stateLine_compose(e){const t=this.groups.reduce((i,r)=>i+r.rows.length,0),s=[];return this.model!==null&&this.model.subject==="folder"&&(s.push(this.model.read===this.model.of?`${this.model.read} FILES`:`${this.model.read} OF ${this.model.of} FILES`),this.model.refused.length>0&&s.push(`REFUSED ${this.model.refused.length}`)),s.push(e.filter!==""?e.filter:`${t} TAGS`),this.redact&&s.push("REDACTED"),s.join(" · ")}redactBlock_paint(){this.redactBlock.textContent=this.redact?"REDACT ON":"REDACT OFF",this.redactBlock.classList.toggle("rail-off",!this.redact),this.pane.classList.toggle("tags-redacted",this.redact)}value_cell(e){const t=document.createElement("span");if(t.className="tags-value",e.phi&&this.redact)return t.textContent=Yp,t.title="identifying value, redacted; the REDACT block on the frame reveals it",t;if(t.textContent=e.value,e.decoded!==void 0){const s=document.createElement("span");s.className="tags-decoded",s.textContent=` ${e.decoded}`,t.appendChild(s)}if(e.distinct!==void 0){const s=document.createElement("span");s.className="tags-decoded",s.textContent=` (${e.distinct} distinct)`,t.appendChild(s)}return t}groupTraits_declare(){return[Fc(()=>!0),{key:"group",label:"GROUP",className:"tags-group-name",width:"minmax(12em, 1fr)",cell:e=>e.group.toUpperCase(),compare:e=>gM.indexOf(e.group)},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}tagTraits_declare(){return[Fc(e=>e.items.length>0),{key:"tag",label:"TAG",className:"tags-tag",width:"7em",cell:e=>e.tag,compare:e=>e.tag},{key:"name",label:"NAME",className:"tags-name",width:"minmax(8em, 1.4fr)",cell:e=>e.name,compare:e=>e.name.toLowerCase()},{key:"vr",label:"VR",className:"tags-vr",width:"2.4em",cell:e=>e.vr,compare:e=>e.vr},{key:"value",label:"VALUE",className:"tags-value-cell",width:"minmax(6em, 2fr)",cell:e=>this.value_cell(e),compare:e=>(e.phi&&this.redact?Yp:`${e.value} ${e.decoded??""}`).toLowerCase()}]}itemTraits_declare(){return[Fc(()=>!0),{key:"item",label:"ITEM",className:"tags-item-name",width:"minmax(12em, 1fr)",cell:e=>`ITEM ${e.index}`,compare:e=>e.index},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}}function Fc(n){return{key:"fold",label:"",className:"tags-fold",capped:!1,width:"1.4em",cell:e=>{const t=document.createElement("span");return t.className=n(e)?"tags-fold":"tags-fold tags-fold-none",t}}}function vD(n){const e=new Map;for(const t of n.constant){const s=t.group;e.has(s)||e.set(s,[]),e.get(s)?.push(MM(t,`${s}/${t.tag}`))}return n.varying.length>0&&e.set("varying",n.varying.map(t=>({tag:t.tag,name:t.name,vr:t.vr,value:t.distinct===1?t.first:`${t.first} .. ${t.last}`,phi:t.phi,items:[],distinct:t.distinct,key:`varying/${t.tag}`}))),gM.filter(t=>e.has(t)).map(t=>({group:t,rows:e.get(t)??[]}))}function MM(n,e){return{tag:n.tag,name:n.name,vr:n.vr,value:n.value,...n.decoded!==void 0?{decoded:n.decoded}:{},phi:n.phi,items:(n.items??[]).map((t,s)=>({index:s+1,key:`${e}/${s+1}`,rows:t.map(i=>MM(i,`${e}/${s+1}/${i.tag}`))})),key:e}}function OD(n){const e=n.path.replace(/\/$/,"").split("/").pop()??n.path;if(n.subject==="folder")return e.length>24?`${e.slice(0,22)}…`:e;const t=/^(\d+)-/.exec(e)?.[1];return t!==void 0?`INSTANCE ${Number(t)}`:e.length>24?`${e.slice(0,22)}…`:e}function xD(n){const e=(n.constant.find(t=>t.name==="Modality")?.value??"").toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}function SD(n){const e=document.createElement("div");return e.className="tags-note",e.textContent=n,e}function Bo(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`tags pane: missing ${e}`);return t}class AD{groups=new Map;membership=new Map;writeObserver=null;writeObserver_set(e){this.writeObserver=e}pane_join(e,t){this.pane_leave(e),this.membership.set(e,t),this.groups.has(t)||this.groups.set(t,{value:null,subscribers:new Map,viewers:new Set})}pane_leave(e){const t=this.membership.get(e);if(t===void 0)return;this.membership.delete(e);const s=this.groups.get(t);if(s!==void 0){s.subscribers.delete(e),s.viewers.delete(e);for(const i of this.membership.values())if(i===t)return;this.groups.delete(t)}}group_of(e){const t=this.membership.get(e);return t!==void 0?t:(this.pane_join(e,e),e)}viewer_mark(e){this.groups.get(this.group_of(e))?.viewers.add(e)}groupHasViewer(e){const t=this.groups.get(this.group_of(e));return t!==void 0&&t.viewers.size>0}regard_write(e,t){const s=this.group_of(e),i=this.groups.get(s),r={...t,paneId:e};i.value=r;for(const a of i.subscribers.values())a(r);this.writeObserver?.(r,s)}regard_subscribe(e,t){const s=this.groups.get(this.group_of(e));s.subscribers.set(e,t),s.value!==null&&t(s.value)}regard_get(e){return this.groups.get(this.group_of(e))?.value??null}}const jc=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],ED=new Set(["done","error","unconfirmed","stalled","timeout"]);function DD(n,e){const t=`${e.operation}:${e.itemId??""}`;if(e.phase==="complete"||e.phase==="failed"){const s=`${e.operation}:`;for(const i of[...n])(i===t||i.startsWith(s))&&n.delete(i);return}if(e.itemId!==void 0&&e.status!==void 0&&ED.has(e.status)){n.delete(t);return}n.add(t)}const ID=100;class TD{fields;running=new Set;activityTimer=null;activityFrame=0;constructor(e){this.fields={identity:Pi(e,"status-identity"),jobs:Pi(e,"status-jobs"),activity:Pi(e,"status-activity"),latency:Pi(e,"status-latency"),mismatch:Pi(e,"status-mismatch"),lamp:Pi(e,"status-lamp"),host:Pi(e,"status-host")}}attach_show(e){if(e.protocolVersion!==Hc){this.fields.mismatch.textContent=`WIRE V${e.protocolVersion} ≠ V${Hc}`,this.fields.mismatch.title="This surface and the daemon speak different contract versions. Some messages may be dropped.",this.hostControl_show(e.hostControl??[]);return}this.fields.mismatch.textContent="",this.fields.mismatch.title=e.stack!==void 0?`chell ${e.stack.chell} · calypso ${e.stack.calypso} · build ${e.stack.build}`:"",this.hostControl_show(e.hostControl??[])}hostControl_show(e){this.fields.host.textContent=e.length>0?`HOST ${e.join(" ")}`:"",this.fields.host.title=e.length>0?"Calypso was started with --host-control: `!` and pipes run on its host, upload/download reach its disk.":""}promptContext_show(e){const t=e.uri.replace(/^https?:\/\//,"");this.fields.identity.textContent=`${e.user}@${t}`.toUpperCase();const s=e.procWarmup,i=[];if(s!==void 0&&s.sweeping!==!1){const o=s.total!==void 0?`/${s.total}`:"",l=s.state!==void 0?` ${s.state.toUpperCase()}`:"";i.push(`JOBS ${s.loaded}${o}${l}`)}const r=s?.feeds??(s?.feed!==void 0?[s.feed]:[]);for(const o of r){const l=o.total>0?`/${o.total}`:"";i.push(o.failed!==void 0?`FEED ${o.id} FAILED ${o.loaded}${l}`:`FEED ${o.id} ${o.loaded}${l}`)}s?.roster!==void 0&&i.push(s.roster==="full"?"ROSTER WALK":"ROSTER DELTA"),s?.arrived!==void 0&&s.arrived.length>0&&i.push(s.arrived.length<=2?`+FEED ${s.arrived.join(" ")}`:`+${s.arrived.length} FEEDS`);const a=e.warmupFailures??[];a.length>0&&i.push(`WARM-UP FAILED: ${a.map(o=>o.label.toUpperCase()).join(" ")}`),this.fields.jobs.textContent=i.join(" · "),this.fields.jobs.classList.toggle("status-degraded",a.length>0),this.fields.jobs.title=a.length>0?a.map(o=>`${o.label}: ${o.message}`).join(`
|
|
4231
|
+
`);this.result.textContent=fD(s)||"(no output)"}}function xa(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`empty pane template is missing ${e}`);return t}function fD(n){return n.replace(/\x1b\[[0-9;:]*[A-Za-z]/g,"")}class pD{container;title;handlers;currentAddress=null;constructor(e,t,s){this.container=e,this.title=t,this.handlers=s,this.awaiting_render()}regard_show(e){if(this.currentAddress=e.address,this.title.textContent=`VIEWER — ${e.address}`.toUpperCase(),this.handlers.path_isImage(e.address)){this.container.replaceChildren();const t=document.createElement("img");t.className="files-image",t.src=this.handlers.imageUrl_build(e.address),t.alt=e.address,this.container.appendChild(t);return}this.handlers.content_fetch(e.address).then(t=>{if(this.currentAddress!==e.address)return;if(this.container.replaceChildren(),t.trim().length===0){const i=document.createElement("p");i.className="files-empty",i.textContent=`NO PREVIEW — ${e.address.toUpperCase()}`,this.container.appendChild(i);return}const s=document.createElement("pre");s.className="files-content",s.textContent=t,this.container.appendChild(s)})}awaiting_render(){this.container.replaceChildren();const e=document.createElement("p");e.className="files-empty",e.textContent="NO REGARD — INDICATE A FILE OR NODE IN THIS PANE’S GROUP",this.container.appendChild(e)}}const mD="modulepreload",gD=function(n,e){return new URL(n,e).href},qp={},Xp=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};const a=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");i=c(t.map(d=>{if(d=gD(d,s),d in qp)return;qp[d]=!0;const u=d.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(s)for(let p=a.length-1;p>=0;p--){const z=a[p];if(z.href===d&&(!u||z.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":mD,u||(g.as="script"),g.crossOrigin="",g.href=d,l&&g.setAttribute("nonce",l),document.head.appendChild(g),u)return new Promise((p,z)=>{g.addEventListener("load",p),g.addEventListener("error",()=>z(new Error(`Unable to preload CSS for ${d}`)))})}))}function r(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&r(o.reason);return e().catch(r)})},MD=[{label:"",tag:"PatientName"},{label:"MRN",tag:"PatientID"},{label:"ACC",tag:"AccessionNumber"},{label:"",tag:"StudyDescription"},{label:"",tag:"SeriesDescription"},{label:"",tag:"StudyDate"},{label:"",tag:"PatientAge"},{label:"",tag:"PatientSex"}],bD=256*1024*1024;function Ro(n){const e=["B","KB","MB","GB","TB"];let t=n,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s++;return s===0?`${n} B`:`${t.toFixed(1)} ${e[s]}`}function zD(n){const e=n.toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}class _D{pane;field;title;modeSpan;stateSpan;layoutPills=new Map;overlayPill;colormapPill;savePill;loadPill;retryPill;presetPill;focusMark;guardBytes=bD;forced=!1;pendingLayout=null;progressNote=null;overlayNote=null;probeNote=null;overlay=!1;overlayLines=[];presetIndex=-1;toolPills=new Map;handlers;engine=null;series=null;siblings=[];colormap="gray";tool="wl";constructor(e,t){this.handlers=t,this.pane=e,this.field=Xs(e,".image-field"),this.title=Xs(e,".pane-title"),this.modeSpan=Xs(e,".pane-mode"),this.stateSpan=Xs(e,".pane-state");for(const s of e.querySelectorAll(".image-layout")){const i=s.dataset.layout??"single";this.layoutPills.set(i,s),s.addEventListener("click",()=>{this.layout_set(i)})}this.overlayPill=Xs(e,".image-overlay"),this.overlayPill.addEventListener("click",()=>{this.overlay_set(!this.overlay)}),this.colormapPill=Xs(e,".image-colormap"),this.savePill=Xs(e,".image-save"),this.loadPill=Xs(e,".image-load"),this.retryPill=Xs(e,".image-retry"),this.presetPill=Xs(e,".image-preset"),this.focusMark=Xs(e,".image-focus"),this.field.tabIndex=0,this.colormapPill.addEventListener("click",()=>{this.colormap_cycle()}),this.savePill.addEventListener("click",()=>{this.annotations_save()}),this.loadPill.addEventListener("click",()=>{this.load_press()}),this.retryPill.addEventListener("click",()=>{this.retry_press()}),this.presetPill.addEventListener("click",()=>this.preset_cycle()),Xs(e,".image-tags").addEventListener("click",()=>this.handlers.tags_open());for(const s of hp){const i=Xs(e,`.image-tool[data-tool="${s}"]`);this.toolPills.set(s,i),i.addEventListener("click",()=>{this.tool_set(s)})}this.toolPills_paint(),this.field.addEventListener("mousedown",()=>{this.field.focus(),this.focusMark_paint(!0)}),this.field.addEventListener("focusin",()=>this.focusMark_paint(!0)),this.field.addEventListener("focusout",s=>{(!(s.relatedTarget instanceof Node)||!this.field.contains(s.relatedTarget))&&this.focusMark_paint(!1)}),this.field.addEventListener("keydown",s=>{if(s.key==="Escape"){this.field_release(),s.stopPropagation();return}s.stopPropagation()})}field_hasFocus(){return document.activeElement instanceof Node&&this.field.contains(document.activeElement)}field_release(){return this.field_hasFocus()?(document.activeElement.blur(),this.focusMark_paint(!1),!0):!1}async series_show(e,t={}){if(this.engine_dispose(),this.series=e,this.forced=t.force===!0,this.pendingLayout=null,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint(e.modality),this.siblings=t.siblings??[],this.pane.dataset.modality=zD(e.modality),this.title.textContent=`IMAGE ${e.modality.toUpperCase()} ${e.seriesDescription}`.trim(),this.title.title=this.title.textContent,this.siblings.length>1){const r=this.siblings.findIndex(a=>a.path===e.path)+1;this.handlers.note(`image: series ${r} of ${this.siblings.length} in this study; image series <n> switches`)}const{CornerstoneEngine:s}=await Xp(async()=>{const{CornerstoneEngine:r}=await import("./cornerstoneEngine-DyH_C-Fw.js").then(a=>a.b2);return{CornerstoneEngine:r}},__vite__mapDeps([0,1]),import.meta.url),i=new s(this.engineHost_get(),e,t.startAt??1);await this.engine_open(i),this.engine===i&&(this.guard_trips()?(this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${Ro(e.bytes)} · LOAD FOR STACK`,this.handlers.note(`image: ${Ro(e.bytes)} to fetch before the stack scrolls; press LOAD, image load, or image --force <path>`)):i.slices_fill(),await this.annotations_reload(i,e))}async annotations_reload(e,t){let s=0;for(const i of t.annotations.filter(r=>/\.dcm$/i.test(r))){if(this.engine!==e)return;const r=i.split("/").pop()??i;try{const a=await fetch(this.handlers.source.url_of(i));if(!a.ok){this.handlers.note(`image: ${r}: HTTP ${a.status}`);continue}const o=await e.annotations_import(await a.arrayBuffer());s+=o,this.handlers.note(o>0?`image: ${o} measurement${o===1?"":"s"} from ${r}`:`image: ${r}: no measurements this engine can place`)}catch(a){this.handlers.note(`image: ${r}: ${a instanceof Error?a.message:String(a)}`)}}this.pane.dataset.annotations=String(s)}async volume_show(e){this.engine_dispose(),this.series=null,this.siblings=[],this.pane.dataset.modality="NIFTI",this.title.textContent=`IMAGE ${e.split("/").pop()??""}`,this.title.title=e,this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0,this.presets_paint("NIFTI");const{NiivueEngine:t}=await Xp(async()=>{const{NiivueEngine:s}=await import("./niivueEngine-DwasekQ0.js");return{NiivueEngine:s}},[],import.meta.url);await this.engine_open(new t(this.engineHost_get(),e))}opening_show(e){const t=e.replace(/\/$/,"").split("/").pop()??e;this.stateSpan.textContent="OPENING",this.progress_show({label:`OPENING ${t}`,done:0,total:0})}opening_fail(e,t){this.stateSpan.textContent=t,this.progress_show({label:t,done:0,total:0});const s=this.progressNote;s!==null&&(s.classList.add("image-working-failed"),s.querySelector(".image-working-count").textContent=e)}siblings_get(){return this.siblings}series_get(){return this.series}state_get(){return this.engine===null?null:{...this.engine.state_get(),colormap:this.colormap,path:this.series?.path??null,guard:this.guardBytes,waiting:this.pendingLayout}}async layout_set(e){if(this.engine===null)return!1;if(e!=="single"&&this.guard_trips())return this.pendingLayout=e,this.loadPill.hidden=!1,this.stateSpan.textContent=`SERIES ${Ro(this.series?.bytes??0)} · LOAD FOR ${e.toUpperCase()}`,this.handlers.note(`image: ${Ro(this.series?.bytes??0)} to fetch for ${e}; press LOAD, image load, or image --force <path>`),!1;const t=this.engine.state_get().layout;return this.layoutPills_paint(e),this.modeSpan.textContent=e==="single"?"":e.toUpperCase(),this.overlay_hide(),await this.engine.layout_set(e)?(this.progress_show(null),this.overlay_paint(),this.toolPills_paint(),!0):(this.progress_show(null),this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),this.handlers.note(`image: layout ${e}: not offered by ${this.engine.name}`),!1)}layoutPills_paint(e){for(const[t,s]of this.layoutPills)s.classList.toggle("rail-off",t!==e)}guard_trips(){return this.guardBytes!==null&&!this.forced&&this.engine?.name==="cornerstone"&&(this.series?.bytes??0)>this.guardBytes}async load_press(){this.forced=!0,this.loadPill.hidden=!0,this.retryPill.hidden=!0;const e=this.pendingLayout;return this.pendingLayout=null,e!==null?this.layout_set(e):this.engine===null||this.engine.state_get().filled?!1:this.engine.slices_fill()}guard_set(e){this.guardBytes=e}guard_get(){return this.guardBytes}preset_cycle(){const e=this.presets_for(this.series?.modality??"NIFTI");if(e.length===0)return;this.presetIndex=(this.presetIndex+1)%e.length;const t=e[this.presetIndex];t!==void 0&&this.wl_set(t.lower,t.upper)&&(this.presetPill.textContent=t.name.toUpperCase())}presets_for(e){const t=e.toUpperCase();return Yg.filter(s=>s.modalities.length===0||s.modalities.includes(t))}presets_paint(e){this.presetIndex=-1;const t=this.presets_for(e);this.presetPill.hidden=t.length===0,this.presetPill.textContent="PRESET"}slice_set(e){if(this.engine===null)return!1;const t=this.engine.slice_set(e);return t||this.handlers.note(`image: slice ${e}: not offered in ${this.engine.state_get().layout} layout by ${this.engine.name}`),t}wl_set(e,t){if(this.engine===null)return!1;const s=this.engine.wl_set(e,t);return s||this.handlers.note(`image: wl: not offered by ${this.engine.name}`),s}ghost_set(e){if(this.engine===null)return!1;const t=this.engine.ghost_set(e);return t||this.handlers.note("image: ghost applies to the SLAB layout"),t}wlPreset_set(e){const t=this.series?.modality??"NIFTI",s=ZA(e,t);return s===void 0?(this.handlers.note(`image: wl preset ${e}: none for ${t}`),!1):this.wl_set(s.lower,s.upper)}colormap_set(e){return this.engine===null?!1:this.engine.colormap_set(e)?(this.colormap=e,this.colormapPill.textContent=e.toUpperCase(),!0):(this.handlers.note(`image: colormap ${e}: not offered by ${this.engine.name}`),!1)}tool_set(e){return this.engine===null?!1:this.engine.tool_set(e)?(this.tool=e,this.toolPills_paint(),!0):(this.handlers.note(`image: ${e}: not offered by ${this.engine.name}`),!1)}async annotations_save(){if(this.engine===null)return!1;const e=this.series?.seriesInstanceUID,t=/^(\/home\/[^/]+)\//.exec(this.series?.path??"")?.[1];if(e===void 0||t===void 0)return this.handlers.note("image: save: this series has no UID to file an annotation under"),!1;const s=await this.engine.annotations_export();if(s===null)return this.handlers.note(`image: save: nothing measured, or ${this.engine.name} writes no report`),!1;const i=`${t}/annotations/${e}/measurements.dcm`,r=await this.handlers.file_put(i,s);return this.handlers.note(r===200?`✓ ${i}`:`image: save: ${i}: HTTP ${r}`),r===200}dispose(){this.engine_dispose()}async colormap_cycle(){const e=qo[(qo.indexOf(this.colormap)+1)%qo.length]??"gray";this.colormap_set(e)}async engine_open(e){this.engine=e,this.field.replaceChildren(),this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.layoutPills_paint("single"),this.modeSpan.textContent="",this.colormapPill.textContent=this.colormap.toUpperCase();try{await e.open(this.field)}catch(s){this.stateSpan.textContent="REFUSED",this.handlers.note(`image: ${s instanceof Error?s.message:String(s)}`);return}const t=e.state_get().layout;this.layoutPills_paint(t),this.modeSpan.textContent=t==="single"?"":t.toUpperCase(),e.tool_set(this.tool),this.toolPills_paint(),this.progress_show(null),this.overlay_fill()}engine_dispose(){this.engine?.dispose(),this.engine=null,this.progressNote=null,this.overlayNote=null,this.probeNote=null,this.field.replaceChildren(),this.stateSpan.textContent=""}retryPill_paint(){const e=this.engine===null?0:this.engine.state_get().refused,t=this.engine?.refused_retry!==void 0;this.retryPill.hidden=!t||e===0,this.retryPill.disabled||(this.retryPill.textContent=`RETRY ${e}`)}async retry_press(){if(!(this.engine?.refused_retry===void 0||this.retryPill.disabled)){this.retryPill.disabled=!0,this.retryPill.textContent="ASKING…";try{await this.engine.refused_retry()}finally{this.retryPill.disabled=!1,this.retryPill_paint()}}}engineHost_get(){return{source:this.handlers.source,readout_set:e=>{this.stateSpan.textContent=e,this.retryPill_paint()},progress_set:e=>this.progress_show(e),note:this.handlers.note,regard:e=>{this.handlers.regard(e),this.overlaySlice_paint()},probe_set:e=>this.probe_show(e)}}probe_show(e){if(e===null){this.probeNote?.remove(),this.probeNote=null;return}if(this.probeNote===null||this.probeNote.parentElement===null){const t=document.createElement("div");t.className="image-probe-note",this.field.appendChild(t),this.probeNote=t}this.probeNote.textContent=e}overlaySlice_paint(){const e=this.overlayNote?.querySelector(".image-overlay-slice")??null;if(e===null||this.engine===null)return;const t=this.engine.state_get();e.textContent=t.slices>1?`SLICE ${Math.max(1,t.slice)} OF ${t.slices}`:"",e.hidden=t.slices<=1}progress_show(e){if(e===null){this.progressNote?.remove(),this.progressNote=null;return}if(this.progressNote===null||this.progressNote.parentElement===null){const a=document.createElement("div");a.className="image-working",a.innerHTML='<span class="image-working-label"></span><span class="image-working-track"><span class="image-working-fill"></span></span><span class="image-working-count"></span>',this.field.appendChild(a),this.progressNote=a}const t=this.progressNote;t.classList.remove("image-working-failed");const s=e.total>0,i=s?Math.min(1,e.done/e.total):0;t.querySelector(".image-working-label").textContent=e.label,t.querySelector(".image-working-count").textContent=s?`${e.done} / ${e.total} · ${Math.round(i*100)}%`:"";const r=t.querySelector(".image-working-fill");r.classList.toggle("image-working-pacing",!s),r.style.width=s?`${Math.round(i*100)}%`:""}async overlay_set(e){if(this.overlay=e,this.overlayPill.textContent=e?"OVERLAY ON":"OVERLAY OFF",this.overlayPill.classList.toggle("rail-off",!e),!e){this.overlay_hide();return}await this.overlay_fill()}overlay_hide(){this.overlayNote?.remove(),this.overlayNote=null}async overlay_fill(){if(!this.overlay||this.series===null)return;const e=this.series.files[0]??this.series.path,t=await this.handlers.tags_read(e);if(t===null){this.handlers.note(`image: overlay: ${e}: no header to read`);return}this.overlayLines=MD.flatMap(s=>{const r=(t.constant.find(a=>a.name===s.tag)?.value??"").trim();return r===""?[]:[s.label===""?r:`${s.label} ${r}`]}),this.overlay_paint()}overlay_paint(){if(!this.overlay||this.overlayLines.length===0)return;this.overlay_hide();const e=document.createElement("div");e.className="image-overlay-note";const t=document.createElement("span");t.className="image-overlay-slice",e.appendChild(t);for(const s of this.overlayLines){const i=document.createElement("span");i.textContent=s,e.appendChild(i)}this.field.appendChild(e),this.overlayNote=e,this.overlaySlice_paint()}toolPills_paint(){const e=new Set(this.engine?.toolsOffered_get()??hp),t=this.engine!==null?this.engine.state_get().primaryTool:this.tool;for(const[s,i]of this.toolPills){const r=e.has(s);i.classList.toggle("rail-na",!r),i.classList.toggle("rail-off",r&&s!==t),i.disabled=!r}}focusMark_paint(e){this.focusMark.hidden=!e,this.pane.classList.toggle("image-field-focused",e)}}function Xs(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`image pane: missing ${e}`);return t}const gM=["patient","study","series","image","equipment","meta","private","other","varying"],wD=new Set(["meta","private"]),Yp="••••";class yD{pane;title;modeSpan;redactBlock;listing;handlers;redact=!0;model=null;groups=[];constructor(e,t){this.handlers=t,this.pane=e,this.title=Bo(e,".pane-title"),this.modeSpan=Bo(e,".pane-mode"),this.redactBlock=Bo(e,".tags-redact"),this.redactBlock.addEventListener("click",()=>this.redact_set(!this.redact));const s=Bo(e,".tags-panel");this.listing=new Qr({mount:s,traits:this.groupTraits_declare(),key:i=>i.group,chrome:{root:e,prefix:"tags"},caps:"root",row:{className:()=>"tags-group-row",groupClassName:i=>`tags-group tags-group-${i.group}`,decorate:i=>{i.title="fold this group open or shut (it keeps its place)"}},child:kr(i=>i.rows,{traits:this.tagTraits_declare(),key:i=>i.key,activatable:i=>i.items.length>0,row:{className:i=>`tags-row${i.phi?" tags-phi":""}`,groupClassName:()=>"tags-sequence",decorate:(i,r)=>{i.title=r.items.length>0?`${r.name}: fold the sequence open or shut`:`${r.tag} ${r.name}`}},child:kr(i=>i.items,{traits:this.itemTraits_declare(),key:i=>i.key,row:{className:()=>"tags-item-row",groupClassName:()=>"tags-item"},child:kr(i=>i.rows,{traits:this.tagTraits_declare(),key:i=>i.key,activatable:()=>!1,row:{className:i=>`tags-row tags-row-deep${i.phi?" tags-phi":""}`}})})}),state:i=>this.stateLine_compose(i),empty:()=>SD("NO TAGS")}),this.redactBlock_paint(),this.listing.rows_set([],{field:"tags"})}model_show(e){this.model=e,this.title.textContent=`TAGS ${OD(e)}`,this.pane.dataset.modality=xD(e),this.groups=vD(e),this.listing.rows_set([{key:e.path,rows:this.groups}],{field:e.path}),this.listing.open_set(0,this.groups.map(t=>t.group).filter(t=>!wD.has(t))),this.modeSpan.textContent=e.subject==="folder"?"FOLDER":""}path_get(){return this.model?.path??null}redact_get(){return this.redact}redact_set(e){this.redact=e,this.redactBlock_paint(),this.model!==null&&this.listing.rows_set([{key:this.model.path,rows:this.groups}],{field:this.model.path})}filter_set(e){if(e===null){this.listing.filter_toggle(!1);return}this.listing.filter_toggle(!0),this.listing.filter_set(e)}stateLine_compose(e){const t=this.groups.reduce((i,r)=>i+r.rows.length,0),s=[];return this.model!==null&&this.model.subject==="folder"&&(s.push(this.model.read===this.model.of?`${this.model.read} FILES`:`${this.model.read} OF ${this.model.of} FILES`),this.model.refused.length>0&&s.push(`REFUSED ${this.model.refused.length}`)),s.push(e.filter!==""?e.filter:`${t} TAGS`),this.redact&&s.push("REDACTED"),s.join(" · ")}redactBlock_paint(){this.redactBlock.textContent=this.redact?"REDACT ON":"REDACT OFF",this.redactBlock.classList.toggle("rail-off",!this.redact),this.pane.classList.toggle("tags-redacted",this.redact)}value_cell(e){const t=document.createElement("span");if(t.className="tags-value",e.phi&&this.redact)return t.textContent=Yp,t.title="identifying value, redacted; the REDACT block on the frame reveals it",t;if(t.textContent=e.value,e.decoded!==void 0){const s=document.createElement("span");s.className="tags-decoded",s.textContent=` ${e.decoded}`,t.appendChild(s)}if(e.distinct!==void 0){const s=document.createElement("span");s.className="tags-decoded",s.textContent=` (${e.distinct} distinct)`,t.appendChild(s)}return t}groupTraits_declare(){return[Fc(()=>!0),{key:"group",label:"GROUP",className:"tags-group-name",width:"minmax(12em, 1fr)",cell:e=>e.group.toUpperCase(),compare:e=>gM.indexOf(e.group)},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}tagTraits_declare(){return[Fc(e=>e.items.length>0),{key:"tag",label:"TAG",className:"tags-tag",width:"7em",cell:e=>e.tag,compare:e=>e.tag},{key:"name",label:"NAME",className:"tags-name",width:"minmax(8em, 1.4fr)",cell:e=>e.name,compare:e=>e.name.toLowerCase()},{key:"vr",label:"VR",className:"tags-vr",width:"2.4em",cell:e=>e.vr,compare:e=>e.vr},{key:"value",label:"VALUE",className:"tags-value-cell",width:"minmax(6em, 2fr)",cell:e=>this.value_cell(e),compare:e=>(e.phi&&this.redact?Yp:`${e.value} ${e.decoded??""}`).toLowerCase()}]}itemTraits_declare(){return[Fc(()=>!0),{key:"item",label:"ITEM",className:"tags-item-name",width:"minmax(12em, 1fr)",cell:e=>`ITEM ${e.index}`,compare:e=>e.index},{key:"count",label:"TAGS",className:"tags-group-count",width:"5em",cell:e=>String(e.rows.length),compare:e=>e.rows.length}]}}function Fc(n){return{key:"fold",label:"",className:"tags-fold",capped:!1,width:"1.4em",cell:e=>{const t=document.createElement("span");return t.className=n(e)?"tags-fold":"tags-fold tags-fold-none",t}}}function vD(n){const e=new Map;for(const t of n.constant){const s=t.group;e.has(s)||e.set(s,[]),e.get(s)?.push(MM(t,`${s}/${t.tag}`))}return n.varying.length>0&&e.set("varying",n.varying.map(t=>({tag:t.tag,name:t.name,vr:t.vr,value:t.distinct===1?t.first:`${t.first} .. ${t.last}`,phi:t.phi,items:[],distinct:t.distinct,key:`varying/${t.tag}`}))),gM.filter(t=>e.has(t)).map(t=>({group:t,rows:e.get(t)??[]}))}function MM(n,e){return{tag:n.tag,name:n.name,vr:n.vr,value:n.value,...n.decoded!==void 0?{decoded:n.decoded}:{},phi:n.phi,items:(n.items??[]).map((t,s)=>({index:s+1,key:`${e}/${s+1}`,rows:t.map(i=>MM(i,`${e}/${s+1}/${i.tag}`))})),key:e}}function OD(n){const e=n.path.replace(/\/$/,"").split("/").pop()??n.path;if(n.subject==="folder")return e.length>24?`${e.slice(0,22)}…`:e;const t=/^(\d+)-/.exec(e)?.[1];return t!==void 0?`INSTANCE ${Number(t)}`:e.length>24?`${e.slice(0,22)}…`:e}function xD(n){const e=(n.constant.find(t=>t.name==="Modality")?.value??"").toUpperCase();return e==="MR"||e==="CT"||e==="PT"?e:"OT"}function SD(n){const e=document.createElement("div");return e.className="tags-note",e.textContent=n,e}function Bo(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`tags pane: missing ${e}`);return t}class AD{groups=new Map;membership=new Map;writeObserver=null;writeObserver_set(e){this.writeObserver=e}pane_join(e,t){this.pane_leave(e),this.membership.set(e,t),this.groups.has(t)||this.groups.set(t,{value:null,subscribers:new Map,viewers:new Set})}pane_leave(e){const t=this.membership.get(e);if(t===void 0)return;this.membership.delete(e);const s=this.groups.get(t);if(s!==void 0){s.subscribers.delete(e),s.viewers.delete(e);for(const i of this.membership.values())if(i===t)return;this.groups.delete(t)}}group_of(e){const t=this.membership.get(e);return t!==void 0?t:(this.pane_join(e,e),e)}viewer_mark(e){this.groups.get(this.group_of(e))?.viewers.add(e)}groupHasViewer(e){const t=this.groups.get(this.group_of(e));return t!==void 0&&t.viewers.size>0}regard_write(e,t){const s=this.group_of(e),i=this.groups.get(s),r={...t,paneId:e};i.value=r;for(const a of i.subscribers.values())a(r);this.writeObserver?.(r,s)}regard_subscribe(e,t){const s=this.groups.get(this.group_of(e));s.subscribers.set(e,t),s.value!==null&&t(s.value)}regard_get(e){return this.groups.get(this.group_of(e))?.value??null}}const jc=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],ED=new Set(["done","error","unconfirmed","stalled","timeout"]);function DD(n,e){const t=`${e.operation}:${e.itemId??""}`;if(e.phase==="complete"||e.phase==="failed"){const s=`${e.operation}:`;for(const i of[...n])(i===t||i.startsWith(s))&&n.delete(i);return}if(e.itemId!==void 0&&e.status!==void 0&&ED.has(e.status)){n.delete(t);return}n.add(t)}const ID=100;class TD{fields;running=new Set;activityTimer=null;activityFrame=0;constructor(e){this.fields={identity:Pi(e,"status-identity"),jobs:Pi(e,"status-jobs"),activity:Pi(e,"status-activity"),latency:Pi(e,"status-latency"),mismatch:Pi(e,"status-mismatch"),lamp:Pi(e,"status-lamp"),host:Pi(e,"status-host")}}attach_show(e){if(e.protocolVersion!==Hc){this.fields.mismatch.textContent=`WIRE V${e.protocolVersion} ≠ V${Hc}`,this.fields.mismatch.title="This surface and the daemon speak different contract versions. Some messages may be dropped.",this.hostControl_show(e.hostControl??[]);return}this.fields.mismatch.textContent="",this.fields.mismatch.title=e.stack!==void 0?`chell ${e.stack.chell} · calypso ${e.stack.calypso} · build ${e.stack.build}`:"",this.hostControl_show(e.hostControl??[])}hostControl_show(e){this.fields.host.textContent=e.length>0?`HOST ${e.join(" ")}`:"",this.fields.host.title=e.length>0?"Calypso was started with --host-control: `!` and pipes run on its host, upload/download reach its disk.":""}promptContext_show(e){const t=e.uri.replace(/^https?:\/\//,"");this.fields.identity.textContent=`${e.user}@${t}`.toUpperCase();const s=e.procWarmup,i=[];if(s!==void 0&&s.sweeping!==!1){const o=s.total!==void 0?`/${s.total}`:"",l=s.state!==void 0?` ${s.state.toUpperCase()}`:"";i.push(`JOBS ${s.loaded}${o}${l}`)}const r=s?.feeds??(s?.feed!==void 0?[s.feed]:[]);for(const o of r){const l=o.total>0?`/${o.total}`:"";i.push(o.failed!==void 0?`FEED ${o.id} FAILED ${o.loaded}${l}`:`FEED ${o.id} ${o.loaded}${l}`)}s?.roster!==void 0&&i.push(s.roster==="full"?"ROSTER WALK":"ROSTER DELTA"),s?.arrived!==void 0&&s.arrived.length>0&&i.push(s.arrived.length<=2?`+FEED ${s.arrived.join(" ")}`:`+${s.arrived.length} FEEDS`);const a=e.warmupFailures??[];a.length>0&&i.push(`WARM-UP FAILED: ${a.map(o=>o.label.toUpperCase()).join(" ")}`),this.fields.jobs.textContent=i.join(" · "),this.fields.jobs.classList.toggle("status-degraded",a.length>0),this.fields.jobs.title=a.length>0?a.map(o=>`${o.label}: ${o.message}`).join(`
|
|
4232
4232
|
`):r.length>0?"A feed is being indexed on its first visit; it opens when the walk completes.":"",this.fields.latency.textContent=e.lastCommandDurationMs>0?`${e.lastCommandDurationMs}MS`:""}progress_observe(e){DD(this.running,e),this.activity_paint()}activity_clear(){this.running.clear(),this.activity_paint()}connection_show(e){this.fields.lamp.textContent=e?"ONLINE":"OFFLINE",this.fields.lamp.classList.toggle("lamp-online",e),this.fields.lamp.classList.toggle("lamp-offline",!e),e||this.activity_clear()}activity_paint(){if(this.running.size===0){this.activityTimer!==null&&(clearInterval(this.activityTimer),this.activityTimer=null),this.fields.activity.textContent="";return}const e=()=>{const t=jc[this.activityFrame]??jc[0];this.fields.activity.textContent=`${t} ${this.running.size} RUNNING`};e(),this.activityTimer===null&&(this.activityTimer=window.setInterval(()=>{this.activityFrame=(this.activityFrame+1)%jc.length,e()},ID))}}function Pi(n,e){const t=n.getElementById(e);if(t===null)throw new Error(`status bar: no element with id '${e}'`);return t}function GD(n){return n>=6e4?`${Math.max(1,Math.round(n/6e4))} MIN`:`${Math.max(1,Math.round(n/1e3))} S`}function tn(n){return n.toLocaleString("en-US")}class RD{mount;counts=null;context=null;msPerPage=null;walkSamples=new Map;clock;acts;state=void 0;constructor(e,t=()=>Date.now(),s={}){this.mount=e,this.clock=t,this.acts=s,this.render()}state_show(e){this.state=e,this.render()}pace_show(e){this.msPerPage=e,this.render()}eta_of(e,t,s){const i=this.clock(),r=this.walkSamples.get(e);let a=r?.rowsPerMs??null;r!==void 0&&t>r.loaded&&i>r.at&&(a=(t-r.loaded)/(i-r.at)),(r===void 0||t!==r.loaded)&&this.walkSamples.set(e,{loaded:t,at:i,rowsPerMs:a});const o=Math.max(0,s-t);return s<=0?null:a!==null&&a>0?o/a:this.msPerPage!==null&&this.msPerPage>0?Math.ceil(o/100/4)*this.msPerPage:null}counts_show(e){this.counts=e,this.render()}promptContext_show(e){this.context=e,e.procIndex!==void 0&&(this.counts={jobs:e.procIndex.jobs,feeds:e.procIndex.feeds}),this.render()}rows_compose(){const e=[],t=this.context?.procWarmup,s=this.context?.warmupFailures??[],i=t!==void 0&&t.sweeping!==!1,r=this.counts!==null?`${tn(this.counts.jobs)} JOBS · ${tn(this.counts.feeds)} FEEDS`:"";if(s.length>0)e.push({label:"INDEX",bar:null,value:`${r}${r?" · ":""}FAILED: ${s.map(l=>l.label.toUpperCase()).join(" ")}`,title:s.map(l=>`${l.label}: ${l.message}`).join(`
|
|
4233
4233
|
`),degraded:!0});else if(i&&t!==void 0){const l=(t.state??"cold").toUpperCase();e.push({label:"INDEX",bar:{loaded:t.loaded,total:t.total??0,state:t.state==="failed"?"failed":"running"},value:`SWEEP ${tn(t.loaded)} / ${t.total!==void 0?tn(t.total):"?"} · ${l}`,title:"The global topology sweep: every plugin instance CUBE holds, walked page by page.",degraded:t.state==="failed"})}else e.push({label:"INDEX",bar:null,value:r?`${r} · CURRENT`:"CURRENT",title:"Nothing is moving: the process index is whole and current.",degraded:!1});if(this.state!==void 0){const l=this.state;e.push({label:"RUNNING",bar:null,value:`${tn(l.running)} IN ${tn(l.runningFeeds)} FEEDS · SCHEDULED ${tn(l.scheduled)}`,title:"Jobs running and waiting across every feed the index holds, from the roster's own counters.",degraded:!1,verb:this.acts.errored_open!==void 0?{label:`ERRORED ${tn(l.errored)} IN ${tn(l.erroredFeeds)} FEEDS`,title:"Open the runs roster filtered to the feeds with errored jobs.",act:this.acts.errored_open}:null})}const a=t?.feeds??(t?.feed!==void 0?[t.feed]:[]);for(const l of Array.from(this.walkSamples.keys()))a.some(c=>c.id===l)||this.walkSamples.delete(l);for(const l of a){const c=l.total>0?tn(l.total):"?";if(l.failed!==void 0)e.push({label:`FEED ${l.id}`,bar:{loaded:l.loaded,total:l.total,state:"failed"},value:`FAILED AT ${tn(l.loaded)} / ${c} · ${l.failed.toUpperCase()}`,title:"The walk stopped; the next visit to the feed starts it again.",degraded:!0});else{const d=this.eta_of(l.id,l.loaded,l.total);e.push({label:`FEED ${l.id}`,bar:{loaded:l.loaded,total:l.total,state:"running"},value:`INDEXING ${tn(l.loaded)} / ${c}${d!==null?` · ETA ${GD(d)}`:""}`,title:"A feed is being indexed on its first visit; it opens when the walk lands.",degraded:!1})}}t?.roster!==void 0&&e.push({label:"ROSTER",bar:null,value:t.roster==="full"?"FULL WALK · every feed the identity can see":"DELTA · feeds newer than the roster knows",title:"The roster is being brought up to date; the listing answered from the cache and refreshes when arrivals land.",degraded:!1});const o=t?.arrived??[];return o.length>0&&e.push({label:"ARRIVED",bar:null,value:o.length<=3?o.map(l=>`FEED ${l}`).join(" · "):`${o.length} FEEDS`,title:"Feeds the roster gained: created here, or shared with this identity.",degraded:!1}),e}render(){const e=this.rows_compose();this.mount.replaceChildren();for(const t of e){const s=document.createElement("div");s.className="index-row telemetry-row",s.classList.toggle("status-degraded",t.degraded),s.title=t.title;const i=document.createElement("span");if(i.className="telemetry-label",i.textContent=t.label,s.appendChild(i),t.bar!==null){const a=document.createElement("span");a.className=`index-bar listing-progress listing-progress-${t.bar.state}`;const o=document.createElement("span");o.className="listing-progress-fill";const l=t.bar.total>0?Math.min(100,Math.round(t.bar.loaded/t.bar.total*100)):0;o.style.width=`${l}%`,a.appendChild(o),s.appendChild(a)}const r=document.createElement("span");if(r.className="telemetry-value",r.textContent=t.value,s.appendChild(r),t.verb!==void 0&&t.verb!==null){const a=document.createElement("button");a.type="button",a.className="index-verb pacs-capsule",a.textContent=t.verb.label,a.title=t.verb.title,a.addEventListener("click",t.verb.act),s.appendChild(a)}this.mount.appendChild(s)}}}const BD=3e3;class ND{mount;clock;lane=void 0;cube=void 0;beatAt=null;constructor(e,t=()=>Date.now()){this.mount=e,this.clock=t,this.render()}telemetry_show(e={}){this.beatAt=this.clock(),e.lane!==void 0&&(this.lane=e.lane),e.cube!==void 0&&(this.cube=e.cube),this.render()}tick(){this.render()}rows_compose(){const e=[],t=this.lane;if(t===void 0)e.push({label:"LANE",value:"—",title:"The daemon has not said what holds its lane (an older daemon).",degraded:!1});else if(t.running===null)e.push({label:"LANE",value:t.waiting>0?`IDLE · ${t.waiting} WAITING`:"IDLE",title:"The serialized command lane: nothing is executing.",degraded:!1});else{const i=(t.running.sinceMs/1e3).toFixed(1);e.push({label:"LANE",value:`${t.running.line} · ${i} S${t.waiting>0?` · ${t.waiting} WAITING`:""}`,title:`The command holding the lane${t.running.surface?`, from surface ${t.running.surface}`:""}; every other command waits behind it.`,degraded:t.running.sinceMs>=1e4})}if(this.beatAt===null)e.push({label:"BEAT",value:"NONE YET",title:"No telemetry heartbeat has landed.",degraded:!1});else{const i=Math.max(0,this.clock()-this.beatAt);e.push({label:"BEAT",value:`${(i/1e3).toFixed(1)} S AGO`,title:"The age of the last telemetry heartbeat; the daemon beats once a second while a surface is attached.",degraded:i>=BD})}const s=this.cube;if(s===void 0)e.push({label:"CUBE",value:"NO PAGE TIMED",title:"CUBE's pace is known once a page of a list has been fetched.",degraded:!1});else{const i=s.msPerPage>0?Math.round(6e4/s.msPerPage):0;e.push({label:"CUBE",value:`${(s.msPerPage/1e3).toFixed(1)} S/PAGE · ${i} PAGES/MIN`,title:`The median of the last ${s.samples} page fetches (100 rows each).`,degraded:!1})}return e}render(){const e=this.rows_compose();this.mount.replaceChildren();for(const t of e){const s=document.createElement("div");s.className="lane-row telemetry-row",s.classList.toggle("status-degraded",t.degraded),s.title=t.title;const i=document.createElement("span");i.className="telemetry-label",i.textContent=t.label;const r=document.createElement("span");r.className="telemetry-value",r.textContent=t.value,s.append(i,r),this.mount.appendChild(s)}}}const CD=[2,3,3,2,2,11,2,2],PD=4,Kp=300,LD=2600,WD=650;class kD{wrapper;cells=[];bootedAt=Date.now();telemetry={jobsLoaded:0,jobsTotal:0,feeds:0,lastLatencyMs:0,latencySumMs:0,lastExitCode:0,commandsRun:0,opsActive:0,opsDone:0,opsFailed:0,itemsCurrent:0,itemsTotal:0,connected:0};activeOperations=new Set;telemetryRows=[];constructor(e){if(this.wrapper=e,e===null){window.setInterval(()=>this.beat_paint(),Kp);return}const t=this.narrowSources_list(),s=this.wideSources_list();let i=0,r=0;for(const a of CD){const o=document.createElement("div");o.className="data-column";for(let l=1;l<=PD;l++){const c=document.createElement("div");c.className=`dc-row-${l}`;let d;a>=6?(d=s[r%s.length],r++):(d=t[i%t.length],i++);const u={element:c,width:a,source:d??(()=>0)};c.textContent=Zp(u.source(),a),o.appendChild(c),this.cells.push(u)}e.appendChild(o)}window.setInterval(()=>this.beat_paint(),Kp),this.sweep_start()}promptContext_observe(e){const t=e.procWarmup;t!==void 0&&(this.telemetry.jobsLoaded=t.loaded,this.telemetry.jobsTotal=t.total??t.loaded);const s=e.procIndex;s!==void 0&&(t===void 0&&(this.telemetry.jobsLoaded=s.jobs,this.telemetry.jobsTotal=s.jobs),this.telemetry.feeds=s.feeds),e.lastCommandDurationMs>0&&(this.telemetry.lastLatencyMs=e.lastCommandDurationMs,this.telemetry.latencySumMs+=e.lastCommandDurationMs,this.telemetry.commandsRun++),this.telemetry.lastExitCode=e.lastExitCode}progress_observe(e){const t=`${e.operation}:${e.itemId??""}`;if(e.phase==="complete"||e.phase==="failed"){const s=`${e.operation}:`;for(const i of[...this.activeOperations])(i===t||i.startsWith(s))&&this.activeOperations.delete(i);e.status==="error"||e.phase==="failed"?this.telemetry.opsFailed++:this.telemetry.opsDone++}else e.itemId!==void 0&&e.status!==void 0&&["done","error","unconfirmed","stalled","timeout"].includes(e.status)?this.activeOperations.delete(t):this.activeOperations.add(t);this.telemetry.opsActive=this.activeOperations.size,e.current!==void 0&&(this.telemetry.itemsCurrent=e.current),e.total!==void 0&&(this.telemetry.itemsTotal=e.total)}index_observe(e){this.telemetry.jobsLoaded=e.jobs,this.telemetry.jobsTotal=e.jobs,this.telemetry.feeds=e.feeds}connection_show(e){this.telemetry.connected=e?1:0,this.wrapper?.classList.toggle("dc-stale",!e)}telemetryPanel_bind(e){const t=this.telemetry,s=[["LINK",()=>t.connected===1?"ONLINE":"OFFLINE"],["JOBS INDEXED",()=>`${t.jobsLoaded} / ${t.jobsTotal}`],["FEEDS VISIBLE",()=>String(t.feeds)],["OPS ACTIVE",()=>String(t.opsActive)],["OPS DONE",()=>String(t.opsDone)],["OPS FAILED",()=>String(t.opsFailed)],["ITEMS",()=>`${t.itemsCurrent} / ${t.itemsTotal}`],["LAST COMMAND",()=>`${t.lastLatencyMs} MS`],["LATENCY SUM",()=>`${t.latencySumMs} MS`],["COMMANDS RUN",()=>String(t.commandsRun)],["LAST EXIT",()=>String(t.lastExitCode)],["UPTIME",()=>`${this.uptimeSeconds_get()} S`]];for(const[i,r]of s){const a=document.createElement("div");a.className="telemetry-row";const o=document.createElement("span");o.className="telemetry-label",o.textContent=i;const l=document.createElement("span");l.className="telemetry-value",l.textContent=r(),a.append(o,l),e.appendChild(a),this.telemetryRows.push({element:l,source:r})}}narrowSources_list(){const e=this.telemetry;return[()=>e.jobsLoaded,()=>e.feeds,()=>e.lastLatencyMs,()=>e.opsActive,()=>e.opsDone,()=>e.jobsTotal,()=>e.itemsCurrent,()=>e.itemsTotal,()=>e.opsFailed,()=>e.commandsRun,()=>e.lastExitCode,()=>new Date().getSeconds(),()=>this.uptimeSeconds_get()]}wideSources_list(){return[()=>Math.floor(Date.now()/1e3),()=>this.uptimeSeconds_get(),()=>this.telemetry.latencySumMs,()=>UD()]}uptimeSeconds_get(){return Math.floor((Date.now()-this.bootedAt)/1e3)}beat_paint(){for(const e of this.cells){const t=Zp(e.source(),e.width);e.element.textContent!==t&&(e.element.textContent=t)}for(const e of this.telemetryRows){const t=e.source();e.element.textContent!==t&&(e.element.textContent=t)}}sweep_start(){if(this.wrapper===null)return;const e=Array.from(this.wrapper.querySelectorAll(".data-column"));window.setInterval(()=>{const t=e[Math.floor(Math.random()*e.length)];t!==void 0&&(t.classList.add("dc-sweep"),window.setTimeout(()=>t.classList.remove("dc-sweep"),WD))},LD)}}function Zp(n,e){const t=String(Math.max(0,Math.floor(n)));return t.length>e?t.slice(t.length-e):t.padStart(e,"0")}function UD(){const n=new Date;return n.getHours()*1e4+n.getMinutes()*100+n.getSeconds()}const FD=2e4;class jD{scene;nameplate;command_run;names=[];cursor=0;timer=null;seen=new Map;constructor(e,t,s){this.nameplate=t,this.command_run=s,this.scene=new Rl(e,{},{ambient:!0}),new MutationObserver(()=>this.scene.palette_refresh()).observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),new MutationObserver(()=>{window.setTimeout(()=>this.scene.size_fit(),60)}).observe(document.body,{attributes:!0,attributeFilter:["data-header"]}),window.addEventListener("resize",()=>this.scene.size_fit())}names_set(e){this.names=e,this.cursor=0,this.timer!==null&&(window.clearInterval(this.timer),this.timer=null),e.length!==0&&(this.next_request(),e.length>1&&(this.timer=window.setInterval(()=>this.next_request(),FD)))}envelope_observe(e){if(e.model?.kind!==zi.pipelineDiagram)return;const t=ed.safeParse(e.model.data);if(!t.success)return;const s=t.data;this.seen.set(s.name,s),this.model_stage(s)}model_stage(e){this.nameplate.textContent=e.name,this.scene.graph_set({nodes:e.nodes.map(t=>({id:t.id,label:t.label,parentIds:t.parentIds,joinParentIds:t.joinParentIds}))}),this.scene.size_fit()}next_request(){const e=this.names[this.cursor%this.names.length];if(this.cursor++,e===void 0)return;const t=this.seen.get(e);if(t!==void 0){this.model_stage(t);return}this.command_run(`pipeline diagram ${e}`)}}const $D=new Set(["pane","view","runs","node","dag","universe","file","pacs","image","tags","header","console","back","desktop","dashboard","launcher","attach","argus"]),bM=new Set(["layout","slice","series","wl","colormap","save","tags","load","guard","ghost","state"]),VD={pacs:new Set(["sort","filter"]),tags:new Set(["redact","filter"]),image:bM};let qn=null;const Gr="argus.desktop.",Qp="~/.config/argus/desktops";function HD(n){const e=n.trim().split(/\s+/),t=(e[0]??"").toLowerCase();if(!$D.has(t))return null;const s=VD[t];if(s!==void 0&&!s.has((e[1]??"").toLowerCase()))return null;let i=null,r=e.slice(1);return(r[0]?.startsWith("@")||r[0]?.startsWith("%"))&&(i=r[0],r=r.slice(1)),{subject:t,target:i,words:r}}function Jp(n,e){if(e===null)return n.focused_get();if(e.startsWith("@"))return e.slice(1);const t=parseInt(e.slice(1),10);return qn===null?null:qn[t-1]??null}function $n(n,e,t){const i=n.paneMount_get(e)?.querySelector(t)??null;return i===null?!1:(i.click(),!0)}function No(n,e,t){const s=n.paneMount_get(e);if(s===null)return!1;for(const i of s.querySelectorAll(".drawer-child"))if(i.textContent?.trim().toUpperCase()===t)return i.click(),!0;return!1}function qD(n,e,t){return $n(n,e,`.drawer-cwdbind[data-follow="${t?"on":"off"}"]`)}function Sa(n,e,t,s){const r=n.paneMount_get(e)?.querySelector(t)??null;if(r===null)return!1;for(let a=0;a<4;a++){if(r.textContent?.trim().toUpperCase()===s)return!0;r.click()}return r.textContent?.trim().toUpperCase()===s}function XD(n,e){const t=n.focused_get(),s=t!==null?n.paneRect_get(t):null;if(s===null)return null;const i=s.x+s.width/2,r=s.y+s.height/2;let a=null;for(const o of n.panes_shown()){if(o===t)continue;const l=n.paneRect_get(o);if(l===null)continue;const c=l.x+l.width/2-i,d=l.y+l.height/2-r,u=e==="left"?-c:e==="right"?c:e==="up"?-d:d;if(u<=1)continue;const h=Math.abs(e==="left"||e==="right"?d:c),g=u+h*2;(a===null||g<a.score)&&(a={id:o,score:g})}return a===null?null:(n.focus_set(a.id),a.id)}const YD={left:{split:"col",place:"before"},right:{split:"col",place:"after"},above:{split:"row",place:"before"},below:{split:"row",place:"after"}},KD=["pane [@id|%n] split left|right|above|below · zoom · close · bind unlinked|fs|viewer","pane [@id|%n] claim files|runs|pacs · focus left|right|up|down|@id","view files|runs|pacs (the gutter givens, workspace scope)","runs enter <feedId> · sort <col> [asc|desc] · filter <text>|off","node enter · immerse · back · clear (the indicated node)","dag [@id] layout ranked|molecule · projection 2d|3d · scale time|size · hue status|compute · pulse · census · physics charge|link|collide|gravity on|off · physics reset · refresh","file [@id] home|back|download|delete · follow · root · list|cards|preview · sort <col> [asc|desc] · filter <text>|off","pacs sort <col> [asc|desc] · filter <text>|off (the results listing; every other pacs verb is the session's)","image [@id] [--force] <path> · layout single|mpr|3d|slab · slice <n> · series <n> · wl <lo> <hi> · wl preset <name> · colormap gray|hot|jet|cool · save · tags · load · guard <bytes>|off · ghost <0..1>|off · state","tags [@id] redact on|off · filter <text>|off (the pane that follows an image pane's slice)","header stats|dag|away|restore","console open|close|toggle|zoom|height <px>","back (contextual back — exactly Esc)","desktop save|load|show|list|delete [name]","attach [--reveal] (how to reach THIS session from a terminal or another browser)","argus verbs (this table; the long form is docs/argus-lang.adoc)"].join(`
|
|
4234
4234
|
`);function ZD(n,e){const t=new URL(window.location.href),s=t.searchParams.get("token")??"",i=s===""?"":e?s:"•".repeat(8),r=s===""?t.origin+t.pathname:`${t.origin}${t.pathname}?token=${i}`,a=n.identity_get(),o=/^(127\.|\[?::1\]?$|localhost$)/.test(t.hostname),l=["attach — this session, from anywhere that can reach it"];return a!==null&&a!==""&&l.push(` identity ${a}`),l.push(""),l.push(" this machine chell --remote"),l.push(` another machine chell --remote --attach "${r}"`),l.push(` another browser ${r}`),l.push(""),o&&(l.push(" bound to loopback — another machine cannot reach this session;"),l.push(" relaunch the daemon with CALYPSO_BIND=0.0.0.0 to change that")),s===""?(l.push(" this page carries no token: it was opened without one, and a"),l.push(" second surface cannot attach with what is on screen")):e?l.push(" revealed — anyone who reads this line holds the session"):(l.push(" the token is masked — `attach --reveal` prints it. It is a bearer"),l.push(" credential with no expiry: treat the line like a password")),l.join(`
|
|
@@ -4237,7 +4237,7 @@ void main() {
|
|
|
4237
4237
|
`)[0]})`}if(e==="delete")return window.localStorage.removeItem(Gr+t),`deleted '${t}' (local; a CFS copy, if any, is yours to rm)`;if(e==="load"){let s=window.localStorage.getItem(Gr+t);if(s===null){const r=await n.session_run(`cat ${Qp}/${t}.desk`);r.trim().length>0&&!r.includes("No such")&&!r.toLowerCase().includes("error")&&(s=r)}if(s===null)return`(no desktop '${t}')`;qn=[];const i=[];try{for(const r of s.split(`
|
|
4238
4238
|
`)){const a=r.trim();if(a===""||a.startsWith("#"))continue;const o=await ou(n,a);i.push(`${a} → ${o??"(session line?)"}`),await new Promise(l=>{window.setTimeout(l,60)})}}finally{qn=null}return`loaded '${t}'
|
|
4239
4239
|
${i.join(`
|
|
4240
|
-
`)}`}return"desktop save|load|show|list|delete [name]"}const zM=new Map,Jr=new Map;let JD=0;function Un(n,e){zM.set(n,e)}function eI(n){const e=zM.get(n);if(e===void 0)throw new Error(`no pane factory registered for kind '${n}'`);const t=e(`${n}-${JD++}`);return Jr.set(t.id,t),t}function Rr(n){Jr.set(n.id,n)}function gn(n){return Jr.get(n)}function Co(){return[...Jr.values()]}function Ys(n){const e=Jr.get(n);e!==void 0&&(Jr.delete(n),e.dispose?.(),e.mount.remove())}const em="argus-layout";class tI{root;mounts;presets=new Map;prefs={};activePreset="";tree=null;focusedPane=null;renderObserver=null;constructor(e,t){this.root=e,this.mounts=t;try{const s=window.localStorage.getItem(em);this.prefs=s!==null?JSON.parse(s):{}}catch{this.prefs={}}}renderObserver_set(e){this.renderObserver=e}preset_register(e,t){this.presets.set(e,t)}mount_register(e,t){this.mounts.set(e,t)}mount_remove(e){this.mounts.delete(e),this.focusedPane===e&&(this.focusedPane=null)}leaf_split(e,t,s,i=!1){if(this.tree===null)return!1;const r=_l(this.tree,e,{dir:t,ratio:.5,first:i?{pane:s}:{pane:e},second:i?{pane:e}:{pane:s}});return r===null?!1:(this.tree=r,this.focusedPane=s,this.render(),!0)}leaf_replace(e,t){if(this.tree===null)return!1;const s=_l(this.tree,e,{pane:t});return s===null?!1:(this.tree=s,this.focusedPane===e&&(this.focusedPane=t),this.render(),!0)}leaf_close(e){if(this.tree===null||"pane"in this.tree)return!1;const t=lu(this.tree,e);return t===null?!1:(this.tree=t,this.focusedPane===e&&(this.focusedPane=null),this.render(),!0)}focused_get(){return this.focusedPane}savedPreset_get(){return this.prefs.preset!==void 0&&this.presets.has(this.prefs.preset)?this.prefs.preset:null}activePreset_get(){return this.activePreset}preset_apply(e){const t=this.presets.get(e);t!==void 0&&(this.activePreset=e,this.prefs.preset=e,this.prefs_save(),this.tree=this.ratios_restore(t(),e,""),this.render(),this.root.classList.remove("layout-arrive"),this.root.offsetWidth,this.root.classList.add("layout-arrive"))}tree_get(){return this.tree===null?null:JSON.parse(JSON.stringify(this.tree))}tree_set(e){this.tree=this.ratios_restore(e,this.activePreset,""),this.render()}panes_shown(){const e=[],t=s=>{if(s!==null){if("pane"in s){e.push(s.pane);return}t(s.first),t(s.second)}};return t(this.tree),e}render(){if(this.tree!==null){for(const e of this.mounts.values())e.remove();this.root.replaceChildren(this.node_render(this.tree,"")),this.renderObserver?.()}}node_render(e,t){if("pane"in e){const o=document.createElement("div");o.className="layout-leaf",o.dataset.leaf=e.pane;const l=this.mounts.get(e.pane);return l!==void 0&&(o.appendChild(l),l.style.display="",o.addEventListener("mousedown",()=>this.focus_set(e.pane),{capture:!0}),e.pane===this.focusedPane&&o.classList.add("pane-focused")),o}const s=document.createElement("div");s.className=`layout-split layout-${e.dir}`;const i=this.node_render(e.first,`${t}0`),r=this.node_render(e.second,`${t}1`);i.style.flex=`${e.ratio} 1 0`,r.style.flex=`${1-e.ratio} 1 0`;const a=document.createElement("div");return a.className="layout-divider",this.divider_wire(a,s,e,i,r,t),s.append(i,a,r),s}divider_wire(e,t,s,i,r,a){let o=!1;e.addEventListener("mousedown",l=>{o=!0,l.preventDefault()}),window.addEventListener("mousemove",l=>{if(!o)return;const c=t.getBoundingClientRect(),d=s.dir==="col"?(l.clientX-c.left)/c.width:(l.clientY-c.top)/c.height;s.ratio=Math.min(.85,Math.max(.15,d)),i.style.flex=`${s.ratio} 1 0`,r.style.flex=`${1-s.ratio} 1 0`}),window.addEventListener("mouseup",()=>{o&&(o=!1,this.ratio_remember(a,s.ratio),this.renderObserver?.())})}focus_set(e){if(this.focusedPane===e)return;this.focusedPane=e,document.body.dataset.focus=e;for(const s of this.root.querySelectorAll(".layout-leaf"))s.classList.remove("pane-focused");this.mounts.get(e)?.parentElement?.classList.add("pane-focused")}ratios_restore(e,t,s){if("pane"in e)return e;const i=this.prefs.ratios?.[`${t}:${s}`];return{...e,ratio:i??e.ratio,first:this.ratios_restore(e.first,t,`${s}0`),second:this.ratios_restore(e.second,t,`${s}1`)}}ratio_remember(e,t){this.prefs.ratios={...this.prefs.ratios??{},[`${this.activePreset}:${e}`]:t},this.prefs_save()}prefs_save(){try{window.localStorage.setItem(em,JSON.stringify(this.prefs))}catch{}}}function _l(n,e,t){if("pane"in n)return n.pane===e?t:null;const s=_l(n.first,e,t);if(s!==null)return{...n,first:s};const i=_l(n.second,e,t);return i!==null?{...n,second:i}:null}function lu(n,e){if("pane"in n)return null;if("pane"in n.first&&n.first.pane===e)return n.second;if("pane"in n.second&&n.second.pane===e)return n.first;const t=lu(n.first,e);if(t!==null)return{...n,first:t};const s=lu(n.second,e);return s!==null?{...n,second:s}:null}const sI=/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i;function nI(n){const e=n instanceof Error?n.message:String(n??"");return sI.test(e)}function iI(n,e=document.body){let t=!1;const s=()=>{if(t)return;t=!0,n("argus: the server has a newer argus than this page — reload to continue (what failed to load was part of the old one)");const i=document.createElement("div");i.className="stale-page",i.setAttribute("role","alert");const r=document.createElement("span");r.className="stale-page-words",r.textContent="ARGUS WAS UPDATED ON THE SERVER — THIS PAGE IS OLDER";const a=document.createElement("button");a.className="pacs-capsule stale-page-reload",a.textContent="RELOAD",a.title="load the argus the server has now",a.addEventListener("click",()=>{window.location.reload()}),i.append(r,a),e.appendChild(i)};window.addEventListener("vite:preloadError",i=>{i.preventDefault(),s()}),window.addEventListener("unhandledrejection",i=>{nI(i.reason)&&s()})}let _M=()=>{};function rI(){_M(document.body.dataset.zoom==="console"?null:"console")}const aI=wA(),oI="ARGUS",tm="argus-audio",lI=.4;let Li=!1;function Lt(n){if(Li)return;const e=document.getElementById(n);e instanceof HTMLAudioElement&&(e.currentTime=0,e.volume=lI,e.play().catch(()=>{}))}function cI(){const n=rt("head-menu-pill"),e=t=>{t?document.body.dataset.headMenu="open":delete document.body.dataset.headMenu,n.setAttribute("aria-expanded",String(t))};n.addEventListener("click",t=>{t.stopPropagation(),e(document.body.dataset.headMenu!=="open")}),document.addEventListener("click",t=>{if(document.body.dataset.headMenu!=="open")return;t.target instanceof Element&&t.target.closest("#header-dag-info")!==null||e(!1)})}function dI(){const n=rt("audio-pill");try{Li=window.localStorage.getItem(tm)==="off"}catch{Li=!1}const e=()=>{n.classList.toggle("audio-off",Li)};e(),n.addEventListener("click",()=>{Li=!Li;try{window.localStorage.setItem(tm,Li?"off":"on")}catch{}e(),Lt("audio2")})}function rt(n){const e=document.getElementById(n);if(e===null)throw new Error(`required element #${n} is missing`);return e}function fn(n){const e=rt(n);if(!(e instanceof HTMLTemplateElement))throw new Error(`#${n} is not a template`);const t=e.content.firstElementChild;if(!(t instanceof HTMLElement))throw new Error(`template #${n} is empty`);return t.cloneNode(!0)}function Rs(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`pane template is missing ${e}`);return t}function uI(){return yA(window.location)}const sm=/\.(csv|tsv)$/i;let $c=null,wl=0;function wM(n,e){const t=()=>{e.dataset.zoom!==void 0||e.dataset.header==="away"||(wl=Math.ceil(n.getBoundingClientRect().bottom),e.style.setProperty("--zoom-header-height",`${wl}px`))};t(),$c===null&&($c=new ResizeObserver(t),$c.observe(n))}const hI=2200,nm=120,fI=96;function pI(n,e,t,s){let i="";const r=d=>{d?(i=n.style.height,n.style.height=""):i!==""&&(n.style.height=i),n.classList.toggle("drawer-closed",d),Lt("audio3"),d||(s.size_fit(),s.focus_take())};t.addEventListener("click",()=>r(!n.classList.contains("drawer-closed")));let a=0,o=0,l=!1;e.addEventListener("pointerdown",d=>{l=!0,a=d.clientY,o=n.getBoundingClientRect().height,n.classList.add("drawer-dragging"),e.setPointerCapture(d.pointerId),d.preventDefault()}),e.addEventListener("pointermove",d=>{if(!l)return;const u=Math.max(nm,window.innerHeight-fI),h=o+(d.clientY-a),g=Math.min(Math.max(nm,h),u);n.style.height=`${g}px`,s.size_fit()});const c=()=>{l=!1,n.classList.remove("drawer-dragging")};return e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c),r}function mI(n){const e=document.body,t=document.querySelector(".wrap:not(#gap)");let s;const i=r=>{for(const a of document.querySelectorAll(".pane-zoomed, .pane-zoomed-path"))a.classList.remove("pane-zoomed","pane-zoomed-path");if(r===null)delete e.dataset.zoom,s!==void 0&&(e.dataset.header=s,s=void 0);else{window.scrollTo(0,0),e.dataset.header==="away"?(s="away",delete e.dataset.header,wl>0&&e.style.setProperty("--zoom-header-height",`${wl}px`)):t!==null&&wM(t,e),e.dataset.zoom=r;const o=gn(r)?.mount?.parentElement??null;o?.classList.add("pane-zoomed");let l=o?.parentElement??null;for(;l!==null&&l.id!=="layout-root";)l.classList.add("pane-zoomed-path"),l=l.parentElement}for(const a of document.querySelectorAll(".drawer-zoom"))a.textContent=r!==null&&a.dataset.pane===r?"RESTORE":"ZOOM";Lt("audio3")};return rt("header-restore").addEventListener("click",()=>{e.dataset.zoom!==void 0&&i(null)}),document.addEventListener("click",r=>{const a=r.target;if(!(a instanceof Element))return;const o=a.closest("[data-pane]");if(o===null)return;const l=o.dataset.pane??"";l!==""&&i(e.dataset.zoom===l?null:l)}),window.addEventListener("keydown",r=>{r.key==="Escape"&&e.dataset.zoom!==void 0&&(i(null),r.stopImmediatePropagation())}),rt("drawer").addEventListener("transitionend",r=>{r.propertyName==="height"&&n.size_fit()}),i}function gI(){const n=new kD(document.getElementById("data-cascade")),e=document.getElementById("header-telemetry");return e!==null&&n.telemetryPanel_bind(e),n}const Vc=96,MI=220,im="argus.headerBand.height";function bI(){const n=document.documentElement,e=document.getElementById("header-strip"),t=document.querySelector(".wrap:not(#gap)");if(e===null||t===null)return;const s=d=>{const u=Math.max(Vc,window.innerHeight-MI),h=Math.min(Math.max(Vc,d),u);n.style.setProperty("--header-band-h",`${h}px`);try{window.localStorage.setItem(im,String(h))}catch{}},i=(()=>{try{return window.localStorage.getItem(im)}catch{return null}})();i!==null&&Number.isFinite(Number(i))&&s(Number(i));const r=()=>{const d=t.getBoundingClientRect();e.style.top=`${Math.max(0,d.bottom-8)}px`};r(),window.addEventListener("resize",r),new MutationObserver(r).observe(document.body,{attributes:!0,attributeFilter:["data-header"]}),window.setInterval(r,500);let a=!1,o=0,l=0;e.addEventListener("pointerdown",d=>{const u=document.querySelector(".header-face");a=!0,o=d.clientY,l=u===null?Vc:u.getBoundingClientRect().height,e.setPointerCapture(d.pointerId),d.preventDefault()}),e.addEventListener("pointermove",d=>{a&&(s(l+(d.clientY-o)),r())});const c=()=>{a=!1,r()};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}let Xu=null;function zI(n){const e=n.querySelector(".gather-rows");if(e===null)return;const t=document.createElement("button");t.type="button",t.className="strategy-pill gather-more",t.title="the whole cohort as a pane on the main panel",t.hidden=!0,t.addEventListener("click",i=>{i.stopPropagation(),Xu?.()}),n.appendChild(t);const s=()=>{const i=e.getBoundingClientRect().bottom,r=[...e.querySelectorAll(".listing-row")].filter(a=>a.getBoundingClientRect().top>=i-2).length;t.hidden=r===0,t.textContent=`+${r} MORE · ON STAGE`};e.addEventListener("scroll",s,{passive:!0}),new ResizeObserver(s).observe(e),new MutationObserver(s).observe(e,{childList:!0,subtree:!0}),s()}function rm(n){n.dataset.more="wired";const e=document.createElement("button");e.type="button",e.className="frame-more",e.hidden=!0;const t=()=>n.scrollTop+n.clientHeight>=n.scrollHeight-2;e.addEventListener("click",i=>{i.stopPropagation(),n.scrollBy({top:t()?-n.scrollHeight:Math.max(1,n.clientHeight-e.offsetHeight),behavior:"smooth"})}),n.appendChild(e);const s=()=>{const i=n.scrollHeight>n.clientHeight+2;if(e.hidden!==!i&&(e.hidden=!i),!i)return;const r=n.getBoundingClientRect().bottom,a=[...n.querySelectorAll(".strategy-pill, .listing-action")].filter(l=>l.getBoundingClientRect().height>0&&l.getBoundingClientRect().top>=r-2).length,o=t()?"▲ TOP":`▼ ${a} MORE`;e.textContent!==o&&(e.textContent=o)};n.addEventListener("scroll",s,{passive:!0}),new ResizeObserver(s).observe(n),new MutationObserver(s).observe(n,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","class"]}),s()}function _I(){const n=e=>{for(const t of e.querySelectorAll(".mode-frame:not([data-more])"))rm(t)};new MutationObserver(e=>{for(const t of e)for(const s of t.addedNodes)s instanceof HTMLElement&&(s.matches(".mode-frame")&&s.dataset.more===void 0&&rm(s),n(s))}).observe(document.body,{childList:!0,subtree:!0}),n(document)}function wI(){const n=document.body,e=document.querySelector(".wrap:not(#gap)"),t=r=>{n.dataset.header===r?(e!==null&&wM(e,n),n.dataset.header="away"):n.dataset.header=r};document.querySelector(".panel-1")?.addEventListener("click",()=>t("stats")),document.querySelector(".panel-2")?.addEventListener("click",()=>t("dag")),document.querySelector(".panel-gather")?.addEventListener("click",()=>t("gather"));const s=document.querySelector(".header-gather-field");s?.querySelector(".gather-stage")?.addEventListener("click",r=>{r.stopPropagation(),Xu?.()}),s!==null&&zI(s),_I();const i=()=>{n.dataset.zoom===void 0&&(delete n.dataset.header,Lt("audio3"))};rt("header-restore").addEventListener("click",i),window.addEventListener("keydown",r=>{r.key==="Escape"&&n.dataset.header==="away"&&n.dataset.zoom===void 0&&n.dataset.gutter!=="away"&&i()})}const Br=[{key:"lower-decks",label:"LOWER DECKS"},{key:"gold",label:"CERRITOS GOLD"},{key:"medical",label:"MEDICAL"},{key:"nemesis",label:"NEMESIS"},{key:"pharos",label:"PHAROS"}],yM="argus-landing",yI=15e3;function am(){try{return(window.localStorage.getItem(yM)??"launcher")==="launcher"}catch{return!0}}function vI(n){try{window.localStorage.setItem(yM,n?"launcher":"last")}catch{}}const om="argus-theme",OI="argus-lcars",xI="medical",SI={sickbay:"medical"};function AI(){const n=rt("theme-pill"),e=Math.max(Br.findIndex(r=>r.key===xI),0);let t=e;try{const r=window.localStorage.getItem(om)??window.localStorage.getItem(OI),a=r===null?null:SI[r]??r,o=Br.findIndex(l=>l.key===a);t=o>=0?o:e}catch{t=e}const s=document.documentElement,i=()=>{const r=Br[t]??Br[0];r.key==="lower-decks"?delete s.dataset.theme:s.dataset.theme=r.key,n.textContent=r.label};i(),n.addEventListener("click",()=>{t=(t+1)%Br.length,i();try{window.localStorage.setItem(om,Br[t]?.key??"lower-decks")}catch{}Lt("audio2")})}function EI(n){const e=document.getElementById("about-rows");if(e===null)return;e.replaceChildren();const t={cumin:n.stack?.cumin,salsa:n.stack?.salsa,chili:n.stack?.chili,brasa:n.stack?.brasa,calypso:n.stack?.calypso,chell:n.stack?.chell},s=[];for(const[i,r]of Object.entries(t))r!==void 0&&s.push([i.toUpperCase(),r]);s.push(["MENU","0.13.0"],["ARGUS","9ebd5bd · 2026-10-01 03:51Z"],["WIRE",`V${n.protocolVersion}`]),n.stack?.build!==void 0&&s.push(["BUILD",n.stack.build]);for(const[i,r]of s){const a=document.createElement("div");a.className="telemetry-row";const o=document.createElement("span");o.className="telemetry-label",o.textContent=i;const l=document.createElement("span");l.className="telemetry-value",l.textContent=r,l.title=r,a.append(o,l),e.appendChild(a)}}function lm(n){return n.replace(/\x1b\[[0-9;:]*[A-Za-z]/g,"")}function DI(){for(const n of document.querySelectorAll(".left-frame button, .left-frame-top button"))n.addEventListener("click",()=>Lt("audio2"))}let Cr=null;async function II(n){const e=new TD(document),t=new RD(rt("index-instrument"),()=>Date.now(),{errored_open:()=>Et("status:error")}),s=new ND(rt("lane-instrument"));window.setInterval(()=>s.tick(),500);const i=new Map,r=new Map,a=new Map,o=new Map,l=new AD;l.writeObserver_set((M,v)=>{Mt.regard_send({address:M.address,...M.modelKind!==void 0?{modelKind:M.modelKind}:{},groupId:v,paneId:M.paneId}),_n()});const c=M=>Vu(M,n),d=M=>vA(M,n),u=M=>{XA(d(M),M).then(v=>{ve.line_note(v.ok?`download: ${v.name}${v.streamed?" — large; the browser fetches it itself":""}`:`download: ${M}: ${v.reason}`)})},p={imageUrl:c,download:u,textHead:async(M,v)=>{const D=await fetch(c(M));if(!D.ok||D.body===null)return(await z(M)).text.slice(0,v);const G=D.body.getReader(),T=new TextDecoder;let C="";for(;C.length<v;){const{done:$,value:U}=await G.read();if($)break;C+=T.decode(U,{stream:!0})}return G.cancel().catch(()=>{}),C.slice(0,v)},pipelineGlimpse:async M=>{const v=/_id(\d+)$/.exec(M)?.[1]??M.replace(/^.*\//,""),D=await Mt.line_execute(`pipeline diagram ${v}`,{silent:!0,observe:!1});for(const G of D.envelopes){if(G.model?.kind!==zi.pipelineDiagram)continue;const T=ed.safeParse(G.model.data);if(T.success)return T.data.nodes.map(C=>({id:C.id,parentIds:[...C.parentIds,...C.joinParentIds??[]]}))}return null}},z=M=>Mt.line_execute(`cat "${M}"`,{silent:!0,observe:!1}).then(v=>{if(!v.envelopes.some(T=>T.status==="error"))return{ok:!0,text:lm(v.envelopes.map(T=>T.rendered).join(`
|
|
4240
|
+
`)}`}return"desktop save|load|show|list|delete [name]"}const zM=new Map,Jr=new Map;let JD=0;function Un(n,e){zM.set(n,e)}function eI(n){const e=zM.get(n);if(e===void 0)throw new Error(`no pane factory registered for kind '${n}'`);const t=e(`${n}-${JD++}`);return Jr.set(t.id,t),t}function Rr(n){Jr.set(n.id,n)}function gn(n){return Jr.get(n)}function Co(){return[...Jr.values()]}function Ys(n){const e=Jr.get(n);e!==void 0&&(Jr.delete(n),e.dispose?.(),e.mount.remove())}const em="argus-layout";class tI{root;mounts;presets=new Map;prefs={};activePreset="";tree=null;focusedPane=null;renderObserver=null;constructor(e,t){this.root=e,this.mounts=t;try{const s=window.localStorage.getItem(em);this.prefs=s!==null?JSON.parse(s):{}}catch{this.prefs={}}}renderObserver_set(e){this.renderObserver=e}preset_register(e,t){this.presets.set(e,t)}mount_register(e,t){this.mounts.set(e,t)}mount_remove(e){this.mounts.delete(e),this.focusedPane===e&&(this.focusedPane=null)}leaf_split(e,t,s,i=!1){if(this.tree===null)return!1;const r=_l(this.tree,e,{dir:t,ratio:.5,first:i?{pane:s}:{pane:e},second:i?{pane:e}:{pane:s}});return r===null?!1:(this.tree=r,this.focusedPane=s,this.render(),!0)}leaf_replace(e,t){if(this.tree===null)return!1;const s=_l(this.tree,e,{pane:t});return s===null?!1:(this.tree=s,this.focusedPane===e&&(this.focusedPane=t),this.render(),!0)}leaf_close(e){if(this.tree===null||"pane"in this.tree)return!1;const t=lu(this.tree,e);return t===null?!1:(this.tree=t,this.focusedPane===e&&(this.focusedPane=null),this.render(),!0)}focused_get(){return this.focusedPane}savedPreset_get(){return this.prefs.preset!==void 0&&this.presets.has(this.prefs.preset)?this.prefs.preset:null}activePreset_get(){return this.activePreset}preset_apply(e){const t=this.presets.get(e);t!==void 0&&(this.activePreset=e,this.prefs.preset=e,this.prefs_save(),this.tree=this.ratios_restore(t(),e,""),this.render(),this.root.classList.remove("layout-arrive"),this.root.offsetWidth,this.root.classList.add("layout-arrive"))}tree_get(){return this.tree===null?null:JSON.parse(JSON.stringify(this.tree))}tree_set(e){this.tree=this.ratios_restore(e,this.activePreset,""),this.render()}panes_shown(){const e=[],t=s=>{if(s!==null){if("pane"in s){e.push(s.pane);return}t(s.first),t(s.second)}};return t(this.tree),e}render(){if(this.tree!==null){for(const e of this.mounts.values())e.remove();this.root.replaceChildren(this.node_render(this.tree,"")),this.renderObserver?.()}}node_render(e,t){if("pane"in e){const o=document.createElement("div");o.className="layout-leaf",o.dataset.leaf=e.pane;const l=this.mounts.get(e.pane);return l!==void 0&&(o.appendChild(l),l.style.display="",o.addEventListener("mousedown",()=>this.focus_set(e.pane),{capture:!0}),e.pane===this.focusedPane&&o.classList.add("pane-focused")),o}const s=document.createElement("div");s.className=`layout-split layout-${e.dir}`;const i=this.node_render(e.first,`${t}0`),r=this.node_render(e.second,`${t}1`);i.style.flex=`${e.ratio} 1 0`,r.style.flex=`${1-e.ratio} 1 0`;const a=document.createElement("div");return a.className="layout-divider",this.divider_wire(a,s,e,i,r,t),s.append(i,a,r),s}divider_wire(e,t,s,i,r,a){let o=!1;e.addEventListener("mousedown",l=>{o=!0,l.preventDefault()}),window.addEventListener("mousemove",l=>{if(!o)return;const c=t.getBoundingClientRect(),d=s.dir==="col"?(l.clientX-c.left)/c.width:(l.clientY-c.top)/c.height;s.ratio=Math.min(.85,Math.max(.15,d)),i.style.flex=`${s.ratio} 1 0`,r.style.flex=`${1-s.ratio} 1 0`}),window.addEventListener("mouseup",()=>{o&&(o=!1,this.ratio_remember(a,s.ratio),this.renderObserver?.())})}focus_set(e){if(this.focusedPane===e)return;this.focusedPane=e,document.body.dataset.focus=e;for(const s of this.root.querySelectorAll(".layout-leaf"))s.classList.remove("pane-focused");this.mounts.get(e)?.parentElement?.classList.add("pane-focused")}ratios_restore(e,t,s){if("pane"in e)return e;const i=this.prefs.ratios?.[`${t}:${s}`];return{...e,ratio:i??e.ratio,first:this.ratios_restore(e.first,t,`${s}0`),second:this.ratios_restore(e.second,t,`${s}1`)}}ratio_remember(e,t){this.prefs.ratios={...this.prefs.ratios??{},[`${this.activePreset}:${e}`]:t},this.prefs_save()}prefs_save(){try{window.localStorage.setItem(em,JSON.stringify(this.prefs))}catch{}}}function _l(n,e,t){if("pane"in n)return n.pane===e?t:null;const s=_l(n.first,e,t);if(s!==null)return{...n,first:s};const i=_l(n.second,e,t);return i!==null?{...n,second:i}:null}function lu(n,e){if("pane"in n)return null;if("pane"in n.first&&n.first.pane===e)return n.second;if("pane"in n.second&&n.second.pane===e)return n.first;const t=lu(n.first,e);if(t!==null)return{...n,first:t};const s=lu(n.second,e);return s!==null?{...n,second:s}:null}const sI=/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i;function nI(n){const e=n instanceof Error?n.message:String(n??"");return sI.test(e)}function iI(n,e=document.body){let t=!1;const s=()=>{if(t)return;t=!0,n("argus: the server has a newer argus than this page — reload to continue (what failed to load was part of the old one)");const i=document.createElement("div");i.className="stale-page",i.setAttribute("role","alert");const r=document.createElement("span");r.className="stale-page-words",r.textContent="ARGUS WAS UPDATED ON THE SERVER — THIS PAGE IS OLDER";const a=document.createElement("button");a.className="pacs-capsule stale-page-reload",a.textContent="RELOAD",a.title="load the argus the server has now",a.addEventListener("click",()=>{window.location.reload()}),i.append(r,a),e.appendChild(i)};window.addEventListener("vite:preloadError",i=>{i.preventDefault(),s()}),window.addEventListener("unhandledrejection",i=>{nI(i.reason)&&s()})}let _M=()=>{};function rI(){_M(document.body.dataset.zoom==="console"?null:"console")}const aI=wA(),oI="ARGUS",tm="argus-audio",lI=.4;let Li=!1;function Lt(n){if(Li)return;const e=document.getElementById(n);e instanceof HTMLAudioElement&&(e.currentTime=0,e.volume=lI,e.play().catch(()=>{}))}function cI(){const n=rt("head-menu-pill"),e=t=>{t?document.body.dataset.headMenu="open":delete document.body.dataset.headMenu,n.setAttribute("aria-expanded",String(t))};n.addEventListener("click",t=>{t.stopPropagation(),e(document.body.dataset.headMenu!=="open")}),document.addEventListener("click",t=>{if(document.body.dataset.headMenu!=="open")return;t.target instanceof Element&&t.target.closest("#header-dag-info")!==null||e(!1)})}function dI(){const n=rt("audio-pill");try{Li=window.localStorage.getItem(tm)==="off"}catch{Li=!1}const e=()=>{n.classList.toggle("audio-off",Li)};e(),n.addEventListener("click",()=>{Li=!Li;try{window.localStorage.setItem(tm,Li?"off":"on")}catch{}e(),Lt("audio2")})}function rt(n){const e=document.getElementById(n);if(e===null)throw new Error(`required element #${n} is missing`);return e}function fn(n){const e=rt(n);if(!(e instanceof HTMLTemplateElement))throw new Error(`#${n} is not a template`);const t=e.content.firstElementChild;if(!(t instanceof HTMLElement))throw new Error(`template #${n} is empty`);return t.cloneNode(!0)}function Rs(n,e){const t=n.querySelector(e);if(t===null)throw new Error(`pane template is missing ${e}`);return t}function uI(){return yA(window.location)}const sm=/\.(csv|tsv)$/i;let $c=null,wl=0;function wM(n,e){const t=()=>{e.dataset.zoom!==void 0||e.dataset.header==="away"||(wl=Math.ceil(n.getBoundingClientRect().bottom),e.style.setProperty("--zoom-header-height",`${wl}px`))};t(),$c===null&&($c=new ResizeObserver(t),$c.observe(n))}const hI=2200,nm=120,fI=96;function pI(n,e,t,s){let i="";const r=d=>{d?(i=n.style.height,n.style.height=""):i!==""&&(n.style.height=i),n.classList.toggle("drawer-closed",d),Lt("audio3"),d||(s.size_fit(),s.focus_take())};t.addEventListener("click",()=>r(!n.classList.contains("drawer-closed")));let a=0,o=0,l=!1;e.addEventListener("pointerdown",d=>{l=!0,a=d.clientY,o=n.getBoundingClientRect().height,n.classList.add("drawer-dragging"),e.setPointerCapture(d.pointerId),d.preventDefault()}),e.addEventListener("pointermove",d=>{if(!l)return;const u=Math.max(nm,window.innerHeight-fI),h=o+(d.clientY-a),g=Math.min(Math.max(nm,h),u);n.style.height=`${g}px`,s.size_fit()});const c=()=>{l=!1,n.classList.remove("drawer-dragging")};return e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c),r}function mI(n){const e=document.body,t=document.querySelector(".wrap:not(#gap)");let s;const i=r=>{for(const a of document.querySelectorAll(".pane-zoomed, .pane-zoomed-path"))a.classList.remove("pane-zoomed","pane-zoomed-path");if(r===null)delete e.dataset.zoom,s!==void 0&&(e.dataset.header=s,s=void 0);else{window.scrollTo(0,0),e.dataset.header==="away"?(s="away",delete e.dataset.header,wl>0&&e.style.setProperty("--zoom-header-height",`${wl}px`)):t!==null&&wM(t,e),e.dataset.zoom=r;const o=gn(r)?.mount?.parentElement??null;o?.classList.add("pane-zoomed");let l=o?.parentElement??null;for(;l!==null&&l.id!=="layout-root";)l.classList.add("pane-zoomed-path"),l=l.parentElement}for(const a of document.querySelectorAll(".drawer-zoom"))a.textContent=r!==null&&a.dataset.pane===r?"RESTORE":"ZOOM";Lt("audio3")};return rt("header-restore").addEventListener("click",()=>{e.dataset.zoom!==void 0&&i(null)}),document.addEventListener("click",r=>{const a=r.target;if(!(a instanceof Element))return;const o=a.closest("[data-pane]");if(o===null)return;const l=o.dataset.pane??"";l!==""&&i(e.dataset.zoom===l?null:l)}),window.addEventListener("keydown",r=>{r.key==="Escape"&&e.dataset.zoom!==void 0&&(i(null),r.stopImmediatePropagation())}),rt("drawer").addEventListener("transitionend",r=>{r.propertyName==="height"&&n.size_fit()}),i}function gI(){const n=new kD(document.getElementById("data-cascade")),e=document.getElementById("header-telemetry");return e!==null&&n.telemetryPanel_bind(e),n}const Vc=96,MI=220,im="argus.headerBand.height";function bI(){const n=document.documentElement,e=document.getElementById("header-strip"),t=document.querySelector(".wrap:not(#gap)");if(e===null||t===null)return;const s=d=>{const u=Math.max(Vc,window.innerHeight-MI),h=Math.min(Math.max(Vc,d),u);n.style.setProperty("--header-band-h",`${h}px`);try{window.localStorage.setItem(im,String(h))}catch{}},i=(()=>{try{return window.localStorage.getItem(im)}catch{return null}})();i!==null&&Number.isFinite(Number(i))&&s(Number(i));const r=()=>{const d=t.getBoundingClientRect();e.style.top=`${Math.max(0,d.bottom-8)}px`};r(),window.addEventListener("resize",r),new MutationObserver(r).observe(document.body,{attributes:!0,attributeFilter:["data-header"]}),window.setInterval(r,500);let a=!1,o=0,l=0;e.addEventListener("pointerdown",d=>{const u=document.querySelector(".header-face");a=!0,o=d.clientY,l=u===null?Vc:u.getBoundingClientRect().height,e.setPointerCapture(d.pointerId),d.preventDefault()}),e.addEventListener("pointermove",d=>{a&&(s(l+(d.clientY-o)),r())});const c=()=>{a=!1,r()};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}let Xu=null;function zI(n){const e=n.querySelector(".gather-rows");if(e===null)return;const t=document.createElement("button");t.type="button",t.className="strategy-pill gather-more",t.title="the whole cohort as a pane on the main panel",t.hidden=!0,t.addEventListener("click",i=>{i.stopPropagation(),Xu?.()}),n.appendChild(t);const s=()=>{const i=e.getBoundingClientRect().bottom,r=[...e.querySelectorAll(".listing-row")].filter(a=>a.getBoundingClientRect().top>=i-2).length;t.hidden=r===0,t.textContent=`+${r} MORE · ON STAGE`};e.addEventListener("scroll",s,{passive:!0}),new ResizeObserver(s).observe(e),new MutationObserver(s).observe(e,{childList:!0,subtree:!0}),s()}function rm(n){n.dataset.more="wired";const e=document.createElement("button");e.type="button",e.className="frame-more",e.hidden=!0;const t=()=>n.scrollTop+n.clientHeight>=n.scrollHeight-2;e.addEventListener("click",i=>{i.stopPropagation(),n.scrollBy({top:t()?-n.scrollHeight:Math.max(1,n.clientHeight-e.offsetHeight),behavior:"smooth"})}),n.appendChild(e);const s=()=>{const i=n.scrollHeight>n.clientHeight+2;if(e.hidden!==!i&&(e.hidden=!i),!i)return;const r=n.getBoundingClientRect().bottom,a=[...n.querySelectorAll(".strategy-pill, .listing-action")].filter(l=>l.getBoundingClientRect().height>0&&l.getBoundingClientRect().top>=r-2).length,o=t()?"▲ TOP":`▼ ${a} MORE`;e.textContent!==o&&(e.textContent=o)};n.addEventListener("scroll",s,{passive:!0}),new ResizeObserver(s).observe(n),new MutationObserver(s).observe(n,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","class"]}),s()}function _I(){const n=e=>{for(const t of e.querySelectorAll(".mode-frame:not([data-more])"))rm(t)};new MutationObserver(e=>{for(const t of e)for(const s of t.addedNodes)s instanceof HTMLElement&&(s.matches(".mode-frame")&&s.dataset.more===void 0&&rm(s),n(s))}).observe(document.body,{childList:!0,subtree:!0}),n(document)}function wI(){const n=document.body,e=document.querySelector(".wrap:not(#gap)"),t=r=>{n.dataset.header===r?(e!==null&&wM(e,n),n.dataset.header="away"):n.dataset.header=r};document.querySelector(".panel-1")?.addEventListener("click",()=>t("stats")),document.querySelector(".panel-2")?.addEventListener("click",()=>t("dag")),document.querySelector(".panel-gather")?.addEventListener("click",()=>t("gather"));const s=document.querySelector(".header-gather-field");s?.querySelector(".gather-stage")?.addEventListener("click",r=>{r.stopPropagation(),Xu?.()}),s!==null&&zI(s),_I();const i=()=>{n.dataset.zoom===void 0&&(delete n.dataset.header,Lt("audio3"))};rt("header-restore").addEventListener("click",i),window.addEventListener("keydown",r=>{r.key==="Escape"&&n.dataset.header==="away"&&n.dataset.zoom===void 0&&n.dataset.gutter!=="away"&&i()})}const Br=[{key:"lower-decks",label:"LOWER DECKS"},{key:"gold",label:"CERRITOS GOLD"},{key:"medical",label:"MEDICAL"},{key:"nemesis",label:"NEMESIS"},{key:"pharos",label:"PHAROS"}],yM="argus-landing",yI=15e3;function am(){try{return(window.localStorage.getItem(yM)??"launcher")==="launcher"}catch{return!0}}function vI(n){try{window.localStorage.setItem(yM,n?"launcher":"last")}catch{}}const om="argus-theme",OI="argus-lcars",xI="medical",SI={sickbay:"medical"};function AI(){const n=rt("theme-pill"),e=Math.max(Br.findIndex(r=>r.key===xI),0);let t=e;try{const r=window.localStorage.getItem(om)??window.localStorage.getItem(OI),a=r===null?null:SI[r]??r,o=Br.findIndex(l=>l.key===a);t=o>=0?o:e}catch{t=e}const s=document.documentElement,i=()=>{const r=Br[t]??Br[0];r.key==="lower-decks"?delete s.dataset.theme:s.dataset.theme=r.key,n.textContent=r.label};i(),n.addEventListener("click",()=>{t=(t+1)%Br.length,i();try{window.localStorage.setItem(om,Br[t]?.key??"lower-decks")}catch{}Lt("audio2")})}function EI(n){const e=document.getElementById("about-rows");if(e===null)return;e.replaceChildren();const t={cumin:n.stack?.cumin,salsa:n.stack?.salsa,chili:n.stack?.chili,brasa:n.stack?.brasa,calypso:n.stack?.calypso,chell:n.stack?.chell},s=[];for(const[i,r]of Object.entries(t))r!==void 0&&s.push([i.toUpperCase(),r]);s.push(["MENU","0.13.0"],["ARGUS","97fef79 · 2026-10-01 04:13Z"],["WIRE",`V${n.protocolVersion}`]),n.stack?.build!==void 0&&s.push(["BUILD",n.stack.build]);for(const[i,r]of s){const a=document.createElement("div");a.className="telemetry-row";const o=document.createElement("span");o.className="telemetry-label",o.textContent=i;const l=document.createElement("span");l.className="telemetry-value",l.textContent=r,l.title=r,a.append(o,l),e.appendChild(a)}}function lm(n){return n.replace(/\x1b\[[0-9;:]*[A-Za-z]/g,"")}function DI(){for(const n of document.querySelectorAll(".left-frame button, .left-frame-top button"))n.addEventListener("click",()=>Lt("audio2"))}let Cr=null;async function II(n){const e=new TD(document),t=new RD(rt("index-instrument"),()=>Date.now(),{errored_open:()=>Et("status:error")}),s=new ND(rt("lane-instrument"));window.setInterval(()=>s.tick(),500);const i=new Map,r=new Map,a=new Map,o=new Map,l=new AD;l.writeObserver_set((M,v)=>{Mt.regard_send({address:M.address,...M.modelKind!==void 0?{modelKind:M.modelKind}:{},groupId:v,paneId:M.paneId}),_n()});const c=M=>Vu(M,n),d=M=>vA(M,n),u=M=>{XA(d(M),M).then(v=>{ve.line_note(v.ok?`download: ${v.name}${v.streamed?" — large; the browser fetches it itself":""}`:`download: ${M}: ${v.reason}`)})},p={imageUrl:c,download:u,textHead:async(M,v)=>{const D=await fetch(c(M));if(!D.ok||D.body===null)return(await z(M)).text.slice(0,v);const G=D.body.getReader(),T=new TextDecoder;let C="";for(;C.length<v;){const{done:$,value:U}=await G.read();if($)break;C+=T.decode(U,{stream:!0})}return G.cancel().catch(()=>{}),C.slice(0,v)},pipelineGlimpse:async M=>{const v=/_id(\d+)$/.exec(M)?.[1]??M.replace(/^.*\//,""),D=await Mt.line_execute(`pipeline diagram ${v}`,{silent:!0,observe:!1});for(const G of D.envelopes){if(G.model?.kind!==zi.pipelineDiagram)continue;const T=ed.safeParse(G.model.data);if(T.success)return T.data.nodes.map(C=>({id:C.id,parentIds:[...C.parentIds,...C.joinParentIds??[]]}))}return null}},z=M=>Mt.line_execute(`cat "${M}"`,{silent:!0,observe:!1}).then(v=>{if(!v.envelopes.some(T=>T.status==="error"))return{ok:!0,text:lm(v.envelopes.map(T=>T.rendered).join(`
|
|
4241
4241
|
`))};const G=v.envelopes.flatMap(T=>(T.errors??[]).map(C=>C.message)).concat(v.envelopes.map(T=>T.renderedErr??"")).map(T=>lm(T).trim()).filter(T=>T!=="").join(`
|
|
4242
4242
|
`);return{ok:!1,text:G===""?"the session refused this read and said nothing further":G}}),m=new Map,f=new Map,_=new Map,O=(M,v)=>{_.set(M,v)},w=M=>{_.get(M)?.()},x=(M,v)=>{f.set(M,v),w(M);const D=i.get(M);D?.follow_set(v),v&&D!==void 0&&Mt.line_execute("ls",{silent:!0,observe:!1}).then(G=>{for(const T of G.envelopes)D.envelope_observe(T)})},S=async(M,v,D)=>{for(const G of D){const T=`${v}/${G.name}`;ve.line_note(`putting ${G.name} in ${v}…`);try{const C=await fetch(c(T),{method:"POST",body:G});if(!C.ok){ve.line_note(`upload: ${G.name}: ${(await C.text()).trim()||C.statusText}`);continue}ve.line_note(`✓ ${T}`)}catch(C){ve.line_note(`upload: ${G.name}: ${C instanceof Error?C.message:String(C)}`)}}I(M,v)},I=(M,v)=>{const D=i.get(M);D!==void 0&&(f.get(M)===!0?ve.line_run("ls"):A(M,D,v))},b=(M,v)=>{zn(M,{message:`New directory in ${v}: `,kind:"text",commit:"MAKE IT"}).then(D=>{const G=(D??"").trim();G!==""&&(ve.line_run(`mkdir "${v}/${G}"`),I(M,v))})},A=(M,v,D)=>{const G=D==="~"?"ls ~":`ls "${D}"`;Mt.line_execute(G,{silent:!0,observe:!1}).then(T=>{for(const C of T.envelopes)v.envelope_observe(C)})},B=M=>/\x1b\[/.test(M)?jn(M):Ks(M).replace(/("[^&]*")/g,'<span class="man-str">$1</span>').replace(/(^|\s)(--?[a-zA-Z][\w-]*)/g,'$1<span class="man-flag">$2</span>').replace(/^(\s{0,2})([A-Za-z_ ]+):(\s)/gm,'$1<span class="man-key">$2:</span>$3').replace(/^([A-Z][A-Z ]{2,})$/gm,'<span class="man-head">$1</span>'),N=(M,v,D,G)=>{let T=null,C=null;const $=M.contentHtml_show(v,"",{diagram:!0,release:()=>{W=null,C?.(),C=null,M.mode_annunciate(""),T?.dispose(),T=null}});$!==null&&D().then(U=>{if(!$.isConnected)return;if(U===null||U.nodes.length===0){$.textContent="NOTHING TO DRAW FOR THIS ENTRY",$.classList.add("files-diagram-empty");return}U.text!==""&&M.contentText_set(U.text);const Z=document.createElement("div");Z.className="dag-facts",$.appendChild(Z);const ne=new Rl($,{select:Se=>U.facts_show(Z,Se.id,!1,G),activate:Se=>ie(Se),deselect:()=>Z.replaceChildren()},{}),ie=Se=>{ne.flight_into(Se.id,()=>{W={scene:ne,facts:Z},U.facts_show(Z,Se.id,!0,G)})};T=ne,ne.graph_set({nodes:U.nodes},{wave:!1}),ne.size_fit(),C=oe($,ne,M,G===null?void 0:G.run);const be=U.nodes.length===1?U.nodes[0]:void 0;be!==void 0&&ie(be)})},k=async M=>{const v=/_id(\d+)$/.exec(M)?.[1]??M.replace(/^.*\//,""),[D,G]=await Promise.all([Mt.line_execute(`cat "${M}"`,{silent:!0,observe:!1}),Mt.line_execute(`pipeline diagram ${v}`,{silent:!0,observe:!1})]),T=D.envelopes.map(C=>C.rendered).join(`
|
|
4243
4243
|
`);for(const C of G.envelopes){if(C.model?.kind!==zi.pipelineDiagram)continue;const $=ed.safeParse(C.model.data);if(!$.success)continue;const U=new Map($.data.nodes.map(Z=>[Z.id,Z]));return{text:B(T),nodes:$.data.nodes.map(Z=>({id:Z.id,label:Z.label,parentIds:Z.parentIds,joinParentIds:Z.joinParentIds})),facts_show:(Z,ne,ie,be)=>{const Se=$.data.nodes.map(Ze=>Ze.label);Q(Z,re(U.get(ne),ie,be!==null,Se),ie,be)}}}return null},L=async M=>{const v=M.replace(/^.*\//,""),D=await Mt.line_execute(`plugin info "${v}"`,{silent:!0,observe:!1});for(const G of D.envelopes){if(G.model?.kind!==w0)continue;const T=_0.safeParse(G.model.data);if(!T.success)continue;const C=T.data;return{text:"",nodes:[{id:v,label:C.name,parentIds:[],joinParentIds:[]}],facts_show:($,U,Z,ne)=>{Q($,Me(C,Z,ne!==null),Z,ne)}}}return null},j=(M,v,D,G)=>{N(v,D,()=>G==="plugin"?L(D):k(D),P(M,v,D,G))},P=(M,v,D,G)=>{const T=fe.get(M);if(T===void 0)return null;const C=D.replace(/^.*\//,"");return Wp(v.commandLine_get())!==C&&v.commandLine_set(Cp(T.input,C)),{line_get:()=>v.commandLine_get(),line_set:$=>v.commandLine_set($),run:()=>{Ae(M,C,G)}}};let W=null;function X(){const M=W;return M===null?!1:(W=null,M.scene.flight_back(()=>{M.facts.classList.remove("dag-facts-immersed"),M.facts.replaceChildren()}),!0)}function Q(M,v,D,G){M.replaceChildren(),M.classList.toggle("dag-facts-immersed",D);for(const{label:T,value:C,edit:$}of v){const U=document.createElement("div");U.className="telemetry-row";const Z=document.createElement("span");if(Z.className="telemetry-label",Z.textContent=T,U.appendChild(Z),$===void 0||G===null){const ne=document.createElement("span");ne.className="telemetry-value",ne.textContent=C,U.appendChild(ne)}else{const ne=IE(G.line_get(),$.flag),ie=document.createElement("input");ie.className="telemetry-input",ie.spellcheck=!1,ie.autocomplete="off",ie.title=`${$.flag} — ${C}`,$.type==="boolean"?(ie.type="checkbox",ie.checked=ne===!0,ie.addEventListener("change",()=>{G.line_set(Lp(G.line_get(),$.flag,ie.checked?!0:null))})):(ie.type="text",ie.placeholder=$.placeholder,ie.value=ne===null||ne===!0?"":ne,ie.addEventListener("input",()=>{G.line_set(Lp(G.line_get(),$.flag,ie.value))}));const be=document.createElement("span");be.className="telemetry-hint",be.textContent=C,U.append(ie,be)}M.appendChild(U)}}function re(M,v,D,G){if(M===void 0)return[];const T=M.arguments??[],C=[{label:"NODE",value:`${M.label} · @${M.id}`},{label:"PLUGIN",value:M.pluginName},...M.pluginVersion!==void 0?[{label:"VERSION",value:M.pluginVersion}]:[]];if(v){const $=RE(M.label,M.id,G);C.push(...T.length===0?[{label:"ARGUMENTS",value:"none — this node runs on the plugin's defaults"}]:T.map(U=>({label:U.name,value:String(U.value??""),...D?{edit:{flag:`--${$}.${U.name}`,type:typeof U.value=="boolean"?"boolean":"string",placeholder:String(U.value??"")}}:{}})))}else C.push({label:"ARGUMENTS",value:T.length===0?"none":`${T.length} — open the node to read them`});return C}function Me(M,v,D){const G=[{label:"PLUGIN",value:M.name},{label:"VERSION",value:M.version},{label:"TYPE",value:M.type.toUpperCase()}],T=M.parameters;if(!v)return G.push({label:"PARAMETERS",value:T.length===0?"none":`${T.length} — open the node to read them`}),G;if(T.length===0)return G.push({label:"PARAMETERS",value:"none — this plugin takes no arguments"}),G;for(const C of T){const $=[C.type];C.optional||$.push("required");const U=C.default===void 0||C.default===null?"":String(C.default);U!==""&&$.push(`default ${U}`);const Z=$.join(" · ");G.push({label:C.flag,value:C.help===void 0?Z:`${Z} — ${C.help}`,...D?{edit:{flag:C.flag,type:C.type,placeholder:U}}:{}})}return G}function oe(M,v,D,G){const T=M.closest(".files-body"),C=T?.querySelector(".diagram-strategy")??null,$=T?.querySelector(".diagram-projection")??null,U=T?.querySelector(".diagram-pulse")??null,Z=G===void 0?null:T?.querySelector(".diagram-run")??null,ne=()=>G?.(),ie=()=>{const $e=[];v.strategy_get()!=="ranked"&&$e.push("MOLECULE"),v.projection_get()!=="3d"&&$e.push("2D"),D.mode_annunciate($e.join(" · "))},be=()=>{v.strategy_set(v.strategy_get()==="ranked"?"molecule":"ranked"),C!==null&&(C.textContent=v.strategy_get().toUpperCase()),ie()},Se=()=>{v.projection_set(v.projection_get()==="3d"?"2d":"3d"),$!==null&&($.textContent=v.projection_get().toUpperCase()),ie()},Ze=()=>{v.wave_start(),U?.classList.add("pulse-running"),window.setTimeout(()=>U?.classList.remove("pulse-running"),hI)};return C!==null&&(C.textContent=v.strategy_get().toUpperCase()),$!==null&&($.textContent=v.projection_get().toUpperCase()),C?.addEventListener("click",be),$?.addEventListener("click",Se),U?.addEventListener("click",Ze),Z?.addEventListener("click",ne),ie(),()=>{C?.removeEventListener("click",be),$?.removeEventListener("click",Se),U?.removeEventListener("click",Ze),Z?.removeEventListener("click",ne),U?.classList.remove("pulse-running")}}const Oe=(M,v,D)=>{if(D.kind==="dir"){if(f.get(M)===!0)ve.line_run(`cd "${D.path}"`);else{const G=v.path_current();G!==null&&m.get(M)?.push(G),A(M,v,D.path)}return}if(D.kind==="plugin"||D.kind==="pipeline"){j(M,v,D.path,D.kind);return}if(Ke(D.path)){R(M,D.path).then(G=>ve.line_note(G));return}if(l.regard_write(M,{address:D.path,modelKind:"fs.file"}),!l.groupHasViewer(M)){if(Yo(D.path)){v.contentImage_show(D.path,c(D.path));return}z(D.path).then(G=>{if(!G.ok){v.contentRefused_show(D.path,G.text);return}sm.test(D.path)?v.contentTable_show(D.path,G.text):v.content_show(D.path,G.text)})}},Ke=M=>Gc.test(M)||Xo.test(M),nt=()=>{const M=fn("tpl-pane-files").querySelector(".files-body");if(M===null)throw new Error("tpl-pane-files has no files-body");return M};let je=null,ce=null;const ue=M=>{const v=/_(\d+)\/data\/?$/.exec(M);return v===null?null:parseInt(v[1]??"",10)},fe=new Map,et=M=>{const v=M.match(/\/(?:feeds|jobs)\/feed_(\d+)(?:\/|$)/);return v===null?null:Number(v[1])},ct=M=>/^\/(proc|net|etc|usr)(\/|$)/.test(M),Qe=(M,v,D)=>{const G=`"${D}"`,T=v.type==="dir"||v.type==="vfs"||v.type==="job",C=et(D),$={kind:v.type==="plugin"||v.type==="pipeline"?"catalogue":T&&Rc(D,v.name)?"seriesFolder":v.type==="file"?"file":"directory",feed:C,node:C===null?null:ue(D),bound:fe.has(M),projection:ct(D)},U={image:()=>{R(M,D).then(Z=>ve.line_note(Z))},download:()=>u(D),process:()=>y(M,{input:D,feed:C,node:C===null?null:ue(D)}),gather:()=>Te([{kind:T?"dir":"file",seriesUID:D,description:v.name,imagery:Rc(D,v.name),modality:Rc(D,v.name)?"MR":"—",patient:je??"",vfsPath:D,folderPath:D}]),run:()=>{Ae(M,v.name,v.type==="pipeline"?"pipeline":"plugin")},move:()=>oi(M,`mv ${G}`),copy:()=>oi(M,`cp ${G}`),delete:()=>oi(M,`rm ${T?"-ri":"-i"} ${G}`),share:()=>oi(M,`setfacl ${G}`)};return Qg.rules.filter(Z=>Z.offered($)).map(Z=>({label:Z.label($),run:()=>U[Z.name]?.()}))},Zt=M=>{for(const v of M.envelopes){const D=v.model;if(typeof D!="object"||D===null)continue;const G=D.data;if(D.kind!=="fs.acl"||!Array.isArray(G))continue;const T=[];for(const C of G)Array.isArray(C.usernames)&&T.push(...C.usernames.map(String));return T.length===0?"SHARED WITH NOBODY":`SHARED WITH ${T.join(", ")}`}return"ACCESS UNREAD"},gt=(M,v,D=!1)=>{const G=fn("tpl-pane-files"),T=new vp(Rs(G,".files-panel"),C=>Oe(M,T,C),p,{catalogue:D});return T.selectionVerbs_declare(C=>{const $=C.map(([be])=>be),U=$.map(be=>`"${be}"`).join(" ");C.every(([,be])=>be.type==="file");const Z=[];for(const be of $){const Se=et(be);Se!==null&&!Z.includes(Se)&&Z.push(Se)}const ne={count:$.length,feeds:Z},ie={delete:()=>oi(M,`rm -rI ${U}`),move:()=>ve.line_run(`mv -t ${U}`),copy:()=>ve.line_run(`cp -t ${U}`),share:()=>ve.line_run(`setfacl ${Z.map(be=>`feed_${be}`).join(" ")}`)};return Jg.rules.filter(be=>be.offered(ne)).map(be=>({label:be.label(ne),run:()=>ie[be.name]?.()}))}),T.rowVerbs_declare((C,$)=>Qe(M,C,$),(C,$)=>{l.regard_write(M,{address:$,modelKind:"fs.file"}),et($)!==null&&Mt.line_execute(`getfacl "${$}"`,{silent:!0,observe:!1}).then(U=>{T.rowReadout_show($,Zt(U))}).catch(()=>{T.rowReadout_show($,"ACCESS UNREAD")})}),i.set(M,T),je!==null&&je!==""&&T.home_set(`/home/${je}`),m.set(M,[]),f.set(M,v),w(M),T.follow_set(v),{id:M,kind:"files",mount:G,dispose:()=>{i.delete(M),m.delete(M),l.pane_leave(M)}}},Rt=new Map,it=new Map,wt=M=>{const v=fn("tpl-pane-universe"),D=new lD({canvas:Rs(v,".universe-canvas"),title:Rs(v,".universe-title"),state:v.querySelector(".pane-state"),empty:Rs(v,".universe-empty"),projectionPill:v.querySelector(".universe-projection"),refreshPill:v.querySelector(".universe-refresh"),replayPill:v.querySelector(".universe-replay"),scalePill:v.querySelector(".universe-scale"),viewPill:v.querySelector(".universe-view"),gravityPill:v.querySelector(".universe-gravity"),densityPill:v.querySelector(".universe-density"),drawPill:v.querySelector(".universe-draw"),captionsPill:v.querySelector(".universe-captions"),arrangementPill:v.querySelector(".universe-arrangement"),facts:v.querySelector(".universe-facts"),backPill:v.querySelector(".universe-back"),openPill:v.querySelector(".universe-open")},{command_run:G=>{Mt.line_execute(G,{silent:!0,observe:!1}).then(T=>{for(const C of T.envelopes)D.envelope_observe(C)})},feed_dag:async G=>{const T=await Mt.line_execute(`feed diagram feed_${G}`,{silent:!0,observe:!1});for(const C of T.envelopes){if(C.model?.kind!==zi.feedDag)continue;const $=td.safeParse(C.model.data);if($.success)return $.data}return null},node_enter:G=>{ve.line_run(`cd "${G}"`)},node_dive:G=>{Vt(M,G.replace(/\/data$/,""))},node_process:G=>{const T=et(G.vfsPath)??(/\/feed_(\d+)(?:\/|$)/.exec(G.vfsPath)===null?null:Number(/\/feed_(\d+)(?:\/|$)/.exec(G.vfsPath)[1])),C=je===null?G.vfsPath:G.vfsPath.replace(/^\/proc\/jobs\//,`/home/${je}/feeds/`);y(M,{input:C,feed:T,node:G.instanceId})},feed_open:G=>{Et(),$s.feed_enter(G)},plugin_open:G=>{(async()=>{const T=await Mt.line_execute("ls /bin",{silent:!0,observe:!1}),C=[];for(const U of T.envelopes){if(U.model?.kind!=="fs.listing")continue;const Z=U.model.data,ne=Array.isArray(Z)?Z:[Z];for(const ie of ne)for(const be of ie.items??[])C.push(be.name)}const $=C.filter(U=>U.startsWith(`${G}-v`)).sort((U,Z)=>U.localeCompare(Z,void 0,{numeric:!0})).pop();if($===void 0){ve.line_note(`universe: ${G} is not in /bin`);return}rt("gutter-files").click(),j("files",i.get("files"),`/bin/${$}`,"plugin")})().catch(T=>{ve.line_note(`universe: could not open ${G} in /bin: ${T instanceof Error?T.message:String(T)}`)})},note:G=>ve.line_note(G)},sp());return o.set(M,D),{id:M,kind:"universe",mount:v,dispose:()=>{o.delete(M),l.pane_leave(M),D.dispose()}}},ns=M=>{const v=fn("tpl-pane-image"),D=new _D(v,{source:{url_of:c},note:G=>ve.line_note(G),regard:G=>l.regard_write(M,{address:G,modelKind:"dicom.instance"}),file_put:async(G,T)=>{try{return(await fetch(c(G),{method:"POST",body:T})).status}catch{return 0}},tags_read:G=>as(G),tags_open:()=>{ve.line_note(es(M))}});return it.set(M,D),{id:M,kind:"image",mount:v,dispose:()=>{D.dispose(),it.delete(M),l.pane_leave(M)}}},Ut=new Map,rs=M=>{const v=fn("tpl-pane-tags"),D=new yD(v,{note:G=>ve.line_note(G)});return Ut.set(M,D),{id:M,kind:"tags",mount:v,dispose:()=>{Ut.delete(M),l.pane_leave(M)}}},as=async M=>{try{const v=await Mt.line_execute(`dcm tags "${M}"`,{silent:!0,observe:!1});for(const D of v.envelopes){if(D.model?.kind!==Ha.tags)continue;const G=uh.safeParse(D.model.data);if(G.success)return G.data}}catch{}return null},Qt=(M,v)=>{const D=Ut.get(M);D===void 0||D.path_get()===v||as(v).then(G=>{if(G===null){ve.line_note(`tags: ${v}: not a readable DICOM file`);return}Ut.get(M)?.model_show(G)})},es=M=>{const v=new Set(ze.panes_shown()),D=l.group_of(M);for(const T of Ut.keys())if(v.has(T)&&l.group_of(T)===D)return ze.focus_set(T),"image tags";if(!v.has(M))return"image tags: the image pane is not on stage";const G=qt("tags",M);return ze.leaf_split(M,me?.dir??"col",G.id,me?.before??!1)?(E(G.id,M,me?.dir??"col",me?.before??!1),"image tags"):(Ys(G.id),ze.mount_remove(G.id),"image tags: could not open beside the image pane")},q=async M=>{try{const v=await Mt.line_execute(`dcm series "${M}"`,{silent:!0,observe:!1});for(const D of v.envelopes){if(D.model?.kind!==Ha.series)continue;const G=hh.safeParse(D.model.data);if(G.success)return G.data}}catch{}return null},Os=async M=>{try{const v=await Mt.line_execute(`ls "${M}"`,{silent:!0,observe:!1});for(const D of v.envelopes){if(D.model?.kind!=="fs.listing")continue;const G=D.model.data,T=(Array.isArray(G)?G[0]:G)??{},C=(T.path??M).replace(/\/$/,"");return(T.items??[]).filter($=>$.type==="dir").map($=>`${C}/${$.name}`)}}catch{}return[]},Bt=(M,v)=>{const D=U=>{v!==void 0&&l.regard_write(U,v)};if(M!==null&&it.has(M))return D(M),it.get(M)??null;const G=new Set(ze.panes_shown());if(v!==void 0){for(const[U,Z]of it)if(G.has(U)&&l.regard_get(U)?.address===v.address)return D(U),Z}const T=M!==null?l.group_of(M):null;for(const[U,Z]of it)if(G.has(U)&&T!==null&&l.group_of(U)===T)return Z;const C=M!==null&&G.has(M)?M:xs();if(C===null)return null;const $=qt("image",M??void 0);return ze.leaf_split(C,me?.dir??"col",$.id,me?.before??!1)?(E($.id,C,me?.dir??"col",me?.before??!1),D($.id),it.get($.id)??null):(Ys($.id),ze.mount_remove($.id),null)},R=async(M,v,D={},G)=>{Ht();const T=M!==null?void 0:Gc.test(v)?{address:v,modelKind:"image.volume"}:{address:Xo.test(v)?v.slice(0,v.lastIndexOf("/")):v.replace(/\/$/,""),modelKind:"dicom.series"},C=Bt(M,T);if(C===null)return"image: no pane to open beside";const $=ft(C);if($!==null&&G?.($),Gc.test(v))return C.opening_show(v),C.volume_show(v),`image ${v}`;const U=Xo.test(v),Z=U?v.slice(0,v.lastIndexOf("/")):v.replace(/\/$/,"");C.opening_show(Z);let ne=await q(Z),ie=[];if(ne===null&&!U){const Se=(await Os(Z)).slice(0,32);for(const Ze of Se){const $e=await q(Ze);if($e!==null){ie=Se.map(yt=>({path:yt,label:yt.split("/").pop()??yt})),ne=$e;break}}}if(ne===null)return C.opening_fail(v,"NOT A READABLE SERIES"),`image: ${v}: not a readable DICOM series, study, or volume`;const be=U?Math.max(1,ne.files.indexOf(v)+1):1;return C.series_show(ne,{siblings:ie,startAt:be,...D.force===!0?{force:!0}:{}}),`image ${ne.path}${ie.length>1?` (1 of ${ie.length} series)`:""}`},y=(M,v)=>{Ht();const D=new Set(ze.panes_shown());for(const[$,U]of fe)if(D.has($)&&U.input===v.input){ze.focus_set($);return}const G=D.has(M)?M:xs()??M,T=qt("catalogue",M);if(!ze.leaf_split(G,me?.dir??"col",T.id,me?.before??!1)){Ys(T.id),ze.mount_remove(T.id);return}E(T.id,G,me?.dir??"col",me?.before??!1),fe.set(T.id,v);const C=i.get(T.id);C!==void 0&&(C.binding_set({input:v.input,place:v.feed===null?"new feed":`feed ${v.feed}${v.node===null?"":` · node ${v.node}`}`}),C.feedOpen_declare($=>ye(T.id,$)),A(T.id,C,"/bin"),ae(C),ze.focus_set(T.id))},K=5,se=40,ae=M=>{Mt.line_execute(`plugininstance list --limit ${se} --fields id,plugin_name,plugin_version,owner_username`,{silent:!0,observe:!1}).then(D=>{const G=[];for(const T of D.envelopes)if(!(T.model?.kind!=="plugininstance.list"||!Array.isArray(T.model.data)))for(const C of T.model.data){if(typeof C.pluginName!="string"||typeof C.pluginVersion!="string"||je!==null&&typeof C.owner=="string"&&C.owner!==je||C.pluginName==="pl-dircopy")continue;const $=`${C.pluginName}-v${C.pluginVersion}`;if(G.includes($)||G.push($),G.length>=K)break}M.recent_set(G.length===0?null:G)}).catch(()=>{})},ye=(M,v)=>{Ht();const D=new Set(ze.panes_shown());for(const[C,$]of a)if(C!=="dag"&&D.has(C)&&$.feed_get()===v){ze.focus_set(C);return}const G=D.has(M)?M:xs()??M,T=qt("dag",M);if(!ze.leaf_split(G,me?.dir??"col",T.id,me?.before??!1)){Ys(T.id),ze.mount_remove(T.id);return}E(T.id,G,me?.dir??"col",me?.before??!1),a.get(T.id)?.feed_enter(v)},Ae=async(M,v,D)=>{const G=fe.get(M),T=i.get(M);if(G===void 0||T===void 0)return;const C=Se=>{ve.output_write("err",`\x1B[31m${Se}\x1B[0m
|